From 601d7b4f926faecddd64d78b38bdcc7e78bb3e70 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 08:20:35 +0000 Subject: [PATCH 1/2] Keep the reply text that had streamed when the user stops a build The AI's text was saved only around tool calls and at the end of a turn. A Stop in the middle of a reply left the sentence in progress on screen but out of the history: it vanished on reload, and Resume didn't send it to the AI, which then wrote it again. Now the stream commits that text when it is aborted. Not for the stall watchdog's abort, whose retry rewrites the reply, and not once a newer turn has started in the chat. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FWCxozAPzozxrNQPgyy2WP --- package.json | 2 +- scripts/test-stopped-reply-kept.mjs | 118 ++++++++++++++++++++++++++++ src/js/app.js | 2 +- src/js/handleMessageStream.js | 20 +++++ 4 files changed, 140 insertions(+), 2 deletions(-) create mode 100644 scripts/test-stopped-reply-kept.mjs 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-stopped-reply-kept.mjs b/scripts/test-stopped-reply-kept.mjs new file mode 100644 index 0000000..1a07487 --- /dev/null +++ b/scripts/test-stopped-reply-kept.mjs @@ -0,0 +1,118 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; + +// ---- A reply cut off by Stop 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 in the middle of the reply returned before either, so the sentence in +// progress stayed on screen but was never saved: gone after a reload, and +// unseen by the model on Resume. Runs the REAL handleMessageStream.js with a +// scripted stream that writes some text, then goes quiet until aborted. + +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', + }; + 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); +}); + +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.']); +}); + +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..d338c74 100644 --- a/src/js/app.js +++ b/src/js/app.js @@ -6168,7 +6168,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) diff --git a/src/js/handleMessageStream.js b/src/js/handleMessageStream.js index 28320eb..e53e115 100644 --- a/src/js/handleMessageStream.js +++ b/src/js/handleMessageStream.js @@ -21,6 +21,25 @@ function saveCurrentMessage(context) { } } +// A Stop (or a switch to another chat) 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: gone after a reload, and unseen by the model on Resume, +// which then wrote it again. Commit what streamed so far; the end-of-turn save +// persists it with interrupted:true, and Resume continues after it. +// Not for the stall watchdog's abort: its 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 keepStoppedReply(context) { + if (!context || !isAborted(context.abortController)) 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 @@ -594,6 +613,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(); + keepStoppedReply(context); } if (isAborted(context.abortController) || isStaleTurn(context)) return; // A stream that ended without its usage line still ran to its end (an From 11c5e23d314e85fd4c8af5dc732d116c5b9e5428 Mon Sep 17 00:00:00 2001 From: Reynaldi Chernando Date: Tue, 24 Nov 2026 03:10:11 +0700 Subject: [PATCH 2/2] Keep a cut-off reply's text on every way a turn can end early The first commit kept the text on Stop. A reply can also be cut off in other ways, and each one lost the text that had streamed. - Stall watchdog, quiet end. Its abort can end the stream without an AbortError, so no retry runs and the backstop offers Resume. The backstop now keeps the text (review comment on #192). - Errors that end the turn, such as a 402 insufficient_funds line mid-reply. The text is kept ahead of the error card. - Network errors past the retries. The text is kept for Resume instead of being dropped for a retry that never comes. - A tab closed, reloaded or killed mid-reply. While text streams, the turn is saved 3 s after its first unsaved chunk, at once when the page is hidden, and on pagehide. The save writes the text after the history (historyWithPendingReply), so the chat reopens interrupted with it. keepStoppedReply is now keepCutOffReply, and its abort check moved to the stream's finally. Co-Authored-By: Claude Opus 5.5 --- scripts/test-chat-list-entry.mjs | 4 +- scripts/test-stopped-reply-kept.mjs | 186 +++++++++++++++++++++++++++- src/js/app.js | 80 +++++++++++- src/js/handleMessageStream.js | 26 ++-- 4 files changed, 275 insertions(+), 21 deletions(-) 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 index 1a07487..2933f5d 100644 --- a/scripts/test-stopped-reply-kept.mjs +++ b/scripts/test-stopped-reply-kept.mjs @@ -2,12 +2,13 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import vm from 'node:vm'; -// ---- A reply cut off by Stop keeps the text that had streamed so far -------- +// ---- 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 in the middle of the reply returned before either, so the sentence in -// progress stayed on screen but was never saved: gone after a reload, and -// unseen by the model on Resume. Runs the REAL handleMessageStream.js with a -// scripted stream that writes some text, then goes quiet until aborted. +// 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'); @@ -37,6 +38,7 @@ function setup({ stallRecovery = false, latestTurnSeq = 7 } = {}) { showSpinner() {}, startSpinnerStub() {}, stopSpinnerStub() {}, scheduleSaveCurrentChat() {}, generateMessageId: () => 'msg', + extractErrorText: (e) => (e && (e.message || (e.error && e.error.message))) || String(e), }; env.window = env; vm.createContext(env); @@ -99,6 +101,101 @@ await check('the stall watchdog\'s abort leaves the text unsaved (its retry rewr 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'))); @@ -111,6 +208,85 @@ await check('a reply that finishes is still saved once', async () => { 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); diff --git a/src/js/app.js b/src/js/app.js index d338c74..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 @@ -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 e53e115..c1c5ebe 100644 --- a/src/js/handleMessageStream.js +++ b/src/js/handleMessageStream.js @@ -21,19 +21,21 @@ function saveCurrentMessage(context) { } } -// A Stop (or a switch to another chat) 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: gone after a reload, and unseen by the model on Resume, -// which then wrote it again. Commit what streamed so far; the end-of-turn save -// persists it with interrupted:true, and Resume continues after it. -// Not for the stall watchdog's abort: its retry regenerates the reply and +// 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 +// late text would land after. Both globals live in app.js. The typeof guards // keep this file loadable on its own. -function keepStoppedReply(context) { - if (!context || !isAborted(context.abortController)) return; +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; @@ -556,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 @@ -613,7 +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(); - keepStoppedReply(context); + 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