diff --git a/package.json b/package.json index f3a971f1..d07f87ad 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-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-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", @@ -130,7 +130,8 @@ "test:github-core": "node scripts/test-github-core.mjs", "test:github-sync": "node scripts/test-github-sync.mjs", "test:worker-secrets": "node scripts/test-worker-secrets.mjs", - "test:worker-sender": "node scripts/test-worker-sender.mjs" + "test:worker-sender": "node scripts/test-worker-sender.mjs", + "test:site-backends": "node scripts/test-site-backends.mjs" }, "keywords": [], "author": "Nariman Jelveh", diff --git a/scripts/test-custom-domain.mjs b/scripts/test-custom-domain.mjs index ce1da395..ea045163 100644 --- a/scripts/test-custom-domain.mjs +++ b/scripts/test-custom-domain.mjs @@ -98,6 +98,13 @@ check('the same page is the same site', CD.sameSite({ body: '

x

' }, { bo check('…and so is the same file modified at the same time', CD.sameSite({ body: 'a', lastModified: 'Wed' }, { body: 'b', lastModified: 'Wed' })); check('a failed read, another page or two empty pages are not', !CD.sameSite(null, { body: 'a' }) && !CD.sameSite({ body: 'a' }, { body: 'b' }) && !CD.sameSite({ body: '' }, { body: '' })); +// Each runs the site's backends as an app of its own (site-backends.js). +check('urlsFor gives the address of the domain serving a site, in any state', + JSON.stringify(CD.urlsFor([pending], 'cafe')) === '["https://www.example.com/"]' + && JSON.stringify(CD.urlsFor([{ hostname: 'a.com', site: 'cafe', status: 'active' }], 'cafe')) === '["https://a.com/"]'); +check('…but not one recorded against another name, which serves another site', + CD.urlsFor([{ hostname: 'a.com', site: 'old', status: 'active' }], 'cafe').length === 0 && CD.urlsFor(undefined, 'cafe').length === 0); + check('hostOf names a saved list\'s domain in any state', CD.hostOf([pending]) === 'www.example.com' && CD.hostOf([{ hostname: 'a.com', status: 'failed' }]) === 'a.com' && CD.hostOf([]) === null && CD.hostOf(undefined) === null); @@ -1053,7 +1060,11 @@ check('the AI offers the chat\'s domain button, and says it needs a paid plan', } const publish = ui.slice(ui.indexOf('async function doPublish('), ui.indexOf('async function loadPublishedSiteMeta(')); check('a first publish with a reserved name points that name at the release, after filling in the address', - /if \(!existingSub && reserved\) \{[\s\S]*?const sub = await reserved;\s*url = `https:\/\/\$\{sub\}\.puter\.site\/`;\s*await absolutizeSocialImagesInRelease\(releaseDir, url, \[startPreviewUrl\]\);\s*await puter\.hosting\.update\(sub, releaseDir\);\s*_reservedPublishNames\.delete\(chatId\);\s*\} else if \(!existingSub\)/.test(publish)); + /if \(!existingSub && reserved\) \{[\s\S]*?const sub = await reserved;\s*url = `https:\/\/\$\{sub\}\.puter\.site\/`;\s*await absolutizeSocialImagesInRelease\(releaseDir, url, \[startPreviewUrl\]\);[\s\S]*?await puter\.hosting\.update\(sub, releaseDir\);\s*_reservedPublishNames\.delete\(chatId\);\s*\} else if \(!existingSub\)/.test(publish)); +// Nothing has run at the reserved name, so a dynamic backend's app and keys +// get there before the release does (see site-backends.js). +check('…with its dynamic backends\' app and keys in place first', + /const sub = await reserved;[\s\S]*?registerApp\(url, [^;]*'live'\);\s*\}\s*siteBackendKeys = await publishSiteBackends\(startPreviewUrl, url, releaseDir, domainUrlsOf\(sub\)\);\s*await puter\.hosting\.update\(sub, releaseDir\);/.test(publish)); check('…and only a first publish uses one', /let reserved = isFirst \? \(ui\.reserved \|\| null\) : null;/.test(publish)); check('the popover passes the reserved name to the shared publish', /async function doPublish\(\{ reserved = null \} = \{\}\) \{[\s\S]{0,400}return publishProject\(\{[\s\S]{0,200}\breserved,/.test(publish)); check('a plain Publish (the popover\'s Enter, or the chat\'s card) waits while the own-domain route reserves the name', diff --git a/scripts/test-preview-canary.mjs b/scripts/test-preview-canary.mjs index ceaa1d6f..d0dfd81d 100644 --- a/scripts/test-preview-canary.mjs +++ b/scripts/test-preview-canary.mjs @@ -107,6 +107,7 @@ function makeEnv(opts = {}) { return { ...api, calls, reloads, reloadUrls, disk, copy, startEarly: () => win.startEarlyPreviewClear(), + pagesChanged: () => win.notePagesChanged('c1'), dropEarly: () => win.dropEarlyPreviewClear(), sleep: (ms) => new Promise((r) => later(r, ms)), now: () => now, @@ -144,6 +145,8 @@ check('there is an upper limit, under the old 22 s', typeof L === 'number' && L check('the builder\'s copy now holds the new value, ready to be the old value next time', env.copy[CANARY] === env.disk[CANARY]); const second = env.now(); + // A page changed since (markProjectModified), as before any refresh. + env.pagesChanged(); await env.run(env.refreshPreviewWhenReady()); check('the next refresh is just as quick', env.reloads[1] - second >= 4000 && env.reloads[1] - second <= 4600, `${env.reloads[1] - second}ms`); } @@ -288,5 +291,64 @@ check('there is an upper limit, under the old 22 s', typeof L === 'number' && L env.calls.canaryWrites === 2 && env.calls.hostingUpdate === 2 && env.reloads.length === before + 1, JSON.stringify(env.calls)); } +// --- A turn that changed only backend files skips the clear --- +// Once a clear has covered every change that may show in the pages, a turn +// whose only changes were the AI's saves of backend files just reloads: no +// canary, no hosting.update, so no backend outage to wait out. +{ + const env = makeEnv({ clearDelay: 4000 }); + await env.run(env.refreshPreviewWhenReady()); + check('pages: the first refresh clears', env.calls.hostingUpdate === 1 && env.reloads.length === 1); + const at = env.now(); + await env.run(env.refreshPreviewWhenReady()); + check('pages: a refresh with only backend saves since then just reloads, at once', + env.calls.hostingUpdate === 1 && env.calls.canaryWrites === 1 && env.reloads.length === 2 && env.reloads[1] - at < 100, + JSON.stringify({ calls: env.calls, ms: env.reloads[1] - at })); + check('…on the same host as before', env.reloadUrls[1].startsWith('https://preview-x.puter.site/?__pv='), env.reloadUrls[1]); + env.startEarly(); + await env.run(env.sleep(10)); + check('pages: no early clear starts for it either', env.calls.hostingUpdate === 1 && env.calls.canaryWrites === 1, JSON.stringify(env.calls)); + env.pagesChanged(); + await env.run(env.refreshPreviewWhenReady()); + check('pages: a page change since then clears again', env.calls.hostingUpdate === 2 && env.reloads.length === 3, JSON.stringify(env.calls)); +} +{ + // Outside a turn a refresh follows a restore or a GitHub update, whose + // writes aren't counted. + const env = makeEnv({ clearDelay: 4000, processing: false }); + await env.run(env.refreshPreviewWhenReady()); + await env.run(env.refreshPreviewWhenReady()); + check('pages: outside a turn every refresh clears', env.calls.hostingUpdate === 2, JSON.stringify(env.calls)); +} +{ + // A clear that never landed covered nothing. + const env = makeEnv({ clearDelay: null }); + await env.run(env.refreshPreviewWhenReady()); + await env.run(env.refreshPreviewWhenReady()); + check('pages: after a clear that never landed, the next refresh clears', env.calls.hostingUpdate === 2, JSON.stringify(env.calls)); +} +{ + // A page change during the clear isn't covered by it. + const env = makeEnv({ clearDelay: 4000 }); + const first = env.refreshPreviewWhenReady(); + await env.run(env.sleep(1000)); + env.pagesChanged(); + await env.run(first); + await env.run(env.refreshPreviewWhenReady()); + check('pages: a page change during a clear makes the next refresh clear', env.calls.hostingUpdate === 2, JSON.stringify(env.calls)); +} +{ + const read = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8'); + const app = read('../src/js/app.js'); + const ver = read('../src/js/versions.js'); + const tools = read('../src/js/tools.js'); + check('pages: opening a project makes its first refresh clear', + /resetChatUIForSwitch\(\);\s*(\/\/[^\n]*\n\s*)*window\.notePagesChanged\?\.\(chatId\);/.test(app.slice(app.indexOf('async function loadChat('), app.indexOf('async function loadChat(') + 3000))); + check('pages: every project change counts, except a backend save', + /window\.markProjectModified = function \(toolName, chatId, opts\) \{\s*if \(toolName && !MUTATING_TOOLS\.has\(toolName\)\) return;\s*if \(!\(opts && opts\.backendOnly\)\) window\.notePagesChanged\?\.\(chatId \|\| openChatId\(\)\);/.test(ver)); + check('pages: the tool loop says which calls were backend saves', + tools.includes('window.markProjectModified?.(toolCall.name, c.currentChatId, { backendOnly: window.isBackendSaveCall(toolCall, c) });')); +} + if (failures) { console.error(`\n${failures} check(s) FAILED`); process.exit(1); } console.log('\nAll preview canary checks passed.'); diff --git a/scripts/test-preview-host.mjs b/scripts/test-preview-host.mjs index 48365838..d858cccf 100644 --- a/scripts/test-preview-host.mjs +++ b/scripts/test-preview-host.mjs @@ -40,6 +40,9 @@ const CANARY = '.puter/canary.txt'; // 'blocked' (the request fails, as a DNS block or an ad blocker does), or // 'hang' (no answer ever). opts.hostMs: how long its answer takes. // opts.manifestMs / opts.stampMs: how long each preparation step takes. +// opts.backends: whether the served folder holds dynamic backends (true, +// false, or 'fail' for a lookup that fails), read each time. opts.lookupMs: +// how long the lookup takes. function makeEnv(opts = {}) { let now = 1_000_000; const start = now; @@ -47,7 +50,7 @@ function makeEnv(opts = {}) { const later = (f, ms) => { timers.push({ at: now + (ms || 0), fn: f }); }; const steps = []; const reloads = []; - const calls = { hostingUpdate: 0, canaryWrites: 0, hostChecks: [] }; + const calls = { hostingUpdate: 0, canaryWrites: 0, hostChecks: [], backendLookups: [] }; // puter.site's edge copy of the canary, dropped 4 s after a hosting.update. const disk = { [CANARY]: 'v0' }; const copy = { [CANARY]: 'v0' }; @@ -65,6 +68,13 @@ function makeEnv(opts = {}) { currentPreviewPath: DIR, ensureAppManifest: () => new Promise((r) => later(() => { steps.push('manifest'); r(); }, opts.manifestMs ?? 200)), applyPreviewCacheBust: () => new Promise((r) => later(() => { steps.push('stamp'); r(); }, opts.stampMs ?? 100)), + SiteBackends: 'backends' in opts ? { + list: (dir) => new Promise((r, no) => later(() => { + calls.backendLookups.push(dir); + if (opts.backends === 'fail') no(new Error('readdir failed')); + else r(opts.backends ? [{ name: 'api', path: dir + '/__workers/api.worker.js' }] : []); + }, opts.lookupMs ?? 100)), + } : undefined, }; const rel = (p) => p.slice(DIR.length + 1); const puter = { @@ -339,6 +349,60 @@ async function opened(env) { /else \{[^}]*loadPreviewOnAnsweringHost\(url\);/.test(show)); } +// ---- A draft with dynamic backends ------------------------------------------------- +// puter.host doesn't run them, so a folder that holds any shows on puter.site, +// even with puter.host up. + +{ + const env = makeEnv({ host: 'up', backends: true }); + await env.run(env.loadPreviewOnAnsweringHost(SITE)); + await env.run(env.sleep(50)); + check('a project whose folder has a backend opens on puter.site', + env.reloads.length === 1 && env.reloads[0].url.startsWith(SITE + '?__pv='), JSON.stringify(env.reloads)); + check('…looking in the folder the preview serves', env.calls.backendLookups.every((d) => d === DIR) && env.calls.backendLookups.length === 1, + JSON.stringify(env.calls.backendLookups)); + await env.run(env.refreshPreviewWhenReady()); + check('…and its refresh reloads on puter.site', + env.reloads.length === 2 && env.reloads[1].url.startsWith(SITE + '?__pv='), JSON.stringify(env.reloads)); + check('…after the puter.site canary and clear', env.calls.hostingUpdate === 1 && env.calls.canaryWrites === 1 && env.reloads[1] && env.reloads[1].at >= 4000, + JSON.stringify(env.calls)); + check('…looking the folder up once', env.calls.backendLookups.length === 2, JSON.stringify(env.calls.backendLookups)); + check('…and the Share link, tests and error mapping use puter.site', env.previewShownUrl(SITE) === SITE); +} +{ + const env = makeEnv({ host: 'up', backends: 'fail' }); + await env.run(env.loadPreviewOnAnsweringHost(SITE)); + await env.run(env.sleep(50)); + check('a folder that can\'t be read counts as having a backend', + env.reloads.length === 1 && env.reloads[0].url.startsWith(SITE + '?__pv='), JSON.stringify(env.reloads)); +} +{ + const opts = { host: 'up', backends: false }; + const env = makeEnv(opts); + await env.run(env.loadPreviewOnAnsweringHost(SITE)); + await env.run(env.sleep(50)); + await env.run(env.refreshPreviewWhenReady()); + check('a project with no backend yet stays on puter.host', + env.reloads.length === 2 && env.reloads.every((r) => r.url.startsWith(HOST + '?__pv=')), JSON.stringify(env.reloads)); + opts.backends = true; // the AI writes its first backend + await env.run(env.refreshPreviewWhenReady()); + check('…and moves to puter.site with the refresh after its first backend', + env.reloads.length === 3 && env.reloads[2].url.startsWith(SITE + '?__pv='), JSON.stringify(env.reloads)); + check('…after the puter.site canary and clear', env.calls.hostingUpdate === 1 && env.calls.canaryWrites === 1, JSON.stringify(env.calls)); +} +{ + const at = async (opts) => { + const env = makeEnv({ host: 'up', hostMs: 400, ...opts }); + await env.run(env.loadPreviewOnAnsweringHost(SITE)); + await env.run(env.sleep(50)); + return env.reloads[0] && env.reloads[0].url.startsWith(HOST) ? env.reloads[0].at : null; + }; + const without = await at({}); + const withLookup = await at({ backends: false, lookupMs: 100 }); + check('the folder lookup runs alongside the puter.host check, so it adds no wait', + without !== null && withLookup === without, `${withLookup}ms with the lookup, ${without}ms without`); +} + // ---- The Share draft link --------------------------------------------------------- // It shows the host the preview is on, so the link matches what the user sees. diff --git a/scripts/test-preview-message-trust.mjs b/scripts/test-preview-message-trust.mjs index 31fedf28..92fffc20 100644 --- a/scripts/test-preview-message-trust.mjs +++ b/scripts/test-preview-message-trust.mjs @@ -179,6 +179,10 @@ check('app-error: still gated on isProcessing/_restoringVersion', appH.includes('if (isProcessing || window._restoringVersion) return;')); check('fetch-error: still gated on isProcessing/_restoringVersion', fetchH.includes('if (isProcessing || window._restoringVersion) return;')); +check('fetch-error: a backend still switching over to its latest save is never sent, checked after the trust gate and before the dedup', + fetchH.indexOf('isTrustedPreviewMessage(event)') < fetchH.indexOf('if (await window.backendStillSwitching?.(url)) return;') + && fetchH.indexOf('if (await window.backendStillSwitching?.(url)) return;') < fetchH.indexOf('lastFetchErrorKey = errorKey;') + && /const chatId = currentChatId;\s*if \(await window\.backendStillSwitching\?\.\(url\)\) return;\s*if \(chatId !== currentChatId\) return;/.test(fetchH)); check('app-error: dedup key unchanged', appH.includes('`${message}|${source}|${lineno}`')); // The debounced send is bound to the chat that raised the error: switching // projects inside the window used to send project A's report into project B. diff --git a/scripts/test-preview-verification.mjs b/scripts/test-preview-verification.mjs index c6085ad4..8d8f208f 100644 --- a/scripts/test-preview-verification.mjs +++ b/scripts/test-preview-verification.mjs @@ -90,7 +90,7 @@ const isRuntimeAssetError = new Function('return ' + UI.slice(bStart, bEnd + 2)) // A fresh, fully-isolated instance per scenario so cases can run in parallel // without sharing the module-level buffer/capturing/pending state. function makeInstance(opts) { - opts = Object.assign({ previewActive: true, hasFrame: true, aborted: false, commit: true, errorsAfterLoad: [] }, opts || {}); + opts = Object.assign({ previewActive: true, hasFrame: true, aborted: false, commit: true, errorsAfterLoad: [], fetchErrorsAfterLoad: [] }, opts || {}); const loadHandlers = []; const frame = { length: opts.hasFrame ? 1 : 0, @@ -115,9 +115,13 @@ function makeInstance(opts) { for (const e of opts.errorsAfterLoad) { listeners.forEach((fn) => fn({ data: { type: 'app-error', message: e }, source: {} })); } + for (const f of opts.fetchErrorsAfterLoad) { + listeners.forEach((fn) => fn({ data: { type: 'fetch-error', url: f.url, status: f.status }, source: {} })); + } }, 30); }, }; + if (opts.switching) win.backendStillSwitching = opts.switching; const post = (msg) => listeners.forEach((fn) => fn({ data: { type: 'app-error', message: msg }, source: {} })); // When verifyPreview said the new page had loaded (opts.onLoaded), and how // many errors it had collected by then. @@ -208,6 +212,23 @@ async function run() { rStopped.status === 'skipped' && stopped.loadedAt.length === 0); check('verify: a status change that throws never fails the check', rThrow.status === 'ok'); } + { + // A failed request to a backend still switching over to its latest + // save is expected (backendStillSwitching in tools.js). The answer can + // come after the watch, from a canary read, and still counts. + const later = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms)); + const switching = (u) => later(u.includes('/api/') ? 50 : 3500, u.includes('/api/')); + const mixed = makeInstance({ switching, fetchErrorsAfterLoad: [{ url: '/__workers/api/items', status: 500 }, { url: '/__workers/other/x', status: 500 }] }); + const allSwitching = makeInstance({ switching, fetchErrorsAfterLoad: [{ url: '/__workers/api/items', status: 500 }, { url: '/__workers/api/more', status: 0 }] }); + const failing = makeInstance({ switching: () => Promise.reject(new Error('no answer')), fetchErrorsAfterLoad: [{ url: '/__workers/api/items', status: 500 }] }); + const plain = makeInstance({ fetchErrorsAfterLoad: [{ url: '/__workers/api/items', status: 500 }] }); + const [rMixed, rAll, rFailing, rPlain] = await Promise.all([mixed.verify(), allSwitching.verify(), failing.verify(), plain.verify()]); + check('verify: a failed request to a backend still switching over is not an error, another backend\'s still is', + rMixed.status === 'errors' && rMixed.errors.length === 1 && rMixed.errors[0] === 'Failed network request (HTTP 500): /__workers/other/x', JSON.stringify(rMixed)); + check('verify: failures only from backends still switching over → ok', rAll.status === 'ok', JSON.stringify(rAll)); + check('verify: a check that fails counts the failure', rFailing.status === 'errors' && rFailing.errors.length === 1, JSON.stringify(rFailing)); + check('verify: without the check (no tools.js) a failure counts as before', rPlain.status === 'errors' && rPlain.errors.length === 1, JSON.stringify(rPlain)); + } } // === 3. The real tool switches its status after the load ====================== diff --git a/scripts/test-publish-card.mjs b/scripts/test-publish-card.mjs index 81cbc33e..17e60fee 100644 --- a/scripts/test-publish-card.mjs +++ b/scripts/test-publish-card.mjs @@ -546,6 +546,9 @@ function setup() { previewSubdomain: (u) => (String(u).match(/^https:\/\/([^.]+)\.puter\.site/) || [])[1] || null, resolvePublishedDir: async (p) => p, absolutizeSocialImagesInRelease: async () => {}, + // A release with no dynamic backend: nothing to ask or move. + planSiteMove: async () => ({ moveApp: false, backends: [] }), + finishSiteMove: async () => {}, saveCurrentChat: async () => log.push('save'), puter: { hosting: { create: async (sub) => log.push('create:' + sub), delete: async (sub) => log.push('delete:' + sub) } }, }; @@ -594,6 +597,13 @@ function setup() { check('no published files: refused, nothing created or dropped', code === 'no-files' && !lost.log.some(l => l.startsWith('create') || l.startsWith('delete')), lost.log.join()); check('…and the project isn\'t left marked as changing', lost.sb.isAddressChanging('p') === false); + // The user keeps the address at the backend question (planSiteMove). + const kept = make(); + kept.sb.planSiteMove = async () => null; + const k = await kept.sb.changePublishedAddress('new'); + check('the address kept at the backend question: cancelled, nothing created or dropped', + k.cancelled === true && k.changed === false && !kept.log.some(l => l.startsWith('create') || l.startsWith('delete')), kept.log.join()); + check('…and the project isn\'t left marked as changing', kept.sb.isAddressChanging('p') === false); const bad = make(); try { await bad.sb.changePublishedAddress('-bad-'); } catch (e) { code = e.code; } check('an invalid address is refused', code === 'invalid-name' && bad.log.length === 0); diff --git a/scripts/test-publish-notes.mjs b/scripts/test-publish-notes.mjs index 5ce4bb30..db5021b5 100644 --- a/scripts/test-publish-notes.mjs +++ b/scripts/test-publish-notes.mjs @@ -56,6 +56,9 @@ function setup({ open = true, processing = false, history = null, typed = 'new-n setPublishBusy() {}, resolvePublishedDir: async (p) => p, absolutizeSocialImagesInRelease: async () => {}, + // A release with no dynamic backend: nothing to ask or move. + planSiteMove: async () => ({ moveApp: false, backends: [] }), + finishSiteMove: async () => {}, generateMessageId: () => 'm1', saveCurrentChat: async (ctx) => { env.saves.push(ctx.chatHistory.map(m => m.content)); }, puter: { diff --git a/scripts/test-publish-switch-race.mjs b/scripts/test-publish-switch-race.mjs index 4730b732..5c0e3f8e 100644 --- a/scripts/test-publish-switch-race.mjs +++ b/scripts/test-publish-switch-race.mjs @@ -340,6 +340,9 @@ check('switch/auto-name: the address is derived from A’s chat, not B’s', resolvePublishedDir: async (p) => p, previewSubdomain: (u) => (u.match(/^https?:\/\/([^.]+)\.puter\.site/) || [])[1] || null, absolutizeSocialImagesInRelease: async (...args) => { absolutized.push(args); }, + // A release with no dynamic backend: nothing to confirm or move. + planSiteMove: async () => ({ moveApp: false, backends: [] }), + finishSiteMove: async () => {}, console: { warn() {} }, }; vm.createContext(sandbox); diff --git a/scripts/test-site-backends.mjs b/scripts/test-site-backends.mjs new file mode 100644 index 00000000..93b35dc4 --- /dev/null +++ b/scripts/test-site-backends.mjs @@ -0,0 +1,796 @@ +import fs from 'node:fs'; + +// ---- Regression guard for dynamic backends (site-backends.js) -------------- +// A project made while FEATURE_FLAGS.dynamicWorkers is on builds its backends +// as files __workers/.worker.js in the folder the site serves, run by +// Puter on that same site, with a store that belongs to the site's address. +// A project made before keeps create_worker for good. What can go wrong: +// * a save of the file isn't checked against the preview, or a file Puter +// never runs (nested, misnamed, outside the served folder) is treated as +// a backend; +// * a key lands in the wrong site's store, or a publish, a duplicate or a +// new live address leaves the destination without its keys; +// * a publish overwrites the live site's own live key, or a new address +// loses the mark that keeps it the live site's; +// * the release ships the preview's save canary; +// * the AI is still told to use create_worker, or not told how pages call +// a backend; +// * a project made before the flag gets the new tools or loses its old +// ones, or the mark that tells them apart reaches the AI. +// Runs the production bytes with puter and fetch stubbed. + +let failures = 0; +function check(name, cond, detail) { + if (cond) console.log('ok - ' + name); + else { console.error('FAIL - ' + name + (detail !== undefined ? ' :: ' + detail : '')); failures++; } +} +async function rejects(promise, substr) { + try { await promise; return false; } + catch (e) { return substr ? String((e && e.message) || e).includes(substr) : true; } +} +const read = (rel) => fs.readFileSync(new URL(rel, import.meta.url), 'utf8'); +function slice(src, from, to, label) { + const a = src.indexOf(from); + const b = src.indexOf(to, a + from.length); + if (a < 0 || b < 0) throw new Error('could not extract ' + label); + return src.slice(a, b); +} + +const HELP = read('../src/js/helpers.js'); +const PATHS = slice(HELP, 'window.normalizePosixPath =', '// ---- Per-path file-write serialization', 'the path-sandbox helpers'); +const CANARY = slice(HELP, '// ---- Worker deploy canary', '// ---- Preview sub-resource cache-busting', 'the canary helpers'); +const TOOLS = slice(read('../src/js/tools.js'), '// Saving a deployed worker', 'window.findTool = function', 'the worker save helpers'); +const UI_SRC = read('../src/js/ui.js'); +const UI_BACKENDS = slice(UI_SRC, '// ----- dynamic backends', '// Remove the runtime tag', 'the dynamic backend helpers') + + slice(UI_SRC, 'function previewSubdomain(url) {', '\n}\n', 'previewSubdomain') + '\n}\n'; +const MODULES = ['worker-ownership', 'custom-domain', 'site-backends', 'worker-secrets', 'worker-sender', 'editor-core', 'template-core'] + .map((n) => read(`../src/js/${n}.js`)).join('\n'); +const TOOL_FILES = ['create_worker', 'delete_worker', 'list_workers', 'get_worker', 'set_secret', 'set_email_sender_name'] + .map((n) => read(`../src/tools/workers/${n}.js`)).join('\n'); + +const KEY = 'sk_' + 'test_' + '51HxYzAbCdEfGhIjKlMn0pQr'; +const LIVE_KEY = 'sk_' + 'live_' + '51HxYzAbCdEfGhIjKlMn0pQr'; +const ROOT = '/u/AppData/b/c1'; +const RELEASE = '/u/AppData/b/.published/c1/r_1_x'; +const PREVIEW = 'https://preview-abc.puter.site/'; +const LIVE = 'https://shop.puter.site/'; +const NEW_LIVE = 'https://store.puter.site/'; +const API = 'https://api.puter.com'; + +// A stub Puter. Sites serve folders, and an address runs as the app whose +// index_url is that address, which Puter makes itself the first time a backend +// there runs when no app has the address. Every app has its own key-value +// store behind a permission the user grants once, and records who created it, +// since Puter lets an app change only the apps it created. Builder's own +// key-value store needs no permission. +function makeEnv(o = {}) { + const files = new Map(Object.entries(o.files || {})); + const sites = Object.assign({ 'https://preview-abc.puter.site': ROOT, 'https://shop.puter.site': RELEASE, 'https://store.puter.site': RELEASE }, o.sites || {}); + const apps = new Map(); // name -> { uid, name, title, index_url, creator } + const stores = new Map(); + const builderKv = new Map(); + const granted = new Set(); + const prompts = []; + const toasts = []; + const confirms = []; + const fetched = { siteApp: 0, wake: [] }; + const writes = []; + const hostingDeleted = []; + const uidFor = (origin) => 'app-' + origin.replace(/^https:\/\//, '').replace(/\./g, '-'); + const originOf = (url) => String(url || '').replace(/\/+$/, ''); + const byOrigin = (origin) => [...apps.values()].find((a) => originOf(a.index_url) === origin) || null; + const byUid = (uid) => [...apps.values()].find((a) => a.uid === uid) || null; + const puterApp = (origin) => { + if (!byOrigin(origin)) { const uid = uidFor(origin); apps.set(uid, { uid, name: uid, title: uid, index_url: origin, creator: 'puter' }); } + return byOrigin(origin); + }; + for (const origin of o.apps || []) puterApp(origin); + const store = (app) => { if (!stores.has(app)) stores.set(app, new Map()); return stores.get(app); }; + const copyOf = (v) => (v === undefined ? null : JSON.parse(JSON.stringify(v))); + let seq = 0; + let made = 0; // Puter gives every new app a uid of its own + const puter = { + APIOrigin: API, + authToken: 'tok', + fs: { + readdir: async (dir) => { + if (o.readdirFails) throw new Error('network down'); + const items = []; + for (const p of files.keys()) { + if (!p.startsWith(dir + '/')) continue; + const rest = p.slice(dir.length + 1); + const name = rest.split('/')[0]; + if (!items.some((i) => i.name === name)) items.push({ name, is_dir: rest.includes('/') }); + } + if (!items.length) throw { code: 'subject_does_not_exist', message: 'Subject does not exist' }; + return items; + }, + read: async (p) => { if (!files.has(p)) throw { code: 'subject_does_not_exist' }; const t = files.get(p); return { text: async () => t }; }, + write: async (p, d) => { writes.push(p); files.set(p, d); }, + }, + apps: { + create: async (opts) => { + const origin = originOf(opts.indexURL); + // Puter merges into an app it made for the address, which an + // app may not change. + if (byOrigin(origin)) throw { status: 403, code: 'forbidden', message: 'Access denied' }; + let name = opts.name; + if (apps.has(name)) { if (!opts.dedupeName) throw { status: 400, code: 'app_name_already_in_use' }; name += '-x' + (++seq); } + const app = { uid: 'app-reg-' + (++made) + '-' + name, name, title: opts.title, index_url: origin + '/', creator: 'builder' }; + apps.set(name, app); + return copyOf(app); + }, + // A URL finds the app a page at its origin runs as. + get: async (name) => { + if (name.includes('://')) { + fetched.siteApp++; + if (o.siteAppFails) throw new Error('network down'); + const a = byOrigin(new URL(name).origin); + if (!a) throw { status: 404, code: 'not_found', message: 'App not found' }; + return copyOf(a); + } + const a = apps.get(name); + if (!a) throw { status: 404, message: 'Entity not found' }; + return copyOf(a); + }, + update: async (name, attrs) => { + const a = apps.get(name); + if (!a) throw { status: 404, message: 'Entity not found' }; + if (a.creator !== 'builder') throw { status: 403, code: 'forbidden', message: 'Access denied' }; + if (attrs.indexURL !== undefined) { + if (o.moveFails) throw { status: 400, code: 'app_index_url_already_in_use' }; + a.index_url = originOf(attrs.indexURL) + '/'; + } + if (attrs.title !== undefined) a.title = attrs.title; + return copyOf(a); + }, + delete: async (name) => { if (!apps.delete(name)) throw { status: 404, message: 'Entity not found' }; return { success: true }; }, + }, + workers: { list: async () => [], get: async () => null }, + hosting: { delete: async (sub) => { hostingDeleted.push(sub); } }, + perms: { + check: async (res, d) => res === 'appData' && granted.has(d.app), + request: async (res, d) => { + if (!byUid(d.app)) throw { status: 404 }; + prompts.push(d.app); + if (o.decline) return false; + granted.add(d.app); + return true; + }, + }, + kv: { + get: async (k, opt) => { + if (!opt || !opt.appUuid) { if (o.recordReadFails) throw new Error('kv down'); return copyOf(builderKv.get(k)); } + if (!granted.has(opt.appUuid)) throw new Error('forbidden'); + return copyOf(store(opt.appUuid).get(k)); + }, + set: async (k, v, opt) => { + if (!opt || !opt.appUuid) { if (o.recordWriteFails) throw new Error('kv down'); builderKv.set(k, copyOf(v)); return true; } + if (!granted.has(opt.appUuid)) throw new Error('forbidden'); + store(opt.appUuid).set(k, copyOf(v)); + return true; + }, + del: async (k, opt) => { + if (!opt || !opt.appUuid) return builderKv.delete(k); + if (!granted.has(opt.appUuid)) throw new Error('forbidden'); + return store(opt.appUuid).delete(k); + }, + }, + }; + globalThis.fetch = async (url, init) => { + const u = new URL(url); + const m = /^\/__workers\/([a-z0-9_-]+)\//.exec(u.pathname); + const dir = sites[u.origin]; + if (m && dir && files.has(`${dir}/__workers/${m[1]}.worker.js`)) { + fetched.wake.push(u.origin + '/' + m[1]); + puterApp(u.origin); + return { ok: false, status: 404, text: async () => 'Not found' }; + } + return { ok: false, status: 404, text: async () => 'Not found' }; + }; + globalThis.puterConfirm = async (text) => { confirms.push(text); return o.confirm !== false; }; + globalThis.currentAppDir = o.openDir === undefined ? ROOT : o.openDir; + // The open project's history, whose system message says which kind it is. + globalThis.chatHistory = [o.dynamic === false ? { role: 'system' } : { role: 'system', dynamicWorkers: true }]; + globalThis.savedChats = [{ id: 'c1', title: 'Shop' }]; + const win = { + FEATURE_FLAGS: { dynamicWorkers: o.flag !== false }, + tools: [], + currentPreviewUrl: o.previewUrl === undefined ? PREVIEW : o.previewUrl, + currentPreviewPath: o.previewPath === undefined ? ROOT : o.previewPath, + currentPublishedUrl: o.publishedUrl === undefined ? LIVE : o.publishedUrl, + currentPublishedDomains: o.domains || [], + showToast: (t) => toasts.push(t), + withFileLock: (p, fn) => Promise.resolve().then(fn), + writeFileVerified: async (p, d) => { files.set(p, d); }, + }; + const ui = new Function('window', 'puter', + PATHS + '\n' + CANARY + '\n' + MODULES + '\n' + TOOLS + '\n' + TOOL_FILES + '\n' + UI_BACKENDS + + '\nreturn { publishSiteBackends, stripCanaryFromReleaseBackends, planSiteMove, finishSiteMove, moveSiteBackends, attachSiteBackends };')(win, puter); + const tool = (name) => win.tools.find((t) => t.function.name === name); + // The app an address runs as, the way Puter finds it. + const appAt = (url) => byOrigin(originOf(url)); + // Register the preview's and the live site's apps the way Builder does + // when it creates the sites. + const registerBoth = async () => { + await win.SiteBackends.registerApp(PREVIEW, 'Shop', 'preview'); + await win.SiteBackends.registerApp(LIVE, 'Shop', 'live'); + }; + return { win, puter, ui, tool, files, apps, stores, builderKv, granted, prompts, toasts, confirms, fetched, writes, hostingDeleted, uidFor, appAt, registerBoth }; +} + +const BACKEND = { [`${ROOT}/__workers/api.worker.js`]: "router.get('/x', () => 1);", [`${ROOT}/index.html`]: '' }; +const PREVIEW_APP = 'app-preview-abc-puter-site'; +const LIVE_APP = 'app-shop-puter-site'; +const NEW_LIVE_APP = 'app-store-puter-site'; +// A turn's state carries its project's history, as a real turn's does. +const st = { appDir: ROOT, currentChatId: 'c1', chatHistory: [{ role: 'system', dynamicWorkers: true }] }; + +// --- what counts as a dynamic backend --- +{ + const { win } = makeEnv(); + const SB = win.SiteBackends; + check('name: a top-level .worker.js file is a backend', SB.nameOf('__workers/api.worker.js') === 'api' && SB.nameOf('/__workers/my_api-2.worker.js') === 'my_api-2'); + check('name: nested, misnamed or uppercase files are not', [ + '__workers/sub/api.worker.js', '__workers/api.js', 'workers/api.js', '__workers/Api.worker.js', 'x/__workers/api.worker.js', '__workers/.worker.js', + ].every((p) => SB.nameOf(p) === null)); + check('origin: a puter.site URL gives its origin', SB.siteOrigin('https://Shop.puter.site/a?b=1') === 'https://shop.puter.site'); + check('origin: other hosts and plain http give none', [ + 'https://shop.puter.app/', 'http://shop.puter.site/', 'https://a.b.puter.site/', 'https://example.com/', '', null, + ].every((u) => SB.siteOrigin(u) === null)); + check('url: a backend answers under /__workers on its site', SB.urlOf(PREVIEW, 'api') === 'https://preview-abc.puter.site/__workers/api' && SB.urlOf(null, 'api') === null && SB.urlOf(PREVIEW, 'A') === null); + const EC = win.EditorCore; + check('code view: a backend file is tagged as backend', EC.classify('__workers/api.worker.js').backend === true); + check('code view: the served-folder path decides when the site serves a subfolder', + EC.classify('site/__workers/api.worker.js', { servedRel: '__workers/api.worker.js' }).backend === true && + EC.classify('__workers/api.worker.js', { servedRel: null }).backend === true && + EC.classify('__workers/sub/a.worker.js').backend === false); +} + +// --- listing a site's backends --- +{ + const { win } = makeEnv({ files: { + [`${ROOT}/__workers/zeta.worker.js`]: '', [`${ROOT}/__workers/api.worker.js`]: '', + [`${ROOT}/__workers/helpers.js`]: '', [`${ROOT}/__workers/sub/x.worker.js`]: '', [`${ROOT}/__workers/Bad.worker.js`]: '', + } }); + const list = await win.SiteBackends.list(ROOT); + check('list: only the backends Puter runs, by name', JSON.stringify(list.map((b) => b.name)) === '["api","zeta"]', JSON.stringify(list)); + check('list: with their paths', list[0].path === `${ROOT}/__workers/api.worker.js`); + check('list: a site without __workers has none', (await win.SiteBackends.list('/u/elsewhere')).length === 0); + const failing = makeEnv({ readdirFails: true }); + check('list: a read that fails is a failure, not "no backends"', await rejects(failing.win.SiteBackends.list(ROOT), 'network down')); +} + +// --- the app a site runs as --- +// The app a page at the address runs as (puter.apps.get with a URL), never +// asked of Puter's API directly. +{ + const src = read('../src/js/site-backends.js'); + check('app: no direct call to Puter\'s API', !/APIOrigin|authToken|app-uid-from-origin|api\.puter\.com/.test(src)); + const env = makeEnv({ files: BACKEND, apps: ['https://preview-abc.puter.site'] }); + check('app: the app Puter made for the address', (await env.win.SiteBackends.appUidOf(PREVIEW)) === PREVIEW_APP + && (await env.win.SiteBackends.appOf(PREVIEW)).uid === PREVIEW_APP); + const none = makeEnv({ files: BACKEND }); + check('app: none before anything has run there, without calling the backends', (await none.win.SiteBackends.appOf(PREVIEW)) === null + && none.fetched.wake.length === 0); + check('app: …and with them called first, the app Puter then makes', (await none.win.SiteBackends.appOf(PREVIEW, ['api'])).uid === PREVIEW_APP + && none.fetched.wake.length === 1); + // Apps outlive sites, so a gone site's keys can still be cleared. + check('app: a site that\'s gone still has its app', (await makeEnv({ files: BACKEND, apps: ['https://gone-x.puter.site'] }).win.SiteBackends.appUidOf('https://gone-x.puter.site/')) === 'app-gone-x-puter-site'); + check('app: an address nothing ran at has none', (await makeEnv().win.SiteBackends.appUidOf('https://never-x.puter.site/')) === null); + // An app the user registered for the address in the Dev Center, not Puter's. + const theirs = makeEnv({ files: BACKEND }); + await theirs.puter.apps.create({ name: 'my-app', indexURL: PREVIEW, title: 'Mine' }); + const warned = []; + const warn = console.warn; + console.warn = (...a) => warned.push(a.join(' ')); + let seen; + try { seen = [await theirs.win.SiteBackends.appOf(PREVIEW), await theirs.win.SiteBackends.appOf(PREVIEW)]; } + finally { console.warn = warn; } + check('app: someone\'s own app at the address counts as none', seen[0] === null && seen[1] === null); + check('app: …and the console says so once', warned.filter((w) => w.includes('my-app')).length === 1, JSON.stringify(warned)); + // Puter keeps the name when the owner changes the title in the Dev Center. + const retitled = makeEnv({ files: BACKEND, apps: ['https://preview-abc.puter.site'] }); + retitled.apps.get(PREVIEW_APP).title = 'My Shop'; + check('app: Puter\'s app still counts after its owner retitles it', (await retitled.win.SiteBackends.appOf(PREVIEW))?.uid === PREVIEW_APP); + const down = makeEnv({ files: BACKEND, siteAppFails: true }); + check('app: a lookup that fails is a failure, not "no app"', await rejects(down.win.SiteBackends.appOf(PREVIEW), 'network down')); +} + +// --- the save check --- +{ + const { win } = makeEnv({ files: BACKEND }); + const t = await win.workerSaveTarget(`${ROOT}/__workers/api.worker.js`, { appDir: ROOT }); + check('save: a backend save is checked on the preview', t && t.name === 'api' && t.url === 'https://preview-abc.puter.site/__workers/api', JSON.stringify(t)); + check('save: a file Puter never runs is not', await win.workerSaveTarget(`${ROOT}/__workers/sub/a.worker.js`, { appDir: ROOT }) === null); + const stamped = win.stampWorkerSave(t, "router.get('/x', () => 1);"); + check('save: the canary goes on the saved code', stamped.startsWith(";router.get('/__builder/canary'")); +} +{ + const { win } = makeEnv({ files: BACKEND, previewUrl: null }); + check('save: with no preview yet there is nothing to check', await win.workerSaveTarget(`${ROOT}/__workers/api.worker.js`, { appDir: ROOT }) === null); +} +{ + const { win } = makeEnv({ files: BACKEND, openDir: '/u/AppData/b/c2' }); + check('save: a project that is not open is never checked against the open one\'s preview', + await win.workerSaveTarget(`${ROOT}/__workers/api.worker.js`, { appDir: ROOT }) === null); +} +{ + const { win } = makeEnv({ previewPath: `${ROOT}/site` }); + const t = await win.workerSaveTarget(`${ROOT}/site/__workers/api.worker.js`, { appDir: ROOT }); + check('save: the backend sits in the folder the preview serves', t && t.name === 'api'); + check('save: a __workers folder the preview doesn\'t serve isn\'t run', await win.workerSaveTarget(`${ROOT}/__workers/api.worker.js`, { appDir: ROOT }) === null); +} +{ + const { win } = makeEnv({ dynamic: false, files: BACKEND }); + check('older project: a __workers file gets no save check', await win.workerSaveTarget(`${ROOT}/__workers/api.worker.js`, { appDir: ROOT }) === null); +} +{ + const { win } = makeEnv({ files: BACKEND }); + const t = await win.workerSaveTarget(`${ROOT}/__workers/api.worker.js`, { appDir: ROOT, chatHistory: [{ role: 'system' }] }); + check('older project: the turn\'s own history decides, not the open chat\'s', t === null); +} + +// --- the tools --- +{ + const on = makeEnv({ files: BACKEND }); + const off = makeEnv({ dynamic: false, files: BACKEND }); + const SB = on.win.SiteBackends; + const dynTools = SB.toolsFor(on.win.tools, [{ role: 'system', dynamicWorkers: true }]); + const oldTools = SB.toolsFor(on.win.tools, [{ role: 'system' }]); + const named = (list, n) => list.find((t) => t.function.name === n); + check('tools: a dynamic project gets no create_worker', !named(dynTools, 'create_worker')); + check('tools: an older project keeps it', !!named(oldTools, 'create_worker') && !!named(SB.toolsFor(on.win.tools, null), 'create_worker')); + check('tools: an older project gets the tools as before', oldTools.length === on.win.tools.length && + oldTools.every((t, i) => t.function === on.win.tools[i].function && t.exec === on.win.tools[i].exec)); + check('tools: neither kind sends the marks to the AI', dynTools.concat(oldTools).every((t) => !('dynamic' in t) && !('legacyOnly' in t))); + check('tools: a dynamic project is told about __workers', /__workers/.test(named(dynTools, 'set_secret').function.description) && + /__workers/.test(named(dynTools, 'set_secret').function.parameters.properties.worker.description)); + check('tools: an older project is not', !/__workers/.test(named(oldTools, 'set_secret').function.description) && + !/__workers/.test(named(oldTools, 'set_secret').function.parameters.properties.worker.description)); + check('tools: the dynamic wording keeps the parameters', JSON.stringify(Object.keys(named(dynTools, 'set_secret').function.parameters.properties)) === + JSON.stringify(Object.keys(named(oldTools, 'set_secret').function.parameters.properties)) && + named(dynTools, 'set_secret').function.strict === named(oldTools, 'set_secret').function.strict); + check('tools: the same exec runs for both', named(dynTools, 'set_secret').exec === named(oldTools, 'set_secret').exec); + check('new projects: marked only while the flag is on', + SB.markNewProject({ role: 'system' }).dynamicWorkers === true && + !('dynamicWorkers' in makeEnv({ flag: false }).win.SiteBackends.markNewProject({ role: 'system' }))); + const listed = await on.tool('list_workers').exec({}, st); + check('list_workers: lists the backends with the path pages call', + listed.backends && listed.backends.length === 1 && listed.backends[0].path === '/__workers/api' && + listed.backends[0].preview_url === 'https://preview-abc.puter.site/__workers/api', JSON.stringify(listed)); + check('list_workers: an older project gets nothing new', !('backends' in await off.tool('list_workers').exec({}, { ...st, chatHistory: [{ role: 'system' }] }))); + const got = await on.tool('get_worker').exec({ name: 'api' }, st); + check('get_worker: a backend is found by its file', got.success && got.file_path === `${ROOT}/__workers/api.worker.js`); + check('delete_worker: a backend is removed by deleting its file', await rejects(on.tool('delete_worker').exec({ name: 'api' }, st), 'delete that file')); +} + +// --- keys --- +{ + const env = makeEnv({ files: BACKEND }); + const r = await env.tool('set_secret').exec({ worker: 'api', name: 'STRIPE_SECRET_KEY', value: KEY, live: false }, st); + check('set_secret: the key lands in the preview site\'s store', r.success && env.stores.get(PREVIEW_APP).get('secret:STRIPE_SECRET_KEY') === KEY, JSON.stringify(r)); + check('set_secret: without Builder\'s app, Puter makes one by running the backend first', env.fetched.wake.length === 1 && env.apps.has(PREVIEW_APP)); + check('set_secret: the user is asked once, for that site', env.prompts.join(',') === PREVIEW_APP); + check('set_secret: the result never repeats the key', !JSON.stringify(r).includes(KEY)); + check('set_secret: the AI is told pages must not read it', /never read a secret: key from browser code/.test(r.note)); + const again = await env.tool('set_secret').exec({ worker: 'api', name: 'OTHER_KEY', value: 'v', live: false }, st); + check('set_secret: a second key asks nothing and wakes nothing', again.success && env.prompts.length === 1 && env.fetched.wake.length === 1); +} +{ + const env = makeEnv({ files: Object.assign({ [`${RELEASE}/__workers/api.worker.js`]: '' }, BACKEND) }); + const r = await env.tool('set_secret').exec({ worker: 'api', name: 'STRIPE_SECRET_KEY', value: LIVE_KEY, live: true }, st); + check('set_secret live: the key goes only to the live site\'s store', r.success && env.stores.get(LIVE_APP).get('secret:STRIPE_SECRET_KEY') === LIVE_KEY && !env.stores.has(PREVIEW_APP)); + check('set_secret live: it is marked as the live site\'s own', JSON.stringify(env.stores.get(LIVE_APP).get('secret-live-only')) === '["STRIPE_SECRET_KEY"]'); +} +{ + const env = makeEnv({ files: BACKEND, publishedUrl: null }); + const r = await env.tool('set_secret').exec({ worker: 'api', name: 'K', value: 'v', live: true }, st); + check('set_secret live: an unpublished site says to publish first', !r.success && /publish first/.test(r.error)); + const env2 = makeEnv({ files: BACKEND, previewUrl: null }); + const r2 = await env2.tool('set_secret').exec({ worker: 'api', name: 'K', value: 'v', live: false }, st); + check('set_secret: with no preview it says to open one', !r2.success && /publish_site/.test(r2.error)); + const env3 = makeEnv({ files: BACKEND }); + check('set_secret: an unknown backend says to write its file', await rejects(env3.tool('set_secret').exec({ worker: 'nope', name: 'K', value: 'v', live: false }, st), '__workers/nope.worker.js')); + const env4 = makeEnv({ files: BACKEND, decline: true }); + const r4 = await env4.tool('set_secret').exec({ worker: 'api', name: 'K', value: 'v', live: false }, st); + check('set_secret: a declined permission says so', !r4.success && /didn't allow Builder/.test(r4.error)); +} + +// --- publish --- +{ + const env = makeEnv({ + files: Object.assign({ [`${RELEASE}/__workers/api.worker.js`]: ";router.get('/__builder/canary', () => 'abc123');router.get('/x', () => 1);" }, BACKEND), + }); + await env.tool('set_secret').exec({ worker: 'api', name: 'STRIPE_SECRET_KEY', value: KEY, live: false }, st); + await env.ui.stripCanaryFromReleaseBackends(RELEASE); + check('publish: the release\'s backend loses the preview\'s save canary', env.files.get(`${RELEASE}/__workers/api.worker.js`) === "router.get('/x', () => 1);"); + const reports = await env.ui.publishSiteBackends(PREVIEW, LIVE, RELEASE); + check('publish: the live site gets the preview\'s keys', env.stores.get(LIVE_APP).get('secret:STRIPE_SECRET_KEY') === KEY); + const note = env.win.WorkerSecrets.publishNote(reports); + check('publish: the line in the conversation names the key and the test key', /STRIPE_SECRET_KEY/.test(note) && /Stripe test key/.test(note) && !note.includes(KEY), note); + // The live site gets a live key of its own, which the next publish keeps. + await env.tool('set_secret').exec({ worker: 'api', name: 'STRIPE_SECRET_KEY', value: LIVE_KEY, live: true }, st); + await env.ui.publishSiteBackends(PREVIEW, LIVE, RELEASE); + check('publish: the live site\'s own key is kept', env.stores.get(LIVE_APP).get('secret:STRIPE_SECRET_KEY') === LIVE_KEY); + // A new live address, for a site whose app Puter made. + const plan = await env.ui.planSiteMove(LIVE, RELEASE); + check('new address: the user is warned the data stays behind', plan && plan.moveApp === false && JSON.stringify(plan.backends) === '["api"]' && + env.confirms.length === 1 && /starts with no saved data/.test(env.confirms[0])); + await env.ui.finishSiteMove(LIVE, NEW_LIVE, plan, 'Shop'); + check('new address: its backend gets the live keys', env.stores.get(NEW_LIVE_APP).get('secret:STRIPE_SECRET_KEY') === LIVE_KEY); + check('new address: a live key stays the live site\'s own', JSON.stringify(env.stores.get(NEW_LIVE_APP).get('secret-live-only')) === '["STRIPE_SECRET_KEY"]'); + check('new address: the old address\'s keys are cleared', !env.stores.get(LIVE_APP).has('secret:STRIPE_SECRET_KEY')); + await env.ui.publishSiteBackends(PREVIEW, NEW_LIVE, RELEASE); + check('new address: the next publish keeps the live key', env.stores.get(NEW_LIVE_APP).get('secret:STRIPE_SECRET_KEY') === LIVE_KEY); +} +{ + const env = makeEnv({ files: BACKEND }); + const reports = await env.ui.publishSiteBackends(PREVIEW, LIVE, '/u/AppData/b/.published/c1/r_2_y'); + check('publish: a release without a backend copies nothing and asks nothing', reports.length === 0 && env.prompts.length === 0 && env.fetched.siteApp === 0); + const plan = await env.ui.planSiteMove(LIVE, '/u/AppData/b/.published/c1/r_2_y'); + check('new address: no backend, no question', plan && JSON.stringify(plan.backends) === '[]' && env.confirms.length === 0); + const declined = makeEnv({ files: { [`${RELEASE}/__workers/api.worker.js`]: '' }, confirm: false }); + check('new address: declining keeps the address', await declined.ui.planSiteMove(LIVE, RELEASE) === null); +} +{ + const env = makeEnv({ files: Object.assign({ [`${RELEASE}/__workers/api.worker.js`]: '' }, BACKEND) }); + await env.ui.publishSiteBackends(PREVIEW, LIVE, RELEASE); + check('publish: a preview with no keys asks nothing', env.prompts.length === 0 && env.toasts.length === 0); +} + +// --- deleting a project clears the site's keys --- +{ + const env = makeEnv({ files: BACKEND }); + await env.tool('set_secret').exec({ worker: 'api', name: 'STRIPE_SECRET_KEY', value: KEY, live: false }, st); + const r = await env.win.WorkerSecrets.clear({ site: PREVIEW }); + check('clear: the site\'s keys go', r.ok && r.cleared === 1 && !env.stores.get(PREVIEW_APP).has('secret:STRIPE_SECRET_KEY')); + const none = makeEnv(); + const r2 = await none.win.WorkerSecrets.clear({ site: PREVIEW }); + check('clear: a site whose backend never ran has nothing to clear and asks nothing', r2.ok && r2.cleared === 0 && none.prompts.length === 0); + const unwoken = makeEnv({ files: BACKEND }); + const r3 = await unwoken.win.WorkerSecrets.clear({ site: PREVIEW, backends: ['api'] }); + check('clear: never calls the site\'s backends, even when given them', r3.ok && r3.cleared === 0 && unwoken.fetched.wake.length === 0 && !unwoken.appAt(PREVIEW)); +} + +// --- the email sender name --- +{ + // A site whose app Puter made, since something ran there first, and a + // live site whose backend has run too. + const env = makeEnv({ files: BACKEND, apps: [LIVE.replace(/\/$/, '')] }); + const r = await env.tool('set_email_sender_name').exec({ worker: 'api', name: 'Shop' }, st); + check('sender: on an app Puter made, the user is sent to the Dev Center with the app ids', + !r.success && /Dev Center/.test(r.error) && r.error.includes(PREVIEW_APP) && r.error.includes(LIVE_APP) && /set both/.test(r.error), JSON.stringify(r)); + // The live site's backend hasn't run, so Puter hasn't made its app yet. + const fresh = makeEnv({ files: BACKEND }); + const r2 = await fresh.tool('set_email_sender_name').exec({ worker: 'api', name: 'Shop' }, st); + check('…and only to apps that exist, with the live site\'s to follow once its backend has run', + !r2.success && r2.error.includes(PREVIEW_APP) && !r2.error.includes(LIVE_APP) && /once the live site's backend has run/.test(r2.error), JSON.stringify(r2)); +} +{ + const env = makeEnv({ files: Object.assign({ [`${RELEASE}/__workers/api.worker.js`]: '' }, BACKEND) }); + await env.registerBoth(); + const r = await env.tool('set_email_sender_name').exec({ worker: 'api', name: 'Makor Family Portal' }, st); + check('sender: on Builder\'s apps, the preview and the live site are both renamed', + r.success && r.live === 'updated' && env.appAt(PREVIEW).title === 'Makor Family Portal' && env.appAt(LIVE).title === 'Makor Family Portal', JSON.stringify(r)); + check('sender: the chosen name is recorded', env.builderKv.get('site-app:https://preview-abc.puter.site').senderName === 'Makor Family Portal'); + await env.win.SiteBackends.retitle(PREVIEW, 'Portal'); + check('sender: renaming the project leaves a chosen name alone', env.appAt(PREVIEW).title === 'Makor Family Portal'); + const reset = await env.tool('set_email_sender_name').exec({ worker: 'api', name: '' }, st); + check('sender: an empty name goes back to the project\'s name', reset.success && env.appAt(PREVIEW).title === 'Portal (preview)' && env.appAt(LIVE).title === 'Shop', + env.appAt(PREVIEW).title + ' / ' + env.appAt(LIVE).title); + check('sender: and forgets the chosen name', env.builderKv.get('site-app:https://preview-abc.puter.site').senderName === null); +} +{ + const env = makeEnv({ files: BACKEND }); + env.apps.set('my-registered-app', { uid: 'app-mine', name: 'my-registered-app', title: 'Mine', index_url: 'https://preview-abc.puter.site/', creator: 'user' }); + check('sender: an app the user registered for the address by hand is never changed', await env.win.SiteBackends.appOf(PREVIEW) === null); +} + +// --- the app Builder registers for a site --- +{ + const env = makeEnv({ files: Object.assign({ [`${RELEASE}/__workers/api.worker.js`]: '' }, BACKEND) }); + const SB = env.win.SiteBackends; + check('title: the live app is the project\'s name and the preview\'s says so', SB.defaultTitle('Shop', 'live') === 'Shop' && SB.defaultTitle(' Shop Mail ', 'preview') === 'Shop Mail (preview)'); + check('title: an unnamed project and a long name still fit', SB.defaultTitle('', 'live') === 'Untitled' && + SB.defaultTitle('x'.repeat(150), 'preview').length === 100 && SB.defaultTitle('x'.repeat(150), 'preview').endsWith(' (preview)')); + const app = await SB.registerApp(PREVIEW, 'Shop', 'preview'); + check('register: the preview runs as Builder\'s app, named after the project', app && env.appAt(PREVIEW).creator === 'builder' && env.appAt(PREVIEW).title === 'Shop (preview)'); + check('register: Builder records it', JSON.stringify(env.builderKv.get('site-app:https://preview-abc.puter.site')) === + JSON.stringify({ name: 'preview-abc', kind: 'preview', defaultTitle: 'Shop (preview)', senderName: null })); + const r = await env.tool('set_secret').exec({ worker: 'api', name: 'STRIPE_SECRET_KEY', value: KEY, live: false }, st); + check('register: keys go into that app\'s store, and Puter never makes one of its own', + r.success && env.stores.get(app.uid).get('secret:STRIPE_SECRET_KEY') === KEY && env.fetched.wake.length === 0 && !env.apps.has(PREVIEW_APP)); + check('register: the user is asked about that app', env.prompts.join(',') === app.uid); + env.apps.set('preview-abc-taken', { uid: 'app-x', name: 'shop', title: 'Someone else', index_url: 'https://elsewhere.puter.site/', creator: 'user' }); + env.apps.set('shop', env.apps.get('preview-abc-taken')); + const live = await SB.registerApp(LIVE, 'Shop', 'live'); + check('register: a name someone else holds gets a suffix', live && live.name.startsWith('shop-') && env.appAt(LIVE).title === 'Shop'); +} +{ + const env = makeEnv({ files: BACKEND, apps: ['https://preview-abc.puter.site'] }); + const app = await env.win.SiteBackends.registerApp(PREVIEW, 'Shop', 'preview'); + check('register: too late once Puter made an app for the address, and nothing is recorded', app === null && env.builderKv.size === 0); +} +{ + const env = makeEnv({ files: BACKEND }); + const SB = env.win.SiteBackends; + await env.registerBoth(); + await SB.retitle(PREVIEW, 'Bakery'); + await SB.retitle(LIVE, 'Bakery'); + check('rename: the apps follow the project\'s name', env.appAt(PREVIEW).title === 'Bakery (preview)' && env.appAt(LIVE).title === 'Bakery'); + // The live app retitled by hand in the Dev Center. + env.appAt(LIVE).title = 'Hand Picked'; + await SB.retitle(PREVIEW, 'Cafe'); + await SB.retitle(LIVE, 'Cafe'); + check('rename: a title set by hand in the Dev Center stays', env.appAt(LIVE).title === 'Hand Picked' && env.appAt(PREVIEW).title === 'Cafe (preview)'); + await SB.retitle('https://elsewhere.puter.site/', 'Bakery'); + check('rename: a site Builder has no app for is left alone', true); + check('delete: Builder knows which apps are its own', await SB.hasApp(PREVIEW) && !(await SB.hasApp('https://elsewhere.puter.site/'))); + await SB.deleteApp(PREVIEW); + check('delete: the app and its record go', !env.appAt(PREVIEW) && !env.builderKv.has('site-app:https://preview-abc.puter.site') && !(await SB.hasApp(PREVIEW))); + await SB.deleteApp(PREVIEW); + check('delete: deleting again is fine', true); +} +{ + // Publish carries a chosen sender name to the live site, and only that. + const env = makeEnv({ files: Object.assign({ [`${RELEASE}/__workers/api.worker.js`]: '' }, BACKEND) }); + await env.registerBoth(); + await env.ui.publishSiteBackends(PREVIEW, LIVE, RELEASE); + check('publish: the live app keeps the project\'s name, not the preview\'s', env.appAt(LIVE).title === 'Shop'); + await env.win.WorkerSender.set({ site: PREVIEW, backends: ['api'] }, 'Shop Mail'); + await env.ui.publishSiteBackends(PREVIEW, LIVE, RELEASE); + check('publish: a chosen sender name goes live', env.appAt(LIVE).title === 'Shop Mail' && + env.builderKv.get('site-app:https://shop.puter.site').senderName === 'Shop Mail'); +} +{ + // A name only the live site has is never reset by a preview on its default. + const env = makeEnv({ files: Object.assign({ [`${RELEASE}/__workers/api.worker.js`]: '' }, BACKEND) }); + await env.registerBoth(); + await env.win.WorkerSender.set({ site: LIVE, backends: ['api'] }, 'Live Only'); + await env.ui.publishSiteBackends(PREVIEW, LIVE, RELEASE); + check('publish: the live site\'s own sender name stays', env.appAt(LIVE).title === 'Live Only'); +} +{ + // A new live address takes the app along. + const env = makeEnv({ files: Object.assign({ [`${RELEASE}/__workers/api.worker.js`]: '' }, BACKEND) }); + await env.registerBoth(); + await env.tool('set_secret').exec({ worker: 'api', name: 'STRIPE_SECRET_KEY', value: LIVE_KEY, live: true }, st); + const liveUid = env.appAt(LIVE).uid; + env.stores.get(liveUid).set('orders', ['o1']); + const plan = await env.ui.planSiteMove(LIVE, RELEASE); + check('move: with Builder\'s app there is nothing to ask', plan && plan.moveApp === true && env.confirms.length === 0); + await env.ui.finishSiteMove(LIVE, NEW_LIVE, plan, 'Shop'); + check('move: the new address runs as the same app', env.appAt(NEW_LIVE) && env.appAt(NEW_LIVE).uid === liveUid && !env.appAt(LIVE)); + check('move: so its data and keys are still there', JSON.stringify(env.stores.get(liveUid).get('orders')) === '["o1"]' && + JSON.stringify(await env.win.WorkerSecrets.names({ site: NEW_LIVE })) === '["STRIPE_SECRET_KEY"]'); + check('move: the record follows the address', env.builderKv.has('site-app:https://store.puter.site') && !env.builderKv.has('site-app:https://shop.puter.site')); + check('move: nothing was copied or warned about', env.toasts.length === 0 && !env.apps.has(NEW_LIVE_APP)); +} +{ + // Puter refusing the move changes nothing. + const env = makeEnv({ files: Object.assign({ [`${RELEASE}/__workers/api.worker.js`]: '' }, BACKEND), moveFails: true }); + await env.registerBoth(); + const liveUid = env.appAt(LIVE).uid; + const plan = await env.ui.planSiteMove(LIVE, RELEASE); + check('move refused: the address change fails', await rejects(env.ui.finishSiteMove(LIVE, NEW_LIVE, plan), 'the address wasn’t changed')); + check('move refused: the app stays on the old address with its record', env.appAt(LIVE) && env.appAt(LIVE).uid === liveUid && + env.builderKv.has('site-app:https://shop.puter.site') && !env.builderKv.has('site-app:https://store.puter.site')); + check('move refused: the new address goes again, and nothing else is made', JSON.stringify(env.hostingDeleted) === '["store"]' && !env.appAt(NEW_LIVE)); +} +{ + // A move that reached Puter but whose answer got lost still counts. + const env = makeEnv({ files: BACKEND }); + await env.registerBoth(); + const update = env.puter.apps.update; + env.puter.apps.update = async (...args) => { await update(...args); throw new Error('connection reset'); }; + check('move: an update whose answer got lost still moved', await env.win.SiteBackends.moveApp(LIVE, NEW_LIVE) && + env.builderKv.has('site-app:https://store.puter.site') && !env.builderKv.has('site-app:https://shop.puter.site')); +} +{ + // Builder's records can't be read or written. + const env = makeEnv({ files: BACKEND }); + await env.registerBoth(); + env.puter.kv.get = async (k, opt) => { if (!opt || !opt.appUuid) throw new Error('kv down'); return null; }; + check('lookup: a record that can\'t be read is an error, not "no app"', await rejects(env.win.SiteBackends.hasApp(LIVE), 'kv down')); + check('lookup: so an address change stops before anything changes', await rejects(env.ui.planSiteMove(LIVE, RELEASE), 'kv down') && env.confirms.length === 0); + check('lookup: and a move reports it didn\'t happen', await env.win.SiteBackends.moveApp(LIVE, NEW_LIVE) === false && env.appAt(LIVE)); + const failing = makeEnv({ files: BACKEND, recordWriteFails: true }); + const app = await failing.win.SiteBackends.registerApp(PREVIEW, 'Shop', 'preview'); + check('register: an app whose record can\'t be written is removed again', app === null && !failing.appAt(PREVIEW)); +} +{ + const env = makeEnv({ files: BACKEND }); + const set = env.puter.kv.set; + let failed = false; + env.puter.kv.set = async (k, v, opt) => { + if (!failed && !(opt && opt.appUuid)) { failed = true; throw new Error('kv down'); } + return set(k, v, opt); + }; + const app = await env.win.SiteBackends.registerApp(PREVIEW, 'Shop', 'preview'); + check('register: a record write that fails once is tried again', app && env.appAt(PREVIEW)?.uid === app.uid + && env.builderKv.get('site-app:https://preview-abc.puter.site')?.name === app.name); + const failing = makeEnv({ files: BACKEND, recordWriteFails: true }); + const del = failing.puter.apps.delete; + let delFailed = false; + failing.puter.apps.delete = async (n) => { if (!delFailed) { delFailed = true; throw new Error('network down'); } return del(n); }; + check('register: …and so is removing the app when the record still fails', await failing.win.SiteBackends.registerApp(PREVIEW, 'Shop', 'preview') === null + && !failing.appAt(PREVIEW)); +} +{ + // Two renames close together, the first one's record write slow. + const env = makeEnv({ files: BACKEND }); + await env.registerBoth(); + const set = env.puter.kv.set; + let slowed = false; + env.puter.kv.set = async (k, v, opt) => { + if (!slowed && !(opt && opt.appUuid)) { slowed = true; await new Promise((r) => setTimeout(r, 30)); } + return set(k, v, opt); + }; + await Promise.all([env.win.SiteBackends.retitle(PREVIEW, 'Bakery'), env.win.SiteBackends.retitle(PREVIEW, 'Cafe')]); + check('rename: two at once end on the last name, record included', env.appAt(PREVIEW).title === 'Cafe (preview)' && + env.builderKv.get('site-app:https://preview-abc.puter.site').defaultTitle === 'Cafe (preview)'); + await env.win.SiteBackends.retitle(PREVIEW, 'Diner'); + check('rename: and later ones still apply', env.appAt(PREVIEW).title === 'Diner (preview)'); +} +{ + // Republishing gives the live site its keys before it switches to the + // new code, a first publish once the address exists. + const publish = UI_SRC.slice(UI_SRC.indexOf('async function doPublish('), UI_SRC.indexOf('async function loadPublishedSiteMeta(')); + const republish = publish.slice(publish.indexOf('} else {', publish.indexOf('if (!existingSub) {'))); + check('publish: a republish copies the keys before the address serves the release', + republish.indexOf('publishSiteBackends(') > 0 && republish.indexOf('publishSiteBackends(') < republish.indexOf('puter.hosting.update(existingSub')); + check('publish: a first publish copies them after the address exists', + publish.indexOf('registerApp(url') > 0 && publish.indexOf('publishSiteBackends(', publish.indexOf('registerApp(url')) < publish.indexOf('} else {', publish.indexOf('if (!existingSub) {'))); +} + +// --- the user's own domain --- +// It runs the live site's backends as an app of its own, which Builder +// registers when the domain is attached (claimDomain), so it can rename it and +// give it keys. +const DOMAIN = 'https://www.shop-example.com/'; +const DOMAIN_ORIGIN = 'https://www.shop-example.com'; +const DOMAINS = [{ hostname: 'www.shop-example.com', site: 'shop', status: 'active' }]; +const LIVE_FILES = Object.assign({ [`${RELEASE}/__workers/api.worker.js`]: '' }, BACKEND); +{ + const SB = makeEnv().win.SiteBackends; + check('domain: the user\'s own domain is an address an app runs at', SB.appOrigin(DOMAIN) === DOMAIN_ORIGIN && SB.appOrigin(LIVE) === 'https://shop.puter.site' + && ['http://www.shop-example.com/', 'https://www.shop-example.com:8443/', 'https://shop.puter.host/', 'https://puter.com/', 'https://localhost/', null].every((u) => SB.appOrigin(u) === null)); + check('domain: its backends answer there too', SB.urlOf(DOMAIN, 'api') === DOMAIN_ORIGIN + '/__workers/api'); +} +{ + const env = makeEnv({ files: LIVE_FILES, sites: { [DOMAIN_ORIGIN]: RELEASE }, domains: DOMAINS }); + const SB = env.win.SiteBackends; + const app = await SB.claimDomain(DOMAIN, 'Shop', 'c1'); + check('domain: attaching it registers the app it runs as, named after the project', + app && env.appAt(DOMAIN) && env.appAt(DOMAIN).uid === app.uid && env.appAt(DOMAIN).title === 'Shop' && env.appAt(DOMAIN).creator === 'builder'); + check('…for this project', (await SB.projectOf(DOMAIN)) === 'c1'); + await env.registerBoth(); + await env.tool('set_secret').exec({ worker: 'api', name: 'STRIPE_SECRET_KEY', value: KEY, live: false }, st); + const reports = await env.ui.publishSiteBackends(PREVIEW, LIVE, RELEASE, [DOMAIN]); + check('domain: publishing gives it the preview\'s keys', env.stores.get(app.uid)?.get('secret:STRIPE_SECRET_KEY') === KEY + && reports.length === 2 && reports.every((r) => r.result && r.result.ok), JSON.stringify(reports)); + const live = await env.tool('set_secret').exec({ worker: 'api', name: 'STRIPE_SECRET_KEY', value: LIVE_KEY, live: true }, st); + check('domain: a live key goes to it too, as its own', live.success && env.stores.get(app.uid).get('secret:STRIPE_SECRET_KEY') === LIVE_KEY + && JSON.stringify(env.stores.get(app.uid).get('secret-live-only')) === '["STRIPE_SECRET_KEY"]', JSON.stringify(live)); + const named = await env.tool('set_email_sender_name').exec({ worker: 'api', name: 'Shop Support' }, st); + check('domain: the sender name renames its app too', named.success && env.appAt(DOMAIN).title === 'Shop Support', JSON.stringify(named)); + const again = await SB.claimDomain(DOMAIN, 'Shop', 'c1'); + check('domain: attaching it again keeps its app and keys', again && again.uid === app.uid && env.stores.get(app.uid).get('secret:STRIPE_SECRET_KEY') === LIVE_KEY); + const other = await SB.claimDomain(DOMAIN, 'Other', 'c2'); + check('domain: another project taking it gets a new app of its own', + other && other.uid !== app.uid && env.appAt(DOMAIN).uid === other.uid && env.appAt(DOMAIN).title === 'Other' && (await SB.projectOf(DOMAIN)) === 'c2'); + check('…and the old app goes, its keys first', ![...env.apps.values()].some((a) => a.uid === app.uid) && !env.stores.get(app.uid).has('secret:STRIPE_SECRET_KEY')); +} +{ + // Something ran on the domain before it was attached, so Puter made its app. + const env = makeEnv({ files: LIVE_FILES, sites: { [DOMAIN_ORIGIN]: RELEASE }, domains: DOMAINS, apps: [DOMAIN_ORIGIN] }); + const SB = env.win.SiteBackends; + const PUTER_DOMAIN_APP = env.uidFor(DOMAIN_ORIGIN); + env.granted.add(PUTER_DOMAIN_APP); + env.stores.set(PUTER_DOMAIN_APP, new Map([['secret:OLD', 'x'], ['secret-names', ['OLD']]])); + check('domain: one Puter made stays on Puter\'s app', (await SB.claimDomain(DOMAIN, 'Shop', 'c1')) === null && env.appAt(DOMAIN).uid === PUTER_DOMAIN_APP); + check('…with the keys it had cleared', !env.stores.get(PUTER_DOMAIN_APP).has('secret:OLD')); + check('domain: Puter\'s app is still found, for its keys', (await SB.appUidOf(DOMAIN)) === PUTER_DOMAIN_APP); + await env.registerBoth(); + const named = await env.tool('set_email_sender_name').exec({ worker: 'api', name: 'Shop Support' }, st); + check('domain: the sender name sends the user to the Dev Center for it', named.success && /Dev Center/.test(named.note) && named.note.includes(PUTER_DOMAIN_APP), JSON.stringify(named)); +} +{ + // The domain goes on a site already published, where the preview has a + // test key and the live site its own live one, and something ran on the + // domain before, so it runs as Puter's app. + const env = makeEnv({ files: LIVE_FILES, sites: { [DOMAIN_ORIGIN]: RELEASE }, apps: [DOMAIN_ORIGIN] }); + const SB = env.win.SiteBackends; + const PUTER_DOMAIN_APP = env.uidFor(DOMAIN_ORIGIN); + await env.registerBoth(); + await env.tool('set_secret').exec({ worker: 'api', name: 'STRIPE_SECRET_KEY', value: KEY, live: false }, st); + await env.ui.publishSiteBackends(PREVIEW, LIVE, RELEASE, []); + await env.tool('set_secret').exec({ worker: 'api', name: 'STRIPE_SECRET_KEY', value: LIVE_KEY, live: true }, st); + env.prompts.length = 0; + await SB.claimDomain(DOMAIN, 'Shop', 'c1'); + const got = await env.ui.attachSiteBackends(LIVE, DOMAIN, RELEASE); + check('attach: the domain gets the live site\'s keys, asking once for the app it runs as', + got && got.ok && env.stores.get(PUTER_DOMAIN_APP)?.get('secret:STRIPE_SECRET_KEY') === LIVE_KEY && env.prompts.join(',') === PUTER_DOMAIN_APP, JSON.stringify(got)); + check('…its live key kept as its own, so a publish leaves it', JSON.stringify(env.stores.get(PUTER_DOMAIN_APP).get('secret-live-only')) === '["STRIPE_SECRET_KEY"]'); + await env.ui.publishSiteBackends(PREVIEW, LIVE, RELEASE, [DOMAIN]); + check('…and the next publish does', env.stores.get(PUTER_DOMAIN_APP).get('secret:STRIPE_SECRET_KEY') === LIVE_KEY); + check('attach: a release with no backend has nothing to give', (await env.ui.attachSiteBackends(LIVE, DOMAIN, '/u/AppData/b/.published/c1/r_none')) === null); +} +{ + // A fresh domain on a published site runs as the app Builder claimed for it. + const env = makeEnv({ files: LIVE_FILES, sites: { [DOMAIN_ORIGIN]: RELEASE } }); + await env.registerBoth(); + await env.tool('set_secret').exec({ worker: 'api', name: 'STRIPE_SECRET_KEY', value: KEY, live: false }, st); + await env.ui.publishSiteBackends(PREVIEW, LIVE, RELEASE, []); + const app = await env.win.SiteBackends.claimDomain(DOMAIN, 'Shop', 'c1'); + const got = await env.ui.attachSiteBackends(LIVE, DOMAIN, RELEASE); + check('attach: a fresh domain\'s app gets them too', app && got && got.ok && env.stores.get(app.uid)?.get('secret:STRIPE_SECRET_KEY') === KEY, JSON.stringify(got)); +} +{ + const app = read('../src/js/app.js'); + const del = app.slice(app.indexOf('async function deleteChat('), app.indexOf('async function deleteChat(') + 9000); + check('delete: the domain\'s app goes with the project, unless another project has it now', + /const domainUrls = \(window\.CustomDomain\?\.list\(chat\?\.publishedDomains\)/.test(del) && /\[chat\?\.previewUrl, chat\?\.publishedUrl, \.\.\.domainUrls\]/.test(del) + && /!\[null, chatId\]\.includes\(await SB\.projectOf\(u\)\)\) return;/.test(del)); + const connect = UI_SRC.slice(UI_SRC.indexOf('function connectCustomDomain('), UI_SRC.indexOf('async function releaseCustomDomainElsewhere(')); + check('attach: a dynamic project claims the domain\'s app as soon as it\'s chosen, read before the dialog', + connect.indexOf('const dynamic = !!window.SiteBackends?.isDynamicProject(chatHistory);') > 0 + && connect.indexOf('const dynamic = !!window.SiteBackends?.isDynamicProject(chatHistory);') < connect.indexOf('puter.hosting.attach(sub)') + && /chosen = domain;[\s\S]{0,400}if \(dynamic\) await window\.SiteBackends\.claimDomain\('https:\/\/' \+ domain\.hostname \+ '\/', window\.SiteBackends\.titleOf\(chatId\), chatId\);\s*_domainNotYet/.test(connect)); + check('attach: a domain on the published site gets its backends\' keys once it\'s saved, the site read before the dialog', + connect.indexOf("const liveUrl = previewSubdomain(window.currentPublishedUrl) === sub ? window.currentPublishedUrl : null;") > 0 + && connect.indexOf('const liveUrl') < connect.indexOf('puter.hosting.attach(sub)') + && connect.indexOf('const liveDir = liveUrl ? window.currentPublishedPath : null;') > 0 + && /await updatePublishedDomains\(chatId[\s\S]{0,200}if \(liveDir\) await attachSiteBackends\(liveUrl, 'https:\/\/' \+ domain\.hostname \+ '\/', liveDir\);/.test(connect)); + check('publish: the live site\'s domains get the keys on every publish', + (UI_SRC.match(/publishSiteBackends\(startPreviewUrl, url, releaseDir, domainUrlsOf\((sub|existingSub)\)\)/g) || []).length === 3); +} + +// --- the prompt --- +{ + const prompt = (flag) => { + const window = { FEATURE_FLAGS: { dynamicWorkers: flag, clickToEdit: true, createdWithBadge: true, webManifest: true } }; + new Function('window', read('../src/js/prompt.js'))(window); + return window.system_prompt_common(); + }; + const on = prompt(true); + const off = prompt(false); + check('prompt: the AI writes backends to __workers', /__workers\/\.worker\.js/.test(on) && /no create_worker tool/.test(on)); + check('prompt: pages call a backend by its relative path', /fetch\('\/__workers\/api\/items'\)/.test(on) && /never with a full address/.test(on)); + check('prompt: create_worker is no longer the way to make one', !/Deploy each worker once with create_worker/.test(on)); + check('prompt: pages never read a key', /never read a secret: key from browser code/.test(on)); + check('prompt: the default sender name is the project\'s name', /sender name is its project's name/.test(on)); + check('prompt: the user\'s own domain has its own store, and live keys reach it', /own domain on the published site runs its backends too/.test(on) + && /gets the live site's keys when it's connected and on each publish/.test(on) && !/own domain on the published site/.test(off)); + check('prompt: the flag off keeps the create_worker rules', /Deploy each worker once with create_worker/.test(off) && !/__workers/.test(off) && /sandbox-/.test(off)); +} + +// --- a template fork's note --- +{ + const { win } = makeEnv(); + const note = win.TemplateCore.buildTemplateNote({ + name: 'Feedback Board', appDir: ROOT, files: ['index.html', '__workers/api.worker.js'], previewUrl: PREVIEW, + workers: [{ templateName: 'api', name: 'api', url: '/__workers/api', dynamic: true }], + }); + check('template: the note points at the backend file and its path', note.includes(`${ROOT}/__workers/api.worker.js`) && note.includes('call at /__workers/api')); + check('template: and never at create_worker', !/create_worker/.test(note)); +} + +// --- the mark never reaches the AI --- +{ + const vm = await import('node:vm'); + const coreBox = { window: {} }; + vm.createContext(coreBox); + vm.runInContext(read('../src/js/model-core.js'), coreBox); + const HELP_SRC = read('../src/js/helpers.js'); + const prep = new Function('window', slice(HELP_SRC, 'function prepareHistoryForAI(', '/**\n * Sum the AI-reported cost', 'prepareHistoryForAI') + + '\nreturn prepareHistoryForAI;')({ ModelCore: coreBox.window.ModelCore }); + const history = [{ role: 'system', content: [{ type: 'text', text: 'common' }], dynamicWorkers: true }, { role: 'user', content: 'hi' }]; + const sent = prep(history); + check('history: the mark is stripped before sending', !JSON.stringify(sent).includes('dynamicWorkers')); + check('history: and kept on the saved project', history[0].dynamicWorkers === true); +} + +if (failures) { console.error(`\n${failures} check(s) failed`); process.exit(1); } +console.log('\nAll site-backends checks passed'); diff --git a/scripts/test-social-images.mjs b/scripts/test-social-images.mjs index 76c0d27a..14a6f40e 100644 --- a/scripts/test-social-images.mjs +++ b/scripts/test-social-images.mjs @@ -68,15 +68,15 @@ check('the module is in the bundle, before ui.js', vite.includes("'js/social-images.js'") && vite.indexOf("'js/social-images.js'") < vite.indexOf("'js/ui.js'")); const publish = ui.slice(ui.indexOf('async function doPublish('), ui.indexOf('async function loadPublishedSiteMeta(')); check('a first publish fills in the new address once it exists', - /url = `https:\/\/\$\{sub\}\.puter\.site\/`;\s*await absolutizeSocialImagesInRelease\(releaseDir, url, \[startPreviewUrl\]\);/.test(publish)); + /url = `https:\/\/\$\{sub\}\.puter\.site\/`;[\s\S]{0,600}?await absolutizeSocialImagesInRelease\(releaseDir, url, \[startPreviewUrl\]\);/.test(publish)); check('a re-publish fills it in before the address serves the release', /await absolutizeSocialImagesInRelease\(releaseDir, url, \[startPreviewUrl\]\);\s*await puter\.hosting\.update\(existingSub, releaseDir\);/.test(publish)); const captures = publish.slice(publish.indexOf('const startUrl = window.currentPublishedUrl;'), publish.indexOf('const startPreviewUrl = window.currentPreviewUrl')); check('the preview address is read with the publish address, before a project switch can change it', captures.length > 0 && !/\bawait\b/.test(captures.replace(/\/\/[^\n]*/g, ''))); check('both address editors move the URLs after the new address exists', - /await puter\.hosting\.create\(newSub, path\);\s*const newUrl = `https:\/\/\$\{newSub\}\.puter\.site\/`;\s*[^\n]*\n\s*await absolutizeSocialImagesInRelease\(path, newUrl, \[oldUrl\]\);/.test(ui) - && /await puter\.hosting\.create\(newSub, path\);\s*(?:\/\/[^\n]*\n\s*)+await absolutizeSocialImagesInRelease\(path, `https:\/\/\$\{newSub\}\.puter\.site\/`, \[pub\.url\]\);/.test(ui)); + /await puter\.hosting\.create\(newSub, path\);\s*const newUrl = `https:\/\/\$\{newSub\}\.puter\.site\/`;[\s\S]{0,400}?await absolutizeSocialImagesInRelease\(path, newUrl, \[oldUrl\]\);/.test(ui) + && /await puter\.hosting\.create\(newSub, path\);[\s\S]{0,400}?await absolutizeSocialImagesInRelease\(path, `https:\/\/\$\{newSub\}\.puter\.site\/`, \[pub\.url\]\);/.test(ui)); const prompt = read('../src/js/prompt.js'); check('the prompt has the AI write a relative path', /og:image and twitter:image at the PNG with a relative path/.test(prompt)); diff --git a/scripts/test-worker-save-canary.mjs b/scripts/test-worker-save-canary.mjs index 21b096e8..9df1594f 100644 --- a/scripts/test-worker-save-canary.mjs +++ b/scripts/test-worker-save-canary.mjs @@ -47,6 +47,8 @@ let LIST_THROWS = false; const SERVED = new Map(); let PROPAGATION_READS = 0; let DEPLOYS = true; // false: Puter keeps the previous code (a save it rejected) +const DOWN = new Set(); // workers answering Puter's 404, as after a site update +const SCRIPT = new Map(); // a worker's canary answers read by read (watchSiteBackends) let pending = null; const calls = { listed: 0, created: 0, canaryReads: 0 }; const reset = () => { @@ -79,6 +81,15 @@ async function fakeFetch(url) { const base = url.slice(0, url.indexOf('/__builder/canary')); if (url.indexOf('/__builder/canary?') === -1) throw new Error('unexpected fetch ' + url); calls.canaryReads++; + if (SCRIPT.has(base)) { + // A scripted run of answers, one per read, the last one repeating. + const run = SCRIPT.get(base); + const answer = run.length > 1 ? run.shift() : run[0]; + if (answer === 404) return { ok: false, text: async () => 'Worker not found' }; + if (answer === 500) return { ok: false, text: async () => 'Internal error' }; + return { ok: true, text: async () => answer }; + } + if (DOWN.has(base)) return { ok: false, text: async () => 'Worker not found' }; if (pending && pending.url === base) { if (pending.reads-- <= 0) { SERVED.set(base, pending.token); pending = null; } } @@ -282,6 +293,69 @@ reset(); && parseInt(t.slice(0, 9), 36) <= Date.now() && parseInt(t.slice(0, 9), 36) > Date.now() - 5000, t); } +// === "Applying changes" while the save goes live ============================ +// The AI's save says so beside the dots and over the preview, as a refresh +// does, since the preview's backend runs the previous code until then. +{ + const events = []; + let refreshing = false; + win.setSpinnerLabel = (t) => events.push('label:' + t); + win.showPreviewUpdating = (on) => events.push((on ? 'overlay:on@' : 'overlay:off@') + calls.canaryReads); + win.isStaleTurn = (s) => !!(s && s.stale); + win.previewRefreshInFlight = () => refreshing; + + reset(); + FILES.set(API, v1); + PROPAGATION_READS = 2; + let r = await tool('edit').exec({ path: API, old_content: "'one'", new_content: "'six'" }, { appDir: ROOT }); + check('an AI save says "Applying changes" and covers the preview before its first canary read', + r.worker && r.worker.live === true && events[0] === 'label:Applying changes' && events[1] === 'overlay:on@0', JSON.stringify(events)); + check('…and uncovers it once the backend serves the save', events.length === 3 && events[2] === 'overlay:off@3', JSON.stringify(events)); + + events.length = 0; + reset(); + DEPLOYS = false; + r = await tool('write').exec({ path: API, data: v1 }, { appDir: ROOT }); + check('a save not live by the limit uncovers it too', r.worker && r.worker.live === false && events[events.length - 1].startsWith('overlay:off@'), JSON.stringify(events)); + + events.length = 0; + reset(); + r = await tool('write').exec({ path: API, data: 'await Promise.resolve();\n' + v1 }, { appDir: ROOT }); + check('a save that doesn\'t compile has nothing to wait for, so shows nothing', r.worker && r.worker.live === false && events.length === 0, JSON.stringify(events)); + + events.length = 0; + reset(); + const later = { appDir: ROOT, laterToolCalls: [{ name: 'write', input: { path: API } }] }; + await tool('write').exec({ path: API, data: v1 }, later); + check('a save the same reply makes again shows nothing', events.length === 0, JSON.stringify(events)); + + events.length = 0; + reset(); + await win.workerSaveResult({ name: 'api', url: 'https://api.puter.work', token: '00000000c' + 'cccccc' }, v1); + check('a Code view save or a GitHub pull (no turn) shows nothing', events.length === 0, JSON.stringify(events)); + + events.length = 0; + reset(); + await tool('write').exec({ path: API, data: v1 }, { appDir: ROOT, stale: true }); + check('a turn whose project is no longer open shows nothing', events.length === 0, JSON.stringify(events)); + + events.length = 0; + reset(); + DEPLOYS = false; + const turn = { appDir: ROOT }; + setTimeout(() => { turn.stale = true; }, 10); + await tool('write').exec({ path: API, data: v1 }, turn); + check('…nor takes the overlay off another project opened during the wait', events.length === 2 && events[1] === 'overlay:on@0', JSON.stringify(events)); + + events.length = 0; + reset(); + refreshing = true; + await tool('write').exec({ path: API, data: v1 }, { appDir: ROOT }); + check('a refresh under way when the save goes live keeps its overlay', events.length === 2 && events[1] === 'overlay:on@0', JSON.stringify(events)); + + delete win.setSpinnerLabel; delete win.showPreviewUpdating; delete win.isStaleTurn; delete win.previewRefreshInFlight; +} + // === multi_edit and write ==================================================== reset(); FILES.set(API, v1); @@ -376,6 +450,200 @@ WORKERS = []; sync.includes('window.workerSaveResult?.(s.worker, s.code)') && !/redeployWorkerSource|workers\.create/.test(sync)); } +// === a failed request while a worker switches over ============================ +// A page's request to a worker that isn't serving its latest save yet can fail +// for that alone, so the preview's error checks drop it (backendStillSwitching). +reset(); +WORKERS = [own('api')]; +FILES.set(API, v1); +{ + const r = await tool('write').exec({ path: API, data: v1.replace('one', 'five') }, st); + check('switching: a save goes live', r.worker && r.worker.live === true); + reset(); + check('switching: a failure once the worker serves its latest save counts, read from its canary', + (await win.backendStillSwitching('https://api.puter.work/items')) === false && calls.canaryReads === 1); + // Any update of a site redeploys its dynamic backends, so a worker that + // was up can be down again. + DOWN.add('https://api.puter.work'); + check('switching: a failure while the worker is down again is expected', (await win.backendStillSwitching('https://api.puter.work/items')) === true); + DOWN.delete('https://api.puter.work'); + check('…and counts once it\'s back', (await win.backendStillSwitching('https://api.puter.work/items')) === false); +} +reset(); +DEPLOYS = false; +{ + const r = await tool('write').exec({ path: API, data: v1.replace('one', 'six') }, st); + check('switching: a save the worker isn\'t serving yet', r.worker && r.worker.live === false); + reset(); + DEPLOYS = false; + const [a, b] = await Promise.all([win.backendStillSwitching('https://api.puter.work/items'), win.backendStillSwitching('https://api.puter.work/items?t=2')]); + check('switching: a failure meanwhile is expected', a === true && b === true); + check('…read from its canary once for failures at the same moment', calls.canaryReads === 1, String(calls.canaryReads)); + check('switching: the worker\'s address itself, and a relative path on the preview, count too', + (await win.backendStillSwitching('https://api.puter.work')) === true + && await (async () => { win.currentPreviewUrl = 'https://api.puter.work/'; try { return await win.backendStillSwitching('/items'); } finally { delete win.currentPreviewUrl; } })()); + check('switching: a failure anywhere else counts', + (await win.backendStillSwitching('https://api2.puter.work/items')) === false && (await win.backendStillSwitching('https://example.com/api.puter.work/x')) === false + && (await win.backendStillSwitching('/items')) === false && (await win.backendStillSwitching('')) === false); + SERVED.set('https://api.puter.work', tokenOf(FILES.get(API))); + check('switching: once its canary shows the save, failures count', (await win.backendStillSwitching('https://api.puter.work/items')) === false); +} +reset(); +DEPLOYS = false; +{ + // Puter never deploys a save that doesn't parse, so the worker isn't + // switching to it, and keeps the previous code it already serves. + await tool('write').exec({ path: API, data: v1 + '\n}' }, st); + reset(); + check('switching: a save that doesn\'t parse leaves failures counting', + (await win.backendStillSwitching('https://api.puter.work/items')) === false); +} +{ + // A dynamic backend of the open preview this tab never saved: its latest + // save is the one stamped in its file. + const SITE = 'https://preview-q.puter.site'; + const FILE = `${ROOT}/__workers/feed.worker.js`; + const saved = { SiteBackends: win.SiteBackends, url: win.currentPreviewUrl, path: win.currentPreviewPath }; + win.SiteBackends = { FOLDER: '__workers', SUFFIX: '.worker.js', validName: (n) => /^[a-z0-9_-]+$/.test(n) }; + win.currentPreviewUrl = SITE + '/'; + win.currentPreviewPath = ROOT; + try { + FILES.set(FILE, win.stampWorkerCanary(v1, '00000000zfeed01')); + SERVED.set(SITE + '/__workers/feed', '00000000zfeed00'); + check('unsaved here: a preview backend not yet serving the save in its file is switching', + (await win.backendStillSwitching('/__workers/feed/items')) === true); + SERVED.set(SITE + '/__workers/feed', '00000000zfeed01'); + check('unsaved here: …and counts once it serves it', (await win.backendStillSwitching('/__workers/feed/items')) === false); + DOWN.add(SITE + '/__workers/feed'); + check('unsaved here: …and is expected to fail while it\'s down after a site update', + (await win.backendStillSwitching(SITE + '/__workers/feed/items')) === true); + DOWN.delete(SITE + '/__workers/feed'); + FILES.set(FILE, v1); + check('unsaved here: a file with no canary leaves failures counting', (await win.backendStillSwitching('/__workers/feed/items')) === false); + FILES.set(FILE, win.stampWorkerCanary(v1 + '\n}', '00000000zfeed02')); + check('unsaved here: …and so does one that doesn\'t parse, which Puter never runs', (await win.backendStillSwitching('/__workers/feed/items')) === false); + FILES.delete(FILE); + check('unsaved here: …and a backend with no file, or a path that isn\'t a backend', + (await win.backendStillSwitching('/__workers/feed/items')) === false && (await win.backendStillSwitching('/__workers/Bad!/x')) === false + && (await win.backendStillSwitching('/api/items')) === false); + } finally { + Object.assign(win, saved); + if (saved.SiteBackends === undefined) delete win.SiteBackends; + if (saved.url === undefined) delete win.currentPreviewUrl; + if (saved.path === undefined) delete win.currentPreviewPath; + } +} + +// === which calls only save a backend ========================================= +// A turn whose only changes were these skips the preview's clear (see +// pagesUnchanged in ui.js). +{ + const saved = win.SiteBackends; + let dynamic = true; + win.SiteBackends = { siteOf: () => (dynamic ? { servedDir: ROOT } : null), + nameOf: (rel) => (/^__workers\/([a-z0-9_-]+)\.worker\.js$/.exec(rel) || [])[1] || null }; + const call = (name, path) => ({ name, input: { path } }); + const B = `${ROOT}/__workers/api.worker.js`; + try { + check('backend save: an edit, multi_edit or write of a backend file', + ['edit', 'multi_edit', 'write'].every((n) => win.isBackendSaveCall(call(n, B), st))); + check('backend save: …not a page, a file in a subfolder of __workers, or another file there', + !win.isBackendSaveCall(call('edit', `${ROOT}/index.html`), st) && !win.isBackendSaveCall(call('write', `${ROOT}/__workers/lib/x.worker.js`), st) + && !win.isBackendSaveCall(call('write', `${ROOT}/__workers/notes.md`), st)); + check('backend save: …nor a delete, move or copy of one', + ['delete', 'move', 'copy', 'rename'].every((n) => !win.isBackendSaveCall(call(n, B), st))); + check('backend save: …nor a path outside the project, or a call with no path', + !win.isBackendSaveCall(call('write', `${OTHER}/__workers/api.worker.js`), st) && !win.isBackendSaveCall({ name: 'write', input: {} }, st) + && !win.isBackendSaveCall(null, st)); + dynamic = false; + check('backend save: …nor anything in a project without dynamic backends', !win.isBackendSaveCall(call('edit', B), st)); + } finally { + if (saved === undefined) delete win.SiteBackends; else win.SiteBackends = saved; + } +} + +// === waiting out the redeploy after a hosting.update ========================== +// The update redeploys a site's backends with no file changed, so each keeps +// its canary token. Each goes down a few seconds later (404, then 500) and +// comes back, and the preview's reload waits until it has. +{ + const SITE = 'https://preview-w.puter.site'; + const DIR = `${ROOT}`; + const saved = { SiteBackends: win.SiteBackends }; + const T = win.workerCanaryTiming; + const timing = { ...T }; + Object.assign(T, { redeployPollMs: 1, redeployDownMs: 60, redeploySettleMs: 15, limitMs: 400 }); + const tokens = { a: '00000000zwaita1', b: '00000000zwaitb1' }; + let names = ['a']; + win.SiteBackends = { FOLDER: '__workers', SUFFIX: '.worker.js', validName: (n) => /^[a-z0-9_-]+$/.test(n), + list: async () => names.map((name) => ({ name })), urlOf: (u, n) => u.replace(/\/+$/, '') + '/__workers/' + n }; + for (const n of ['a', 'b']) FILES.set(`${DIR}/__workers/${n}.worker.js`, win.stampWorkerCanary(v1, tokens[n])); + const base = (n) => SITE + '/__workers/' + n; + const run = async (live = () => true) => { + const wait = await win.watchSiteBackends(SITE + '/', DIR); + const t = Date.now(); + const r = await wait(live); + return { r, ms: Date.now() - t }; + }; + try { + // Up before, up a while after the update, then down and back. + SCRIPT.set(base('a'), [tokens.a, tokens.a, tokens.a, 404, 404, 500, 500, tokens.a]); + const cycle = await run(); + check('redeploy: the reload waits until the backend has gone down and come back', cycle.r === true && SCRIPT.get(base('a')).length === 1, JSON.stringify(cycle)); + // Never goes down: waited on only for redeployDownMs. + SCRIPT.set(base('a'), [tokens.a]); + const untouched = await run(); + check('redeploy: a backend that never goes down is waited on only for a while', untouched.r === true && untouched.ms >= 55 && untouched.ms < 200, JSON.stringify(untouched)); + // Back for a moment between the 404 and the 500: not over yet. + SCRIPT.set(base('a'), [tokens.a, 404, tokens.a, 500, 500, tokens.a]); + const flap = await run(); + check('redeploy: …and back for a moment between the 404 and the 500 isn\'t back yet', flap.r === true && SCRIPT.get(base('a')).length === 1, JSON.stringify(flap)); + // Already down before the update: not waited on, it may never come up. + SCRIPT.set(base('a'), [500]); + const broken = await run(); + check('redeploy: a backend already down before the update isn\'t waited on', broken.r === true && broken.ms < 20, JSON.stringify(broken)); + // Serving an older save before the update counts as not up either. + SCRIPT.set(base('a'), ['00000000zwaita0']); + check('redeploy: …nor one still serving an older save', (await run()).ms < 20); + // Still down at the limit. + SCRIPT.set(base('a'), [tokens.a, 404]); + const stuck = await run(); + check('redeploy: a backend still down at the limit gives up', stuck.r === false && stuck.ms >= 390, JSON.stringify(stuck)); + // A refresh that's superseded stops at once. + SCRIPT.set(base('a'), [tokens.a, 404]); + let alive = true; + setTimeout(() => { alive = false; }, 20); + const stopped = await run(() => alive); + check('redeploy: a superseded refresh stops waiting', stopped.r === null && stopped.ms < 100, JSON.stringify(stopped)); + // Two backends: the wait is for both. + names = ['a', 'b']; + SCRIPT.set(base('a'), [tokens.a, 404, tokens.a]); + SCRIPT.set(base('b'), [tokens.b, tokens.b, tokens.b, tokens.b, tokens.b, 404, 404, 500, tokens.b]); + const both = await run(); + check('redeploy: with two backends it waits for both', both.r === true && SCRIPT.get(base('b')).length === 1, JSON.stringify(both)); + // Nothing to wait for. + names = []; + check('redeploy: a site with no backends has nothing to wait for', (await run()).r === true); + win.SiteBackends = undefined; + check('redeploy: …nor does one without the backend helpers', (await run()).r === true); + } finally { + Object.assign(T, timing); + SCRIPT.clear(); + if (saved.SiteBackends === undefined) delete win.SiteBackends; else win.SiteBackends = saved.SiteBackends; + for (const n of ['a', 'b']) FILES.delete(`${DIR}/__workers/${n}.worker.js`); + } +} +{ + const ui = read('../src/js/ui.js'); + const clear = ui.slice(ui.indexOf('async function waitForPreviewClear('), ui.indexOf('// ---- Clearing early')); + check('redeploy: the preview refresh reads the backends before its update and waits for them after it', + clear.indexOf('window.watchSiteBackends(baseUrl, dir)') > 0 + && clear.indexOf('window.watchSiteBackends(baseUrl, dir)') < clear.indexOf('await puter.hosting.update(sub, dir);') + && /await puter\.hosting\.update\(sub, dir\);[\s\S]{0,120}if \(wait\) backendsBack = wait\(live\);/.test(clear) + && clear.indexOf('const back = await backendsBack;') > clear.indexOf("log(flipped ? 'cleared'") + && /if \(back === null \|\| !live\(\)\) return null;/.test(clear)); +} + // === what the model is told ================================================= { const desc = tool('create_worker').function.description; diff --git a/src/js/app.js b/src/js/app.js index bba8741f..89476dcc 100644 --- a/src/js/app.js +++ b/src/js/app.js @@ -1341,6 +1341,9 @@ async function loadChat(chatId, { urlMode = 'push', preloaded = null } = {}) { // below. terminateActiveTurn(); resetChatUIForSwitch(); + // Its files may have changed anywhere since this tab last cleared its + // preview, so its first refresh clears (pagesUnchanged in ui.js). + window.notePagesChanged?.(chatId); const chat = preloaded || JSON.parse(await puter.fs.read(`chat-history/${chatId}.json`).then(data => data.text())); @@ -1832,6 +1835,33 @@ async function deleteChat(chatId) { // and left behind it held one of the account's sites. const reservedSub = window.reservedPublishName?.(chatId); if (reservedSub) subsToDelete.add(reservedSub); + // A site's app and its store outlive the site (see site-backends.js). + // The keys a dynamic backend kept there go first, best effort like a + // worker's below, then the app Builder registered for the site, so no + // later site at that address runs as it. A folder that can't be read + // counts as holding a backend, since clearing never asks anything. + const SB = window.SiteBackends; + if (SB) { + let hasSiteBackends = false; + try { hasSiteBackends = (await SB.list(`/${window.user.username}/AppData/${puter.appID}/${chatId}`)).length > 0; } + catch (e) { hasSiteBackends = true; } + // The user's own domain runs the live site's backends as an app + // of its own, which goes with the project, unless the domain has + // since moved to another project, whose app it is now. + const domainUrls = (window.CustomDomain?.list(chat?.publishedDomains) || []).map(d => 'https://' + d.hostname + '/'); + for (const u of new Set([chat?.previewUrl, chat?.publishedUrl, ...domainUrls].filter(Boolean))) { + // A lookup that fails counts as unfinished, like a failed + // delete, so a retry still finds the app. + await cleanup(`the app of ${u.replace(/^https:\/\//, '').replace(/\/+$/, '')}`, async () => { + if (domainUrls.includes(u) && ![null, chatId].includes(await SB.projectOf(u))) return; + const registered = await SB.hasApp(u); + if (registered || hasSiteBackends) { + try { await window.WorkerSecrets?.clear({ site: u }); } catch (e) { /* best effort */ } + } + if (registered) await SB.deleteApp(u); + }); + } + } for (const sub of subsToDelete) { await cleanup(`the site ${sub}.puter.site`, () => puter.hosting.delete(sub)); } @@ -2255,6 +2285,12 @@ async function duplicateChat(chatId) { // aren't its own. unpublishCopiedHistory(finalHistory, origPublishedUrl); + // The copy's name: "X copy", then "X copy 2", "X copy 3"… + const baseTitle = source.title || savedChats.find(c => c.id === chatId)?.title || 'Untitled'; + const taken = new Set(savedChats.map(c => c.title || '')); + let newTitle = `${baseTitle} copy`; + for (let n = 2; taken.has(newTitle); n++) newTitle = `${baseTitle} copy ${n}`; + // --- Publish the copy to its OWN subdomain (if the source was live) - let newPreviewUrl = null, newPreviewPath = null; if (filesCopied && origPreviewUrl) { @@ -2268,20 +2304,42 @@ async function duplicateChat(chatId) { copySubdomain = site.subdomain; newPreviewUrl = `https://${site.subdomain}.puter.site/`; newPreviewPath = publishRoot; + // A project with dynamic backends runs its preview as an app + // Builder registers now, before anything runs there (see + // site-backends.js). The copy is that kind if the original is. + if (window.SiteBackends?.isDynamicProject(clonedHistory)) { + await window.SiteBackends.registerApp(newPreviewUrl, newTitle, 'preview'); + } } catch (e) { // Publishing failed — keep the copy unpublished rather than // aborting the whole duplication; the user can republish later. console.warn('Duplicate: could not publish the copy:', e); } } + // The copy's dynamic backends run on its own new preview, whose store + // starts empty (see site-backends.js). They get the original's keys + // and sender name, and a copy without them still works except for the + // calls that need them, so this never fails the duplicate. + if (newPreviewUrl && origPreviewUrl && window.SiteBackends) { + let backends = []; + try { backends = (await window.SiteBackends.list(newPreviewPath)).map(b => b.name); } + catch (e) { /* no backends to set up */ } + if (backends.length) { + const to = { site: newPreviewUrl, backends }; + try { + const keys = await window.WorkerSecrets?.copy({ site: origPreviewUrl }, to); + if (keys && !keys.ok) { + window.showToast?.('The copy’s backend didn’t get the original’s keys. Ask the AI in the copy to set them up again.', + { type: 'warning', key: 'duplicate-keys', throttleMs: 5000 }); + } + } catch (e) { /* the warning above covers it */ } + try { await window.WorkerSender?.copy({ site: origPreviewUrl }, to); } + catch (e) { /* the copy still sends, under the default name */ } + } + } // --- Persist the new chat ------------------------------------------- const now = new Date().toISOString(); - const baseTitle = source.title || savedChats.find(c => c.id === chatId)?.title || 'Untitled'; - // Disambiguate repeated copies: "X copy", then "X copy 2", "X copy 3"… - const taken = new Set(savedChats.map(c => c.title || '')); - let newTitle = `${baseTitle} copy`; - for (let n = 2; taken.has(newTitle); n++) newTitle = `${baseTitle} copy ${n}`; // Flag the name as customTitle so neither the first-message title // generator nor the AI auto-namer overwrites it (the copy shares the // original's first user message): the copy keeps its "… copy" name until @@ -2353,6 +2411,10 @@ async function duplicateChat(chatId) { // site limit, and every retry would leak another set. Take them back. if (!copySaved && newAppDir) { if (copySubdomain) { + // Its app first (see site-backends.js), while the site still + // says which one it is. + try { await window.SiteBackends?.deleteApp(`https://${copySubdomain}.puter.site/`); } + catch (e) { console.warn('Duplicate: could not remove the app of the copy’s site:', e); } try { await puter.hosting.delete(copySubdomain); } catch (e) { console.warn('Duplicate: could not remove the copy’s site:', e); } } @@ -2374,6 +2436,20 @@ window.duplicateChat = duplicateChat; // synchronously (before the first await) so callers can render the new title // optimistically; the on-disk chat-list index and the per-chat file (the latter // is what list recovery rebuilds from) are then persisted in the background. +// The apps of a project's sites follow its name (site-backends.js). The open +// project's addresses are read live as well, since a preview made this turn +// isn't in its list entry until the turn's save. +function retitleProjectApps(chatId, entry, title) { + const urls = [entry && entry.previewUrl, entry && entry.publishedUrl]; + // And its own domain's (custom-domain.js). + if (entry && entry.publishedDomainHost) urls.push('https://' + entry.publishedDomainHost + '/'); + if (chatId === currentChatId) { + urls.push(window.currentPreviewUrl, window.currentPublishedUrl); + for (const d of window.CustomDomain?.list(window.currentPublishedDomains) || []) urls.push('https://' + d.hostname + '/'); + } + for (const u of new Set(urls.filter(Boolean))) void window.SiteBackends?.retitle(u, title); +} + async function renameChat(chatId, newTitle) { // Clamp to a sensible length (defense-in-depth beyond the editor's maxlength, // since a programmatic caller or paste could exceed it); trim again after the @@ -2389,6 +2465,7 @@ async function renameChat(chatId, newTitle) { savedChats[idx].customTitle = true; // Reflect the rename in the tab title too (optimistically, like the sidebar). if (chatId === currentChatId) updateDocumentTitle(); + retitleProjectApps(chatId, savedChats[idx], title); // Mirror the title into the per-chat file so it survives a chat-list rebuild // (recoverChatListFromFiles reads titles from these files). Read-modify-write @@ -3053,6 +3130,9 @@ async function initAuthenticatedState() { { type: "text", text: window.system_prompt_dynamic(currentAppDir) } ] }; + // A project made now gets dynamic backends when the flag is on, and keeps + // them, like the instructions above (see site-backends.js). + window.SiteBackends?.markNewProject(system_prompt); chatHistory = [system_prompt]; window.ModelPicker?.render?.(); @@ -3671,6 +3751,7 @@ function new_chat({ updateUrl = true } = {}) { { type: "text", text: window.system_prompt_dynamic(currentAppDir) } ] }; + window.SiteBackends?.markNewProject(system_prompt); chatHistory = [system_prompt]; window._authInitDone = authReady; } @@ -5969,7 +6050,7 @@ async function sendChatMessage(userInput = null, skipAddToHistory = false, opts // Not from a turn stopped during the plan check above. A newer turn // may have started by then, and this one would take its place. if (!turnAbandoned()) window.BuildNotify?.turnStarted?.({ chatId: turnChatId, firstBuild: isFirstBuildTurn }); - const turnTools = window.getTurnTools(turnModel); + const turnTools = window.getTurnTools(turnModel, turnSaveContext.chatHistory); const turnUnavailableTools = window.getUnavailableTools?.(turnModel) || []; turnAccountRead = readTurnAccount().then(a => { turnAccount = a; }, () => {}); while (true) { @@ -6968,6 +7049,7 @@ async function applyAiProjectTitle(chatId, title) { savedChats[idx].aiTitled = true; // Reflect the AI-generated name in the tab title for the open project. if (chatId === currentChatId) updateDocumentTitle(); + retitleProjectApps(chatId, savedChats[idx], title); } // Mirror into the per-chat file so it survives a chat-list rebuild // (recoverChatListFromFiles reads titles from these files). Read-modify-write diff --git a/src/js/custom-domain.js b/src/js/custom-domain.js index dc31999b..4a5bb9c1 100644 --- a/src/js/custom-domain.js +++ b/src/js/custom-domain.js @@ -150,6 +150,15 @@ return url && url !== publishedUrl ? url : null; } + /** + * The addresses of the domains connected to the site at `sub`, whatever + * their state, since each runs the site's backends as an app of its own. + * A domain recorded against another name ('moved') serves another site. + */ + function urlsFor(saved, sub) { + return list(saved).map((d) => view(d, sub)).filter((v) => v && v.kind !== 'moved').map((v) => v.url); + } + /** * The hostname of a saved list's domain, whatever its state, or null. The * project list keeps it, so a domain another project takes is found there @@ -172,5 +181,5 @@ return !!a.lastModified && a.lastModified === b.lastModified; } - window.CustomDomain = { normalize, list, set, remove, markActive, markLost, view, waiting, liveUrl, domainUrl, hostOf, sameSite }; + window.CustomDomain = { normalize, list, set, remove, markActive, markLost, view, waiting, liveUrl, domainUrl, urlsFor, hostOf, sameSite }; })(); diff --git a/src/js/editor-core.js b/src/js/editor-core.js index 1c590845..6c6ac335 100644 --- a/src/js/editor-core.js +++ b/src/js/editor-core.js @@ -81,6 +81,9 @@ window.EditorCore = (function () { ]); // A deployed backend's source, as create_worker names it. const WORKER_SOURCE_RE = /^workers\/[A-Za-z0-9_-]{1,50}\.js$/; + // A dynamic backend, at the top of the folder the site serves (see + // site-backends.js). + const DYNAMIC_SOURCE_RE = /^__workers\/[a-z0-9_-]+\.worker\.js$/; // The icons manifest.js renders into /icons/. const GENERATED_ICON_RE = /^icons\/(?:icon-192|icon-512|maskable-512|apple-touch-icon-180)\.png$/; // What the Code view never shows, files and folders: old deploy markers @@ -111,7 +114,7 @@ window.EditorCore = (function () { kind, ext, language: kind === 'text' ? (LANGUAGE_BY_EXT[ext] || 'plain') : null, - backend: WORKER_SOURCE_RE.test(rel), + backend: WORKER_SOURCE_RE.test(rel) || DYNAMIC_SOURCE_RE.test(servedRel !== null ? servedRel : rel), generatedIcon: servedRel !== null && GENERATED_ICON_RE.test(servedRel), maybeGeneratedManifest: servedRel === 'manifest.json', hidden: isHidden(rel), diff --git a/src/js/helpers.js b/src/js/helpers.js index 98625e60..6ebf43ed 100644 --- a/src/js/helpers.js +++ b/src/js/helpers.js @@ -116,6 +116,14 @@ window.FEATURE_FLAGS = { // and goes one message per turn once the turn finishes cleanly. When // false the composer is locked for the whole turn, as before. messageQueue: true, + // Projects made while this is on build their backends as Puter dynamic + // workers: a file __workers/.worker.js in the folder the site + // serves, which Puter runs at /__workers// on that same site + // (js/site-backends.js). There is nothing to deploy, and the live site + // runs the copy in its release. A project keeps the kind it was made + // with, so projects made before keep create_worker, their named workers + // and the "-live" copies Publish deploys, whatever this says later. + dynamicWorkers: true, }; // Analytics. Fires a Plausible custom event for the handful of product actions @@ -1190,6 +1198,11 @@ function prepareHistoryForAI(historyArray, modelId, opts) { if ('buildModel' in msg) { delete msg.buildModel; } + // Whether the project has dynamic backends (site-backends.js), kept + // on its system message too; never sent. + if ('dynamicWorkers' in msg) { + delete msg.dynamicWorkers; + } // Bookkeeping fields that record the AI response cost + token usage on // assistant messages (see handleMessageStream / sumChatCostCents / // sumChatTokenUsage). They're for the project-info dialog only — strip @@ -2326,6 +2339,13 @@ window.stripWorkerCanary = function (text) { return text.replace(_WORKER_CANARY_RE, ''); }; +// The token of the canary route in `text`, or null without one. +window.workerCanaryToken = function (text) { + if (typeof text !== 'string') return null; + const m = /router\.get\('\/__builder\/canary', \(\) => '([a-z0-9]+)'\);/.exec(text); + return m ? m[1] : null; +}; + // `text` with a canary route answering `token` (letters and digits) in place // of any old one. window.stampWorkerCanary = function (text, token) { diff --git a/src/js/prompt.js b/src/js/prompt.js index eb4931ab..6183c8e6 100644 --- a/src/js/prompt.js +++ b/src/js/prompt.js @@ -72,6 +72,19 @@ const appTestsSnippet = (window.FEATURE_FLAGS && window.FEATURE_FLAGS.appTests) IMPORTANT: Hidden tests. When an app has behaviour worth protecting (forms and validation, calculations, games, carts and checkout, saved data, multi-step flows, a backend), save a few automated tests of its main features with the AppTests tool in the same turn you build or change them, before calling update_preview, which runs them and reports failures. Skip tests for pages that only show content (a landing page, portfolio or menu) and for purely visual changes. Keep them in step with the app: before changing a feature of an app you built in an earlier turn, read its tests, and update or remove the ones your change affects. When a test fails, fix the app unless the test itself is wrong, and never weaken or delete a test just to make it pass. The tests are invisible to the user: never mention tests, the AppTests tool or test results in your replies, todos or suggestions, and never add test code, test pages or test buttons to the app itself.` : ''; +// Backends are Puter dynamic workers (__workers/.worker.js, see +// js/site-backends.js) while FEATURE_FLAGS.dynamicWorkers is on, and named +// workers deployed with create_worker while it's off. Static (flag-derived at +// load), so it does not break the cache-stable prefix. +const dynamicBackends = !!(window.FEATURE_FLAGS && window.FEATURE_FLAGS.dynamicWorkers); +const backendDeployRule = dynamicBackends + ? `IMPORTANT: A backend is a Puter dynamic worker, a file named __workers/.worker.js at the top of the folder the preview serves (next to its index.html), where uses only lowercase letters, digits, hyphens and underscores. Write it with write like any other file. There is no deploy step and no create_worker tool. Puter runs it at /__workers// on the same site and strips that prefix, so router.get('/items') answers /__workers//items. Pages call it with that relative path, for example fetch('/__workers/api/items') or puter.workers.exec('/__workers/api/items'), never with a full address, so the same code works on the preview and on the published site. A file in a subfolder of __workers never runs, and Puter never serves the file itself, so its code stays private. To change a backend, edit its file with edit or multi_edit, and the result's worker field says whether the new code is live. If live is false, the backend may still be running its previous code, so follow the note in that field. To remove one, delete its file. Every address has its own store for me.puter, so the preview and the published site keep separate data. The user's own domain on the published site runs its backends too, whatever Puter's docs say about custom domains, and as another address it has a store of its own. Workers this project made earlier with create_worker (workers/.js) keep working, and you change them by editing their files.` + : `IMPORTANT: Deploy each worker once with create_worker. To change a deployed worker, edit its file workers/.js with edit or multi_edit, and never send its whole code to create_worker again. Saving the file redeploys the worker at the same URL, and the result's worker field says whether the new code is live. If live is false, the worker may still be running its previous code, so follow the note in that field.`; +// The email rule, built outside the template so its prose holds no template +// syntax (scripts/test-worker-sender.mjs checks). +const emailSenderRule = "IMPORTANT: Email a worker sends with puter.email.sendTransactional always goes out from a Puter address, which can't be changed. Recipients see the backend's sender name next to that address, and a new backend's sender name is " + + (dynamicBackends ? "its project's name (with \"(preview)\" after it on the preview), shared by every backend of the site" : "its internal name (sandbox-)") + + ". So whenever you make a worker send email, set its sender name with the set_email_sender_name tool, using the name the user wants or else the site's or business's name. Use the same tool whenever the user asks to change who the email appears to come from. Don't try to set a from address in the code, since Puter doesn't allow it. Publishing copies the sender name to the live site by itself. Replies go to the replyTo address, so when recipients should be able to reply (a contact form, a booking confirmation), pass replyTo with the address the user wants replies to reach, and ask for it if you don't have it."; return ` You are an expert, helpful web application developer. You are to complete required tasks using the functions provided. @@ -93,15 +106,15 @@ CRITICAL: Do not rely on Puter.js's automatic sign-in flow (the popup that trigg CRITICAL: puter.kv and puter.fs are scoped to the user. Do not use them to store state that is not user-specific. If you need shared state use you should probably use Puter's serverless workers. -CRITICAL: If you decide to use serverless workers, make sure you thoroughly read the documentation for it and understand how to use it. Do not skip over the details. The documentation index is available at https://docs.puter.com/llms.txt. +CRITICAL: If you decide to use serverless workers, make sure you thoroughly read the documentation for it and understand how to use it. Do not skip over the details. The documentation index is available at https://docs.puter.com/llms.txt.${dynamicBackends ? ' Backends here are dynamic workers, documented at https://docs.puter.com/Workers/dynamic/, written with the router described at https://docs.puter.com/Workers/router/.' : ''} -IMPORTANT: Deploy each worker once with create_worker. To change a deployed worker, edit its file workers/.js with edit or multi_edit, and never send its whole code to create_worker again. Saving the file redeploys the worker at the same URL, and the result's worker field says whether the new code is live. If live is false, the worker may still be running its previous code, so follow the note in that field. +${backendDeployRule} CRITICAL: For any feature that needs real-time peer-to-peer communication between users — video chat, audio/voice chat, text/data messaging, screen sharing, multiplayer games, live collaboration, or anything else WebRTC-like — you MUST use the Puter Peer API (puter.peer). Do NOT use raw WebRTC (RTCPeerConnection) directly, and do NOT use any third-party signaling or realtime service (PeerJS, simple-peer, socket.io, Firebase, Agora, Twilio, etc.). With it, one client calls puter.peer.serve() to start a session and get an invite code, the others join via puter.peer.connect(inviteCode), and puter.peer.ensureTurnRelays() keeps connections reliable across different networks. Thoroughly read the Peer API documentation before building — the index is at https://docs.puter.com/llms.txt and the Peer docs are under https://docs.puter.com/Peer/. -CRITICAL: Keys and other secrets (a Stripe or Whop key, any API key or token the user gives you) live only in the private store of the worker that uses them. Never write a key into any file, the worker's code included, never put one in an HTML page, browser JavaScript or the browser's puter.kv, and never repeat one back in your replies or todos. Deploy the worker with create_worker first, then save each key with the set_secret tool (the worker's name, a name in UPPER_SNAKE_CASE, the key, and live set to false). In the worker, read a key inside the route handler that uses it, never at the top of the script, for example const stripeKey = await me.puter.kv.get('secret:STRIPE_SECRET_KEY'). Read it on every request and never keep it in a variable outside the handler or cache it, so a key saved again with set_secret takes effect at once, without redeploying the worker. If a key comes back empty, have the route return a clear error saying that key is not set up yet. The preview and the published (live) site run the same worker code, each with its own store. Publishing copies the preview's keys to the live site by itself. A key only the live site should use, such as a live payment key while the preview keeps a test key, is saved with live set to true once the site has been published, and publishing never replaces it. After each publish, Builder adds a line in italics saying which keys the live site got and whether one is still a Stripe test key or Whop's sandbox. The user sees that line too, so don't repeat it. When they want the live site to take real payments, ask for the live key and save it with live set to true. If a worker you are changing still has a key written in its code (an older project), don't move it on your own. Tell the user in one short sentence that the key is written in the code, where anyone who can see the project's files can read it, and offer to move it into the worker's private store. Only once they agree, save it with set_secret, read it from the worker's store as above, and remove it from the code. +CRITICAL: Keys and other secrets (a Stripe or Whop key, any API key or token the user gives you) live only in the private store of the ${dynamicBackends ? 'site whose backend uses them' : 'worker that uses them'}. Never write a key into any file, the worker's code included, never put one in an HTML page, browser JavaScript or the browser's puter.kv, ${dynamicBackends ? "never read a secret: key from browser code, since a site's pages run as the same app as its backends, " : ''}and never repeat one back in your replies or todos. ${dynamicBackends ? "Write the backend's file and open the preview first, then save each key with the set_secret tool (the backend's name, a name in UPPER_SNAKE_CASE, the key, and live set to false)." : "Deploy the worker with create_worker first, then save each key with the set_secret tool (the worker's name, a name in UPPER_SNAKE_CASE, the key, and live set to false)."} In the worker, read a key inside the route handler that uses it, never at the top of the script, for example const stripeKey = await me.puter.kv.get('secret:STRIPE_SECRET_KEY'). Read it on every request and never keep it in a variable outside the handler or cache it, so a key saved again with set_secret takes effect at once, without ${dynamicBackends ? 'changing the code' : 'redeploying the worker'}. If a key comes back empty, have the route return a clear error saying that key is not set up yet. The preview and the published (live) site run the same worker code, each with its own store. Publishing copies the preview's keys to the live site by itself. A key only the live site should use, such as a live payment key while the preview keeps a test key, is saved with live set to true once the site has been published, and publishing never replaces it.${dynamicBackends ? " The user's own domain on the published site gets the live site's keys when it's connected and on each publish, and a key saved with live set to true goes there too. If its backend is missing a key, save the key again with live set to true." : ''} After each publish, Builder adds a line in italics saying which keys the live site got and whether one is still a Stripe test key or Whop's sandbox. The user sees that line too, so don't repeat it. When they want the live site to take real payments, ask for the live key and save it with live set to true. If a worker you are changing still has a key written in its code (an older project), don't move it on your own. Tell the user in one short sentence that the key is written in the code, where anyone who can see the project's files can read it, and offer to move it into the worker's private store. Only once they agree, save it with set_secret, read it from the worker's store as above, and remove it from the code. -IMPORTANT: Email a worker sends with puter.email.sendTransactional always goes out from a Puter address, which can't be changed. Recipients see the backend's sender name next to that address, and a new backend's sender name is its internal name (sandbox-). So whenever you make a worker send email, set its sender name with the set_email_sender_name tool, using the name the user wants or else the site's or business's name. Use the same tool whenever the user asks to change who the email appears to come from. Don't try to set a from address in the code, since Puter doesn't allow it. Publishing copies the sender name to the live site by itself. Replies go to the replyTo address, so when recipients should be able to reply (a contact form, a booking confirmation), pass replyTo with the address the user wants replies to reach, and ask for it if you don't have it. +${emailSenderRule} CRITICAL: When the app needs to take payments (a buy button, a store checkout, donations, paid plans, subscriptions), use Stripe Checkout through a Puter serverless worker. Use Whop instead only when the user asks for Whop or gives you a Whop key (see the Whop rules below). Rules: - You need the user's Stripe key. If they have not given one, build everything else, then ask for it in plain words: create a free account at stripe.com, open https://dashboard.stripe.com/apikeys, and paste a key here. A test key (sk_test_ or rk_test_) is best while building; a live key (sk_live_ or rk_live_) charges real cards. Add that if Stripe is not available in their country, Whop (whop.com) works in more countries and they can use it instead. Never invent a key or use a placeholder that looks like a real one. diff --git a/src/js/site-backends.js b/src/js/site-backends.js new file mode 100644 index 00000000..23ebdb47 --- /dev/null +++ b/src/js/site-backends.js @@ -0,0 +1,472 @@ +// site-backends.js — a project's dynamic backends (window.SiteBackends). +// +// A dynamic backend is a file __workers/.worker.js in the folder a site +// serves. Puter runs it at /__workers//..., starts it on the first +// request, and runs a saved change within about a second. It has no deploy +// step, no worker record and no name shared with the rest of Puter, so a page +// calls it with the relative path /__workers//... and the same code +// works on the preview and on the live site. Puter never serves the file +// itself. +// +// It runs as the app registered for the site's address, so every address has +// a store of its own. The preview and the live site keep separate data and +// keys, and so does a copy of the project. Builder puts keys into that store +// the way it does for a worker (worker-secrets.js). +// +// For a project with dynamic backends, Builder registers that app itself the +// moment it creates a site (registerApp), before anything runs there. Puter +// finds an app by its address, so the backend and the site's pages run as +// Builder's app, and Builder, being its creator, may change it. That's what +// lets it set the email sender name (the app's title, worker-sender.js), and +// keep a live site's data when its address changes, by pointing the same app +// at the new address (moveApp). The app is named after the project, "" +// for the live site and " (preview)" for the preview, until a sender +// name is chosen. Builder keeps the app's name, and that bookkeeping, in its +// own key-value store under "site-app:", since Puter looks apps up by +// name and a registered app's name can't be worked out from the address. +// When something ran on the site before Builder could register the app, +// Puter has made one of its own, which Builder can't change. That site still +// works, with keys but without a sender name Builder can set. +// +// A project gets dynamic backends when it's made while +// FEATURE_FLAGS.dynamicWorkers is on, and keeps that for good. The mark sits +// on its system message, which holds the instructions the AI was given and is +// never rebuilt, so a project made earlier keeps create_worker and the +// instructions that go with it. What a site's files hold is handled either +// way, at publish, duplicate, a new address and delete, since Puter runs any +// __workers file it finds. +window.SiteBackends = (function () { + 'use strict'; + + const FOLDER = '__workers'; + const SUFFIX = '.worker.js'; + // Puter's rule for the part before .worker.js, which is also the URL + // segment. + const NAME_RE = /^[a-z0-9_-]+$/; + const FILE_RE = /^__workers\/([a-z0-9_-]+)\.worker\.js$/; + + // Whether a project made now gets dynamic backends. + function forNewProjects() { + return !!(window.FEATURE_FLAGS && window.FEATURE_FLAGS.dynamicWorkers); + } + + // Mark a new project's system message when it gets dynamic backends. + // Returns the message. + function markNewProject(systemMessage) { + if (systemMessage && forNewProjects()) systemMessage.dynamicWorkers = true; + return systemMessage; + } + + // Whether the project with this history has dynamic backends. + function isDynamicProject(history) { + const sys = Array.isArray(history) ? history[0] : null; + return !!(sys && sys.role === 'system' && sys.dynamicWorkers === true); + } + + // The builder's tools as a project with this history gets them. A project + // with dynamic backends gets no tool marked legacyOnly (create_worker), + // and the wording in each tool's `dynamic` block, which can replace its + // description and its parameters' descriptions. Any other project gets + // the tools as they always were. Neither mark goes out with the tools, + // since they're sent to the AI as they are. + function toolsFor(tools, history) { + const list = (Array.isArray(tools) ? tools : []).filter(Boolean); + const bare = ({ dynamic, legacyOnly, ...t }) => t; + if (!isDynamicProject(history)) return list.map((t) => (t.dynamic || 'legacyOnly' in t ? bare(t) : t)); + return list.filter((t) => !t.legacyOnly).map((t) => { + if (!t.dynamic) return bare(t); + const spec = t.function; + const props = {}; + for (const [key, prop] of Object.entries((spec.parameters && spec.parameters.properties) || {})) { + const said = t.dynamic.parameters && t.dynamic.parameters[key]; + props[key] = said ? { ...prop, description: said } : prop; + } + return { + ...bare(t), + function: { + ...spec, + description: t.dynamic.description || spec.description, + parameters: { ...spec.parameters, properties: props }, + }, + }; + }); + } + + function validName(name) { return typeof name === 'string' && NAME_RE.test(name); } + + // The backend name of a file, from its path relative to the folder the + // site serves, or null for any other file. Top level only, since Puter + // never runs a file in a subfolder of __workers. + function nameOf(servedRel) { + const m = FILE_RE.exec(String(servedRel == null ? '' : servedRel).replace(/^\/+/, '')); + return m ? m[1] : null; + } + + // The https://.puter.site origin of a site's URL, or null. Puter runs + // dynamic backends on puter.site only. + function siteOrigin(url) { + let u; + try { u = new URL(String(url == null ? '' : url)); } catch (e) { return null; } + if (u.protocol !== 'https:' || !/^[a-z0-9-]+\.puter\.site$/i.test(u.host)) return null; + return u.origin.toLowerCase(); + } + + // The address an app runs at: a site's puter.site origin, or the origin + // of the user's own domain serving one (https://www.example.com). null + // for anything else, Puter's other hosts included. + function appOrigin(url) { + const site = siteOrigin(url); + if (site) return site; + let u; + try { u = new URL(String(url == null ? '' : url)); } catch (e) { return null; } + if (u.protocol !== 'https:' || u.port || !u.hostname.includes('.')) return null; + if (/(^|\.)puter\.(site|host|com|app|work)$/i.test(u.hostname)) return null; + return u.origin.toLowerCase(); + } + + // The path a page calls a backend at, on its own site. + function pathOf(name) { return '/' + FOLDER + '/' + name; } + + // Where a backend answers on a site or its domain, with no trailing + // slash. null when either half is unusable. + function urlOf(siteUrl, name) { + const origin = appOrigin(siteUrl); + return origin && validName(name) ? origin + pathOf(name) : null; + } + + function notFound(e) { + for (const p of [e, e && e.error]) { + if (!p) continue; + if (p.status === 404 || /not_?found|does_not_exist/i.test(String(p.code || ''))) return true; + if (typeof p.message === 'string' && /not found|does not exist|no such/i.test(p.message)) return true; + } + return false; + } + + function timeout(ms) { + try { return AbortSignal.timeout(ms); } catch (e) { return undefined; } + } + + // The backends in the folder a site serves, as [{ name, path }] sorted by + // name. [] when the folder has no __workers. Any other failure throws, so + // a read that failed never passes for a site without backends. + async function list(servedDir) { + const dir = String(servedDir || '').replace(/\/+$/, '') + '/' + FOLDER; + let items; + try { items = await puter.fs.readdir(dir); } + catch (e) { if (notFound(e)) return []; throw e; } + const out = []; + for (const item of items || []) { + if (!item || item.is_dir || typeof item.name !== 'string' || !item.name.endsWith(SUFFIX)) continue; + const name = item.name.slice(0, -SUFFIX.length); + if (validName(name)) out.push({ name, path: dir + '/' + item.name }); + } + return out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + } + + // The app a site or its domain runs as, the one a page at that address + // acts as (puter.apps.get with a URL). That's the app Builder registered, + // or the one Puter made the first time something ran there. Null while + // there is none. Throws when Puter can't be reached. + async function siteAppOf(siteUrl) { + const origin = appOrigin(siteUrl); + if (!origin) return null; + let app; + try { app = await puter.apps.get(origin); } + catch (e) { if (notFound(e)) return null; throw e; } + return app && typeof app.uid === 'string' && app.uid ? app : null; + } + + // The uid of the app a site runs as, or null while there is none. + async function appUidOf(siteUrl) { + const app = await siteAppOf(siteUrl); + return app ? app.uid : null; + } + + // Call the site's backends, one at a time, until one answers, so Puter + // starts it and makes the site's app. A 503 is a backend Puter couldn't + // start. Resolves whether one answered. + async function wake(siteUrl, names) { + for (const name of names || []) { + const url = urlOf(siteUrl, name); + if (!url) continue; + try { + const resp = await fetch(url + window.WORKER_CANARY_PATH + '?__pv=' + Date.now(), { cache: 'no-store', signal: timeout(10000) }); + if (resp.status !== 503) return true; + } catch (e) { /* try the next one */ } + } + return false; + } + + // -- The app Builder registers for a site -- + + // A project's name, from the project list, or '' when it isn't there. + function titleOf(chatId) { + const list = typeof savedChats !== 'undefined' && Array.isArray(savedChats) ? savedChats : []; + const entry = list.find((c) => c && c.id === chatId); + return (entry && entry.title) || ''; + } + + const APP_KEY = 'site-app:'; + // Puter's limit on an app's title. + const MAX_TITLE = 100; + + function appKey(siteUrl) { + const origin = appOrigin(siteUrl); + return origin ? APP_KEY + origin : null; + } + + // What Builder recorded about the app it registered for a site or a + // domain, { name, kind, defaultTitle, senderName }, with `project` for a + // domain's, or null for one it didn't. + async function record(siteUrl) { + const key = appKey(siteUrl); + if (!key) return null; + const r = await puter.kv.get(key); + return r && typeof r === 'object' && typeof r.name === 'string' && r.name ? r : null; + } + + // The title a site's app has while no sender name is chosen. kind is + // 'preview' or 'live'. + function defaultTitle(projectTitle, kind) { + const name = String(projectTitle == null ? '' : projectTitle).replace(/\s+/g, ' ').trim() || 'Untitled'; + const suffix = kind === 'preview' ? ' (preview)' : ''; + return name.slice(0, MAX_TITLE - suffix.length).trim() + suffix; + } + + // Run a Puter call, and once more if it fails. + async function twice(fn) { + try { return await fn(); } catch (e) { return fn(); } + } + + // Register the app a new site or domain runs as, named after the + // project. Call it right after creating the site, before anything runs + // there, or Puter makes one of its own first. `project` is kept with a + // domain's, since a domain can move to another project. Resolves the app, + // or null when Puter refused, which leaves the site on an app Puter + // makes. Never throws, since a site without Builder's app still works. + // Puter refuses an app at a site, or at a domain attached to one, that + // isn't the user's, so this can't take someone else's address. + async function registerApp(siteUrl, projectTitle, kind, project) { + const origin = appOrigin(siteUrl); + if (!origin) return null; + const title = defaultTitle(projectTitle, kind); + const host = origin.slice('https://'.length); + let app; + try { + // The app is named after the site. With dedupeName, Puter adds a + // suffix when another app has that name instead of refusing, so + // the name it gets is only known from its answer. That's why the + // name is recorded below. + app = await puter.apps.create({ name: siteOrigin(origin) ? host.split('.')[0] : host.replace(/\./g, '-'), indexURL: origin, title, dedupeName: true }); + } catch (e) { + console.warn('Could not register an app for', origin, e); + return null; + } + if (!app || !app.name || !app.uid) return null; + try { + await twice(() => puter.kv.set(APP_KEY + origin, { name: app.name, kind, defaultTitle: title, senderName: null, ...(project ? { project } : {}) })); + } catch (e) { + // Without its record Builder could never find the app again, and + // the site would run as it anyway, with no keys. So it goes, and + // the site runs as the app Puter makes. + console.warn('Could not record the app for', origin, e); + try { await twice(() => puter.apps.delete(app.name)); } + catch (e2) { if (!notFound(e2)) console.warn('Could not remove the unrecorded app', app.name, e2); } + return null; + } + return app; + } + + // Change the record of a site's app. Resolves whether it was there. + async function updateRecord(siteUrl, patch) { + const r = await record(siteUrl); + if (!r) return false; + await puter.kv.set(appKey(siteUrl), { ...r, ...patch }); + return true; + } + + // Note the sender name chosen for a site's app, or null for its default. + function setSenderName(siteUrl, name) { + return updateRecord(siteUrl, { senderName: name || null }); + } + + // Follow a project's new name on the app Builder registered for its + // site, while it still has the name Builder gave it. A sender name + // chosen in chat, or a title set by hand in the Dev Center, stays. Best + // effort. In one tab, renames of one site run one at a time, so a quick + // second one reads the record the first one left. Two tabs renaming the + // same project at the same moment can still cross. + const retitles = new Map(); + function retitle(siteUrl, projectTitle) { + const key = appOrigin(siteUrl); + if (!key) return Promise.resolve(); + const run = (retitles.get(key) || Promise.resolve()).then(() => retitleNow(siteUrl, projectTitle)); + retitles.set(key, run); + run.then(() => { if (retitles.get(key) === run) retitles.delete(key); }); + return run; + } + async function retitleNow(siteUrl, projectTitle) { + try { + const r = await record(siteUrl); + if (!r) return; + const title = defaultTitle(projectTitle, r.kind); + if (title === r.defaultTitle) return; + if (!r.senderName) { + const app = await puter.apps.get(r.name); + if (app && app.title === r.defaultTitle) await puter.apps.update(r.name, { title }); + } + await puter.kv.set(appKey(siteUrl), { ...r, defaultTitle: title }); + } catch (e) { + console.warn('Could not rename the app of', siteUrl, e); + } + } + + // Point the app Builder registered for `oldUrl` at `newUrl`, a site just + // created, so the new address runs as the same app and keeps its data and + // keys. Resolves whether it moved, and when it didn't, nothing changed. + // The new address's record is written first and removed again if Puter + // refuses, and a leftover old record is harmless, since a record only + // counts while its app still has that address (builderAppOf). + async function moveApp(oldUrl, newUrl) { + const origin = siteOrigin(newUrl); + let r; + try { r = await record(oldUrl); } catch (e) { return false; } + if (!r || !origin) return false; + try { await puter.kv.set(APP_KEY + origin, r); } catch (e) { return false; } + let moved = false; + try { + await puter.apps.update(r.name, { indexURL: origin }); + moved = true; + } catch (e) { + // An update that reached Puter but whose answer got lost still + // moved the app. + try { moved = siteOrigin((await puter.apps.get(r.name)).index_url) === origin; } catch (e2) { /* not moved */ } + if (!moved) console.warn('Could not move the app of', oldUrl, 'to', newUrl, e); + } + if (!moved) { + try { await puter.kv.del(APP_KEY + origin); } catch (e) { /* only ever read with its app's address */ } + return false; + } + try { await puter.kv.del(appKey(oldUrl)); } catch (e) { /* only ever read with its app's address */ } + return true; + } + + // Whether Builder registered the app a site runs as. Throws when that + // can't be read, since "no" would leave the app behind. + async function hasApp(siteUrl) { + return !!(await builderAppOf(siteUrl)); + } + + // Delete the app Builder registered for a site, with the site. Throws + // when Puter refuses, so the caller can say what's left. + async function deleteApp(siteUrl) { + const r = await record(siteUrl); + if (!r) return; + try { await puter.apps.delete(r.name); } + catch (e) { if (!notFound(e)) throw e; } + await puter.kv.del(appKey(siteUrl)); + } + + // The app Builder registered for a site, with its record as `builder`, + // or null. One that no longer points at the site isn't the site's. + async function builderAppOf(siteUrl) { + const r = await record(siteUrl); + if (!r) return null; + let app; + try { app = await puter.apps.get(r.name); } + catch (e) { if (notFound(e)) return null; throw e; } + return app && appOrigin(app.index_url) === appOrigin(siteUrl) ? { ...app, builder: r } : null; + } + + // The project the app Builder registered for a domain belongs to, or + // null. Throws when that can't be read. + async function projectOf(domainUrl) { + const r = await record(domainUrl); + return (r && r.project) || null; + } + + // Register the app the user's own domain runs as for `project`, right + // after the domain is attached to its site, before anything runs there + // (see registerApp), so Builder can rename it and give it keys. A domain + // whose app this project already has keeps it, data and keys included. + // At a domain another project had, or Puter's own app, the keys go + // first, so this project's backend never reads another's, and Builder's + // app goes too, for a new one. Resolves the app, or null when the domain + // stays on Puter's. Never throws. + async function claimDomain(domainUrl, projectTitle, project) { + if (!appOrigin(domainUrl) || siteOrigin(domainUrl)) return null; + try { + const r = await record(domainUrl); + const mine = await builderAppOf(domainUrl); + if (mine && r.project === project) return mine; + try { await window.WorkerSecrets?.clear({ site: domainUrl }); } catch (e) { /* best effort */ } + if (r) await deleteApp(domainUrl); + } catch (e) { + console.warn('Could not check the app of', domainUrl, e); + return null; + } + return registerApp(domainUrl, projectTitle, 'live', project); + } + + // The app a site runs as, or null when there is none. That's the app + // Builder registered for it, with its record as `builder`, or else the + // one Puter made for the address. With `wakeNames`, a site whose app + // Puter hasn't made yet gets its backends called first. An app someone + // else registered for the address counts as none, since changing it would + // change something else. Throws when Puter can't be reached, so a failed + // lookup is never mistaken for "no app". + const foreignApps = new Set(); // addresses already warned about + async function appOf(siteUrl, wakeNames) { + const registered = await builderAppOf(siteUrl); + if (registered) return registered; + let app = await siteAppOf(siteUrl); + if (!app && wakeNames && wakeNames.length && await wake(siteUrl, wakeNames)) { + // A site created a moment ago can answer before Puter has made + // its app, so the app gets a few seconds to show up. + for (let i = 0; i < 5 && !app; i++) { + if (i) await new Promise((r) => setTimeout(r, 1000)); + app = await siteAppOf(siteUrl); + } + } + // Puter names the app it makes for an address after its uid + // (isOriginBootstrapApp in Puter's util/appView.ts), and the name + // stays when the owner changes its title in the Dev Center. Any + // other app is someone's. + if (!app || app.name === app.uid) return app; + const origin = appOrigin(siteUrl); + if (!foreignApps.has(origin)) { + foreignApps.add(origin); + console.warn('The app', app.name, 'at', origin, 'wasn\'t made by Builder or by Puter for the address, so Builder leaves it alone and its backends get no keys or sender name from Builder.'); + } + return null; + } + + // The open project's site, for a tool call or a save. That's the folder + // the site serves (it holds __workers) and its preview and live + // addresses. null when the call's project isn't the open one, whose + // addresses are the only ones in memory, or doesn't have dynamic + // backends. + function siteOf(state) { + const root = window.projectRootDir(state); + const open = typeof currentAppDir !== 'undefined' && currentAppDir ? window.normalizePosixPath(currentAppDir) : ''; + if (!root || root !== open) return null; + const history = (state && state.chatHistory) || (typeof chatHistory !== 'undefined' ? chatHistory : null); + if (!isDynamicProject(history)) return null; + const served = window.currentPreviewPath ? window.normalizePosixPath(window.currentPreviewPath) : root; + const live = siteOrigin(window.currentPublishedUrl); + return { + root, + servedDir: served === root || served.startsWith(root + '/') ? served : root, + previewUrl: siteOrigin(window.currentPreviewUrl) ? window.currentPreviewUrl : null, + publishedUrl: live ? window.currentPublishedUrl : null, + // The user's own domain serving the live site, which runs its + // backends as an app of its own (custom-domain.js). + domainUrls: live && window.CustomDomain + ? window.CustomDomain.urlsFor(window.currentPublishedDomains, live.slice('https://'.length).split('.')[0]) : [], + }; + } + + return { FOLDER, SUFFIX, NAME_RE, forNewProjects, markNewProject, isDynamicProject, toolsFor, + titleOf, defaultTitle, registerApp, setSenderName, retitle, moveApp, hasApp, deleteApp, projectOf, claimDomain, validName, nameOf, siteOrigin, appOrigin, pathOf, urlOf, list, appUidOf, wake, appOf, siteOf }; +})(); diff --git a/src/js/template-core.js b/src/js/template-core.js index 4c5cfdf3..4c24dcad 100644 --- a/src/js/template-core.js +++ b/src/js/template-core.js @@ -18,7 +18,10 @@ // A fork deploys each one under a fresh account-unique name of its own, and // the template's frontend refers to a worker only through a placeholder, // {{WORKER_URL:}}, which the fork replaces with that deployment's URL. -// Nothing a fork runs is shared with anyone else's copy. +// Nothing a fork runs is shared with anyone else's copy. With dynamic workers +// on (site-backends.js), a fork writes each one to __workers/.worker.js +// instead, and the placeholder becomes the path /__workers/, which runs +// it on the fork's own site. // // PURE by design: no I/O, no DOM, no reads of other window.* modules. The // I/O half (fetching, forking, the landing section and dialog) is @@ -198,7 +201,12 @@ window.TemplateCore = (function () { lines.push(`The live preview is already open and serves ${appDir}. It updates automatically when files change, so do not call publish_site for this project.`); } const workers = opts.workers || []; - if (workers.length) { + if (workers.some(w => w.dynamic)) { + lines.push('The app has a backend, a dynamic worker that runs on whichever site serves the project:'); + for (const w of workers) { + lines.push(`- Source ${appDir}/__workers/${w.name}.worker.js, which the pages call at ${String(w.url).replace(/\/+$/, '')}. To change it, edit that file.`); + } + } else if (workers.length) { lines.push('The app has a serverless backend that is already deployed:'); for (const w of workers) { lines.push(`- Source ${appDir}/workers/${w.name}.js, running at ${String(w.url).replace(/\/+$/, '')}. Its worker name is the file name without ".js"; to change it, call create_worker with that same name and the full updated code.`); diff --git a/src/js/templates.js b/src/js/templates.js index a4a79170..600799df 100644 --- a/src/js/templates.js +++ b/src/js/templates.js @@ -128,10 +128,14 @@ // except a worker, which is why those go first. async function discardFork(appDir, deployed, subdomain) { for (const w of deployed) { + // A dynamic backend goes with the directory below. + if (w.dynamic) continue; try { await puter.workers.delete(w.name); } catch (e) { console.warn('Template: could not remove the worker of a failed fork:', w.name, e); } } if (subdomain) { + try { await window.SiteBackends?.deleteApp(`https://${subdomain}.puter.site/`); } + catch (e) { console.warn('Template: could not remove the app of a failed fork\'s preview:', subdomain, e); } try { await puter.hosting.delete(subdomain); } catch (e) { console.warn('Template: could not remove the preview of a failed fork:', subdomain, e); } } @@ -172,6 +176,21 @@ // files that don't call it upload meanwhile. const deployWorkers = async () => { if (!template.workers.length) return; + // A dynamic backend is just its file, at the top of the + // folder the preview serves, and the pages call it on their + // own site (see site-backends.js). Nothing to deploy. + const SB = window.SiteBackends; + if (SB?.forNewProjects()) { + for (const workerName of template.workers) { + const name = workerName.toLowerCase(); + if (!SB.validName(name)) throw new Error(`the backend name ${workerName} can't be a dynamic backend's`); + const filePath = `${appDir}/${SB.FOLDER}/${name}${SB.SUFFIX}`; + const source = byPath.get(`workers/${workerName}.js`).text; + await window.withFileLock(filePath, () => window.writeFileVerified(filePath, source)); + deployed.push({ templateName: workerName, name, url: SB.pathOf(name), dynamic: true }); + } + return; + } const existing = await puter.workers.list(); const taken = (Array.isArray(existing) ? existing : []).map(w => w && w.name).filter(Boolean); for (const workerName of template.workers) { @@ -230,10 +249,16 @@ // same call duplicateChat makes. let previewUrl = null; let siteLive = Promise.resolve(); + const title = core().uniqueTitle(template.name, savedChats.map(c => c.title || '')); try { const site = await puter.hosting.create(window.makeDraftSubdomain(), appDir); subdomain = site.subdomain; previewUrl = `https://${site.subdomain}.puter.site/`; + // A fork with dynamic backends runs its preview as an app Builder + // registers now, before anything runs there (see site-backends.js). + if (window.SiteBackends?.forNewProjects()) { + await window.SiteBackends.registerApp(previewUrl, title, 'preview'); + } // Checked while the project is saved below; awaited before return. siteLive = waitForSite(previewUrl); } catch (e) { @@ -247,7 +272,9 @@ progress.stage = 'save'; const renamedFiles = template.files.map(p => { const w = template.workers.find(n => p === `workers/${n}.js`); - return w ? `workers/${deployed.find(d => d.templateName === w).name}.js` : p; + if (!w) return p; + const d = deployed.find(x => x.templateName === w); + return d.dynamic ? `${window.SiteBackends.FOLDER}/${d.name}${window.SiteBackends.SUFFIX}` : `workers/${d.name}.js`; }); const note = core().buildTemplateNote({ name: template.name, @@ -269,8 +296,10 @@ ], templateOrigin: { slug: template.slug, name: template.name, version: template.version }, }; + // The fork's backends were written as dynamic ones above exactly when + // a new project gets them (see site-backends.js). + window.SiteBackends?.markNewProject(systemMessage); const now = new Date().toISOString(); - const title = core().uniqueTitle(template.name, savedChats.map(c => c.title || '')); const chatData = { id: newId, title, diff --git a/src/js/tools.js b/src/js/tools.js index 6eba1112..3bbc690f 100644 --- a/src/js/tools.js +++ b/src/js/tools.js @@ -22,10 +22,13 @@ window.builtinTools = function() { // The tools for a turn on `modelId`: the builder's own, then the MCP tools // that model can take (see ModelCore.turnTools). -window.getTurnTools = function(modelId) { +// `history` is the project's, whose kind of backend decides how the worker +// tools read (SiteBackends.toolsFor). +window.getTurnTools = function(modelId, history) { const mcp = window.mcpManager?.getTools() || []; const own = window.builtinTools(); - return window.ModelCore ? window.ModelCore.turnTools(modelId, own, mcp) : [...own, ...mcp]; + const builtin = window.SiteBackends ? window.SiteBackends.toolsFor(own, history) : own; + return window.ModelCore ? window.ModelCore.turnTools(modelId, builtin, mcp) : [...builtin, ...mcp]; }; // The MCP tools left out of a turn on `modelId` ({label, server}), which the // model is told about (ModelCore.unavailableToolsNote). @@ -68,9 +71,14 @@ const SKIPPED_PREVIEW_ERROR = 'Not run, because an earlier call in this reply fa // stampWorkerCanary in helpers.js), and after the save waits until the worker // serves that token (workerSaveResult). So the AI's result tells it whether // its change is live, and it never resends the whole worker to create_worker -// just to deploy an edit. +// just to deploy an edit. A dynamic backend's save (__workers/.worker.js) +// gets the same check, against the copy the preview runs. // Puter documents up to 30 seconds for a deploy to reach every edge. -window.workerCanaryTiming = { pollMs: 500, limitMs: 30000 }; +window.workerCanaryTiming = { pollMs: 500, limitMs: 30000, + // The wait after a hosting.update (watchSiteBackends): how often a + // backend's canary is read, how long a backend has to go down before it + // counts as untouched by the update, and how long it has to stay back. + redeployPollMs: 250, redeployDownMs: 8000, redeploySettleMs: 2000 }; // The deployed worker this project runs from `path`: { name, url, path }. // { lookupFailed: true } when the worker list can't be read, null for any @@ -78,6 +86,15 @@ window.workerCanaryTiming = { pollMs: 500, limitMs: 30000 }; window.workerSaveTarget = async function(path, state) { const root = window.projectRootDir(state); if (!root || typeof path !== 'string' || path.indexOf(root + '/') !== 0) return null; + // A dynamic backend runs from the file itself, on the open project's + // preview (see site-backends.js). With no preview yet there is nothing + // running it to wait for. + const site = window.SiteBackends?.siteOf(state); + const name = site && path.indexOf(site.servedDir + '/') === 0 ? window.SiteBackends.nameOf(path.slice(site.servedDir.length + 1)) : null; + if (name) { + const url = window.SiteBackends.urlOf(site.previewUrl, name); + return url ? { name, url, path } : null; + } if (!window.EditorCore?.classify(path.slice(root.length + 1)).backend) return null; let owned; try { owned = window.WorkerOwnership.ownedWorkers(await puter.workers.list(), root); } @@ -87,6 +104,18 @@ window.workerSaveTarget = async function(path, state) { return { name: worker.name, url: worker.url, path }; }; +// Whether `call` is an edit, multi_edit or write of one of the open preview's +// dynamic backends (__workers/.worker.js in the folder it serves), a +// change no page of the site shows (see pagesUnchanged in ui.js). +window.isBackendSaveCall = function(call, state) { + if (!call || !['edit', 'multi_edit', 'write'].includes(call.name) || !call.input) return false; + let path; + try { path = window.assertPathInProject(call.input.path, state); } catch (e) { return false; } + const site = window.SiteBackends?.siteOf(state); + return !!(site && typeof path === 'string' && path.indexOf(site.servedDir + '/') === 0 + && window.SiteBackends.nameOf(path.slice(site.servedDir.length + 1))); +}; + // `text` stamped with a fresh canary token for `target`'s save, kept on the // target for workerSaveResult. Called inside the file's write lock, so tokens // are made in the order the saves are written. A token starts with the time it @@ -122,6 +151,143 @@ async function readWorkerCanary(url) { } catch (e) { return null; } } +// The latest save this tab made of each worker, its canary token, by the +// address the canary is read at. Any update of a site redeploys its dynamic +// backends, not only a save of one, so whether a worker serves its latest save +// is read from its canary each time it's asked (backendStillSwitching). +const backendSaves = new Map(); + +// `url` as the address a worker's saves are kept under, its origin and path +// with no trailing slash. A relative one is the preview's, where a page's own +// requests go. null when it isn't an address. +function backendAddress(url) { + try { + const u = new URL(String(url || ''), window.currentPreviewUrl || undefined); + return (u.origin + u.pathname).replace(/\/+$/, ''); + } catch (e) { return null; } +} + +function noteBackendSave(target) { + const key = backendAddress(target.url); + if (key) backendSaves.set(key, target.token); +} + +// The latest save of the worker a request to `at` went to, as { key, token }, +// where key is the address its canary is read at. A save this tab made is +// known. A dynamic backend of the site at `siteUrl` serving `dir` (the open +// preview unless given) this tab never saved is read from its file, which +// every save stamps. null when neither says, or when the file doesn't parse, +// since Puter never runs that save. +async function latestBackendSave(at, siteUrl, dir) { + for (const [key, token] of backendSaves) { + if (at === key || at.startsWith(key + '/')) return { key, token }; + } + const SB = window.SiteBackends; + const site = backendAddress(siteUrl || window.currentPreviewUrl); + const prefix = site && SB ? site + '/' + SB.FOLDER + '/' : null; + if (!prefix || !at.startsWith(prefix)) return null; + const name = at.slice(prefix.length).split('/')[0]; + if (!dir) dir = window.currentPreviewPath || (typeof currentAppDir !== 'undefined' ? currentAppDir : null); + if (!SB.validName(name) || !dir) return null; + let text; + try { text = await (await puter.fs.read(dir + '/' + SB.FOLDER + '/' + name + SB.SUFFIX)).text(); } + catch (e) { return null; } + const token = window.workerCanaryToken(text); + if (!token) return null; + try { new Function(text); } catch (e) { return null; } + return { key: prefix + name, token }; +} + +// Checks under way, by the address a failed request went to, so a page +// failing many times at once reads the canary once. +const backendChecks = new Map(); + +// Whether a failed request to `url` went to a worker that isn't serving its +// latest save at this moment, read from its canary. The worker is down or +// switching over, so the failure is expected and says nothing about the +// code. false for a request to anything else, or to a worker whose latest +// save isn't known. +window.backendStillSwitching = function(url) { + const at = backendAddress(url); + if (!at) return Promise.resolve(false); + if (backendChecks.has(at)) return backendChecks.get(at); + const check = (async () => { + const save = await latestBackendSave(at); + return !!save && !servesSave(await readWorkerCanary(save.key), save.token); + })().catch(() => false).finally(() => backendChecks.delete(at)); + backendChecks.set(at, check); + return check; +}; + +// Any hosting.update of a site redeploys its dynamic backends, even ones +// whose files didn't change. A few seconds after the update each one goes +// down (Puter's 404, then a 500) and comes back by itself, so a page loaded +// in between finds it failing. Its canary keeps the same token, since nothing +// was saved, so going down and coming back is the only sign the redeploy is +// over. +// +// Called before the update of the site at `siteUrl`, which serves `dir`: reads +// which of its backends serve their latest save. Resolves the wait to run once +// the update is done, which resolves true when each of those has gone down +// and been back for redeploySettleMs, false at limitMs, or null as soon as +// `live()` turns false. A backend that hasn't gone down within redeployDownMs +// of the update counts as untouched. One that wasn't up before isn't waited +// on, since it may not come up at all. +window.watchSiteBackends = async function(siteUrl, dir) { + const none = async () => true; + const SB = window.SiteBackends; + if (!SB || !siteUrl || !dir) return none; + let saves; + try { + saves = await Promise.all((await SB.list(dir)).map((b) => { + const at = backendAddress(SB.urlOf(siteUrl, b.name)); + return at ? latestBackendSave(at, siteUrl, dir).catch(() => null) : null; + })); + } catch (e) { return none; } + const up = async (save) => servesSave(await readWorkerCanary(save.key), save.token); + const watched = (await Promise.all(saves.filter(Boolean).map(async (save) => ((await up(save)) ? save : null)))).filter(Boolean); + if (!watched.length) return none; + return async function(live) { + const { limitMs, redeployPollMs, redeployDownMs, redeploySettleMs } = window.workerCanaryTiming; + const start = Date.now(); + // When each backend went down, and when it was last seen back since. + const wentDown = new Map(); + const backSince = new Map(); + let waiting = watched; + while (waiting.length) { + if (Date.now() - start >= limitMs) return false; + const seen = await Promise.all(waiting.map(up)); + if (!live()) return null; + const now = Date.now(); + waiting = waiting.filter((save, i) => { + if (!seen[i]) { wentDown.set(save, true); backSince.delete(save); return true; } + if (!wentDown.has(save)) return now - start < redeployDownMs; + if (!backSince.has(save)) backSince.set(save, now); + return now - backSince.get(save) < redeploySettleMs; + }); + if (!waiting.length) break; + await new Promise((r) => setTimeout(r, redeployPollMs)); + if (!live()) return null; + } + return true; + }; +}; + +// "Applying changes" while the AI's save of a backend waits to go live, beside +// the dots and over the preview, the words update_preview's refresh shows, +// since the preview's backend runs the previous code until then. Returns what +// takes the overlay down, leaving it up for a refresh under way. Nothing for +// a Code view save or a GitHub pull (no `state`), or for a turn whose project +// is no longer open, whose dots and preview are another project's. +function showBackendApplying(state) { + if (!state || window.isStaleTurn?.(state) || state.abortController?.signal?.aborted) return () => {}; + window.setSpinnerLabel?.('Applying changes'); + window.showPreviewUpdating?.(true); + return () => { + if (!window.isStaleTurn?.(state) && !window.previewRefreshInFlight?.()) window.showPreviewUpdating?.(false); + }; +} + // The `worker` field of a worker save's result, once the worker serves the // saved `code` or the wait runs out. Null when the file isn't a worker's. window.workerSaveResult = async function(target, code, state) { @@ -148,15 +314,20 @@ window.workerSaveResult = async function(target, code, state) { return { name: target.name, live: false, error: e && e.message ? (e.name || 'Error') + ': ' + e.message : String(e), note: "The file is saved, but it doesn't parse, so the worker is still running its previous code. Fix the error and save the file again." }; } + // Puter deploys it, so from now the worker switches over to it. + noteBackendSave(target); const { pollMs, limitMs } = window.workerCanaryTiming; const deadline = Date.now() + limitMs; - for (;;) { - if (servesSave(await readWorkerCanary(target.url), target.token)) { - return { name: target.name, url: target.url, live: true }; + const hide = showBackendApplying(state); + let live = false; + try { + for (;;) { + if (servesSave(await readWorkerCanary(target.url), target.token)) { live = true; break; } + if (Date.now() >= deadline || state?.abortController?.signal?.aborted) break; + await new Promise(r => setTimeout(r, pollMs)); } - if (Date.now() >= deadline || state?.abortController?.signal?.aborted) break; - await new Promise(r => setTimeout(r, pollMs)); - } + } finally { hide(); } + if (live) return { name: target.name, url: target.url, live: true }; return { name: target.name, live: false, note: `The file is saved, but the worker wasn't serving it yet after ${Math.round(limitMs / 1000)} seconds. It may still be updating, or still running its previous code.` }; }; @@ -384,7 +555,7 @@ async function handleToolCalls(completion, isTopLevel = false, c) { // version history. Done in finally because multi-path tools (move, // mkdir) can mutate the filesystem and then throw — the change still // happened. No-op for non-mutating tool names. - window.markProjectModified?.(toolCall.name, c.currentChatId); + window.markProjectModified?.(toolCall.name, c.currentChatId, { backendOnly: window.isBackendSaveCall(toolCall, c) }); // Counted for the Usage Limit Hit event (limitHitTurnProps). if (c.turnStats && toolCall.name === 'update_preview') c.turnStats.previewChecks++; if (!window.isMutatingTool || window.isMutatingTool(toolCall.name)) { diff --git a/src/js/ui.js b/src/js/ui.js index af49cf5e..d8636dcd 100644 --- a/src/js/ui.js +++ b/src/js/ui.js @@ -839,6 +839,10 @@ window.previewHostSkipsBrowserCache = previewHostSkipsBrowserCache; // it answers, the frame shows puter.host. If not, the frame shows puter.site // and the refresh clears its cache as described above. // +// puter.host doesn't run dynamic backends. A /__workers/ request there gets +// its own 404 page (checked 2026-11-17). So a draft whose folder holds any +// shows on puter.site, with no check. +// // The frame and the Share draft link move. window.currentPreviewUrl, the saved // project and what the AI sees keep the puter.site address the hosting API // gives, and previewShownUrl turns it into the one to show. @@ -893,6 +897,24 @@ async function checkPuterHost(url) { return ok; } +// Whether the served folder holds dynamic backends (see site-backends.js). A +// lookup that fails counts as yes, which only costs the slower refresh on +// puter.site. +function siteHasBackends(dir) { + const SB = window.SiteBackends; + if (!SB || !dir) return Promise.resolve(false); + return SB.list(dir).then((list) => list.length > 0, () => true); +} + +// Whether the draft at `url` shows on puter.host. `backends` is +// siteHasBackends of the folder it serves, and a folder with dynamic backends +// shows on puter.site. puter.host is asked at the same time, so the lookup +// adds no wait. +async function previewOnPuterHost(url, backends) { + const answers = checkPuterHost(url); + return !(await backends) && answers; +} + function showPreviewUpdating(show) { const $body = $('.preview-body'); if (!$body.length) return; @@ -1046,6 +1068,30 @@ async function refreshPreviewWhenReady() { } window.refreshPreviewWhenReady = refreshPreviewWhenReady; +// ---- Pages unchanged since the last clear ---- +// A clear (waitForPreviewClear) is there so puter.site serves the project's +// changed pages, and its hosting.update takes the site's dynamic backends +// down for a few seconds (watchSiteBackends in tools.js). So during a turn +// whose only changes were the AI's saves of backend files, which no page +// shows, the preview just reloads, once a clear has covered every other +// change. Per project: a count of the changes that may show in its pages, +// bumped by every change to its files except those saves +// (markProjectModified in versions.js) and whenever it's opened, and the count +// its last completed clear covered. +const _pageChanges = new Map(); +const _pagesClearedAt = new Map(); +window.notePagesChanged = function (chatId) { + if (chatId) _pageChanges.set(chatId, (_pageChanges.get(chatId) || 0) + 1); +}; +function pageChangeCount(chatId) { return _pageChanges.get(chatId) || 0; } +// Whether a refresh of `chatId`'s preview can skip the clear. Only during a +// turn: a refresh outside one follows a restore or a GitHub update, whose +// writes aren't counted here. +function pagesUnchanged(chatId) { + return !!isProcessing && !!chatId && _pagesClearedAt.has(chatId) + && _pagesClearedAt.get(chatId) === pageChangeCount(chatId); +} + // The body of refreshPreviewWhenReady: it bows out the moment `seq` is no // longer _previewRefreshSeq. async function runPreviewRefresh($frame, baseUrl, ownerChatId, seq, early) { @@ -1055,7 +1101,7 @@ async function runPreviewRefresh($frame, baseUrl, ownerChatId, seq, early) { const dir = publishedRootDir(); // puter.host or puter.site (see "Which host shows the draft"). The check // runs alongside the manifest pass, or alongside the early clear. - const hostCheck = checkPuterHost(baseUrl); + const hostCheck = previewOnPuterHost(baseUrl, siteHasBackends(dir)); let onHost; if (early) { // The early clear is this refresh's now, and bows out with it. Handed @@ -1075,11 +1121,16 @@ async function runPreviewRefresh($frame, baseUrl, ownerChatId, seq, early) { } else if (await early.cleared === null) { return; // superseded } + } else if (pagesUnchanged(ownerChatId)) { + // Only backend files changed since the last clear, so there's nothing + // for puter.site to clear (see pagesUnchanged). + onHost = await hostCheck; + if (!live()) return; // superseded while checking } else { const shown = hostCheck.then((ok) => (ok ? toPuterHost(baseUrl) : baseUrl)); if (await preparePreviewFiles(shown, dir, live) === null) return; // superseded onHost = await hostCheck; - if (!onHost && await waitForPreviewClear(baseUrl, dir, live) === null) return; // superseded + if (!onHost && await waitForPreviewClear(baseUrl, dir, live, ownerChatId) === null) return; // superseded } // Bail if a newer reload/refresh/chat-switch happened, or the live preview @@ -1118,9 +1169,9 @@ async function runPreviewRefresh($frame, baseUrl, ownerChatId, seq, early) { // Get puter.site serving the project's current files, up to the reload. // Resolves true once the canary shows the site-wide clear, false at the limit, // and null as soon as `live()` turns false, checked after every await. -async function clearPreviewCache(baseUrl, dir, live) { +async function clearPreviewCache(baseUrl, dir, live, chatId) { if (await preparePreviewFiles(baseUrl, dir, live) === null) return null; - return waitForPreviewClear(baseUrl, dir, live); + return waitForPreviewClear(baseUrl, dir, live, chatId); } // Prepare the project's files for the reload: the install block, then the @@ -1159,8 +1210,10 @@ async function preparePreviewFiles(shownUrl, dir, live) { } // The canary wait on puter.site (see the top of this section), once the files -// are prepared. Resolves like clearPreviewCache. -async function waitForPreviewClear(baseUrl, dir, live) { +// are prepared. Resolves like clearPreviewCache. A clear that went through +// records, for `chatId`, the changes it covered (see pagesUnchanged). +async function waitForPreviewClear(baseUrl, dir, live, chatId) { + const changes = chatId ? pageChangeCount(chatId) : null; // The canary (see the top of this section). Every step comes after the // project's writes and preparePreviewFiles, so the clear it proves covers // all of them. @@ -1182,7 +1235,14 @@ async function waitForPreviewClear(baseUrl, dir, live) { const canaryPath = dir + '/' + PREVIEW_CANARY; const t0 = Date.now(); let before = null; + // The update below redeploys the site's dynamic backends, which go down a + // few seconds later and come back by themselves. The reload waits that + // out (watchSiteBackends in tools.js), so the page never calls one while + // it's down. Which backends are up is read now, alongside the canary. + let backendsBack = null; if (sub && dir && typeof fetch === 'function') { + const backends = window.watchSiteBackends + ? window.watchSiteBackends(baseUrl, dir).catch(() => null) : Promise.resolve(null); before = await readPreviewCanary(baseUrl); if (!live()) return null; // superseded while reading the canary if (before === null) { @@ -1199,9 +1259,12 @@ async function waitForPreviewClear(baseUrl, dir, live) { log('wrote', next); } catch (e) { before = null; log('write failed', e); } if (!live()) return null; // superseded while writing the canary + const wait = await backends; + if (!live()) return null; // superseded while reading the backends try { await puter.hosting.update(sub, dir); log('asked for the clear', (Date.now() - t0) + 'ms'); + if (wait) backendsBack = wait(live); } catch (e) { before = null; log('hosting.update failed', e); } if (!live()) return null; // superseded while asking for the clear } @@ -1217,6 +1280,12 @@ async function waitForPreviewClear(baseUrl, dir, live) { if (!live()) return null; // superseded while waiting } log(flipped ? 'cleared' : 'no clear seen by the limit', (Date.now() - t0) + 'ms'); + if (backendsBack) { + const back = await backendsBack; + if (back === null || !live()) return null; // superseded while the backends came back + log(back ? 'backends back' : 'backends not back by the limit', (Date.now() - t0) + 'ms'); + } + if (flipped && chatId) _pagesClearedAt.set(chatId, changes); return flipped; } @@ -1246,11 +1315,12 @@ window.startEarlyPreviewClear = function () { // stopped answering by the time the refresh checks again, the refresh // clears puter.site itself. if (frameOnPuterHost(baseUrl)) return; + if (pagesUnchanged(currentChatId)) return; const run = { baseUrl, dir: publishedRootDir(), chatId: currentChatId, seq: _previewRefreshSeq, dropped: false }; // Superseded like a refresh, or dropped. The refresh that takes it over // swaps in its own test. run.live = () => !run.dropped && run.seq === _previewRefreshSeq; - run.cleared = clearPreviewCache(baseUrl, run.dir, () => run.live()); + run.cleared = clearPreviewCache(baseUrl, run.dir, () => run.live(), run.chatId); _earlyPreviewClear = run; }; window.dropEarlyPreviewClear = function () { @@ -1408,7 +1478,8 @@ window.showAppPreview = function(url, opts) { }; // Load the draft at `url` (its puter.site address) in the frame, on puter.host -// when it answers (see "Which host shows the draft"). The frame leaves the +// when it answers and the folder has no dynamic backends (see "Which host +// shows the draft"). The frame leaves the // previous project before the check, and its stored address becomes this // project's, so a reload that lands during the check (the toolbar's Reload, // the badge sync refreshPublishButton runs) loads this project, not the one @@ -1422,7 +1493,7 @@ async function loadPreviewOnAnsweringHost(url) { const $frame = $('.preview-frame'); $frame.data('preview-url', url); $frame.attr('src', 'about:blank'); - const onHost = await checkPuterHost(url); + const onHost = await previewOnPuterHost(url, siteHasBackends(publishedRootDir())); if (open !== _previewOpenSeq || window.currentPreviewUrl !== url || !$('body').hasClass('preview-active')) return; reloadPreviewFrame(onHost ? toPuterHost(url) : url, { keepPendingUpdate: true }); } @@ -2485,6 +2556,145 @@ async function deployPublishedWorkers(chatId, appDir, releaseDir, srcPath = appD return renames; } +// ----- dynamic backends ----------------------------------------------------- +// +// A dynamic backend (__workers/.worker.js, see site-backends.js) runs +// from the files of the site that serves it, so a release carries its own and +// the live site runs them as they were at publish, with nothing to deploy. +// What doesn't travel with the files is the site's store, which belongs to the +// site's address. The live site gets the preview's keys and sender name at +// every publish, and a new live address gets the old one's. + +// Take the preview's save canary (see stampWorkerCanary) off the release's +// backends, as a published worker's frozen copy never has it. Best effort, +// since the canary only answers a route nobody calls. +async function stripCanaryFromReleaseBackends(releaseDir) { + let backends = []; + try { backends = await window.SiteBackends.list(releaseDir); } catch (e) { return; } + for (const backend of backends) { + try { + const text = await puter.fs.read(backend.path).then(d => d.text()); + const clean = window.stripWorkerCanary(text); + if (clean !== text) await puter.fs.write(backend.path, clean, { overwrite: true }); + } catch (e) { + console.warn('Publish: could not remove the save canary from', backend.path, e); + } + } +} + +// The names of the dynamic backends a site's files hold, [] when there are +// none or the folder can't be read. +async function siteBackendNames(dir) { + if (!window.SiteBackends || !dir) return []; + try { return (await window.SiteBackends.list(dir)).map(b => b.name); } + catch (e) { return []; } +} + +// Give the backends of the site at `toUrl` the keys and sender name of the +// one at `fromUrl` (see worker-secrets.js and worker-sender.js), warning when +// one doesn't arrive. `what` names the destination in those warnings, and +// opts.liveOnly carries live-only keys over as live-only. Resolves the key +// copy's result, for WorkerSecrets.publishNote. Never throws. +async function copySiteBackendStore(fromUrl, toUrl, backends, what, opts) { + const to = { site: toUrl, backends }; + let keys = null; + try { + keys = await window.WorkerSecrets?.copy({ site: fromUrl }, to, opts); + if (keys && !keys.ok) { + window.showToast?.(keys.reason === 'declined' + ? `${what} didn’t get its keys, so the parts that need them won’t work until you allow it. Publish again to be asked again.` + : `${what} didn’t get its keys. Publish again in a moment.`, + { type: 'warning', key: 'publish-keys', throttleMs: 5000, duration: 10000 }); + } + } catch (e) { /* copy reports its own failures */ } + try { + const sender = await window.WorkerSender?.copy({ site: fromUrl }, to); + if (sender && !sender.ok) { + window.showToast?.(sender.reason === 'forbidden' + ? `${what} still sends email under its old sender name. Builder can’t rename a site’s app, so set its title in the Dev Center.` + : `${what} still sends email under its old sender name. Publish again in a moment.`, + { type: 'warning', key: 'publish-sender', throttleMs: 5000, duration: 10000 }); + } + } catch (e) { /* the warning above covers it */ } + return keys; +} + +// Give the live site's dynamic backends the preview's keys, except the live +// site's own, and its sender name, at its address and at each of +// `domainUrls`, the user's own domains serving it, which run them as apps of +// their own. A republish runs it before the live site switches to the +// release, a first publish right after creating the address. Resolves the +// reports for WorkerSecrets.publishNote, [] for a release with no dynamic +// backend. +async function publishSiteBackends(previewUrl, liveUrl, releaseDir, domainUrls) { + if (!previewUrl || !liveUrl) return []; + const backends = await siteBackendNames(releaseDir); + if (!backends.length) return []; + const reports = [{ live: liveUrl, result: await copySiteBackendStore(previewUrl, liveUrl, backends, 'Your live site’s backend') }]; + for (const url of domainUrls || []) { + const host = url.replace(/^https:\/\//, '').replace(/\/+$/, ''); + reports.push({ live: url, result: await copySiteBackendStore(previewUrl, url, backends, `Your backend at ${host}`) }); + } + return reports; +} + +// Before the live site moves from `oldUrl` to a new address. The app Builder +// registered for it moves along with everything in it (finishSiteMove), so +// there's nothing to ask. Without one, the dynamic backends' data stays in the +// old address's store, so the user decides first. Resolves the plan for +// finishSiteMove, or null when the user keeps the address. +async function planSiteMove(oldUrl, releaseDir) { + const backends = await siteBackendNames(releaseDir); + if (await window.SiteBackends?.hasApp(oldUrl)) return { moveApp: true, backends }; + if (!backends.length) return { moveApp: false, backends }; + const go = await puterConfirm('Your live site’s backend keeps the data it saved under its current address. At the new address it starts with no saved data, though its keys come along. Change the address anyway?'); + return go ? { moveApp: false, backends } : null; +} + +// Right after the site at `newUrl` is created, before anything runs there. +// The app Builder registered for the old address moves to it, data, keys and +// sender name included. When Puter refuses the move, the new address goes +// again and this throws, so the address stays as it was, data and all, +// instead of leaving the app on an address that's about to be given up. +// Without Builder's app, the backends get their keys copied over while their +// saved data stays behind (planSiteMove asked about that). +async function finishSiteMove(oldUrl, newUrl, plan) { + if (!plan) return; + if (plan.moveApp) { + if (await window.SiteBackends.moveApp(oldUrl, newUrl)) return; + const newSub = previewSubdomain(newUrl); + try { if (newSub) await puter.hosting.delete(newSub); } + catch (e) { console.warn('Could not remove the new address after its app failed to move:', e); } + throw new Error('Your live site’s data couldn’t move to the new address, so the address wasn’t changed. Try again in a moment.'); + } + await moveSiteBackends(oldUrl, newUrl, plan.backends); +} + +// After the live site moved from `oldUrl` to `newUrl` without its app, give +// its dynamic backends their keys and sender name there, and clear the keys +// from the old address's store, which nothing serves anymore. +async function moveSiteBackends(oldUrl, newUrl, backends) { + if (!backends || !backends.length) return; + const keys = await copySiteBackendStore(oldUrl, newUrl, backends, 'Your live site’s backend', { liveOnly: true }); + // Only once the keys arrived, so a failed copy can be tried again. + if (keys && keys.ok) { + try { await window.WorkerSecrets?.clear({ site: oldUrl }); } catch (e) { /* best effort */ } + } +} + +// Right after the user's own domain at `domainUrl` is attached to the live +// site at `liveUrl`, which serves `releaseDir`. The domain runs the release's +// dynamic backends as an app of its own, so, as a publish would, it gets their +// keys and sender name, the live site's, its live-only keys included. +// Resolves what the key copy did, or null for a release with no dynamic +// backend. +async function attachSiteBackends(liveUrl, domainUrl, releaseDir) { + const backends = await siteBackendNames(releaseDir); + if (!backends.length) return null; + const host = domainUrl.replace(/^https:\/\//, '').replace(/\/+$/, ''); + return copySiteBackendStore(liveUrl, domainUrl, backends, `Your backend at ${host}`, { liveOnly: true }); +} + // Remove the runtime tag (and with it the "Made with Puter" badge) from every // HTML page of a staged release — see branding.js. The release is a private // copy nothing else writes to, so no file locks. assets/ holds the user's own @@ -2694,6 +2904,7 @@ async function stagePublishRelease(chatId, appDir, srcPath, { removeBadge = fals const user = window.refreshUserPlan ? await window.refreshUserPlan() : window.user; const branding = removeBadge && window.Branding?.isSubscribed(user) ? 'removed' : 'kept'; if (branding === 'removed') await stripBrandingFromRelease(releaseDir); + if (window.SiteBackends) await stripCanaryFromReleaseBackends(releaseDir); // Give the release its own backend and point it there, BEFORE the public // address starts serving it: the new frontend may need endpoints the old @@ -3014,6 +3225,9 @@ async function publishProject(ui) { // The preview's address too: a social image the AI pointed at the preview // is moved to the published address (absolutizeSocialImagesInRelease). const startPreviewUrl = window.currentPreviewUrl || null; + // And its own domains, whose backends get the keys too. + const startDomains = window.currentPublishedDomains; + const domainUrlsOf = (sub) => window.CustomDomain?.urlsFor(startDomains, sub) || []; // Same for the version baseline: getCurrentVersionId() answers for whichever // project is open, so it is only trustworthy for this one while it still is. // If the user switches away, no "Published" snapshot is taken below (that is @@ -3076,6 +3290,9 @@ async function publishProject(ui) { let url = startUrl; const existingSub = previewSubdomain(url); + // What the live site's dynamic backends got, for the line added to the + // conversation below. + let siteBackendKeys = []; if (!existingSub && reserved) { // First publish by the own-domain route: the name is already the // project's, serving an empty folder, so point it at the release @@ -3083,6 +3300,13 @@ async function publishProject(ui) { const sub = await reserved; url = `https://${sub}.puter.site/`; await absolutizeSocialImagesInRelease(releaseDir, url, [startPreviewUrl]); + // Nothing has run at the address yet, so its app and its backends' + // keys come before the release, as on the first publish below. A + // retry after a failed publish finds the app already there. + if (window.SiteBackends?.isDynamicProject(startHistory) && !(await window.SiteBackends.hasApp(url))) { + await window.SiteBackends.registerApp(url, window.SiteBackends.titleOf(chatId), 'live'); + } + siteBackendKeys = await publishSiteBackends(startPreviewUrl, url, releaseDir, domainUrlsOf(sub)); await puter.hosting.update(sub, releaseDir); _reservedPublishNames.delete(chatId); } else if (!existingSub) { @@ -3091,13 +3315,26 @@ async function publishProject(ui) { // coded error for an invalid/taken explicit name (handled below). const sub = await createPublishSubdomain(releaseDir, desiredName, startHistory); url = `https://${sub}.puter.site/`; + // A project with dynamic backends runs its live site as an app + // Builder registers now, before anything runs there (see + // site-backends.js). + if (window.SiteBackends?.isDynamicProject(startHistory)) { + await window.SiteBackends.registerApp(url, window.SiteBackends.titleOf(chatId), 'live'); + } await absolutizeSocialImagesInRelease(releaseDir, url, [startPreviewUrl]); + // The release's dynamic backends get their keys and sender name, + // while the address is new to everyone. + siteBackendKeys = await publishSiteBackends(startPreviewUrl, url, releaseDir, domainUrlsOf(sub)); if (leftReserved) { _reservedPublishNames.delete(chatId); try { await puter.hosting.delete(leftReserved); } catch (e) { console.warn('Publish: could not remove the reserved address:', e); } } } else { + // A new key reaches the live site's dynamic backends before the + // code that needs it does, so its first visitor isn't the one to + // find it missing. + siteBackendKeys = await publishSiteBackends(startPreviewUrl, url, releaseDir, domainUrlsOf(existingSub)); // Re-publish: re-point the existing public subdomain at the freshly // copied release, once its pages carry the full address. await absolutizeSocialImagesInRelease(releaseDir, url, [startPreviewUrl]); @@ -3161,7 +3398,7 @@ async function publishProject(ui) { // WorkerSecrets.publishNote). A project without keys gets no line. // No turn can be running here, since a turn waits for a publish. const keysNote = window.WorkerSecrets?.publishNote?.( - publishedWorkers.map(w => ({ live: w.newName, result: w.keys }))); + publishedWorkers.map(w => ({ live: w.newName, result: w.keys })).concat(siteBackendKeys)); if (keysNote && typeof chatHistory !== 'undefined' && Array.isArray(chatHistory)) { const messageId = (typeof generateMessageId === 'function') ? generateMessageId() : null; // versionNote: not a build reply (see countCompletedBuilds). @@ -3625,10 +3862,14 @@ async function changePublishedAddress(typed) { try { const path = await resolvePublishedDir(window.currentPublishedPath, chatId); if (!path) throw fail('no-files'); + // The site's app moves with it, or the user hears what stays behind. + const move = await planSiteMove(oldUrl, path); + if (!move) return { changed: false, cancelled: true }; // Create the new subdomain first; only drop the old one once that // succeeds, so a failure (e.g. name taken) leaves the site reachable. await puter.hosting.create(newSub, path); const newUrl = `https://${newSub}.puter.site/`; + await finishSiteMove(oldUrl, newUrl, move); // Social image URLs move to the new address before the old one goes. await absolutizeSocialImagesInRelease(path, newUrl, [oldUrl]); try { await puter.hosting.delete(oldSub); } @@ -3914,6 +4155,13 @@ function connectCustomDomain(sub = previewSubdomain(window.currentPublishedUrl), openUpgradeModal('custom_domain'); return; } + // Read before the dialog, which the user may leave for another project. + const dynamic = !!window.SiteBackends?.isDynamicProject(chatHistory); + // The live site the domain goes on and the release it serves, whose + // backends' keys the domain gets. Before a first publish there's none, + // and the publish gives the domain its keys. + const liveUrl = previewSubdomain(window.currentPublishedUrl) === sub ? window.currentPublishedUrl : null; + const liveDir = liveUrl ? window.currentPublishedPath : null; let attaching; try { attaching = Promise.resolve(puter.hosting.attach(sub)); } catch (e) { attaching = Promise.reject(e); } @@ -3930,9 +4178,14 @@ function connectCustomDomain(sub = previewSubdomain(window.currentPublishedUrl), const domain = window.CustomDomain.normalize({ ...raw, site: raw.site || sub }); if (!domain) return null; chosen = domain; + // A project with dynamic backends runs them on the domain as an app + // Builder registers now, before anything runs there, so it can be + // renamed and given keys (see site-backends.js). + if (dynamic) await window.SiteBackends.claimDomain('https://' + domain.hostname + '/', window.SiteBackends.titleOf(chatId), chatId); _domainNotYet.delete(domain.hostname); await updatePublishedDomains(chatId, (list) => window.CustomDomain.set(list, domain)); releaseCustomDomainElsewhere(chatId, domain.hostname); + if (liveDir) await attachSiteBackends(liveUrl, 'https://' + domain.hostname + '/', liveDir); try { await onDomain?.(domain); } catch (e) { console.warn('Custom domain: could not record the domain on its card:', e); } window.track?.('Custom Domain Connected', { status: domain.status, apex: domain.isApex }); if (currentChatId === chatId) { @@ -4939,7 +5192,7 @@ window.resetPreviewErrorDedup = function () { const FETCH_ERROR_DEBOUNCE_MS = 2000; _autoFixDedupResets.push(function () { lastFetchErrorKey = ''; }); - window.addEventListener('message', function(event) { + window.addEventListener('message', async function(event) { if (!event.data || event.data.type !== 'fetch-error') return; // Only accept messages from the live preview iframe (sender window + @@ -4947,6 +5200,12 @@ window.resetPreviewErrorDedup = function () { if (!isTrustedPreviewMessage(event)) return; const { url, status, body } = event.data; + // A backend still switching over to its latest save fails for that + // alone, so the failure is expected (backendStillSwitching in + // tools.js). + const chatId = currentChatId; + if (await window.backendStillSwitching?.(url)) return; + if (chatId !== currentChatId) return; const errorKey = `${url}|${status}|${(body || '').slice(0, 200)}`; if (errorKey === lastFetchErrorKey) return; lastFetchErrorKey = errorKey; @@ -5014,6 +5273,12 @@ window.resetPreviewErrorDedup = function () { const buffer = []; let capturing = false; // true only between reload-commit and observe-end let pending = false; // arm the NEXT reload-commit to begin capturing + // A failed request counts once the backend it went to is known not to be + // switching over to a new save (backendStillSwitching in tools.js). These + // are those checks, for this pass, numbered so a late one never lands in + // the next pass's buffer. + const checks = []; + let pass = 0; function pushError(text) { if (capturing !== true) return; @@ -5046,7 +5311,11 @@ window.resetPreviewErrorDedup = function () { } else { const url = d.url ? String(d.url) : ''; const status = +d.status > 0 ? Math.trunc(+d.status) : 0; - pushError('Failed network request' + (status ? ' (HTTP ' + status + ')' : ' (network/CORS error)') + (url ? ': ' + url : '')); + const text = 'Failed network request' + (status ? ' (HTTP ' + status + ')' : ' (network/CORS error)') + (url ? ': ' + url : ''); + const mine = pass; + checks.push(Promise.resolve(window.backendStillSwitching?.(url)) + .catch(function () { return false; }) + .then(function (switching) { if (!switching && mine === pass) pushError(text); })); } }); @@ -5062,7 +5331,7 @@ window.resetPreviewErrorDedup = function () { capturing = true; }; - function reset() { pending = false; capturing = false; buffer.length = 0; } + function reset() { pending = false; capturing = false; buffer.length = 0; checks.length = 0; pass++; } // Run one verification pass: trigger the preview reload (the same background // refresh the tool used to fire directly), wait for the fresh document to @@ -5162,6 +5431,9 @@ window.resetPreviewErrorDedup = function () { if (aborted()) { testsDropped = true; return { status: 'skipped', reason: 'aborted' }; } await new Promise(function (r) { setTimeout(r, 300); }); } + // A canary read takes at most 5 seconds (readWorkerCanary). + await Promise.all(checks.slice()); + if (aborted()) { testsDropped = true; return { status: 'skipped', reason: 'aborted' }; } const errors = buffer.slice(); if (errors.length) { testsDropped = true; return { status: 'errors', errors: errors }; } @@ -6202,9 +6474,18 @@ async function showChatProperties(chatId) { renderPublishedCell(); return; } + // The site's app moves with it (see the toolbar's address + // editor). + const move = await planSiteMove(pub.url, path); + if (!move) { + $save.prop('disabled', false); + $input.prop('disabled', false).trigger('focus'); + return; + } // Create the new subdomain first; only drop the old one once that // succeeds, so a failure leaves the site reachable. await puter.hosting.create(newSub, path); + await finishSiteMove(pub.url, `https://${newSub}.puter.site/`, move); // Social image URLs move to the new address (see the toolbar's // address editor). await absolutizeSocialImagesInRelease(path, `https://${newSub}.puter.site/`, [pub.url]); diff --git a/src/js/versions.js b/src/js/versions.js index 6dec9a6c..7a6d6db2 100644 --- a/src/js/versions.js +++ b/src/js/versions.js @@ -33,9 +33,12 @@ // Called by the tool dispatcher after a project-modifying tool runs, and by // the attachment-save path. Non-mutating tool names are ignored. `chatId` // is the turn's chat (a mid-turn switch must not dirty the chat the user - // moved to); it defaults to the open chat. - window.markProjectModified = function (toolName, chatId) { + // moved to); it defaults to the open chat. Every change counts as one the + // preview's pages may show (notePagesChanged in ui.js), except the AI's + // save of a backend file (opts.backendOnly), which no page shows. + window.markProjectModified = function (toolName, chatId, opts) { if (toolName && !MUTATING_TOOLS.has(toolName)) return; + if (!(opts && opts.backendOnly)) window.notePagesChanged?.(chatId || openChatId()); window._filesChangedThisTurn = (window._filesChangedThisTurn || 0) + 1; // The working dir now has changes that may not yet be captured by a // snapshot. restoreVersion reads this to take a pre-restore safety diff --git a/src/js/worker-secrets.js b/src/js/worker-secrets.js index d2ffc8dd..0d1552e1 100644 --- a/src/js/worker-secrets.js +++ b/src/js/worker-secrets.js @@ -24,6 +24,12 @@ // and Publish never copies over a live-only key. Keys never go the other way, // so a live key can't end up in the preview. // +// A dynamic backend (site-backends.js) runs as its site's own app instead, so +// its keys go into that app's store, shared by every backend of the site. Its +// target here is { site, backends }, the site's address and the names of its +// backends, and the preview and the live site are two addresses with a store +// each. Everything else works the same. +// // Builder also keeps the list of key names in the store itself // ("secret-names"), so copying and clearing never depend on listing another // app's store. Values never leave these functions: nothing here logs, tracks @@ -45,10 +51,17 @@ function validName(name) { return NAME_RE.test(String(name || '')); } - // The worker's own app, or null when it has none (a worker bound to no - // app can't hold keys of its own). - async function appOf(workerName) { - const info = await puter.workers.get(workerName); + // The app a target's keys live in, or null when it has none (a worker + // bound to no app can't hold keys of its own). A target is a worker's + // name, or { site, backends } for a site's dynamic backends. Puter makes a + // site's app the first time a backend there runs, so the backends are + // called first when it doesn't exist yet. + async function appOf(target) { + if (target && typeof target === 'object') { + const app = await window.SiteBackends.appOf(target.site, target.backends); + return (app && app.uid) || null; + } + const info = await puter.workers.get(target); return (info && info.app_uid) || null; } @@ -87,16 +100,16 @@ return 'other'; } - // Save one key into one worker's store. opts.liveOnly also marks it as the - // live site's own key, which Publish never copies over. Resolves + // Save one key into one target's store. opts.liveOnly also marks it as + // the live site's own key, which Publish never copies over. Resolves // { ok: true } or { ok: false, reason } with reason 'bad-name', 'empty', // 'too-long', 'no-app', 'declined' or 'failed'. - async function set(workerName, name, value, opts) { + async function set(target, name, value, opts) { if (!validName(name)) return { ok: false, reason: 'bad-name' }; if (typeof value !== 'string' || !value.trim()) return { ok: false, reason: 'empty' }; if (value.length > MAX_VALUE) return { ok: false, reason: 'too-long' }; let app; - try { app = await appOf(workerName); } catch (e) { return { ok: false, reason: 'failed' }; } + try { app = await appOf(target); } catch (e) { return { ok: false, reason: 'failed' }; } if (!app) return { ok: false, reason: 'no-app' }; if (!(await allow(app))) return { ok: false, reason: 'declined' }; try { @@ -109,11 +122,11 @@ } } - // The key names a worker holds (never the values). [] when Builder was + // The key names a target holds (never the values). [] when Builder was // never allowed into it, which means it holds none Builder put there. - async function names(workerName) { + async function names(target) { try { - const app = await appOf(workerName); + const app = await appOf(target); if (!app || !(await allowed(app))) return []; return await namesIn(app); } catch (e) { @@ -121,20 +134,23 @@ } } - // Copy every key from one worker to another (Publish: draft to live. - // Duplicate: original to copy), except the target's live-only keys. A - // worker with no keys copies nothing and never asks the user anything. + // Copy every key from one target to another (Publish: draft to live. + // Duplicate: original to copy. A new live address: old to new), except + // the target's live-only keys. A source with no keys copies nothing and + // never asks the user anything. // Resolves { ok, reason?, copied, keys: [{ name, kind, kept }] }, where // kept means the target kept its own live-only key. Never a value. - async function copy(fromWorker, toWorker) { + // opts.liveOnly carries the source's live-only marks over too, for a live + // site moving to a new address, whose live keys stay the live site's own. + async function copy(fromTarget, toTarget, opts) { let from, to; - try { from = await appOf(fromWorker); } catch (e) { return { ok: false, reason: 'failed', copied: 0, keys: [] }; } + try { from = await appOf(fromTarget); } catch (e) { return { ok: false, reason: 'failed', copied: 0, keys: [] }; } // Builder was never allowed into the source, so it put no keys there. if (!from || !(await allowed(from))) return { ok: true, copied: 0, keys: [] }; let list; try { list = await namesIn(from); } catch (e) { return { ok: false, reason: 'failed', copied: 0, keys: [] }; } if (!list.length) return { ok: true, copied: 0, keys: [] }; - try { to = await appOf(toWorker); } catch (e) { return { ok: false, reason: 'failed', copied: 0, keys: [] }; } + try { to = await appOf(toTarget); } catch (e) { return { ok: false, reason: 'failed', copied: 0, keys: [] }; } if (!to) return { ok: false, reason: 'no-app', copied: 0, keys: [] }; if (to === from) return { ok: true, copied: 0, keys: [] }; if (!(await allow(to))) return { ok: false, reason: 'declined', copied: 0, keys: [] }; @@ -156,6 +172,11 @@ const there = await namesIn(to); const merged = there.concat(list.filter((n) => !there.includes(n))); await puter.kv.set(NAMES_KEY, merged, { appUuid: to }); + if (opts && opts.liveOnly) { + for (const name of await listIn(from, LIVE_ONLY_KEY)) { + if (keys.some((k) => k.name === name && !k.kept)) await addTo(to, LIVE_ONLY_KEY, name); + } + } return { ok: true, copied, keys }; } catch (e) { return { ok: false, reason: 'failed', copied, keys }; @@ -204,12 +225,14 @@ return '*' + parts.join(' ') + '*'; } - // Remove every key Builder put into a worker, before the worker is deleted - // (a deleted project, a retired live backend). Never asks, since a worker - // Builder was never allowed into holds no keys of Builder's. - async function clear(workerName) { + // Remove every key Builder put into a target, before it goes (a deleted + // project, a retired live backend, a live address given up). Never asks, + // since a store Builder was never allowed into holds no keys of Builder's. + // Never calls a site's backends either, since a site whose app Puter + // hasn't made yet holds no keys. + async function clear(target) { try { - const app = await appOf(workerName); + const app = await appOf(target && typeof target === 'object' ? { site: target.site } : target); if (!app || !(await allowed(app))) return { ok: true, cleared: 0 }; const list = await namesIn(app); for (const name of list) await puter.kv.del(PREFIX + name, { appUuid: app }); diff --git a/src/js/worker-sender.js b/src/js/worker-sender.js index 5a3a7d50..73baa501 100644 --- a/src/js/worker-sender.js +++ b/src/js/worker-sender.js @@ -17,6 +17,15 @@ // by worker name, so a later worker with the same name would otherwise send // under it. // +// A dynamic backend (site-backends.js) runs as its site's app, so its target +// here is { site, backends } and the name belongs to the whole site. Builder +// registers that app itself, titled after the project, so the default is the +// project's name and the chosen name is kept in Builder's record of the app +// (`builder.senderName`). A site whose app Puter made instead (something ran +// there before Builder registered one) starts out titled with the app's id, +// and Puter lets an app rename only apps it made, so a rename comes back +// 'forbidden' and the tool tells the user how to set it in the Dev Center. +// // A backend still on its default name never changes anything, so a project // that never set a name sees no change. Copy only ever carries a name someone // chose. It never resets a name on the target, so a live backend renamed by @@ -49,11 +58,14 @@ // The worker's sandbox app ({ uid, name, title }), or null when the worker // runs as no app or as an app that isn't its own sandbox app (renaming - // that would rename something else). Throws when Puter can't be reached, - // so a lookup failure is never mistaken for "no app". Both lookups go out - // at once: this runs for every backend on every publish, duplicate and + // that would rename something else). For { site, backends }, the site's + // own app (SiteBackends.appOf). Throws when Puter can't be reached, so a + // lookup failure is never mistaken for "no app". Both lookups go out at + // once: this runs for every backend on every publish, duplicate and // delete. - async function appOf(workerName) { + async function appOf(target) { + if (target && typeof target === 'object') return await window.SiteBackends.appOf(target.site, target.backends); + const workerName = target; const [info, found] = await Promise.allSettled([ puter.workers.get(workerName), puter.apps.get(SANDBOX_PREFIX + workerName), @@ -74,6 +86,7 @@ // Whether someone gave the app a name of its own. A new sandbox app's // title is its name. function isCustom(app) { + if (app && app.builder) return !!app.builder.senderName; return !!app && typeof app.title === 'string' && app.title.trim() !== '' && app.title !== app.name; } @@ -96,17 +109,27 @@ return false; } - // Give one worker's app this title, unless it already has it. Resolves + // Give one target's app this title, unless it already has it. Resolves // { ok: true, changed } or { ok: false, reason } with reason 'no-app', // 'forbidden' or 'failed'. - async function setTitle(workerName, title) { + async function setTitle(target, title) { let app; - try { app = await appOf(workerName); } catch (e) { return { ok: false, reason: 'failed' }; } + try { app = await appOf(target); } catch (e) { return { ok: false, reason: 'failed' }; } if (!app) return { ok: false, reason: 'no-app' }; - const wanted = title === null ? app.name : title; - if (app.title === wanted) return { ok: true, changed: false }; + // A site's app Builder registered goes back to the project's name. + const wanted = title === null ? (app.builder ? app.builder.defaultTitle : app.name) : title; + // Builder's record says whether the title is a chosen name, so it's + // kept even when the title already reads that way. + const note = async () => { + if (app.builder && (app.builder.senderName || null) !== title) await window.SiteBackends.setSenderName(target.site, title); + }; try { + if (app.title === wanted) { + await note(); + return { ok: true, changed: false }; + } await puter.apps.update(app.name, { title: wanted }); + await note(); return { ok: true, changed: true }; } catch (e) { return { ok: false, reason: forbidden(e) ? 'forbidden' : 'failed' }; @@ -117,39 +140,41 @@ // the default back. Resolves { ok: true, changed, name } (name is null // for the default) or { ok: false, reason } with reason 'too-long', // 'bad-chars', 'no-app', 'forbidden' or 'failed'. - async function set(workerName, raw) { + async function set(target, raw) { let title = null; if (String(raw == null ? '' : raw).trim()) { const c = check(raw); if (!c.ok) return c; title = c.name; } - const r = await setTitle(workerName, title); + const r = await setTitle(target, title); return r.ok ? { ok: true, changed: r.changed, name: title } : r; } - // Carry the sender name from one worker to another (Publish: preview to - // live. Duplicate: original to copy). A source on the default name copies - // nothing and leaves the target alone. So does a source that can't be - // read: every project publishes through here, most never set a name, and - // warning them all about one Puter hiccup would be wrong far more often - // than right (the next publish tries again). The name is copied as it is, + // Carry the sender name from one target to another (Publish: preview to + // live. Duplicate: original to copy). A + // source on the default name copies nothing and leaves the target alone. + // So does a source that can't be read: every project publishes through + // here, most never set a name, and warning them all about one Puter + // hiccup would be wrong far more often than right (the next publish tries + // again). The name is copied as it is, // even one set by hand that check() would refuse, since Puter already // took it. Resolves { ok, reason?, copied }. - async function copy(fromWorker, toWorker) { + async function copy(fromTarget, toTarget) { let from; - try { from = await appOf(fromWorker); } catch (e) { return { ok: true, copied: false }; } + try { from = await appOf(fromTarget); } catch (e) { return { ok: true, copied: false }; } if (!isCustom(from)) return { ok: true, copied: false }; - const r = await setTitle(toWorker, from.title); + const r = await setTitle(toTarget, from.builder ? from.builder.senderName : from.title); return r.ok ? { ok: true, copied: r.changed } : { ok: false, reason: r.reason, copied: false }; } - // Put the default name back before a worker is deleted (a deleted project, - // a retired live backend). A worker on its default name is left alone. - async function clear(workerName) { + // Put the default name back before a target goes (a deleted project, a + // retired live backend). A target on its default name is left alone, and + // so is a site's app Builder registered, which goes with the project. + async function clear(target) { let app; - try { app = await appOf(workerName); } catch (e) { return { ok: false, reason: 'failed' }; } - if (!isCustom(app)) return { ok: true, cleared: false }; + try { app = await appOf(target); } catch (e) { return { ok: false, reason: 'failed' }; } + if (!isCustom(app) || app.builder) return { ok: true, cleared: false }; try { await puter.apps.update(app.name, { title: app.name }); return { ok: true, cleared: true }; diff --git a/src/tools/apps_and_sites/publish_site.js b/src/tools/apps_and_sites/publish_site.js index 208c13d4..2fa9e5a6 100644 --- a/src/tools/apps_and_sites/publish_site.js +++ b/src/tools/apps_and_sites/publish_site.js @@ -53,6 +53,14 @@ ABSOLUTELY VERY IMPORTANT: you only need to call this ONCE per app. The preview if (!url) { const site = await puter.hosting.create(window.makeDraftSubdomain(), path); url = `https://${site.subdomain}.puter.site/`; + // A project with dynamic backends runs its preview as an app + // Builder registers now, before anything runs there (see + // js/site-backends.js). A draft that replaces one the project + // had takes that one's app along, with the keys saved in it. + if (window.SiteBackends?.isDynamicProject(state?.chatHistory)) { + const moved = existing && await window.SiteBackends.moveApp(`https://${existing}.puter.site/`, url); + if (!moved) await window.SiteBackends.registerApp(url, window.SiteBackends.titleOf(state?.currentChatId), 'preview'); + } } // The hosting.create above is awaited, so the user may have navigated to // another project while it was in flight. If this turn is no longer the diff --git a/src/tools/chat_ui/publish.js b/src/tools/chat_ui/publish.js index ee766921..04467570 100644 --- a/src/tools/chat_ui/publish.js +++ b/src/tools/chat_ui/publish.js @@ -666,8 +666,8 @@ (text === ADDRESS_FAILED ? 'It may be taken. Try another.' : text)); return; } - // The user kept the address at the custom-domain question (or moved - // on while it was open): the card stays as it was. + // The user kept the address at the custom-domain or backend question + // (or moved on while it was open): the card stays as it was. if (r.cancelled) { const $now = cardNow(chatId, $card); if ($now) focusAddress($now); diff --git a/src/tools/workers/create_worker.js b/src/tools/workers/create_worker.js index e76689ed..c9d194ce 100644 --- a/src/tools/workers/create_worker.js +++ b/src/tools/workers/create_worker.js @@ -1,4 +1,7 @@ window.tools.push({ + // A project with dynamic backends writes a backend to __workers/ like any + // other file (see js/site-backends.js), so it never gets this tool. + legacyOnly: true, type: "function", function: { name: "create_worker", diff --git a/src/tools/workers/delete_worker.js b/src/tools/workers/delete_worker.js index e15dcd72..4679e868 100644 --- a/src/tools/workers/delete_worker.js +++ b/src/tools/workers/delete_worker.js @@ -16,6 +16,11 @@ window.tools.push({ }, strict: true }, + // What a project with dynamic backends is told instead (see + // SiteBackends.toolsFor). + dynamic: { + description: "Deletes one of THIS project's older workers, made with create_worker, and stops its execution. A backend in __workers/ is removed by deleting its file instead. A worker that belongs to another project on the account is refused.", + }, exec: async function(args, state) { const name = String((args && args.name) || '').trim(); if (!name) throw new Error('name must be a non-empty worker name.'); @@ -33,6 +38,14 @@ window.tools.push({ // a lookup failure fails CLOSED (nothing is deleted on a blip). const root = window.projectRootDir(state); if (!root) throw new Error('Cannot determine the project directory, so the worker operation was refused for safety.'); + // A dynamic backend is just its file (see js/site-backends.js), and + // the file tools already handle deleting one. + const SB = window.SiteBackends; + const site = SB?.siteOf(state) || null; + const backend = site ? (await SB.list(site.servedDir)).find(b => b.name === name) : null; + if (backend) { + throw new Error(`The backend '${name}' is the file ${backend.path}. To remove it, delete that file with the delete tool. The preview stops running it right away, and the live site at the next publish.`); + } const worker = window.WorkerOwnership.findByName(await puter.workers.list(), name); if (!worker) throw new Error(`Worker '${name}' not found.`); if (!window.WorkerOwnership.ownedWorkers([worker], root).length) { diff --git a/src/tools/workers/get_worker.js b/src/tools/workers/get_worker.js index 76e8bd8c..0c0dfef6 100644 --- a/src/tools/workers/get_worker.js +++ b/src/tools/workers/get_worker.js @@ -16,6 +16,11 @@ window.tools.push({ }, strict: false }, + // What a project with dynamic backends is told instead (see + // SiteBackends.toolsFor). + dynamic: { + description: "Gets information about one of THIS project's backends, a file in __workers/ or an older worker made with create_worker. A worker that belongs to another project on the account is reported as not found.", + }, exec: async function(args, state) { const name = String((args && args.name) || '').trim(); if (!name) throw new Error('name must be a non-empty worker name.'); @@ -28,6 +33,22 @@ window.tools.push({ // details then come from workers.get, which carries file_uid. const root = window.projectRootDir(state); if (!root) throw new Error('Cannot determine the project directory, so the worker operation was refused for safety.'); + // A dynamic backend is a file in this project's own __workers folder + // (see js/site-backends.js), so it's this project's by being there. + const SB = window.SiteBackends; + const site = SB?.siteOf(state) || null; + if (site) { + const backend = (await SB.list(site.servedDir)).find(b => b.name === name); + if (backend) { + return { + success: true, + name: backend.name, + file_path: backend.path, + path: SB.pathOf(backend.name), + preview_url: SB.urlOf(site.previewUrl, backend.name), + }; + } + } const owned = window.WorkerOwnership.findByName(await puter.workers.list(), name); if (!owned || !window.WorkerOwnership.ownedWorkers([owned], root).length) { // Same shape as before for a miss, so the model handles it the same diff --git a/src/tools/workers/list_workers.js b/src/tools/workers/list_workers.js index 9db8ce5d..3ee01af9 100644 --- a/src/tools/workers/list_workers.js +++ b/src/tools/workers/list_workers.js @@ -11,6 +11,11 @@ window.tools.push({ }, strict: false }, + // What a project with dynamic backends is told instead (see + // SiteBackends.toolsFor). + dynamic: { + description: "Lists THIS project's backends: the files in __workers/ (in backends, with the path the pages call each one at and where it runs on the preview), and any older worker the project deployed with create_worker (in workers). Workers belonging to other projects on the account are not listed and cannot be used from here.", + }, exec: async function(args, state) { // Deployed workers are ACCOUNT-level resources shared by every project // (and every other Puter app) on the account, so the raw list is not this @@ -30,7 +35,7 @@ window.tools.push({ const root = window.projectRootDir(state); if (!root) throw new Error('Cannot determine the project directory, so the worker operation was refused for safety.'); const workers = window.WorkerOwnership.ownedWorkers(await puter.workers.list(), root); - return { + const out = { success: true, workers: workers.map(w => ({ name: w.name, @@ -39,5 +44,18 @@ window.tools.push({ created_at: w.created_at })) }; + // A dynamic backend is a file of this project, so its list is the + // project's own __workers folder (see js/site-backends.js). + const SB = window.SiteBackends; + const site = SB?.siteOf(state) || null; + if (site) { + out.backends = (await SB.list(site.servedDir)).map(b => ({ + name: b.name, + file_path: b.path, + path: SB.pathOf(b.name), + preview_url: SB.urlOf(site.previewUrl, b.name), + })); + } + return out; } }) diff --git a/src/tools/workers/set_email_sender_name.js b/src/tools/workers/set_email_sender_name.js index e9835d65..cba11b8c 100644 --- a/src/tools/workers/set_email_sender_name.js +++ b/src/tools/workers/set_email_sender_name.js @@ -6,6 +6,12 @@ // live one too, so the user asks once and both send under the same name. // Before the first publish only the preview has a backend, and publishing // copies the name over by itself. +// +// A dynamic backend (__workers/.worker.js, see js/site-backends.js) +// sends as its site's app, so the name is the site's. Builder registers that +// app itself and can rename it. On a site whose app Puter made instead, +// Puter doesn't let Builder rename it, so the tool tells the user how to name +// it in the Dev Center. window.tools.push({ type: "function", function: { @@ -28,6 +34,14 @@ window.tools.push({ }, strict: true }, + // What a project with dynamic backends is told instead (see + // SiteBackends.toolsFor). + dynamic: { + description: "Sets the sender name recipients see on email that one of THIS project's backends (a file in __workers/, or an older worker made with create_worker) sends with puter.email.sendTransactional, for example \"Makor Family Portal\". The address after the name is always a Puter address and can't be changed. Only the name can. A backend in __workers/ sends under its site's name, which starts out as the project's name (with \"(preview)\" after it on the preview), so set one whenever a backend sends email. Use the name the user asked for, or else the site's or business's name. Sets the preview and, if the site is published, the live site too, and publishing copies it to the live site later. Pass an empty name to go back to the default.", + parameters: { + worker: "The name of this project's backend that sends the email: the file name in __workers/ without .worker.js, or an older worker's name." + } + }, exec: async function (args, state) { const WSN = window.WorkerSender; // What the AI should do when the name can't be set. @@ -57,9 +71,66 @@ window.tools.push({ // lookup failure refuses instead of guessing. const root = window.projectRootDir(state); if (!root) throw new Error('Cannot determine the project directory, so the sender name was not changed.'); + // A dynamic backend sends as its site's own app, the preview's and, + // once published, the live site's. + const SB = window.SiteBackends; + const site = SB?.siteOf(state) || null; + const backends = site ? (await SB.list(site.servedDir)).map(b => b.name) : []; + if (backends.includes(worker)) { + if (!site.previewUrl) { + return { success: false, error: 'The preview isn’t open yet, so the backend isn’t running anywhere to send email from. Open the preview with publish_site, then set the sender name again.' }; + } + const r = await WSN.set({ site: site.previewUrl, backends }, reset ? '' : name); + if (!r.ok) { + if (r.reason !== 'forbidden') return { success: false, error: refusal(r.reason, r.length) }; + // Puter lets an app rename only apps it made, and it made the + // site's app itself, so the owner names it in the Dev Center. + let ids = []; + try { + ids = (await Promise.all([site.previewUrl, site.publishedUrl].filter(Boolean).map(u => SB.appUidOf(u)))).filter(Boolean); + } catch (e) { /* the instructions below still work without the ids */ } + const which = ids.length ? ids.map(id => `"${id}"`).join(' and ') : 'named after the site\'s app id (app-)'; + return { success: false, error: `Builder can't set the sender name for a backend in __workers/, because Puter doesn't let Builder rename the site's app, and email from it goes out under that app's title. Tell the user they can set it themselves: open the Dev Center at https://puter.com/app/dev-center, find the app ${which}, change its title to the name they want, and save. ${ids.length > 1 ? 'The first is the preview\'s and the second the live site\'s, so they set both.' : 'Each address of the site has its own app, so once the live site\'s backend has run, they set the live site\'s app too.'}` }; + } + let live = 'not-published'; + // The user's own domains serving the live site send as apps of + // their own, each renamed the same way. + let domains = ''; + if (site.publishedUrl) { + const lr = await WSN.set({ site: site.publishedUrl, backends }, reset ? '' : name); + live = lr.ok ? 'updated' : 'failed'; + for (const url of site.domainUrls || []) { + const dr = await WSN.set({ site: url, backends }, reset ? '' : name); + if (dr.ok) continue; + const host = url.replace(/^https:\/\//, '').replace(/\/+$/, ''); + if (dr.reason !== 'forbidden') { + domains += ` The site’s own domain ${host} couldn’t be changed this time, so its email still uses the old name. Call set_email_sender_name again to change it too.`; + continue; + } + let id = null; + try { id = await SB.appUidOf(url); } catch (e) { /* the instructions below still work without the id */ } + domains += ` Email from the site’s own domain ${host} still goes out under its old name, since it runs as an app Puter made, which Builder can’t rename. Tell the user they can change its title in the Dev Center at https://puter.com/app/dev-center${id ? `, where it’s the app "${id}"` : ''}.`; + } + } + const where = live === 'updated' ? 'on the preview and the live site' : 'on the preview'; + const after = (live === 'updated' ? '' + : live === 'failed' ? ' The live site couldn’t be changed this time, so its email still uses the old name. Call set_email_sender_name again to change it too.' + : ' The site isn’t published yet. Publishing gives the live site the same name by itself.') + domains; + return { + success: true, + worker, + sender_name: name, + live, + note: `Email from this site’s backends ${where} now goes out as ${reset ? 'its default name, the project’s name' : `"${name}"`}.${after} The address after the name is always a Puter address and can't be changed. Tell the user in one short sentence.`, + }; + } const all = await puter.workers.list(); const record = window.WorkerOwnership.findByName(all, worker); - if (!record) throw new Error(`Worker '${worker}' not found. Create it with create_worker first, then set its sender name.`); + if (!record) { + throw new Error(SB?.isDynamicProject(state?.chatHistory) + ? `Backend '${worker}' not found. Write its file, __workers/${worker}.worker.js in the folder the preview serves, first, then set its sender name.` + : `Worker '${worker}' not found. Create it with create_worker first, then set its sender name.`); + } if (!window.WorkerOwnership.ownedWorkers([record], root).length) { throw new Error(`Worker '${record.name}' does not belong to this project, so its sender name can't be changed here.`); } diff --git a/src/tools/workers/set_secret.js b/src/tools/workers/set_secret.js index 81ab3011..5b98ae81 100644 --- a/src/tools/workers/set_secret.js +++ b/src/tools/workers/set_secret.js @@ -10,6 +10,10 @@ // preview keeps a test key. It's the one way the AI reaches the live backend, // and it can only save a key there, never change its code. // +// A dynamic backend (__workers/.worker.js, see js/site-backends.js) +// runs as its site's own app, so its key goes into the preview site's store, +// shared by every backend of the site, and with live into the live site's. +// // The result never repeats the key, so it doesn't spread further through the // conversation than the message the user pasted it in. window.tools.push({ @@ -42,6 +46,14 @@ window.tools.push({ }, strict: true }, + // What a project with dynamic backends is told instead (see + // SiteBackends.toolsFor). + dynamic: { + description: "Saves an API key or other secret for one of THIS project's backends (a file in __workers/, or an older worker made with create_worker), in its own private key-value store, which every backend of the site shares. Use it for every key the user gives you, such as a Stripe or Whop key or any other API key, and never write a key into any file. Write the backend's file and open the preview first, then call this. In the backend, read the key inside a route handler with await me.puter.kv.get('secret:NAME'). The user may be asked once to allow Builder to give keys to that site. Publishing copies the preview's keys to the live site by itself. For a key only the live site should use, such as a live payment key while the preview keeps a test key, set live to true. That needs the site published first. The user's own domain on the live site has a store of its own. It gets the live site's keys when it's connected and on each publish, and live set to true saves the key there too, so a key its backend is missing is saved again with live set to true.", + parameters: { + worker: "The name of this project's backend that uses the key: the file name in __workers/ without .worker.js, or an older worker's name." + } + }, exec: async function (args, state) { const WS = window.WorkerSecrets; if (!WS) throw new Error('Keys can’t be saved in this version of Builder.'); @@ -54,13 +66,64 @@ window.tools.push({ // list so a lookup failure refuses instead of guessing. const root = window.projectRootDir(state); if (!root) throw new Error('Cannot determine the project directory, so the key was not saved.'); + const live = !!(args && args.live); + const value = String((args && args.value) || ''); + // For a dynamic backend, the key goes into the store of the site that + // runs it, the preview's, or the live site's with live. + const SB = window.SiteBackends; + const site = SB?.siteOf(state) || null; + const backends = site ? (await SB.list(site.servedDir)).map(b => b.name) : []; + if (backends.includes(worker)) { + const siteUrl = live ? site.publishedUrl : site.previewUrl; + if (!siteUrl) { + return { success: false, error: live + ? 'The site isn’t published yet, so it has no live backend to hold this key. Ask the user to publish first, then save the key again with live set to true.' + : 'The preview isn’t open yet, so the backend isn’t running anywhere to hold this key. Open the preview with publish_site, then save the key again.' }; + } + const r = await WS.set({ site: siteUrl, backends }, name, value, { liveOnly: live }); + // The user's own domains serving the live site run its backends + // as apps of their own, so a live key goes into each of those too. + const missed = []; + if (r.ok && live) { + for (const url of site.domainUrls || []) { + const dr = await WS.set({ site: url, backends }, name, value, { liveOnly: true }); + if (!dr.ok) missed.push(url.replace(/^https:\/\//, '').replace(/\/+$/, '')); + } + } + if (r.ok) { + return { + success: true, + worker, + name, + live, + read_it_with: `await me.puter.kv.get('secret:${name}')`, + note: live + ? 'The key is saved only in the live site’s store, which all of its backends share. The live site uses it from the next request, the preview keeps its own, and publishing never replaces it. The code stays the same. Never write the key into a file or repeat it in your replies.' + + (missed.length ? ` It didn’t reach the site’s own domain ${missed.join(' and ')}, so the backend there doesn’t have it yet. Call set_secret again with live set to true to try again.` : '') + : 'The key is saved in the preview’s private store, which all of this site’s backends share. Read it inside a route handler, never at the top of the script. The site’s pages run as the same app, so never read a secret: key from browser code, never write the key into a file, and never repeat it in your replies.', + }; + } + const why = { + declined: 'The user didn\'t allow Builder to give keys to this site, so the backend can\'t use the key yet. Tell the user in one short sentence, and offer to try again when they\'re ready (calling set_secret again asks them again).', + 'no-app': live + ? 'The live site doesn’t run this backend yet, so it has no store to hold the key. Ask the user to publish first, then save the key again with live set to true.' + : 'The backend didn’t start on the preview, so the site has no store to hold the key yet. Check that the backend’s file is valid (saving it says whether it runs), then save the key again.', + empty: 'The key is empty. Ask the user for the key.', + 'too-long': 'That is too long to be a key. Ask the user to check what they pasted.', + failed: 'Saving the key failed. Try once more, and if it fails again tell the user.', + }; + return { success: false, error: why[r.reason] || why.failed }; + } const all = await puter.workers.list(); const record = window.WorkerOwnership.findByName(all, worker); - if (!record) throw new Error(`Worker '${worker}' not found. Create it with create_worker first, then save the key.`); + if (!record) { + throw new Error(SB?.isDynamicProject(state?.chatHistory) + ? `Backend '${worker}' not found. Write its file, __workers/${worker}.worker.js in the folder the preview serves, first, then save the key.` + : `Worker '${worker}' not found. Create it with create_worker first, then save the key.`); + } if (!window.WorkerOwnership.ownedWorkers([record], root).length) { throw new Error(`Worker '${record.name}' does not belong to this project, so it can't hold this project's keys.`); } - const live = !!(args && args.live); let target = record.name; if (live) { // The published copy of this backend, owned the way publishing @@ -73,7 +136,7 @@ window.tools.push({ } target = liveRecord.name; } - const r = await WS.set(target, name, String((args && args.value) || ''), { liveOnly: live }); + const r = await WS.set(target, name, value, { liveOnly: live }); if (r.ok) { return { success: true, diff --git a/vite.config.js b/vite.config.js index 8add57ff..deb1e08b 100644 --- a/vite.config.js +++ b/vite.config.js @@ -53,6 +53,9 @@ const SCRIPTS = [ 'js/custom-domain.js', 'js/issues-core.js', 'js/worker-ownership.js', + // A project's dynamic backends (__workers/.worker.js), behind + // FEATURE_FLAGS.dynamicWorkers. + 'js/site-backends.js', // A project's API keys, kept in each backend worker's own store (the // set_secret tool, publish, duplicate and delete use it). 'js/worker-secrets.js',