From 396b9cee74476fcdb833aee1dec9c874fbc8fdb3 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 20 Nov 2026 09:31:47 -0700 Subject: [PATCH 1/4] Clear the out-of-credits error once the account can pay again The red "not enough credits" card stayed in the chat after the user upgraded or bought credits, above the build that went on, and came back on every reload since it is saved in the chat history. An upgrade, a top-up, or a plan change noticed when the tab regains focus now removes the out-of-credits and usage-limit cards from the chat, and marks the saved entries so a reload doesn't draw them again. The entries stay in the history the AI reads, so it still knows why the build stopped. New errors are tagged creditError; older ones are matched by their text. --- src/js/app.js | 41 ++++++++++++++++++++++++++++++++++++++--- src/js/helpers.js | 3 +++ src/js/ui.js | 6 +++++- 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/src/js/app.js b/src/js/app.js index b8fa189..a0406da 100644 --- a/src/js/app.js +++ b/src/js/app.js @@ -1492,6 +1492,8 @@ async function loadChat(chatId, { urlMode = 'push', preloaded = null } = {}) { // (prepareResumeHistory). It carries no user-visible text — sent to the // model only — so never render it as an (empty) chat bubble. if (message.resumeNudge) continue; + // An out-of-credits error the account has since paid past. + if (message.creditErrorCleared) continue; // Render each persisted message defensively: a single corrupted entry // (e.g. a partial tool_use from a build interrupted mid-stream) must // not throw out of the whole loop, which would abort loadChat before @@ -1631,7 +1633,8 @@ async function loadChat(chatId, { urlMode = 'push', preloaded = null } = {}) { // Errors were persisted with an isError marker — re-render them // as the same styled error card rather than a plain AI message. if (message.isError) { - appendErrorMessage(message.content); + const $card = appendErrorMessage(message.content); + if (isCreditErrorEntry(message)) $card.addClass('credit-error'); } else { appendMessage(message.content, false, false, false, false, messageId); } @@ -4359,6 +4362,7 @@ async function consumePaidAfterLimit(key) { if (!user || user.uuid !== (window.user && window.user.uuid)) return; const found = planChange(hit.plan, await readPlanSnapshot(user)); if (!found) return; + window.clearCreditErrors?.(); // A new limit hit saved while this check was waiting on Puter is a new // baseline. Leave it for the next check. const now = JSON.parse(localStorage.getItem(key) || 'null'); @@ -4609,6 +4613,34 @@ function lastRequestSize(history) { } // ===== usage-limit-unblock (end) ===== +// An out-of-credits error card in the history. Entries saved before the +// creditError marker are told by their text. +function isCreditErrorEntry(msg) { + if (!msg || msg.role !== 'assistant' || !msg.isError || typeof msg.content !== 'string') return false; + return msg.creditError === true || /\b(enough|insufficient)\b[^.]*\bcredits?\b/i.test(msg.content); +} + +// The account can pay again (an upgrade or bought credit), so the out-of-credits +// and usage-limit cards in this project no longer apply. They leave the chat, +// and the saved entries are marked so a reload doesn't draw them again. The +// entries stay in the history the AI reads, so it still knows why the build +// stopped. A running turn saves the mark at its next checkpoint. +function clearCreditErrors() { + $('.chat-box .message.credit-error, .chat-box .message.upgrade-message').remove(); + if (!Array.isArray(chatHistory)) return; + let changed = false; + for (const msg of chatHistory) { + if (!msg.creditErrorCleared && isCreditErrorEntry(msg)) { + msg.creditErrorCleared = true; + changed = true; + } + } + if (changed && !isProcessing) { + saveCurrentChat({ currentChatId, chatHistory }).catch(() => {}); + } +} +window.clearCreditErrors = clearCreditErrors; + window.addEventListener('focus', () => { checkPaidAfterLimit(); }); document.addEventListener('visibilitychange', () => { if (document.visibilityState !== 'hidden') checkPaidAfterLimit(); @@ -6284,9 +6316,12 @@ async function sendChatMessage(userInput = null, skipAddToHistory = false, opts recordUsageLimitHit('credits', turnTemplate.template, turnStats.fastMode); } const friendlyError = friendlyErrorMessage(errorText); - appendErrorMessage(friendlyError); + const lowBalance = isLowBalanceRefusal(error); + const $card = appendErrorMessage(friendlyError); window.announce?.('Error: ' + friendlyError, { assertive: true }); - turnSaveContext.chatHistory.push({ role: "assistant", content: friendlyError, isError: true }); + // Tagged so an upgrade or a top-up can clear it (clearCreditErrors). + if (lowBalance) $card.addClass('credit-error'); + turnSaveContext.chatHistory.push({ role: "assistant", content: friendlyError, isError: true, ...(lowBalance && { creditError: true }) }); } // hide the message that contains a progress message (handle both floating spinner and message-based spinner) diff --git a/src/js/helpers.js b/src/js/helpers.js index 6ebf43e..273b326 100644 --- a/src/js/helpers.js +++ b/src/js/helpers.js @@ -1170,6 +1170,9 @@ function prepareHistoryForAI(historyArray, modelId, opts) { if (msg.isError) { delete msg.isError; } + // Out-of-credits markers (clearCreditErrors in app.js); UI-only. + delete msg.creditError; + delete msg.creditErrorCleared; // Marker for the hidden "continue where you left off" nudge added when // resuming an interrupted build (prepareResumeHistory). UI-only — strip it // so this extra top-level field never reaches the chat endpoint. The diff --git a/src/js/ui.js b/src/js/ui.js index aeadac7..bca39bb 100644 --- a/src/js/ui.js +++ b/src/js/ui.js @@ -7086,7 +7086,10 @@ function openTopUp(source, props) { _creditBeforeTopUp = readCreditLeft(); return Promise.resolve(shown).then((result) => { const bought = !!(result && result.toppedUp === true); - if (bought) window.track?.('Top-up Completed', { source }); + if (bought) { + window.track?.('Top-up Completed', { source }); + window.clearCreditErrors?.(); + } return bought; }, () => false); } @@ -7476,6 +7479,7 @@ async function completeUpgrade(key) { if (_publishPanelOpen) renderPublishPanel(); // This path skips refreshUserPlan, so tell the Code view here too. window.CodeEditor?.onPlanChanged?.(); + window.clearCreditErrors?.(); openUpgradeModal(source, { justUpgraded: true }); } From dc7ad2277cc6c22e2fed26ddd45c6fc978681894 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 20 Nov 2026 09:41:31 -0700 Subject: [PATCH 2/4] Clear an out-of-credits card without Puter's code right away too A card whose text said out of credits, but whose error had no insufficient_funds code or 402, wasn't tagged credit-error. After an upgrade it stayed in the chat while its saved entry, told by its text, was marked cleared, so it only went on the next reload. The live card is now tagged by isCreditErrorEntry on the entry that is saved, the same test a reload uses. Adds test-clear-credit-errors. --- package.json | 2 +- scripts/test-clear-credit-errors.mjs | 125 +++++++++++++++++++++++++++ src/js/app.js | 10 ++- 3 files changed, 134 insertions(+), 3 deletions(-) create mode 100644 scripts/test-clear-credit-errors.mjs diff --git a/package.json b/package.json index d07f87a..6cc8405 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-usage-limit-unblock.mjs && node scripts/test-add-credits.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-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: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-clear-credit-errors.mjs b/scripts/test-clear-credit-errors.mjs new file mode 100644 index 0000000..e336808 --- /dev/null +++ b/scripts/test-clear-credit-errors.mjs @@ -0,0 +1,125 @@ +import fs from 'node:fs'; + +// ---- Regression guard: out-of-credits cards leave once the account can pay ---- +// An upgrade or a top-up clears the out-of-credits error cards from the open +// chat (clearCreditErrors in app.js) and marks their saved entries so a reload +// doesn't draw them again. This test: +// * evaluates the REAL isCreditErrorEntry / clearCreditErrors sliced out of +// app.js against a fake jQuery, document and save, and +// * text-asserts the wiring: the live card is told the same way a reload +// tells it, and loadChat skips cleared entries. + +let failures = 0; +function check(name, cond, detail) { + if (cond) console.log('ok - ' + name); + else { console.error('FAIL - ' + name + (detail ? '\n ' + detail : '')); failures++; } +} + +const APP = fs.readFileSync(new URL('../src/js/app.js', import.meta.url), 'utf8'); +const a = APP.indexOf('// ===== clear-credit-errors (start) ====='); +const b = APP.indexOf('// ===== clear-credit-errors (end) ====='); +if (a < 0 || b < 0) throw new Error('could not extract clear-credit-errors block'); +const BLOCK = APP.slice(a, b); + +// A card in the fake chat box. `classes` are its .message classes; `focused` +// says whether the page's focus is inside it. +function card(classes) { return { classes: new Set(classes), removed: false }; } + +function harness({ history = [], processing = false, cards = [], focusIn = null, keyboard = false } = {}) { + const saves = []; + const focused = []; + const document = { activeElement: focusIn ? focusIn.inner : { tag: 'body' }, body: { tag: 'body' } }; + if (!focusIn) document.activeElement = document.body; + // Only the selectors clearCreditErrors uses are understood. + const $ = (sel) => { + let picked = []; + if (sel === '.chat-box .message.credit-error, .chat-box .message.upgrade-message') { + picked = cards.filter(c => !c.removed && (c.classes.has('credit-error') || c.classes.has('upgrade-message'))); + } else if (sel === '.chat-input-message') { + picked = [{ composer: true }]; + } + const set = { + length: picked.length, + toArray: () => picked.map(c => c.composer ? c : { contains: (el) => !!focusIn && focusIn === c && el === focusIn.inner }), + remove() { + for (const c of picked) { + c.removed = true; + if (focusIn === c) document.activeElement = document.body; + } + return set; + }, + trigger(ev) { if (ev === 'focus') { focused.push(sel); document.activeElement = { composer: true }; } return set; }, + }; + return set; + }; + const window = { lastInputWasKeyboard: () => keyboard }; + const fns = new Function('window', 'document', '$', 'chatHistory', 'isProcessing', 'currentChatId', 'saveCurrentChat', + BLOCK + '\nreturn { isCreditErrorEntry, clearCreditErrors };')( + window, document, $, history, processing, 'chat-1', + (ctx) => { saves.push(ctx); return Promise.resolve(); }); + return { ...fns, saves, focused, document, window }; +} + +const CREDITS_TEXT = "Your account doesn't have enough credits to complete this request."; + +// ---- isCreditErrorEntry ------------------------------------------------------- +{ + const { isCreditErrorEntry } = harness(); + check('marked out-of-credits error is a credit error', + isCreditErrorEntry({ role: 'assistant', isError: true, content: 'Payment required', creditError: true })); + check('an error saved before the marker is told by its text', + isCreditErrorEntry({ role: 'assistant', isError: true, content: CREDITS_TEXT })); + check('another error is not', + !isCreditErrorEntry({ role: 'assistant', isError: true, content: 'The request timed out. Please try again.' })); + check('an ordinary reply mentioning credits is not', + !isCreditErrorEntry({ role: 'assistant', content: CREDITS_TEXT })); + check('a user message is not', + !isCreditErrorEntry({ role: 'user', isError: true, content: CREDITS_TEXT })); + check('a missing entry is not', !isCreditErrorEntry(null)); +} + +// ---- clearCreditErrors: history and saving -------------------------------------- +{ + const history = [ + { role: 'system', content: 'sys' }, + { role: 'user', content: 'build me a site' }, + { role: 'assistant', isError: true, content: CREDITS_TEXT, creditError: true }, + { role: 'user', content: 'again' }, + { role: 'assistant', isError: true, content: 'The request timed out. Please try again.' }, + ]; + const credit = card(['error-message', 'credit-error']); + const limit = card(['upgrade-message']); + const other = card(['error-message']); + const h = harness({ history, cards: [credit, limit, other] }); + h.clearCreditErrors(); + check('the out-of-credits card and the usage-limit card leave the chat', credit.removed && limit.removed); + check('another error card stays', !other.removed); + check('the out-of-credits entry is marked cleared', history[2].creditErrorCleared === true); + check('another error entry is not', !history[4].creditErrorCleared); + check('the chat is saved once', h.saves.length === 1 && h.saves[0].chatHistory === history && h.saves[0].currentChatId === 'chat-1'); + h.clearCreditErrors(); + check('nothing new to mark: no second save', h.saves.length === 1); +} +{ + const history = [{ role: 'assistant', isError: true, content: CREDITS_TEXT }]; + const h = harness({ history, processing: true }); + h.clearCreditErrors(); + check('during a build the entry is marked, and the build\'s own save writes it', history[0].creditErrorCleared === true && h.saves.length === 0); +} + +// ---- Wiring -------------------------------------------------------------------- +{ + // The live card is tagged by the same test a reload uses, on the very entry + // that is saved, so the two can't disagree. + const at = APP.indexOf('const friendlyError = friendlyErrorMessage(errorText);'); + const body = APP.slice(at, APP.indexOf('turnSaveContext.chatHistory.push(errorEntry);', at) + 60); + check('the live card is tagged with isCreditErrorEntry on the saved entry', + at > 0 && /if \(isCreditErrorEntry\(errorEntry\)\) \$card\.addClass\('credit-error'\);/.test(body), body.slice(0, 400)); + check('the entry tagged is the entry saved', body.includes('turnSaveContext.chatHistory.push(errorEntry);')); + check('a reload tags its card the same way', + /appendErrorMessage\(message\.content\);\s*if \(isCreditErrorEntry\(message\)\) \$card\.addClass\('credit-error'\);/.test(APP)); + check('a reload skips cleared entries', /if \(message\.creditErrorCleared\) continue;/.test(APP)); +} + +console.log(failures ? `\n${failures} failed` : '\nall passed'); +process.exit(failures ? 1 : 0); diff --git a/src/js/app.js b/src/js/app.js index a0406da..3e5d17f 100644 --- a/src/js/app.js +++ b/src/js/app.js @@ -4613,6 +4613,7 @@ function lastRequestSize(history) { } // ===== usage-limit-unblock (end) ===== +// ===== clear-credit-errors (start) ===== // An out-of-credits error card in the history. Entries saved before the // creditError marker are told by their text. function isCreditErrorEntry(msg) { @@ -4640,6 +4641,7 @@ function clearCreditErrors() { } } window.clearCreditErrors = clearCreditErrors; +// ===== clear-credit-errors (end) ===== window.addEventListener('focus', () => { checkPaidAfterLimit(); }); document.addEventListener('visibilitychange', () => { @@ -6317,11 +6319,15 @@ async function sendChatMessage(userInput = null, skipAddToHistory = false, opts } const friendlyError = friendlyErrorMessage(errorText); const lowBalance = isLowBalanceRefusal(error); + const errorEntry = { role: "assistant", content: friendlyError, isError: true, ...(lowBalance && { creditError: true }) }; const $card = appendErrorMessage(friendlyError); window.announce?.('Error: ' + friendlyError, { assertive: true }); // Tagged so an upgrade or a top-up can clear it (clearCreditErrors). - if (lowBalance) $card.addClass('credit-error'); - turnSaveContext.chatHistory.push({ role: "assistant", content: friendlyError, isError: true, ...(lowBalance && { creditError: true }) }); + // Told the same way a reload tells it, so an out-of-credits text + // without Puter's code leaves the chat now too, not only after a + // reload. + if (isCreditErrorEntry(errorEntry)) $card.addClass('credit-error'); + turnSaveContext.chatHistory.push(errorEntry); } // hide the message that contains a progress message (handle both floating spinner and message-based spinner) From b42e61012c4186ad900a97d8c663838136215d29 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 20 Nov 2026 09:43:24 -0700 Subject: [PATCH 3/4] Keep keyboard focus when a paid-past card leaves the chat Paying from a card's own Add credits or Upgrade button leaves focus on that button. clearCreditErrors removed the card, so focus fell to : the next Tab started over from the top of the page, and the success dialog opened right after (completeUpgrade) remembered as the element to hand focus back to. After keyboard use focus now moves to the composer. After a tap it isn't moved, so a phone's keyboard doesn't pop up. --- scripts/test-clear-credit-errors.mjs | 33 ++++++++++++++++++++++++++++ src/js/app.js | 12 +++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/scripts/test-clear-credit-errors.mjs b/scripts/test-clear-credit-errors.mjs index e336808..0eb28c4 100644 --- a/scripts/test-clear-credit-errors.mjs +++ b/scripts/test-clear-credit-errors.mjs @@ -48,6 +48,7 @@ function harness({ history = [], processing = false, cards = [], focusIn = null, } return set; }, + filter: () => set, trigger(ev) { if (ev === 'focus') { focused.push(sel); document.activeElement = { composer: true }; } return set; }, }; return set; @@ -107,6 +108,38 @@ const CREDITS_TEXT = "Your account doesn't have enough credits to complete this check('during a build the entry is marked, and the build\'s own save writes it', history[0].creditErrorCleared === true && h.saves.length === 0); } +// ---- clearCreditErrors: focus --------------------------------------------------- +// The card's own button had focus (the user paid from it). Removing the card +// must not leave focus on . +{ + const credit = card(['upgrade-message']); + credit.inner = { tag: 'button' }; + const h = harness({ cards: [credit], focusIn: credit, keyboard: true }); + h.clearCreditErrors(); + check('keyboard user: focus moves to the composer when its card leaves', + credit.removed && h.focused.length === 1 && h.focused[0] === '.chat-input-message' && h.document.activeElement.composer === true); +} +{ + const credit = card(['error-message', 'credit-error']); + credit.inner = { tag: 'button' }; + const h = harness({ cards: [credit], focusIn: credit, keyboard: false }); + h.clearCreditErrors(); + check('after a tap or click the composer is not focused (no phone keyboard)', credit.removed && h.focused.length === 0); +} +{ + const credit = card(['error-message', 'credit-error']); + const h = harness({ cards: [credit], keyboard: true }); + h.clearCreditErrors(); + check('focus elsewhere is left alone', credit.removed && h.focused.length === 0 && h.document.activeElement === h.document.body); +} +{ + // completeUpgrade clears before it opens the success dialog, whose focus + // trap remembers the focused element to return to. + const UI = fs.readFileSync(new URL('../src/js/ui.js', import.meta.url), 'utf8'); + check('the upgrade clears the cards before the success dialog opens', + /window\.clearCreditErrors\?\.\(\);\s*openUpgradeModal\(source, \{ justUpgraded: true \}\);/.test(UI)); +} + // ---- Wiring -------------------------------------------------------------------- { // The live card is tagged by the same test a reload uses, on the very entry diff --git a/src/js/app.js b/src/js/app.js index 3e5d17f..01e0b4a 100644 --- a/src/js/app.js +++ b/src/js/app.js @@ -4627,7 +4627,17 @@ function isCreditErrorEntry(msg) { // entries stay in the history the AI reads, so it still knows why the build // stopped. A running turn saves the mark at its next checkpoint. function clearCreditErrors() { - $('.chat-box .message.credit-error, .chat-box .message.upgrade-message').remove(); + const $cards = $('.chat-box .message.credit-error, .chat-box .message.upgrade-message'); + // The user may have paid from a card's own Add credits or Upgrade button, + // which keeps focus while they pay. Removing the card dropped focus to + // , so the next Tab started over from the top of the page, and the + // success dialog that opens next had nothing to hand focus back to. The + // composer is the next thing to use. Only after keyboard use: focusing it + // after a tap would pop a phone's keyboard up. + const active = document.activeElement; + const hadFocus = !!active && active !== document.body && $cards.toArray().some(el => el.contains(active)); + $cards.remove(); + if (hadFocus && window.lastInputWasKeyboard?.()) $('.chat-input-message').filter(':visible').trigger('focus'); if (!Array.isArray(chatHistory)) return; let changed = false; for (const msg of chatHistory) { From dca1b2ce970bced582b32549c409c50bc822e4b1 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 20 Nov 2026 09:45:42 -0700 Subject: [PATCH 4/4] Keep a newer out-of-credits card when the paid check finds a payment consumePaidAfterLimit cleared the cards before it checked that no new limit hit was saved while it waited on Puter. A build that ran out again in that time had its new, current card removed and its entry marked cleared, though the account couldn't pay. The cards are now cleared only once the record the payment was measured against is the one consumed. --- scripts/test-usage-limit-unblock.mjs | 35 +++++++++++++++++++++++++++- src/js/app.js | 4 +++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/scripts/test-usage-limit-unblock.mjs b/scripts/test-usage-limit-unblock.mjs index 8e2949e..3c5b317 100644 --- a/scripts/test-usage-limit-unblock.mjs +++ b/scripts/test-usage-limit-unblock.mjs @@ -360,7 +360,11 @@ function lockManager() { function fakePuter(box) { return { auth: { - getMonthlyUsage: async () => ({ allowanceInfo: { monthUsageAllowance: box.state.allowance, addons: { purchasedCredits: box.state.purchased }, ...(box.state.unit && { unit: box.state.unit }) } }), + getMonthlyUsage: async () => { + // Something that happens while Puter is answering, once. + if (box.hit) { const hit = box.hit; box.hit = null; hit(); } + return { allowanceInfo: { monthUsageAllowance: box.state.allowance, addons: { purchasedCredits: box.state.purchased }, ...(box.state.unit && { unit: box.state.unit }) } }; + }, getUser: async () => { if (box.failUser) throw new Error('offline'); return { uuid: box.uuid || 'user-a', subscribed: box.state.subscribed, paid_storage: box.state.paid_storage }; @@ -456,6 +460,35 @@ async function paidHarness({ before, after, ageMs = 5 * 60 * 1000, cached, other check('two tabs sharing the Web Lock report once', await twoTabs({ locks }) === 1); check('the lock is per account', locks.names.length === 2 && locks.names.every(n => n === 'usage_limit_pay:user-a')); check('no Web Locks → the re-read still reports once', await twoTabs({}) === 1); + + // The out-of-credits cards leave the chat (clearCreditErrors) once a + // payment is found, and only then. + const clears = h => h._clears || 0; + async function clearHarness({ before, after, newHitDuringCheck = false }) { + const box = { state: before }; + const h = tab(box, memStorage(), { locks: lockManager() }); + h.win.clearCreditErrors = () => { h._clears = clears(h) + 1; }; + await h.recordPlanAtLimit('credits'); + box.state = after; + if (newHitDuringCheck) { + // A build runs out again while the check waits on Puter: a new + // limit hit is saved under the same key, with the paid plan as its + // baseline. Its card is current and must stay. + box.hit = () => { + h.storage.setItem(h.LIMIT_PAY_PREFIX + 'user-a', JSON.stringify({ at: T0 + 6 * 60 * 1000, kind: 'credits', plan: { ...after }, template: '' })); + }; + } + h.setNow(T0 + 5 * 60 * 1000); + await h.checkPaidAfterLimit(); + return h; + } + h = await clearHarness({ before: free, after: paid }); + check('a payment found → the out-of-credits cards are cleared once', clears(h) === 1); + h = await clearHarness({ before: free, after: free }); + check('no payment → the cards stay', clears(h) === 0); + h = await clearHarness({ before: free, after: paid, newHitDuringCheck: true }); + check('a new limit hit saved during the check → its card stays (left for the next check)', + clears(h) === 0 && paidCalls(h).length === 0); } // Credits and plan at turn start, and how far the turn got diff --git a/src/js/app.js b/src/js/app.js index 01e0b4a..8929437 100644 --- a/src/js/app.js +++ b/src/js/app.js @@ -4362,12 +4362,14 @@ async function consumePaidAfterLimit(key) { if (!user || user.uuid !== (window.user && window.user.uuid)) return; const found = planChange(hit.plan, await readPlanSnapshot(user)); if (!found) return; - window.clearCreditErrors?.(); // A new limit hit saved while this check was waiting on Puter is a new // baseline. Leave it for the next check. const now = JSON.parse(localStorage.getItem(key) || 'null'); if (!now || now.at !== hit.at) return; localStorage.removeItem(key); + // The account can pay again. Not before the check above: a new limit + // hit means it ran out again, and that card is current. + window.clearCreditErrors?.(); const mins = (Date.now() - hit.at) / 6e4; window.track?.('Upgrade After Limit', { change: found.change,