diff --git a/package.json b/package.json index 74f86c6..034abc0 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "prebuild": "npm test", "build": "vite build", "preview": "vite preview", - "test": "node scripts/test-edit-matcher.mjs && node scripts/test-edit-read-errors.mjs && node scripts/test-click-to-edit.mjs && node scripts/test-badge.mjs && node scripts/test-branding.mjs && node scripts/test-upgrade-pending.mjs && node scripts/test-preview-message-trust.mjs && node scripts/test-fs-path-scoping.mjs && node scripts/test-search-files.mjs && node scripts/test-markdown-link-sanitizer.mjs && node scripts/test-publish-state.mjs && node scripts/test-publish-errors.mjs && node scripts/test-publish-analytics.mjs && node scripts/test-publish-card.mjs && node scripts/test-publish-switch-race.mjs && node scripts/test-publish-button-return.mjs && node scripts/test-publish-rollback.mjs && node scripts/test-publish-mutation-lock.mjs && node scripts/test-publish-notes.mjs && node scripts/test-publish-drain-writes.mjs && node scripts/test-chat-thumb-refresh.mjs && node scripts/test-sidebar-search-filter.mjs && node scripts/test-chat-list-entry.mjs && node scripts/test-chat-list-save-race.mjs && node scripts/test-chat-list-tabs.mjs && node scripts/test-missing-projects.mjs && node scripts/test-delete-cleanup.mjs && node scripts/test-preview-verification.mjs && node scripts/test-app-tests.mjs && node scripts/test-preview-canary.mjs && node scripts/test-preview-host.mjs && node scripts/test-early-preview-clear.mjs && node scripts/test-turn-progress.mjs && node scripts/test-build-abandoned.mjs && node scripts/test-transient-retry.mjs && node scripts/test-mobile-lifecycle.mjs && node scripts/test-ai-cost-tracking.mjs && node scripts/test-sign-in-analytics.mjs && node scripts/test-usage-limit-unblock.mjs && node scripts/test-add-credits.mjs && node scripts/test-clear-credit-errors.mjs && node scripts/test-limit-hit-call-count.mjs && node scripts/test-pwa.mjs && node scripts/test-error-tracking.mjs && node scripts/test-todo-finalize.mjs && node scripts/test-issues.mjs && node scripts/test-composer-drafts.mjs && node scripts/test-composer-handoff.mjs && node scripts/test-message-queue.mjs && node scripts/test-voice-input.mjs && node scripts/test-voice-recorder-inert.mjs && node scripts/test-worker-ownership.mjs && node scripts/test-duplicate-worker-isolation.mjs && node scripts/test-published-workers.mjs && node scripts/test-publish-site-reuse.mjs && node scripts/test-version-index-integrity.mjs && node scripts/test-tool-use-repair.mjs && node scripts/test-manifest.mjs && node scripts/test-seo.mjs && node scripts/test-ime-enter.mjs && node scripts/test-worker-tools.mjs && node scripts/test-worker-save-canary.mjs && node scripts/test-read-cap.mjs && node scripts/test-send-button-state.mjs && node scripts/test-html-escape-roundtrip.mjs && node scripts/test-code-highlight.mjs && node scripts/test-chat-switch-reset.mjs && node scripts/test-load-media-urls.mjs && node scripts/test-history-dead-link.mjs && node scripts/test-storage-guards.mjs && node scripts/test-fresh-reads.mjs && node scripts/test-composer-autoresize.mjs && node scripts/test-preview-reload.mjs && node scripts/test-blockquote-render.mjs && node scripts/test-message-links.mjs && node scripts/test-drag-highlight.mjs && node scripts/test-composer-focus-guard.mjs && node scripts/test-suggestions-scroll.mjs && node scripts/test-stale-pdf-blocks.mjs && node scripts/test-view-document.mjs && node scripts/test-view-image.mjs && node scripts/test-render-svg.mjs && node scripts/test-social-images.mjs && node scripts/test-custom-domain.mjs && node scripts/test-whats-new.mjs && node scripts/test-generated-media.mjs && node scripts/test-grid-restore-missing.mjs && node scripts/test-lightbox-chat-switch.mjs && node scripts/test-lightbox-caption.mjs && node scripts/test-media-card-size.mjs && node scripts/test-media-broken-image.mjs && node scripts/test-media-image-load.mjs && node scripts/test-media-status-quiet.mjs && node scripts/test-read-url-cache.mjs && node scripts/test-unsaved-media-download.mjs && node scripts/test-live-media-read-url.mjs && node scripts/test-image-reference-svg.mjs && node scripts/test-attachment-snapshot.mjs && node scripts/test-attachment-names.mjs && node scripts/test-extract-zip.mjs && node scripts/test-paste-intake.mjs && node scripts/test-paste-as-attachment.mjs && node scripts/test-confirm-modal-keys.mjs && node scripts/test-alert-escape.mjs && node scripts/test-toasts.mjs && node scripts/test-popover-focus-return.mjs && node scripts/test-apps-panel.mjs && node scripts/test-user-menu-element.mjs && node scripts/test-puter-dialog-clicks.mjs && node scripts/test-input-labels.mjs && node scripts/test-announce.mjs && node scripts/test-menu-keyboard-close.mjs && node scripts/test-sidebar-focus.mjs && node scripts/test-mobile-view-switch.mjs && node scripts/test-theme-radio.mjs && node scripts/test-busy-entries.mjs && node scripts/test-toolbar-a11y.mjs && node scripts/test-clarify-keys.mjs && node scripts/test-version-prune.mjs && node scripts/test-project-readme.mjs && node scripts/test-restore-safety-snapshot.mjs && node scripts/test-restore-dirty-tracking.mjs && node scripts/test-restore-prune-failure.mjs && node scripts/test-restore-readdir-failure.mjs && node scripts/test-stopped-turn-unwind.mjs && node scripts/test-restore-workers.mjs && node scripts/test-restore-concurrency.mjs && node scripts/test-tool-result-dedup.mjs && node scripts/test-click-to-edit-intake.mjs && node scripts/test-external-fetch.mjs && node scripts/test-friendly-errors.mjs && node scripts/test-thinking-preview.mjs && node scripts/test-final-reply-reveal.mjs && node scripts/test-checklist-spinner.mjs && node scripts/test-mcp.mjs && node scripts/test-profile-picture.mjs && node scripts/test-templates.mjs && node scripts/test-editor-core.mjs && node scripts/test-github-core.mjs && node scripts/test-github-sync.mjs && node scripts/test-worker-secrets.mjs && node scripts/test-worker-sender.mjs && node scripts/test-site-backends.mjs && node scripts/test-model-core.mjs && node scripts/test-compaction.mjs && node scripts/test-tool-batching.mjs && node scripts/test-suggest-after-turn.mjs && node scripts/test-model-picker.mjs && node scripts/test-keyboard-viewport.mjs && node scripts/test-starter-test.mjs && node scripts/test-speed-test.mjs && node scripts/test-experiments.mjs && node scripts/test-fast-mode.mjs && node scripts/test-build-notify.mjs", + "test": "node scripts/test-edit-matcher.mjs && node scripts/test-edit-read-errors.mjs && node scripts/test-click-to-edit.mjs && node scripts/test-badge.mjs && node scripts/test-branding.mjs && node scripts/test-upgrade-pending.mjs && node scripts/test-preview-message-trust.mjs && node scripts/test-fs-path-scoping.mjs && node scripts/test-search-files.mjs && node scripts/test-markdown-link-sanitizer.mjs && node scripts/test-publish-state.mjs && node scripts/test-publish-errors.mjs && node scripts/test-publish-analytics.mjs && node scripts/test-publish-card.mjs && node scripts/test-publish-switch-race.mjs && node scripts/test-publish-button-return.mjs && node scripts/test-publish-rollback.mjs && node scripts/test-publish-mutation-lock.mjs && node scripts/test-publish-notes.mjs && node scripts/test-publish-drain-writes.mjs && node scripts/test-chat-thumb-refresh.mjs && node scripts/test-sidebar-search-filter.mjs && node scripts/test-chat-list-entry.mjs && node scripts/test-chat-list-save-race.mjs && node scripts/test-chat-list-tabs.mjs && node scripts/test-missing-projects.mjs && node scripts/test-delete-cleanup.mjs && node scripts/test-preview-verification.mjs && node scripts/test-app-tests.mjs && node scripts/test-preview-canary.mjs && node scripts/test-preview-host.mjs && node scripts/test-early-preview-clear.mjs && node scripts/test-turn-progress.mjs && node scripts/test-build-abandoned.mjs && node scripts/test-transient-retry.mjs && node scripts/test-mobile-lifecycle.mjs && node scripts/test-ai-cost-tracking.mjs && node scripts/test-sign-in-analytics.mjs && node scripts/test-usage-limit-unblock.mjs && node scripts/test-add-credits.mjs && node scripts/test-clear-credit-errors.mjs && node scripts/test-limit-hit-call-count.mjs && node scripts/test-pwa.mjs && node scripts/test-error-tracking.mjs && node scripts/test-todo-finalize.mjs && node scripts/test-issues.mjs && node scripts/test-composer-drafts.mjs && node scripts/test-composer-handoff.mjs && node scripts/test-message-queue.mjs && node scripts/test-voice-input.mjs && node scripts/test-voice-recorder-inert.mjs && node scripts/test-worker-ownership.mjs && node scripts/test-duplicate-worker-isolation.mjs && node scripts/test-published-workers.mjs && node scripts/test-publish-site-reuse.mjs && node scripts/test-version-index-integrity.mjs && node scripts/test-tool-use-repair.mjs && node scripts/test-manifest.mjs && node scripts/test-seo.mjs && node scripts/test-ime-enter.mjs && node scripts/test-worker-tools.mjs && node scripts/test-worker-save-canary.mjs && node scripts/test-read-cap.mjs && node scripts/test-send-button-state.mjs && node scripts/test-html-escape-roundtrip.mjs && node scripts/test-code-highlight.mjs && node scripts/test-chat-switch-reset.mjs && node scripts/test-load-media-urls.mjs && node scripts/test-history-dead-link.mjs && node scripts/test-storage-guards.mjs && node scripts/test-fresh-reads.mjs && node scripts/test-composer-autoresize.mjs && node scripts/test-preview-reload.mjs && node scripts/test-blockquote-render.mjs && node scripts/test-message-links.mjs && node scripts/test-drag-highlight.mjs && node scripts/test-composer-focus-guard.mjs && node scripts/test-suggestions-scroll.mjs && node scripts/test-stale-pdf-blocks.mjs && node scripts/test-view-document.mjs && node scripts/test-view-image.mjs && node scripts/test-render-svg.mjs && node scripts/test-social-images.mjs && node scripts/test-custom-domain.mjs && node scripts/test-whats-new.mjs && node scripts/test-generated-media.mjs && node scripts/test-grid-restore-missing.mjs && node scripts/test-lightbox-chat-switch.mjs && node scripts/test-lightbox-caption.mjs && node scripts/test-media-card-size.mjs && node scripts/test-media-broken-image.mjs && node scripts/test-media-image-load.mjs && node scripts/test-media-status-quiet.mjs && node scripts/test-read-url-cache.mjs && node scripts/test-unsaved-media-download.mjs && node scripts/test-live-media-read-url.mjs && node scripts/test-image-reference-svg.mjs && node scripts/test-attachment-snapshot.mjs && node scripts/test-attachment-names.mjs && node scripts/test-extract-zip.mjs && node scripts/test-paste-intake.mjs && node scripts/test-paste-as-attachment.mjs && node scripts/test-confirm-modal-keys.mjs && node scripts/test-alert-escape.mjs && node scripts/test-toasts.mjs && node scripts/test-popover-focus-return.mjs && node scripts/test-apps-panel.mjs && node scripts/test-user-menu-element.mjs && node scripts/test-puter-dialog-clicks.mjs && node scripts/test-input-labels.mjs && node scripts/test-announce.mjs && node scripts/test-menu-keyboard-close.mjs && node scripts/test-sidebar-focus.mjs && node scripts/test-mobile-view-switch.mjs && node scripts/test-theme-radio.mjs && node scripts/test-busy-entries.mjs && node scripts/test-toolbar-a11y.mjs && node scripts/test-clarify-keys.mjs && node scripts/test-version-prune.mjs && node scripts/test-project-readme.mjs && node scripts/test-restore-safety-snapshot.mjs && node scripts/test-restore-dirty-tracking.mjs && node scripts/test-restore-prune-failure.mjs && node scripts/test-restore-readdir-failure.mjs && node scripts/test-stopped-turn-unwind.mjs && node scripts/test-stopped-reply-kept.mjs && node scripts/test-restore-workers.mjs && node scripts/test-restore-concurrency.mjs && node scripts/test-tool-result-dedup.mjs && node scripts/test-click-to-edit-intake.mjs && node scripts/test-external-fetch.mjs && node scripts/test-friendly-errors.mjs && node scripts/test-thinking-preview.mjs && node scripts/test-final-reply-reveal.mjs && node scripts/test-checklist-spinner.mjs && node scripts/test-mcp.mjs && node scripts/test-profile-picture.mjs && node scripts/test-templates.mjs && node scripts/test-editor-core.mjs && node scripts/test-github-core.mjs && node scripts/test-github-sync.mjs && node scripts/test-worker-secrets.mjs && node scripts/test-worker-sender.mjs && node scripts/test-site-backends.mjs && node scripts/test-model-core.mjs && node scripts/test-compaction.mjs && node scripts/test-tool-batching.mjs && node scripts/test-suggest-after-turn.mjs && node scripts/test-model-picker.mjs && node scripts/test-keyboard-viewport.mjs && node scripts/test-starter-test.mjs && node scripts/test-speed-test.mjs && node scripts/test-experiments.mjs && node scripts/test-fast-mode.mjs && node scripts/test-build-notify.mjs", "test:thinking": "node scripts/test-thinking-preview.mjs", "test:fresh-reads": "node scripts/test-fresh-reads.mjs", "test:model-core": "node scripts/test-model-core.mjs", diff --git a/scripts/test-chat-list-entry.mjs b/scripts/test-chat-list-entry.mjs index 29e0fe6..4180c8d 100644 --- a/scripts/test-chat-list-entry.mjs +++ b/scripts/test-chat-list-entry.mjs @@ -39,14 +39,14 @@ function sandbox({ savedChats, currentChatId, onWrite }) { const factory = new Function( '_deletedChatIds', 'savedChats', '_aiProjectTitles', 'generateChatTitle', 'chatFilePath', 'puter', 'currentChatId', 'window', '_suggestionsByChat', 'setUrlChat', 'saveChatList', - 'updateChatHistorySidebar', 'updateDocumentTitle', 'console', '_chatListWrittenAt', + 'updateChatHistorySidebar', 'updateDocumentTitle', 'console', '_chatListWrittenAt', 'historyWithPendingReply', body + '\n; return saveCurrentChatUnlocked;', ); const fn = factory( deleted, savedChats, new Map(), () => 'Generated title', (id) => `chat-history/${id}.json`, puter, currentChatId, { currentPreviewUrl: 'https://y.puter.site/' }, new Map(), (id) => calls.url.push(id), async () => { calls.saveChatList++; }, - () => { calls.sidebar++; }, () => {}, { error: () => {}, warn: () => {} }, new Map(), + () => { calls.sidebar++; }, () => {}, { error: () => {}, warn: () => {} }, new Map(), (ctx) => ctx.chatHistory, ); return { fn, written, calls, deleted }; } diff --git a/scripts/test-stopped-reply-kept.mjs b/scripts/test-stopped-reply-kept.mjs new file mode 100644 index 0000000..2933f5d --- /dev/null +++ b/scripts/test-stopped-reply-kept.mjs @@ -0,0 +1,294 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; + +// ---- A reply that gets cut off keeps the text that had streamed so far ------ +// Text is committed to the history around tool calls and at the end of a turn. +// A Stop, a credit error or a closed tab in the middle of the reply came +// before either, so the sentence in progress was never saved. It was gone +// after a reload, and unseen by the model on Resume or "continue". Runs the +// REAL handleMessageStream.js with scripted streams, and the blocks of app.js +// that end a turn without a retry or save a reply while it streams. + +const read = (p) => fs.readFileSync(new URL(p, import.meta.url), 'utf8'); +const streamSource = read('../src/js/handleMessageStream.js'); + +// Yields its chunks, then hangs like a live stream until the caller aborts. +async function* hangingAfter(...items) { + yield* items; + await new Promise(() => {}); +} +async function* chunks(...items) { yield* items; } +const text = (t) => ({ type: 'text', text: t }); + +function setup({ stallRecovery = false, latestTurnSeq = 7 } = {}) { + const jq = () => ({ length: 0, find: () => ({ html() {} }), attr() {}, remove() {} }); + const env = { + AbortController, DOMException, setTimeout, clearTimeout, console, + currentChatId: 'one', shouldStop: false, + marked: { parse: (s) => s }, + escapeMarkdownSource: (s) => s, + $: () => ({ length: 0 }), + hasActiveTodos: () => false, + appendMessage: jq, + autoScrollTrigger() {}, + createThinkingPreview: () => ({ append() {}, remove() {} }), + isStaleTurn: (c) => c.currentChatId !== env.currentChatId, + isAborted: (ac) => !!(ac && ac.signal.aborted), + showSpinner() {}, startSpinnerStub() {}, stopSpinnerStub() {}, + scheduleSaveCurrentChat() {}, + generateMessageId: () => 'msg', + extractErrorText: (e) => (e && (e.message || (e.error && e.error.message))) || String(e), + }; + env.window = env; + vm.createContext(env); + // app.js's globals, which the stream reads by name. + vm.runInContext(`var _stallRecovery = ${stallRecovery}; var _latestTurnSeqByChat = new Map([['one', ${latestTurnSeq}]]);`, env); + vm.runInContext(streamSource, env); + const context = { + currentChatId: 'one', abortController: new AbortController(), turnSeq: 7, + chatHistory: [{ role: 'user', content: 'Build a menu page' }], + currentMessage: null, currentMessageContent: '', + }; + return { env, context }; +} + +// Start the stream, let its chunks land, then Stop it. +async function stopMidReply(h, stream) { + const run = h.env.handleMessageStream(stream, h.context).catch((e) => e); + await new Promise((r) => setTimeout(r, 5)); + h.context.abortController.abort(); + return run; +} + +const replies = (h) => h.context.chatHistory.filter((m) => m.role === 'assistant'); + +let failures = 0; +async function check(name, fn) { + try { await fn(); console.log('ok - ' + name); } + catch (e) { failures++; console.log('FAIL - ' + name + '\n ' + e.message); } +} + +await check('Stop keeps the text that had streamed so far', async () => { + const h = setup(); + await stopMidReply(h, hangingAfter(text('Done! I added the menu page '), text('and'))); + const r = replies(h); + assert.equal(r.length, 1); + assert.equal(r[0].content, 'Done! I added the menu page and'); + assert.equal(h.context.currentMessageContent, '', 'committed, not left pending'); +}); + +await check('a stream already aborted when its next chunk arrives keeps it too', async () => { + const h = setup(); + async function* abortsItself() { + yield text('Half a sentence'); + h.context.abortController.abort(); + yield text(' more'); + } + await h.env.handleMessageStream(abortsItself(), h.context).catch(() => {}); + assert.deepEqual(replies(h).map((m) => m.content), ['Half a sentence']); +}); + +await check('a Stop before any text adds nothing', async () => { + const h = setup(); + await stopMidReply(h, hangingAfter()); + assert.equal(replies(h).length, 0); +}); + +await check('the stall watchdog\'s abort leaves the text unsaved (its retry rewrites it)', async () => { + const h = setup({ stallRecovery: true }); + await stopMidReply(h, hangingAfter(text('Working on it'))); + assert.equal(replies(h).length, 0); +}); + +// The watchdog's abort can also end the stream without an AbortError. When a +// chunk is already in hand as the abort lands, the loop's own isAborted check +// returns. sendChatMessage then never reaches its retry, and the post-loop +// backstop turns the turn into a Resume. That block runs here from app.js. +const appSource = read('../src/js/app.js'); +// The source from `at` through the brace that closes the first block opened +// after it. +function blockFrom(at) { + assert.ok(at >= 0, 'block found in app.js'); + let depth = 0, i = appSource.indexOf('{', at); + for (; i < appSource.length; i++) { + if (appSource[i] === '{') depth++; + else if (appSource[i] === '}' && --depth === 0) break; + } + return appSource.slice(at, i + 1); +} +const stallBackstop = () => blockFrom(appSource.indexOf('if (_stallRecovery) {', appSource.indexOf('// Belt-and-suspenders'))); +// Reads that are already settled. The abort fires as the last one is taken, +// so that chunk wins the race against the abort. The reads use the page's own +// Promise, as a real stream's do. One from another realm settles a tick late. +function abortsWithChunkInHand(env, controller, ...items) { + const PagePromise = vm.runInContext('Promise', env); + let i = 0; + return { + [Symbol.asyncIterator]() { return this; }, + next() { + if (i === items.length - 1) controller.abort(); + return PagePromise.resolve(i < items.length ? { value: items[i++], done: false } : { done: true }); + }, + }; +} + +await check('a watchdog abort that ends the stream quietly, with no retry, keeps the text', async () => { + const h = setup({ stallRecovery: true }); + await h.env.handleMessageStream(abortsWithChunkInHand(h.env, h.context.abortController, text('Working on it'), text(' more')), h.context); + assert.equal(replies(h).length, 0, 'held back while a retry could still rewrite it'); + h.env.context = h.context; + vm.runInContext(`var turnChatId = 'one', activeTurnInterrupted = false, retryGaveUp = false, gaveUpBannerText = '';`, h.env); + vm.runInContext(stallBackstop(), h.env); + assert.equal(h.env.retryGaveUp, true, 'offers Resume'); + assert.deepEqual(replies(h).map((m) => m.content), ['Working on it']); +}); + +// ---- Out of credits --------------------------------------------------------- +// Puter either cuts the stream short (usage_limited, which ends like any other +// reply) or sends a 402 insufficient_funds error line. The error line throws +// out of the stream, which is no abort, so the text is kept where +// sendChatMessage records the error card. That catch block runs here from +// app.js. +const turnCatch = () => { + const at = appSource.lastIndexOf('} catch (error) {', appSource.indexOf('error.error?.delegate === "usage-limited-chat"')); + return `(function (error) ${blockFrom(at + 1).slice('catch (error) '.length)})`; +}; +function runTurnCatch(h, error) { + const chainable = { length: 0, remove() {}, hide() {}, closest() { return chainable; } }; + Object.assign(h.env, { + context: h.context, turnSaveContext: { chatHistory: h.context.chatHistory }, + spinner: null, turnSeq: 7, _turnSeq: 7, turnChatId: 'one', activeTurnInterrupted: false, + turnErrored: false, isFirstBuildTurn: false, turnModel: 'm', turnTemplate: {}, turnStats: {}, savedChats: [], + $: () => chainable, + trackLimitHit() {}, recordUsageLimitHit() {}, usageLimitHitProps: () => ({}), + isLowBalanceRefusal: (e) => e?.error?.code === 'insufficient_funds', + friendlyErrorMessage: () => 'You are out of credits.', + appendErrorMessage: () => ({ addClass() {} }), + isCreditErrorEntry: (m) => !!m.creditError, + }); + vm.runInContext(turnCatch(), h.env)(error); +} +const creditErrorLine = { type: 'error', error: { code: 'insufficient_funds', message: 'Insufficient funds' } }; +const shown = (h) => h.context.chatHistory.slice(1).map((m) => (m.isError ? '[error card]' : m.content)); + +await check('a reply Puter cuts short for credits is saved', async () => { + const h = setup(); + await h.env.handleMessageStream(chunks(text('Adding the menu sec'), { type: 'usage', usage: {}, metadata: { usage_limited: true } }), h.context); + assert.equal(h.context.usageLimited, true); + assert.deepEqual(replies(h).map((m) => m.content), ['Adding the menu sec']); +}); + +await check('a credit error mid-reply keeps the text, ahead of the error card', async () => { + const h = setup(); + const err = await h.env.handleMessageStream(chunks(text('Adding the menu sec'), creditErrorLine), h.context).catch((e) => e); + assert.equal(err?.error?.code, 'insufficient_funds', 'the error line throws'); + assert.equal(replies(h).length, 0, 'not kept by the stream, it was not aborted'); + runTurnCatch(h, err); + assert.equal(h.env.turnErrored, true); + assert.deepEqual(shown(h), ['Adding the menu sec', '[error card]']); +}); + +await check('a credit error before any text adds only the error card', async () => { + const h = setup(); + const err = await h.env.handleMessageStream(chunks(creditErrorLine), h.context).catch((e) => e); + runTurnCatch(h, err); + assert.deepEqual(shown(h), ['[error card]']); +}); + +await check('a newer turn in the same chat gets the history to itself', async () => { + const h = setup({ latestTurnSeq: 8 }); + await stopMidReply(h, hangingAfter(text('Working on it'))); + assert.equal(replies(h).length, 0); +}); + +await check('a reply that finishes is still saved once', async () => { + const h = setup(); + await h.env.handleMessageStream(chunks(text('All done.'), { type: 'usage', usage: {} }), h.context); + assert.deepEqual(replies(h).map((m) => m.content), ['All done.']); +}); + +// ---- Network errors past the retries ---------------------------------------- +check('out of retries, the text is kept instead of dropped for a retry', () => { + assert.match(appSource, /if \(!stallRecovery && attempt >= MAX_TURN_RETRIES\) keepCutOffReply\(context\);\s*else removeUncommittedBubble\(context\);/); +}); + +// ---- A tab closed, reloaded or killed mid-reply ----------------------------- +// Nothing runs then, so the text is saved while it streams. Runs app.js's +// pending-reply and reply-checkpoints blocks next to the real stream, on fake +// timers. +function checkpointSetup(opts) { + const h = setup(opts); + const timers = []; + const listeners = {}; + h.saves = []; + Object.assign(h.env, { + setTimeout: (fn) => { const t = { fn }; timers.push(t); return t; }, + clearTimeout: (t) => { if (t) t.cleared = true; }, + document: { visibilityState: 'visible', addEventListener: (type, fn) => { listeners[type] = fn; } }, + // What the save would write as the chat's history. + scheduleSaveCurrentChat: (ctx) => { h.saves.push([...h.env.historyWithPendingReply(ctx)].map((m) => m.content)); }, + }); + for (const name of ['pending-reply', 'reply-checkpoints']) { + const a = appSource.indexOf(`// ===== ${name} (start) =====`); + const b = appSource.indexOf(`// ===== ${name} (end) =====`); + assert.ok(a >= 0 && b > a, `${name} block found in app.js`); + vm.runInContext(appSource.slice(a, b), h.env); + } + h.runTimers = () => timers.splice(0).forEach((t) => { if (!t.cleared) t.fn(); }); + h.hidePage = () => { h.env.document.visibilityState = 'hidden'; listeners.visibilitychange(); }; + h.start = (stream) => { + const run = h.env.handleMessageStream(stream, h.context).catch(() => {}); + return new Promise((r) => setTimeout(r, 5)).then(() => run); + }; + return h; +} + +await check('a reply still being written is saved within seconds, after the history', async () => { + const h = checkpointSetup(); + h.start(hangingAfter(text('Here is what I built '), text('so far'))); + await new Promise((r) => setTimeout(r, 5)); + assert.equal(h.saves.length, 0, 'not on every chunk'); + h.runTimers(); + assert.deepEqual(h.saves, [['Build a menu page', 'Here is what I built so far']]); + assert.equal(h.context.chatHistory.length, 1, 'the live history is left to the turn'); + h.context.abortController.abort(); +}); + +await check('hiding the page saves it at once', async () => { + const h = checkpointSetup(); + h.start(hangingAfter(text('Half of the reply'))); + await new Promise((r) => setTimeout(r, 5)); + h.hidePage(); + assert.deepEqual(h.saves, [['Build a menu page', 'Half of the reply']]); + h.runTimers(); + assert.equal(h.saves.length, 1, 'the timer was cancelled'); + h.context.abortController.abort(); +}); + +check('the save writes the text, and pagehide sends it', () => { + assert.match(appSource, /history: historyWithPendingReply\(context\),/); + assert.match(appSource, /window\.addEventListener\('pagehide', \(\) => \{\s*\/\/[^\n]*\n\s*flushReplyCheckpoint\(\);/); +}); + +await check('nothing more is saved once the reply was committed', async () => { + const h = checkpointSetup(); + await h.env.handleMessageStream(chunks(text('All done.'), { type: 'usage', usage: {} }), h.context); + h.runTimers(); + assert.equal(h.saves.length, 0); +}); + +await check('a turn a newer one replaced is not saved', async () => { + const h = checkpointSetup({ latestTurnSeq: 8 }); + h.start(hangingAfter(text('Working on it'))); + await new Promise((r) => setTimeout(r, 5)); + h.runTimers(); + assert.equal(h.saves.length, 0); + h.context.abortController.abort(); +}); + +if (failures) { + console.error(`\n${failures} check(s) failed`); + process.exit(1); +} +console.log('\nAll stopped-reply checks passed'); diff --git a/src/js/app.js b/src/js/app.js index 6399e12..b2e5f64 100644 --- a/src/js/app.js +++ b/src/js/app.js @@ -608,6 +608,29 @@ function withChatFileLock(chatId, fn) { return typeof window.withFileLock === 'function' ? window.withFileLock(chatFilePath(chatId), fn) : fn(); } +// ===== pending-reply (start) ===== +// A reply still being written isn't in the history until its round ends. A +// save during it (a reply checkpoint, see reply-checkpoints) writes it after +// the history, so the chat reopens interrupted with it. + +// The reply the turn is writing, when it is one to save. Not once a newer +// turn has started in this chat (Stop with messages queued), since the +// history belongs to that turn then (see keepCutOffReply). +function pendingReplyText(context) { + const text = context && typeof context.currentMessageContent === 'string' ? context.currentMessageContent : ''; + if (!text.trim()) return ''; + if (context.turnSeq != null && _latestTurnSeqByChat.get(context.currentChatId) !== context.turnSeq) return ''; + return text; +} + +// What a save of `context` writes as the chat's history. +function historyWithPendingReply(context) { + const text = pendingReplyText(context); + if (!text) return context.chatHistory; + return [...context.chatHistory, { role: 'assistant', content: text, messageId: generateMessageId() }]; +} +// ===== pending-reply (end) ===== + async function saveCurrentChat(context) { return withChatFileLock(context && context.currentChatId, () => saveCurrentChatUnlocked(context)); } @@ -721,7 +744,7 @@ async function saveCurrentChatUnlocked(context) { customTitle: isCustomTitle, aiTitled: isAiTitle, timestamp: timestamp, - history: context.chatHistory, + history: historyWithPendingReply(context), lastModified: timestamp, previewUrl: previewUrl, previewPath: previewPath, @@ -987,12 +1010,52 @@ function scheduleSaveCurrentChat(context) { // queue is cleared so the drain cannot write them a second time either. Uses // pagehide (fires on bfcache + unload) rather than the unreliable unload event. window.addEventListener('pagehide', () => { + // A reply still being written goes out now too (reply checkpoints below). + flushReplyCheckpoint(); if (_chatSavePending.size === 0) return; const batch = Array.from(_chatSavePending.values()); _chatSavePending.clear(); for (const ctx of batch) saveCurrentChat(ctx).catch(() => {}); // fire-and-forget; we can't await during teardown }); +// ===== reply-checkpoints (start) ===== +// ---- Reply checkpoints ------------------------------------------------------ +// A reply's text joins the history around a tool call or at the end of the +// turn, and is saved with it. A tab closed, reloaded or killed partway through +// a long reply lost all of it. While text streams, the turn is saved a few +// seconds after its first unsaved chunk, and at once when the page is hidden +// (a phone may kill a backgrounded tab) or goes away. The save writes the text +// after the history (historyWithPendingReply, above saveCurrentChat), so the +// chat reopens interrupted with it, and Resume continues after it. +const REPLY_CHECKPOINT_MS = 3000; +let _replyCheckpoint = null; // { context, timer }, the save due for that turn's text + +// Called by handleMessageStream for each text chunk. +function scheduleReplyCheckpoint(context) { + if (_replyCheckpoint && _replyCheckpoint.context === context) return; // already due + flushReplyCheckpoint(); // another turn's, after a chat switch, is saved now + const due = { context, timer: setTimeout(() => { + if (_replyCheckpoint === due) _replyCheckpoint = null; + if (pendingReplyText(context)) scheduleSaveCurrentChat(context); + }, REPLY_CHECKPOINT_MS) }; + _replyCheckpoint = due; +} +window.scheduleReplyCheckpoint = scheduleReplyCheckpoint; + +// Save the due checkpoint now. Nothing to save once the text has been +// committed (its round ended, the turn stopped) or dropped for a retry. +function flushReplyCheckpoint() { + const due = _replyCheckpoint; + if (!due) return; + _replyCheckpoint = null; + clearTimeout(due.timer); + if (pendingReplyText(due.context)) scheduleSaveCurrentChat(due.context); +} +document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') flushReplyCheckpoint(); +}); +// ===== reply-checkpoints (end) ===== + // --- Project deep-linking ---------------------------------------------------- // The open project is reflected in the URL as the query param ?p= so a // permalink is a real, shareable link rather than a # fragment. Because @@ -6168,7 +6231,7 @@ async function sendChatMessage(userInput = null, skipAddToHistory = false, opts // (handleToolCalls) keep the chat flagged in-progress until the // end-of-turn save clears it — this is what makes a refresh during a // long multi-round build resumable. - context = {abortController, tools: turnTools, model: turnModel, serviceSpeed: turnServiceSpeed, unavailableTools: turnUnavailableTools, chatHistory: turnSaveContext.chatHistory, currentMessage: null, currentMessageContent: '', currentChatId: turnChatId, appDir: turnAppDir, interrupted: true, turnStats}; + context = {abortController, tools: turnTools, model: turnModel, serviceSpeed: turnServiceSpeed, unavailableTools: turnUnavailableTools, chatHistory: turnSaveContext.chatHistory, currentMessage: null, currentMessageContent: '', currentChatId: turnChatId, appDir: turnAppDir, turnSeq, interrupted: true, turnStats}; await handleMessageStream(stream, context); if (abortController === attemptController) _turnAwaitingStream = false; break; // stream drained (completed, or aborted/switched — handled below) @@ -6196,8 +6259,12 @@ async function sendChatMessage(userInput = null, skipAddToHistory = false, opts throw streamError; } } - // Drop any partial, unsaved narration bubble before resuming. - removeUncommittedBubble(context); + // Drop any partial, unsaved narration bubble before resuming, + // since the retry writes the reply again. Out of retries, + // nothing will, so keep it as a Stop does. Resume continues + // after it. + if (!stallRecovery && attempt >= MAX_TURN_RETRIES) keepCutOffReply(context); + else removeUncommittedBubble(context); // This attempt's rounds were generated (and billed) even though // it failed; keep their usage — the retry builds a new context. if (context) flushTurnUsage(context); @@ -6247,8 +6314,11 @@ async function sendChatMessage(userInput = null, skipAddToHistory = false, opts // unwound WITHOUT throwing (some iterators resolve `done` on abort // instead of rejecting), so the catch above never ran. Don't let the // turn end silently — route it to the same resumable give-up path. + // No retry will rewrite the reply, so keep the text that had streamed, + // as a Stop does (keepCutOffReply skipped it while the flag was up). if (_stallRecovery) { _stallRecovery = false; + keepCutOffReply(context); if (turnChatId === currentChatId && !shouldStop && !activeTurnInterrupted) { retryGaveUp = true; gaveUpBannerText = 'The build was interrupted while the app was in the background. Resume to continue where it left off.'; @@ -6338,6 +6408,10 @@ async function sendChatMessage(userInput = null, skipAddToHistory = false, opts // Its error card and history entry would land in the newer turn's chat. if (!shouldStop && !activeTurnInterrupted && turnChatId === currentChatId && turnSeq === _turnSeq) { turnErrored = true; + // The reply may have been partway written when the error came (a + // credit error line mid-stream). Errors that end the turn are never + // retried, so keep that text, ahead of the error card. + keepCutOffReply(context); if(error.error?.delegate === "usage-limited-chat"){ trackLimitHit({ first_build: isFirstBuildTurn, model: turnModel, kind: 'tier', ...usageLimitHitProps(turnSaveContext.chatHistory, savedChats, turnChatId, window.currentPublishedUrl) }); recordUsageLimitHit('tier', turnTemplate.template, turnStats.fastMode); diff --git a/src/js/handleMessageStream.js b/src/js/handleMessageStream.js index 28320eb..c1c5ebe 100644 --- a/src/js/handleMessageStream.js +++ b/src/js/handleMessageStream.js @@ -21,6 +21,27 @@ function saveCurrentMessage(context) { } } +// A Stop, a switch to another chat, or an error the turn ends on (out of +// credits) cut the reply off while it was being written. Text is otherwise +// only committed to the history around a tool call or at the end of the turn, +// so the sentence in progress stayed on screen but was never saved. It was +// gone after a reload, and unseen by the model on Resume or "continue", which +// then wrote it again. Commit what streamed so far. Called from the stream's finally on +// an abort, and from sendChatMessage ahead of its error card and its stall +// backstop. The end-of-turn save persists it. +// Not for the stall watchdog's abort, whose retry regenerates the reply and +// drops the unsaved bubble (removeUncommittedBubble). Not once a newer turn +// has started in this chat (Stop with messages queued), whose history this +// late text would land after. Both globals live in app.js. The typeof guards +// keep this file loadable on its own. +function keepCutOffReply(context) { + if (!context) return; + if (typeof _stallRecovery !== 'undefined' && _stallRecovery) return; + if (context.turnSeq != null && typeof _latestTurnSeqByChat !== 'undefined' + && _latestTurnSeqByChat.get(context.currentChatId) !== context.turnSeq) return; + saveCurrentMessage(context); +} + // While the progress checklist has unfinished items, text bubbles are // suppressed so mid-turn narration doesn't clutter the chat (see the "text" // branch below and handleToolCalls). But a turn that ENDS on text isn't @@ -537,6 +558,8 @@ async function handleMessageStream(stream, context) { context.currentMessage = hasActiveTodos() ? $() : appendMessage('', false); } context.currentMessageContent += completion.text; + // Saved within seconds, so a tab closed mid-reply keeps it. + window.scheduleReplyCheckpoint?.(context); // Only render when there is a bubble to render into. While the // checklist suppresses narration, currentMessage is an EMPTY jQuery @@ -594,6 +617,7 @@ async function handleMessageStream(stream, context) { // Includes stream errors, Stop, navigation, retries and reasoning-only // responses, even when the stream never emits another chunk. clearThinking(); + if (isAborted(context.abortController)) keepCutOffReply(context); } if (isAborted(context.abortController) || isStaleTurn(context)) return; // A stream that ended without its usage line still ran to its end (an