diff --git a/frontend/src/lib/components/sessions/RawAppEditorView.svelte b/frontend/src/lib/components/sessions/RawAppEditorView.svelte index 9b90d48e6b..55f747d09d 100644 --- a/frontend/src/lib/components/sessions/RawAppEditorView.svelte +++ b/frontend/src/lib/components/sessions/RawAppEditorView.svelte @@ -108,6 +108,8 @@ const awaitingSetup = $derived( newRawApp && !setupSettled && + // Held until the first send, it was set up before this view remounted. + !runtime.holdsDraft(workspaceId, 'raw_app', path) && isActiveSession && active && cell.slot.loadedPath === path && @@ -131,8 +133,18 @@ data: result.data, policy: result.policy } + if (mode === 'ai') { + // The session's first send saves it; until then it lives in this tab only. + runtime.holdDraftUntilSend(workspaceId, 'raw_app', path) + cell.store.val = setUp + // Written now rather than on the autosave debounce: the reload below reads it back. + UserDraft.save('raw_app', path, runtimeRawAppToDraft(setUp), { workspace: workspaceId }) + // Remounts the editor so the preview builds the picked template. + await runtime.loadRawApp(workspaceId, path, true) + return + } cell.store.val = setUp - // Saved now rather than on the autosave debounce: both ways out read it back by path. + // Saved now rather than on the autosave debounce: the editor page reads it back by path. const key = { workspace: workspaceId, itemKind: 'raw_app' as const, path } UserDraft.save('raw_app', path, runtimeRawAppToDraft(setUp), { workspace: workspaceId }) await tick() @@ -143,15 +155,10 @@ sendUserToast(`Could not save the app: ${saved.failureMessage ?? 'unknown error'}`, true) return } - if (mode === 'code') { - // The session was opened for this app alone; with nothing said in it, it goes. - const unused = runtime.manager.displayMessages.length === 0 - await goto(withWorkspaceParam(`/apps_raw/edit/${path}`, workspaceId)) - if (unused) removeSession(runtime.sessionId) - return - } - // Remounts the editor so the preview builds the picked template. - await runtime.loadRawApp(workspaceId, path, true) + // The session was opened for this app alone; with nothing said in it, it goes. + const unused = runtime.manager.displayMessages.length === 0 + await goto(withWorkspaceParam(`/apps_raw/edit/${path}`, workspaceId)) + if (unused) removeSession(runtime.sessionId) } // Path typed in the editor header, surfaced when it differs from the stored diff --git a/frontend/src/lib/components/sessions/SessionPicker.svelte b/frontend/src/lib/components/sessions/SessionPicker.svelte index 091ca6435d..ac47a1fdbd 100644 --- a/frontend/src/lib/components/sessions/SessionPicker.svelte +++ b/frontend/src/lib/components/sessions/SessionPicker.svelte @@ -177,10 +177,10 @@ // total, and keyboard navigation. const visibleSessions = $derived( sessionState.sessions.filter((s) => { - // A blank nobody has typed in is Home's composer at rest, not a session yet. - if (s.transient) return false - // Pending (unsent) sessions show like any other, so several drafts can be - // set up in parallel; they group by pending_workspace_id via sessionRootOf. + // A draft Home's composer holds becomes a session when its first send starts, typed + // or not. Unsent drafts opened onto an item stay listed: the row is their only way + // back. They group by pending_workspace_id via sessionRootOf. + if (s.transient || opensOnHome(s)) return false // The row on screen always stays in the list, ignoring every filter. if (s.id === activeRowId) return true if (s.archived && !showArchived.val) return false diff --git a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts index 22dc68e1d3..895c5cb440 100644 --- a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts @@ -275,6 +275,10 @@ export interface SessionRuntime { * setup has not been confirmed. Held in the cell only, nothing is saved. */ seedIfMissing?: boolean ): Promise + /** Keep a new item's draft in this tab, unsaved, until the session's first send saves it: + * an AI start the user never sends leaves nothing behind. */ + holdDraftUntilSend(workspace: string, kind: SessionTargetKind, path: string): void + holdsDraft(workspace: string, kind: SessionTargetKind, path: string): boolean /** Register a mounted raw-app preview's log requester, keyed by app path, like * `registerDomRequester`: build state is per editor, so reads route to the app edited. */ registerRuntimeLogRequester(appPath: string, requester: RawAppRuntimeLogRequester): void @@ -511,11 +515,48 @@ function createRuntime(session: Session): SessionRuntime { if (slot.kind !== 'pageitem') return undefined return { type: 'agent', path: slot.ref.path, storagePath: slot.ref.path, isLiveDraft: true } } + // Drafts held by holdDraftUntilSend. Their sync is suspended, so an edit made meanwhile is + // in the cell only, so the save sends the current value whatever the mirror last saw. + let heldDrafts: { workspace: string; kind: SessionTargetKind; path: string }[] = [] + // The live editor's value, else the runtime cell's: a collapsed or remounting preview has + // released its UserDraft entry, but the cell lives as long as a tab shows the app. + function heldDraftValue(workspace: string, kind: SessionTargetKind, path: string) { + const live = UserDraft.get(kind, path, { workspace }) + if (live !== undefined || kind !== 'raw_app') return live + const val = rawAppCells.get(path)?.store.val + return val ? runtimeRawAppToDraft(val) : undefined + } + // A draft leaves the list only once saved: a failed send keeps it held, so its retry saves it. + async function persistHeldDrafts(): Promise { + while (heldDrafts.length > 0) { + const { workspace, kind, path } = heldDrafts[0] + const value = heldDraftValue(workspace, kind, path) + if (value === undefined) throw new Error('the app to save is no longer open') + UserDraft.restartSync(kind, path, { workspace }) + await UserDraftDbSyncer.save({ workspace, itemKind: kind, path, value, immediate: true }) + const saved = UserDraftDbSyncer.getState({ workspace, itemKind: kind, path }) + if (saved.state === 'failed') { + UserDraft.stopSync(kind, path, { workspace }) + throw new Error(`the app could not be saved: ${saved.failureMessage ?? 'unknown error'}`) + } + heldDrafts.shift() + } + } + function isHeldDraft(workspace: string, kind: SessionTargetKind, path: string): boolean { + return heldDrafts.some((d) => d.workspace === workspace && d.kind === kind && d.path === path) + } + function releaseHeldDraft(workspace: string, kind: SessionTargetKind, path: string): void { + heldDrafts = heldDrafts.filter( + (d) => !(d.workspace === workspace && d.kind === kind && d.path === path) + ) + } // Pre-flight: materialise the (still-transient) session, then commit // the workspace (creating a staged fork if needed) before any send. // AIChatManager awaits this so the first message hits a persisted // session targeting the right workspace. Both calls are idempotent. manager.beforeSend = async () => { + // Drafts first: a session stored before its app is saved would reopen onto nothing. + await persistHeldDrafts() materializeTransient(session.id) // Session is now persisted → flush any linked files buffered while it was transient. await manager.attachedFiles.flushPending() @@ -611,6 +652,11 @@ function createRuntime(session: Session): SessionRuntime { for (const p of [...flowCells.keys()]) if (!keep.flow.has(p)) flowCells.delete(p) for (const p of [...scriptCells.keys()]) if (!keep.script.has(p)) scriptCells.delete(p) for (const p of [...rawAppCells.keys()]) if (!keep.raw_app.has(p)) rawAppCells.delete(p) + // A held app whose tab is gone was dropped before anything was sent: it is not saved. + for (const d of heldDrafts.filter((d) => d.kind === 'raw_app' && !keep.raw_app.has(d.path))) { + UserDraft.restartSync(d.kind, d.path, { workspace: d.workspace }) + releaseHeldDraft(d.workspace, d.kind, d.path) + } } // Hydrate the preview-tab owner from the session record (the durable backing); @@ -1065,6 +1111,19 @@ function createRuntime(session: Session): SessionRuntime { ) { const { slot, store, saved } = rawAppCell(path) if (slot.loadedPath === path && slot.loadedWorkspace === workspace && !force) return + // A held draft exists only in this cell: the server has nothing yet, and the preview's + // unmount dropped its UserDraft entry, sync suspension included. + if ( + !force && + store.val && + slot.loadedWorkspace === workspace && + isHeldDraft(workspace, 'raw_app', path) + ) { + UserDraft.stopSync('raw_app', path, { workspace }) + slot.notFound = false + slot.loadedPath = path + return + } // See loadScript: forced reload remounts via the render gate. if (force || slot.loadedWorkspace !== workspace) slot.loadedPath = undefined slot.loading = true @@ -1225,7 +1284,16 @@ function createRuntime(session: Session): SessionRuntime { } }, + holdDraftUntilSend(workspace, kind, path) { + UserDraft.stopSync(kind, path, { workspace }) + if (!isHeldDraft(workspace, kind, path)) heldDrafts.push({ workspace, kind, path }) + }, + holdsDraft: isHeldDraft, + itemDeployed(workspace, kind, storagePath, deployedPath = storagePath) { + // Deployed, it is saved: forcePersist would write a draft over the deployed item. + releaseHeldDraft(workspace, kind, storagePath) + releaseHeldDraft(workspace, kind, deployedPath) if (deployedPath !== storagePath) { // Nothing is deployed at the storage path, so its editor would go on // creating the item again and its draft would outlive the deploy: drop diff --git a/frontend/src/lib/components/sessions/sessionState.svelte.ts b/frontend/src/lib/components/sessions/sessionState.svelte.ts index f9224e7395..fed45687c0 100644 --- a/frontend/src/lib/components/sessions/sessionState.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionState.svelte.ts @@ -126,9 +126,9 @@ export type Session = { // untouched draft never persists, so idle `+` clicks vanish on reload // instead of littering the sidebar. transient?: boolean - // In memory only, on a transient session opened onto an item that lives on its own (a new - // app's draft): its preview writes are not a touch, so a session the user never starts - // vanishes on reload instead of reopening onto the item. Cleared with `transient`. + // In memory only, on a transient session opened onto an item (a new app): no touch stores + // it, a typed prompt included, so only its first send does. A session the user never + // starts vanishes on reload instead of reopening onto the item. Cleared with `transient`. untilStarted?: boolean // Epoch ms of the last write to this record — typing, renaming, archiving, // changing preview tabs, or catching up on new messages. Stamped by the two @@ -483,16 +483,12 @@ export function takeSessionAutoSend(sessionId: string): boolean { // unread watermark via putSession) persist directly, so an untouched draft // stays in memory and vanishes on reload. function persistTouched(s: Session): void { - if (s.transient) delete s.transient - delete s.untilStarted s.lastActivityAt = Date.now() - void putSession(s) -} - -// Preview state (tabs, collapse, width) is a touch except on an `untilStarted` session. -function persistPreviewTouch(s: Session): void { + // Stored only by its first send (materializeTransient): stored earlier, a reload would + // reopen it onto an item that was never saved. if (s.transient && s.untilStarted) return - persistTouched(s) + if (s.transient) delete s.transient + void putSession(s) } // When the session was last used. Pre-dates-the-field records report their @@ -1403,7 +1399,7 @@ export function setSessionTabs(id: string, tabs: SessionPreviewTab[], activeTabI if (!s) return s.previewTabs = tabs.map((t) => ({ ...t })) s.activePreviewTabId = activeTabId - persistPreviewTouch(s) + persistTouched(s) } // Persist whether the preview panel is collapsed for this session (a touch). @@ -1411,7 +1407,7 @@ export function setSessionPreviewCollapsed(id: string, collapsed: boolean): void const s = sessionState.sessions.find((x) => x.id === id) if (!s || !!s.previewCollapsed === collapsed) return s.previewCollapsed = collapsed - persistPreviewTouch(s) + persistTouched(s) } // Persist the preview split size the user dragged for this session (a touch). @@ -1419,7 +1415,7 @@ export function setSessionPreviewSize(id: string, size: number): void { const s = sessionState.sessions.find((x) => x.id === id) if (!s || s.previewSize === size) return s.previewSize = size - persistPreviewTouch(s) + persistTouched(s) } // Persist the session's Use or Build choice (a touch). Plan is left out: a reload ends the diff --git a/frontend/src/lib/components/sessions/sessionState.test.ts b/frontend/src/lib/components/sessions/sessionState.test.ts index e8159779d6..c670e6dcc8 100644 --- a/frontend/src/lib/components/sessions/sessionState.test.ts +++ b/frontend/src/lib/components/sessions/sessionState.test.ts @@ -535,6 +535,14 @@ describe('createSession — reuses an untouched draft, family-scoped', () => { ] setSessionTabs('held-on-app', tabs, 'session') expect(held.transient).toBe(true) + vi.useFakeTimers() + try { + setSessionDraftPrompt('held-on-app', 'make it blue') + vi.advanceTimersByTime(1000) + } finally { + vi.useRealTimers() + } + expect(held.transient).toBe(true) createdId = createSession().id expect(createdId).not.toBe('held-on-app') expect(sessionState.sessions).toContain(held) diff --git a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts index ce699998de..3549ae9347 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts @@ -6,6 +6,7 @@ import { createSession, holdSessionUntilStarted, homeDraft, + homeStarterSession, opensOnHome, selectSession, sessionInCurrentFamily, @@ -97,9 +98,10 @@ async function toHome(id: string, opts?: { replace?: boolean; flash?: boolean }) await goto('/', { replaceState: opts?.replace ?? false }) } -/** New session: Home's composer, blank, focused and outlined for a moment. It acts on the - * header's workspace, switched to `workspaceId` first when given. A draft already typed stays - * in the list. */ +/** New session: Home's composer, focused and outlined for a moment. It acts on the header's + * workspace, switched to `workspaceId` first when given. An unsent draft of that family is + * shown again rather than replaced by a blank: the sidebar does not list it, so a blank would + * strand it. */ export async function openNewSession(workspaceId?: string): Promise { if (workspaceId && workspaceId !== get(workspaceStore)) { // Home's current draft stays where it is: the switch must not take it along. @@ -109,7 +111,7 @@ export async function openNewSession(workspaceId?: string): Promise { // switch back to it and take the new draft along. await fixupUrlAfterWorkspaceSwitch(workspaceId) } - await toHome(blankHomeDraft().id, { flash: true }) + await toHome(homeStarterSession().id, { flash: true }) } /** An unsent draft, opened in Home's composer. `replace` for a redirect off the sessions @@ -173,12 +175,13 @@ async function openInSession( export function editorSessionHref( target: SessionTarget, workspaceId?: string, - previewParams?: Record + previewParams?: Record, + opts?: Pick ): Promise { return sessionHrefFor( withPreviewParams(sessionTargetHref(target), previewParams), workspaceId, - undefined, + opts, presetScopeFor(target.path) ) } diff --git a/frontend/src/routes/(root)/(logged)/apps_raw/add/+page.ts b/frontend/src/routes/(root)/(logged)/apps_raw/add/+page.ts index 49d215ab8d..7f6e952025 100644 --- a/frontend/src/routes/(root)/(logged)/apps_raw/add/+page.ts +++ b/frontend/src/routes/(root)/(logged)/apps_raw/add/+page.ts @@ -29,9 +29,12 @@ async function newAppSessionHref(url: URL): Promise { if ((url.searchParams.get('workspace') ?? workspace) !== workspace) return undefined if (get(copilotWorkspace) !== workspace) await loadCopilot(workspace) if (get(copilotWorkspace) !== workspace || !get(copilotInfo).enabled) return undefined - return editorSessionHref({ kind: 'raw_app', path: mintDraftPath() }, workspace, { - new_draft: 'true' - }) + return editorSessionHref( + { kind: 'raw_app', path: mintDraftPath() }, + workspace, + { new_draft: 'true' }, + { untilStarted: true } + ) } export const load: PageLoad = async (event) => {