From c70ddea1de5312aae5ba0cb2def836060645b893 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Oliveira?= Date: Sun, 15 Nov 2026 21:00:15 -0300 Subject: [PATCH 1/7] docs: plan Studio sessions (PR 2 of 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Signed-off-by: André Oliveira --- .../plans/2026-11-16-studio-sessions.md | 189 ++++++++++++++++++ 1 file changed, 189 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-16-studio-sessions.md diff --git a/docs/superpowers/plans/2026-11-16-studio-sessions.md b/docs/superpowers/plans/2026-11-16-studio-sessions.md new file mode 100644 index 0000000..b76bc8e --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-studio-sessions.md @@ -0,0 +1,189 @@ +# Studio Sessions (Phase 2, sessions PR 2 of 2) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make the Studio use the local session store. It should autosave, list sessions, resume them, rename and delete them, start a new session, and show a changed-architecture notice. It also adds `archwise --serve --resume ` and retires browser `localStorage` for Sandbox state. + +**Architecture:** +- The session lifecycle stays in `SessionService`, which gains one method: `startNew`. +- The web app talks to the session API through a small typed client and a framework-free autosave controller. Both are unit-tested. +- `ArchitectureCanvas` stops touching `localStorage`. It receives an initial Sandbox document and reports serialized changes upward. +- `App.svelte` owns the session state. It also owns the saved-state indicator, the Sessions panel, and the notice that shows when the graph being displayed is a resumed session's base revision. + +**Tech Stack:** Svelte 5, TypeScript, Vitest (jsdom, fake timers), Playwright smoke (`scripts/browser-smoke.mjs`). + +**Spec:** `docs/superpowers/specs/2026-11-16-sessions-and-local-store-design.md`. PR 1 (#11) delivered the store and API; see `docs/sessions.md`. + +## Global Constraints + +- All server calls go to the same origin with `credentials: 'same-origin'`. Mutating calls send `Content-Type: application/json`; the browser adds `Origin` automatically. +- The Sandbox document format stays `archwise-sandbox` v1, and its `projectSignature` must match the graph being displayed. +- **Autosave:** saves are debounced by 750 ms after the last change. The indicator has four states: `saved`, `saving`, `unsaved` and `disabled`. A failed save never discards in-memory state. The indicator offers a Retry, and the next change retries too. +- **Single active tab.** If a save returns 404 because the session was replaced or deleted in another tab, the indicator shows `unsaved` with "This session changed elsewhere. Reload to continue." The tab never writes into a different session on its own. +- **Resume ruling** (deferred minor from PR #11): resuming discards the reserved, never-persisted current ID. Nothing was stored under it, so nothing is lost. +- **`--no-store`:** the indicator reads "Not saving (store disabled)", the Sessions button is hidden, and JSON export and import keep working. +- **`localStorage` is no longer read or written** for Sandbox state. +- Use `npx --yes pnpm@10.34.9`. Commits are signed off and end with the Co-Authored-By attribution line. Docs must match the delivered behavior. + +## Review Focus + +1. **Reload during a pending debounce:** an edit made less than 750 ms before a page reload must not be lost silently. Flush the pending save on `pagehide`/`visibilitychange` with `fetch(..., { keepalive: true })` (owner: Task 2). +2. **Resuming a session whose base differs from current discovery:** the canvas must render the session's stored view, not today's graph. Otherwise `parseSandboxDocument` rejects it on signature mismatch (owner: Task 3, smoke in Task 4). +3. **Deleting the session currently open:** the Studio must switch to the fresh reserved session with an empty Sandbox. It must not keep autosaving into the deleted ID (owner: Tasks 1 and 3). +4. **Hostile labels in the session list** (for example ``) render as text (owner: Task 3, Svelte escaping, and an assertion in the smoke). +5. **A `--resume` ID that doesn't exist, or `latest` with no sessions:** exit with code 2 and an actionable message, without starting a server (owner: Task 1). + +--- + +### Task 1: `startNew`, a `POST /api/v1/sessions/new` route, and `--resume` + +**Files:** +- Modify: + - `packages/application/src/session-service.ts` (add `startNew(): { id: string; persisted: false }`, which reserves a fresh ID as current) + - `apps/cli/src/session-routes.ts` (`POST /api/v1/sessions/new` returns the new current ID; same-origin required) + - `apps/cli/src/index.ts` (parse `--resume `: it requires `--serve` and conflicts with `--no-store`; the value is `latest` or matches `^ses-[0-9a-f]{24}$`; anything else exits 2) + - `apps/cli/src/store-runtime.ts` (add `resumeTarget(service, value): string | null`) + - `apps/cli/src/bin.ts` (resolve the target before starting the server; a miss exits 2 with "No saved session matches … Run --sessions to list them.") +- Test: + - `packages/application/tests/session-service.test.ts` + - `apps/cli/tests/session-api.test.ts` + - `apps/cli/tests/cli.test.ts` + - `apps/cli/tests/store-runtime.test.ts` + - `scripts/tests/session-store-integration.test.mjs` + +**Interfaces — Produces:** +- `SessionService.startNew()` +- `POST /api/v1/sessions/new` → `{ id, persisted: false, storeEnabled: true }` +- The `CliCommand` inspect variant gains `resume: string | null` +- `resumeTarget(service: SessionService, value: string): string | null` + +- [ ] **Step 1:** Write the failing tests. + - `startNew` after a save gives a new unpersisted current ID, and the old session stays listed. + - `POST /new` without `Origin` returns 403; with it, it returns a new ID that differs from the previous one. + - `parseCli(['--serve','--resume','latest'])` gives `resume: 'latest'`. + - `--resume` without `--serve`, `--resume ses-bad`, and `--resume latest --no-store` each exit 2. + - `resumeTarget`: `latest` returns the newest ID; an unknown ID returns null; `latest` with no sessions returns null. + - Integration: `--serve --resume latest` on an empty store exits 2 with "Run --sessions". After a save, `--serve --resume latest` serves `current.id` equal to the saved ID. +- [ ] **Step 2:** Run `npx --yes pnpm@10.34.9 build && npx --yes pnpm@10.34.9 --filter @archwise/application test && npx --yes pnpm@10.34.9 --filter @archwise/cli test && node --test scripts/tests/session-store-integration.test.mjs`. Expected: FAIL. +- [ ] **Step 3:** Implement. +- [ ] **Step 4:** Run the same command. Expected: PASS. +- [ ] **Step 5:** Commit with `feat: start new sessions and resume from the CLI`. + +### Task 2: Web session client and autosave controller + +**Files:** +- Create: + - `apps/web/src/session-client.ts` + - `apps/web/src/autosave.ts` +- Test: + - `apps/web/src/session-client.test.ts` + - `apps/web/src/autosave.test.ts` + +**Interfaces — Produces:** + +```ts +// session-client.ts — all functions take an injectable fetch (default globalThis.fetch) +export interface CurrentSession { readonly id: string | null; readonly persisted: boolean; readonly storeEnabled: boolean } +export interface SessionSummary { id: string; label: string; createdAt: string; updatedAt: string; componentCount: number; hasSnapshots: boolean; baseIsCurrent: boolean } +export interface SessionDetail extends SessionSummary { sandbox: string; view: unknown } +export type ClientResult = { ok: true; value: T } | { ok: false; status: number; error: string }; +export function getCurrent(f?: typeof fetch): Promise>; +export function listSessions(f?): Promise>; +export function getSession(id: string, f?): Promise>; +export function resumeSession(id: string, f?): Promise>; +export function startNewSession(f?): Promise>; +export function saveSandbox(id: string, text: string, f?, init?: { keepalive?: boolean }): Promise>; +export function renameSession(id: string, label: string, f?): Promise>; +export function deleteSession(id: string, f?): Promise>; + +// autosave.ts — framework-free +export type SaveState = 'saved' | 'saving' | 'unsaved' | 'disabled'; +export interface AutosaveStatus { readonly state: SaveState; readonly message: string } +export interface Autosave { schedule(text: string): void; flush(options?: { keepalive?: boolean }): Promise; retry(): void; dispose(): void } +export function createAutosave(options: { save: (text: string, keepalive: boolean) => Promise>; + delayMs?: number /* default 750 */; onStatus: (status: AutosaveStatus) => void }): Autosave; +``` + +Autosave behavior: +- `schedule` stores the latest text and restarts the timer. +- When the timer fires, the controller saves (`saving`). On success it reports `saved` "All changes saved". On a 404 it reports `unsaved` "This session changed elsewhere. Reload to continue.", and after that it ignores every `schedule` call except an explicit `retry`. On any other failure it reports `unsaved` "Not saved — retrying on next change"; the next `schedule` or `retry` saves again. +- If text changes while a save is in flight, the controller saves again after the in-flight save completes, so the last write is always the latest text. +- Saving identical text twice in a row is a no-op that reports `saved`. + +- [ ] **Step 1:** Write the failing tests. + - **Client:** each function calls the right method, path and headers (`Content-Type` only on PUT/PATCH/POST with a body), and parses JSON. A non-2xx response gives `{ok:false, status, error}`. The client never throws on network errors; those give `status: 0`. + - **Autosave** (Vitest fake timers): three schedules within 750 ms produce one save of the last text; success gives `saved`; a 500 gives `unsaved`, and a later schedule saves; a 404 gives the "changed elsewhere" message, and a later schedule does not save; changes during an in-flight save produce a follow-up save with the latest text; `flush({keepalive:true})` saves immediately with `keepalive` true; `dispose` cancels the timer. +- [ ] **Step 2:** Run `npx --yes pnpm@10.34.9 --filter @archwise/web test`. Expected: FAIL. +- [ ] **Step 3:** Implement both modules. +- [ ] **Step 4:** Run the same command. Expected: PASS. +- [ ] **Step 5:** Commit with `feat(web): session API client and autosave controller`. + +### Task 3: Studio wiring, Sessions panel, and changed-architecture notice + +**Files:** +- Create: `apps/web/src/SessionsPanel.svelte`, an accessible dialog (`role="dialog"`, `aria-label="Sessions"`) that: + - lists sessions, newest first, each showing its label, a relative or absolute updated time, `N components`, an `A/B` badge, a `Architecture changed` badge when `!baseIsCurrent`, and a `Current` marker; + - has actions Resume, Rename (an inline input with Save/Cancel) and Delete, which asks for confirmation inside the panel, not through `confirm()`; + - has a "New session" button; + - shows errors inline. +- Modify: + - `apps/web/src/ArchitectureCanvas.svelte` + - Remove the `localStorage` read/write (the `onMount` restore and the `$effect` write). + - Add the props `initialDocument: string | null` (when present, restore it once on mount through `parseSandboxDocument`, with errors shown in `persistenceStatus`) and `onDocumentChange: (text: string) => void` (called from the existing `$effect` with `serializeSandboxDocument(createDocument())`). + - Keep JSON export, import and reset. + - `apps/web/src/App.svelte` + - On mount, load `getCurrent`. With the store enabled and the session persisted, load `getSession`, use `detail.view` as the graph when `!detail.baseIsCurrent` (validated with `isGraph`; otherwise use `/api/v1/graph`), and pass `detail.sandbox` as `initialDocument`. Otherwise fetch `/api/v1/graph` as today, with `initialDocument = null`. + - Create the autosave with `saveSandbox(currentId, text, fetch, {keepalive})`, and flush on `pagehide` and on `visibilitychange` to hidden. + - Header: a save indicator (`role="status"`, `aria-live="polite"`) with a Retry button when `unsaved`, and a "Sessions" button when the store is enabled. + - Resume, delete-current and new-session all reload the workspace state from the server (current, then graph and initial document). Remount the canvas with a `{#key}` block so state does not leak between sessions. + - When the graph shown is a resumed session's base view, show a notice: "Architecture changed since this session started. You are viewing the graph as it was then." It has a "Start a new session on the current graph" button that calls `startNewSession` and reloads. +- Test: `apps/web/src/session-view.test.ts`, which tests a pure helper `chooseWorkspaceGraph(detail, currentGraph)` extracted to `apps/web/src/session-view.ts`. UI behavior is verified in Task 4. + +**Interfaces — Produces:** + +```ts +// session-view.ts +export function chooseWorkspaceGraph(detail: { baseIsCurrent: boolean; view: unknown } | null, current: Graph): { graph: Graph; historical: boolean }; +``` + +`chooseWorkspaceGraph` returns `{current, false}` when there is no detail, when `baseIsCurrent` is true, or when `view` fails `isGraph`. Otherwise it returns `{view, true}`. + +- [ ] **Step 1:** Write the failing tests for `chooseWorkspaceGraph`: null detail, a current base, a historical base with a valid view, and a historical base with an invalid view. +- [ ] **Step 2:** Run `npx --yes pnpm@10.34.9 --filter @archwise/web test`. Expected: FAIL. +- [ ] **Step 3:** Implement `session-view.ts`, the panel, and the canvas and App changes. +- [ ] **Step 4:** Run `npx --yes pnpm@10.34.9 --filter @archwise/web test && npx --yes pnpm@10.34.9 --filter @archwise/web build`. Expected: PASS, and `svelte-check` reports 0 errors and 0 warnings. +- [ ] **Step 5:** Commit with `feat(web): autosaved sessions, session list and resume in the Studio`. + +### Task 4: Browser smoke for sessions + +**Files:** +- Modify: `scripts/browser-smoke.mjs` + +Changes: +- Analyze a temporary synthetic fixture project, written by the script (two packages with one dependency), instead of `--path .`. Use a temporary `ARCHWISE_DATA_DIR`. Delete both in `finally`. +- Replace the `localStorage` reads with `savedDocument()`, which runs in the page, fetches `/api/v1/sessions/current`, then `/api/v1/sessions/{id}`, and parses `sandbox`. Wait for the indicator to read "All changes saved" before reading. +- After the existing flow (reload restores from the store), add a **cross-launch resume**: + 1. Stop the server. + 2. Add a third package manifest to the fixture. + 3. Start a new server with the same data directory and open a new page. The canvas has 0 proposed nodes. + 4. Open Sessions. The previous session shows `A/B` and `Architecture changed`. + 5. Click Resume. Expect 3 proposed nodes, 2 edges, the changed-architecture notice visible, and `savedA` and `savedB` in the document. + 6. Rename the session to ``. The list shows that literal text and no `img` element is created inside the panel (Review Focus 4). + 7. Delete it after confirmation. The canvas is empty and the indicator is not `unsaved` (Review Focus 3). +- Keep failing on any page error. + +- [ ] **Step 1:** Install the driver locally into the scratchpad: `npm install --prefix /pw --no-save --no-package-lock --ignore-scripts playwright@1.56.1`. +- [ ] **Step 2:** Modify the smoke, then run `npx --yes pnpm@10.34.9 build && ARCHWISE_BROWSER_CHANNEL=chrome ARCHWISE_PLAYWRIGHT_ENTRY=/pw/node_modules/playwright/index.mjs node scripts/browser-smoke.mjs`. Expected: the script prints the passed message. If local Chrome is unavailable, rely on the CI `Browser Studio Smoke` job and record that in the ledger. +- [ ] **Step 3:** Commit with `test(browser): exercise autosave, cross-launch resume, rename and delete`. + +### Task 5: Documentation, full check, PR + +**Files:** +- `docs/sessions.md`: remove the "Studio does not use them yet" status, describe the Studio flows (indicator, Sessions panel, resume, notice, new session, `--resume`, single-tab rule, `--no-store`), and add `POST /api/v1/sessions/new` to the API table. +- `docs/sandbox-persistence.md`: Sandbox state now lives in the local store and autosaves; reload restores from the store; `localStorage` is retired (older browser-only Sandboxes move through JSON export/import from a previous build); export/import are unchanged. +- `docs/scenario-comparison.md`, `docs/alpha-testing.md` (steps 10–11 and the limits), `docs/browser-qa.md` (the new scenarios), and `docs/canvas-first-ux.md` (if it mentions browser storage). +- `README.md` status line, `docs/implementation-roadmap.md` (Phase 2 current-state table and status: the sessions slice is complete; remaining items are export redaction of home paths and the exit-gate evidence), `apps/web/README.md`, `apps/cli/README.md` (`--resume`), and `.changeset/studio-sessions.md`. + +- [ ] **Step 1:** Update the docs, and grep for `localStorage` across `docs/` and `README.md` to confirm that each remaining mention is accurate. +- [ ] **Step 2:** Run `npx --yes pnpm@10.34.9 check` and the relative-link check. Expected: both pass. +- [ ] **Step 3:** Commit with `docs: Studio sessions, autosave and resume`. Then run the final review, push, open the PR, wait for the required checks and the browser smoke, and merge. From 10d978855dc1dcaa8837ccf6e9e9bebc171d8c14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Oliveira?= Date: Sun, 15 Nov 2026 21:02:00 -0300 Subject: [PATCH 2/7] feat: start new sessions and resume from the CLI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Signed-off-by: André Oliveira --- apps/cli/src/bin.ts | 56 +++++++++++-------- apps/cli/src/index.ts | 35 +++++++++++- apps/cli/src/session-routes.ts | 8 +++ apps/cli/src/store-runtime.ts | 20 +++++++ apps/cli/tests/cli.test.ts | 18 ++++++ apps/cli/tests/session-api.test.ts | 12 ++++ apps/cli/tests/store-runtime.test.ts | 27 +++++++++ packages/application/src/session-service.ts | 10 ++++ .../application/tests/session-service.test.ts | 20 +++++++ .../tests/session-store-integration.test.mjs | 47 +++++++++++++++- 10 files changed, 226 insertions(+), 27 deletions(-) diff --git a/apps/cli/src/bin.ts b/apps/cli/src/bin.ts index 9606a65..bd4abcb 100644 --- a/apps/cli/src/bin.ts +++ b/apps/cli/src/bin.ts @@ -9,7 +9,12 @@ import { inspectWorkspace } from './inventory.js'; import { buildArchitectureGraph } from './graph.js'; import { parseCli } from './index.js'; import { startLocalGraphServer } from './local-server.js'; -import { formatSessionList, prepareStore, storeUnavailableMessage } from './store-runtime.js'; +import { + applyResume, + formatSessionList, + prepareStore, + storeUnavailableMessage, +} from './store-runtime.js'; const metadata: unknown = JSON.parse( readFileSync(new URL('../package.json', import.meta.url), 'utf8'), @@ -69,28 +74,35 @@ if (command.kind === 'output') { } } else if (command.serve) { const runtime = await prepareRuntime(command.store); - const webDistPath = resolve(fileURLToPath(new URL('../../web/dist/', import.meta.url))); - // CLI/API mode works before the browser bundle is built; serve assets if available. - let assets: string | undefined; - try { - const { stat } = await import('node:fs/promises'); - if ((await stat(resolve(webDistPath, 'index.html'))).isFile()) assets = webDistPath; - } catch { - process.stderr.write('Browser assets are not built; serving JSON API only.\n'); + const resumeError = command.resume === null ? null : applyResume(runtime, command.resume); + if (resumeError !== null) { + process.stderr.write(`${resumeError}\n`); + if (runtime.kind === 'ready') runtime.store.close(); + process.exitCode = 2; + } else { + const webDistPath = resolve(fileURLToPath(new URL('../../web/dist/', import.meta.url))); + // CLI/API mode works before the browser bundle is built; serve assets if available. + let assets: string | undefined; + try { + const { stat } = await import('node:fs/promises'); + if ((await stat(resolve(webDistPath, 'index.html'))).isFile()) assets = webDistPath; + } catch { + process.stderr.write('Browser assets are not built; serving JSON API only.\n'); + } + const server = await startLocalGraphServer(graph, { + ...(assets ? { webDistPath: assets } : {}), + sessions: runtime.kind === 'ready' ? runtime.service : null, + }); + process.stdout.write(`Archwise API listening at ${server.address}\n`); + process.stdout.write(`Local session URL: ${server.bootstrapUrl}\n`); + process.stdout.write( + runtime.kind === 'ready' + ? 'Local session store ready (outside the project). List saved sessions with --sessions.\n' + : 'Local session store disabled for this run.\n', + ); + process.stdout.write('Press Ctrl+C to stop.\n'); + if (command.open && assets) openBrowser(server.bootstrapUrl); } - const server = await startLocalGraphServer(graph, { - ...(assets ? { webDistPath: assets } : {}), - sessions: runtime.kind === 'ready' ? runtime.service : null, - }); - process.stdout.write(`Archwise API listening at ${server.address}\n`); - process.stdout.write(`Local session URL: ${server.bootstrapUrl}\n`); - process.stdout.write( - runtime.kind === 'ready' - ? 'Local session store ready (outside the project). List saved sessions with --sessions.\n' - : 'Local session store disabled for this run.\n', - ); - process.stdout.write('Press Ctrl+C to stop.\n'); - if (command.open && assets) openBrowser(server.bootstrapUrl); } else if (command.graph) { process.stdout.write(`${JSON.stringify(graph, null, 2)}\n`); } else if (command.json) { diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts index 96a1557..c415ea8 100644 --- a/apps/cli/src/index.ts +++ b/apps/cli/src/index.ts @@ -17,6 +17,8 @@ export type CliCommand = readonly sessions: boolean; /** Use the local session store (disabled by --no-store). */ readonly store: boolean; + /** `latest` or a session ID to resume when serving; null starts a fresh session. */ + readonly resume: string | null; }; /** Parse arguments without touching the filesystem or executing project code. */ @@ -30,10 +32,11 @@ export function parseCli(args: readonly string[], version = 'development'): CliC result: { exitCode: 0, stdout: - 'Usage: archwise [--path DIRECTORY] [--json | --graph | --sessions | --serve [--no-open] [--no-store]] [--help | --version]\n' + + 'Usage: archwise [--path DIRECTORY] [--json | --graph | --sessions | --serve [--no-open] [--no-store | --resume latest|SESSION_ID]] [--help | --version]\n' + 'Read-only inventory of local Node.js package manifests. --graph emits a deterministic evidence-backed graph.\n' + '--sessions lists saved Sandbox sessions for this project. --serve opens the local Studio and records\n' + - 'the discovered graph in the local store outside the project; --no-store disables the store.\n', + 'the discovered graph in the local store outside the project; --no-store disables the store.\n' + + '--resume continues the newest (latest) or a specific saved session instead of a fresh one.\n', stderr: '', }, }; @@ -45,6 +48,7 @@ export function parseCli(args: readonly string[], version = 'development'): CliC let open = true; let sessions = false; let store = true; + let resume: string | null = null; for (let i = 0; i < args.length; i++) { if (args[i] === '--path' && args[i + 1] && !args[i + 1]!.startsWith('--')) { path = args[++i]!; @@ -60,6 +64,20 @@ export function parseCli(args: readonly string[], version = 'development'): CliC sessions = true; } else if (args[i] === '--no-store') { store = false; + } else if (args[i] === '--resume') { + const value = args[i + 1]; + if (!value || !(value === 'latest' || /^ses-[0-9a-f]{24}$/.test(value))) { + return { + kind: 'output', + result: { + exitCode: 2, + stdout: '', + stderr: '--resume expects "latest" or a session ID from --sessions.\n', + }, + }; + } + resume = value; + i += 1; } else { return { kind: 'output', @@ -93,7 +111,18 @@ export function parseCli(args: readonly string[], version = 'development'): CliC result: { exitCode: 2, stdout: '', stderr: '--no-store requires --serve.\n' }, }; } - return { kind: 'inspect', path, json, graph, serve, open, sessions, store }; + if (resume !== null && (!serve || !store)) { + return { + kind: 'output', + result: { + exitCode: 2, + stdout: '', + stderr: + '--resume requires --serve and the local store (it cannot be combined with --no-store).\n', + }, + }; + } + return { kind: 'inspect', path, json, graph, serve, open, sessions, store, resume }; } /** Kept as a pure CLI helper for compatibility with the existing CLI tests. */ diff --git a/apps/cli/src/session-routes.ts b/apps/cli/src/session-routes.ts index 7ddcf9e..dfb3332 100644 --- a/apps/cli/src/session-routes.ts +++ b/apps/cli/src/session-routes.ts @@ -69,6 +69,14 @@ export async function handleSessionRoute( notFound(res); return; } + if (pathname === `${PREFIX}/new` && method === 'POST') { + if (req.headers.origin !== context.origin) { + json(res, 403, { error: 'Same-origin request required' }); + return; + } + json(res, 200, { ...sessions.startNew(), storeEnabled: true }); + return; + } if (pathname === PREFIX && method === 'GET') { json(res, 200, { sessions: sessions.list() }); return; diff --git a/apps/cli/src/store-runtime.ts b/apps/cli/src/store-runtime.ts index e50b865..ccf7790 100644 --- a/apps/cli/src/store-runtime.ts +++ b/apps/cli/src/store-runtime.ts @@ -94,6 +94,26 @@ export async function prepareStore(options: PrepareStoreOptions): Promise { open: true, sessions: false, store: true, + resume: null, }); }); @@ -24,6 +25,7 @@ test('accepts a workspace path and graph output', () => { open: true, sessions: false, store: true, + resume: null, }); }); @@ -47,6 +49,7 @@ test('prints help and rejects unsupported or contradictory options', () => { open: false, sessions: false, store: true, + resume: null, }); }); @@ -66,3 +69,18 @@ test('help does not claim the Studio already saves sessions', () => { expect(help).not.toMatch(/saves Sandbox sessions/); expect(help).toContain('local store'); }); + +test('--resume requires --serve, the store, and latest or a session id', () => { + expect(parseCli(['--serve', '--resume', 'latest'])).toMatchObject({ + serve: true, + resume: 'latest', + }); + const id = `ses-${'a'.repeat(24)}`; + expect(parseCli(['--serve', '--resume', id])).toMatchObject({ resume: id }); + expect(parseCli(['--serve'])).toMatchObject({ resume: null }); + expect(runCli(['--resume', 'latest']).exitCode).toBe(2); + expect(runCli(['--serve', '--resume', 'ses-bad']).exitCode).toBe(2); + expect(runCli(['--serve', '--resume']).exitCode).toBe(2); + expect(runCli(['--serve', '--resume', 'latest', '--no-store']).exitCode).toBe(2); + expect(runCli(['--help']).stdout).toContain('--resume'); +}); diff --git a/apps/cli/tests/session-api.test.ts b/apps/cli/tests/session-api.test.ts index 6de2014..aba04a4 100644 --- a/apps/cli/tests/session-api.test.ts +++ b/apps/cli/tests/session-api.test.ts @@ -200,3 +200,15 @@ test('non-session routes still reject mutating methods', async () => { const { call } = await start(); expect((await call('/api/v1/graph', { method: 'POST' })).status).toBe(405); }); + +test('POST /new reserves a fresh current session for same-origin callers', async () => { + const { call } = await start(); + const before = (await (await call('/api/v1/sessions/current')).json()) as { id: string }; + const denied = await call('/api/v1/sessions/new', { method: 'POST', headers: { origin: '' } }); + expect(denied.status).toBe(403); + const created = await call('/api/v1/sessions/new', { method: 'POST' }); + expect(created.status).toBe(200); + const body = (await created.json()) as { id: string; persisted: boolean; storeEnabled: boolean }; + expect(body).toMatchObject({ persisted: false, storeEnabled: true }); + expect(body.id).not.toBe(before.id); +}); diff --git a/apps/cli/tests/store-runtime.test.ts b/apps/cli/tests/store-runtime.test.ts index d7e2e88..6b5814e 100644 --- a/apps/cli/tests/store-runtime.test.ts +++ b/apps/cli/tests/store-runtime.test.ts @@ -62,3 +62,30 @@ test('a data directory outside the root opens the store', async () => { expect(runtime.kind).toBe('ready'); if (runtime.kind === 'ready') runtime.store.close(); }); + +test('resumeTarget resolves latest and known ids only', async () => { + const { resumeTarget } = await import('../src/store-runtime.js'); + const root = temp('archwise-root-'); + const data = temp('archwise-data-'); + const runtime = await prepareStore({ + enabled: true, + dataDir: data, + rootPath: root, + rootLabel: 'r', + graph, + }); + if (runtime.kind !== 'ready') throw new Error('store expected'); + try { + expect(resumeTarget(runtime.service, 'latest')).toBeNull(); + const id = runtime.service.current().id; + runtime.service.saveSandbox( + id, + JSON.stringify({ format: 'archwise-sandbox', version: 1, nodes: [], draft: {} }), + ); + expect(resumeTarget(runtime.service, 'latest')).toBe(id); + expect(resumeTarget(runtime.service, id)).toBe(id); + expect(resumeTarget(runtime.service, `ses-${'f'.repeat(24)}`)).toBeNull(); + } finally { + runtime.store.close(); + } +}); diff --git a/packages/application/src/session-service.ts b/packages/application/src/session-service.ts index 39cc4f9..3ba01e4 100644 --- a/packages/application/src/session-service.ts +++ b/packages/application/src/session-service.ts @@ -136,6 +136,12 @@ export class SessionService { return { ...this.#current }; } + /** Reserves a fresh, unpersisted session as current (e.g. "New session" in the Studio). */ + startNew(): { readonly id: string; readonly persisted: boolean } { + this.#current = { id: this.#deps.ids.next('ses'), persisted: false }; + return { ...this.#current }; + } + list(): readonly SessionSummary[] { return this.#deps.store.sessions .list(this.workspaceId) @@ -150,6 +156,10 @@ export class SessionService { return { ok: true, value: this.#detail(session, base) }; } + /** + * Continues a stored session in place. A reserved, never-persisted current ID is discarded: + * nothing was stored under it, and later saves to it are rejected as not-found. + */ resume(id: string): ServiceResult { const detail = this.get(id); if (detail.ok) this.#current = { id, persisted: true }; diff --git a/packages/application/tests/session-service.test.ts b/packages/application/tests/session-service.test.ts index 8528f1b..93fe26a 100644 --- a/packages/application/tests/session-service.test.ts +++ b/packages/application/tests/session-service.test.ts @@ -182,3 +182,23 @@ test('a changed view with an unchanged revision records a new revision', () => { '{"framework":"react"}', ); }); + +test('startNew reserves a fresh session and keeps saved ones listed', () => { + const service = open(deps()); + const first = service.current().id; + service.saveSandbox(first, sandboxDoc(1)); + const next = service.startNew(); + expect(next).toEqual({ id: next.id, persisted: false }); + expect(next.id).not.toBe(first); + expect(service.current()).toEqual(next); + expect(service.list().map((s) => s.id)).toEqual([first]); +}); + +test('resuming discards the reserved, never-persisted session id', () => { + const service = open(deps()); + const saved = service.current().id; + service.saveSandbox(saved, sandboxDoc(1)); + const reserved = service.startNew().id; + service.resume(saved); + expect(service.saveSandbox(reserved, sandboxDoc(1))).toEqual({ ok: false, error: 'not-found' }); +}); diff --git a/scripts/tests/session-store-integration.test.mjs b/scripts/tests/session-store-integration.test.mjs index 77b61c7..ade7ec5 100644 --- a/scripts/tests/session-store-integration.test.mjs +++ b/scripts/tests/session-store-integration.test.mjs @@ -46,8 +46,8 @@ const run = (args, env) => }); /** Starts `--serve --no-open`, resolves with the bootstrap URL once printed. */ -function serve(root, env) { - const child = spawn(process.execPath, [cli, '--serve', '--no-open', '--path', root], { +function serve(root, env, extra = []) { + const child = spawn(process.execPath, [cli, '--serve', '--no-open', ...extra, '--path', root], { env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'], }); @@ -135,3 +135,46 @@ test('an unusable data directory stops --serve with an actionable message', asyn await rm(parent, { recursive: true, force: true }); } }); + +test('--resume latest fails clearly on an empty store and resumes the newest session otherwise', async () => { + const root = await fixture(); + const dataDir = await mkdtemp(join(tmpdir(), 'archwise-session-data-')); + const env = { ARCHWISE_DATA_DIR: dataDir }; + let server; + try { + const empty = run(['--serve', '--no-open', '--resume', 'latest', '--path', root], env); + assert.equal(empty.status, 2, empty.stdout + empty.stderr); + assert.match(empty.stderr, /Run --sessions/); + + server = await serve(root, env); + let origin = new URL(server.bootstrapUrl).origin; + let cookie = (await fetch(server.bootstrapUrl, { redirect: 'manual' })).headers + .get('set-cookie') + .split(';')[0]; + const current = await ( + await fetch(`${origin}/api/v1/sessions/current`, { headers: { cookie } }) + ).json(); + const saved = await fetch(`${origin}/api/v1/sessions/${current.id}/sandbox`, { + method: 'PUT', + headers: { cookie, origin, 'content-type': 'application/json' }, + body: JSON.stringify({ format: 'archwise-sandbox', version: 1, nodes: [], draft: {} }), + }); + assert.equal(saved.status, 200); + server.child.kill(); + await new Promise((accept) => server.child.once('exit', accept)); + + server = await serve(root, env, ['--resume', 'latest']); + origin = new URL(server.bootstrapUrl).origin; + cookie = (await fetch(server.bootstrapUrl, { redirect: 'manual' })).headers + .get('set-cookie') + .split(';')[0]; + const resumed = await ( + await fetch(`${origin}/api/v1/sessions/current`, { headers: { cookie } }) + ).json(); + assert.deepEqual(resumed, { id: current.id, persisted: true, storeEnabled: true }); + } finally { + server?.child.kill(); + await rm(root, { recursive: true, force: true }); + await rm(dataDir, { recursive: true, force: true }); + } +}); From cfcd0cb719fc599baab027cb15b3a6e4faf833e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Oliveira?= Date: Sun, 15 Nov 2026 21:03:54 -0300 Subject: [PATCH 3/7] feat(web): session API client and autosave controller MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Signed-off-by: André Oliveira --- apps/web/src/autosave.test.ts | 138 ++++++++++++++++++++++++++++ apps/web/src/autosave.ts | 112 ++++++++++++++++++++++ apps/web/src/session-client.test.ts | 94 +++++++++++++++++++ apps/web/src/session-client.ts | 106 +++++++++++++++++++++ 4 files changed, 450 insertions(+) create mode 100644 apps/web/src/autosave.test.ts create mode 100644 apps/web/src/autosave.ts create mode 100644 apps/web/src/session-client.test.ts create mode 100644 apps/web/src/session-client.ts diff --git a/apps/web/src/autosave.test.ts b/apps/web/src/autosave.test.ts new file mode 100644 index 0000000..3a35cde --- /dev/null +++ b/apps/web/src/autosave.test.ts @@ -0,0 +1,138 @@ +import { afterEach, beforeEach, expect, test, vi } from 'vitest'; +import { createAutosave, type AutosaveStatus } from './autosave.js'; +import type { ClientResult } from './session-client.js'; + +let statuses: AutosaveStatus[]; +let save: ReturnType< + typeof vi.fn<(text: string, keepalive: boolean) => Promise>> +>; +const ok = (): Promise> => Promise.resolve({ ok: true, value: null }); + +beforeEach(() => { + vi.useFakeTimers(); + statuses = []; + save = vi.fn(ok); +}); +afterEach(() => { + vi.useRealTimers(); +}); + +const make = () => createAutosave({ save, onStatus: (s) => statuses.push(s) }); +const last = () => statuses[statuses.length - 1]; + +test('debounces bursts into one save of the latest text', async () => { + const autosave = make(); + autosave.schedule('a'); + autosave.schedule('b'); + autosave.schedule('c'); + await vi.advanceTimersByTimeAsync(749); + expect(save).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(save).toHaveBeenCalledTimes(1); + expect(save).toHaveBeenCalledWith('c', false); + expect(last()).toEqual({ state: 'saved', message: 'All changes saved' }); +}); + +test('reports saving while a request is in flight', async () => { + let resolve!: (r: ClientResult) => void; + save.mockImplementationOnce(() => new Promise((r) => (resolve = r))); + const autosave = make(); + autosave.schedule('a'); + await vi.advanceTimersByTimeAsync(750); + expect(last()?.state).toBe('saving'); + resolve({ ok: true, value: null }); + await vi.runAllTimersAsync(); + expect(last()?.state).toBe('saved'); +}); + +test('a failed save keeps changes and retries on the next change', async () => { + save.mockResolvedValueOnce({ ok: false, status: 500, error: 'HTTP 500' }); + const autosave = make(); + autosave.schedule('a'); + await vi.advanceTimersByTimeAsync(750); + expect(last()).toEqual({ state: 'unsaved', message: 'Not saved — retrying on next change' }); + autosave.schedule('b'); + await vi.advanceTimersByTimeAsync(750); + expect(save).toHaveBeenLastCalledWith('b', false); + expect(last()?.state).toBe('saved'); +}); + +test('retry saves the pending text immediately', async () => { + save.mockResolvedValueOnce({ ok: false, status: 0, error: 'network' }); + const autosave = make(); + autosave.schedule('a'); + await vi.advanceTimersByTimeAsync(750); + autosave.retry(); + await vi.runAllTimersAsync(); + expect(save).toHaveBeenCalledTimes(2); + expect(last()?.state).toBe('saved'); +}); + +test('a 404 stops autosave until an explicit retry', async () => { + save.mockResolvedValueOnce({ ok: false, status: 404, error: 'not-found' }); + const autosave = make(); + autosave.schedule('a'); + await vi.advanceTimersByTimeAsync(750); + expect(last()).toEqual({ + state: 'unsaved', + message: 'This session changed elsewhere. Reload to continue.', + }); + autosave.schedule('b'); + await vi.advanceTimersByTimeAsync(2000); + expect(save).toHaveBeenCalledTimes(1); +}); + +test('changes during an in-flight save trigger a follow-up save of the latest text', async () => { + let resolve!: (r: ClientResult) => void; + save.mockImplementationOnce(() => new Promise((r) => (resolve = r))); + const autosave = make(); + autosave.schedule('a'); + await vi.advanceTimersByTimeAsync(750); + autosave.schedule('b'); + await vi.advanceTimersByTimeAsync(750); + expect(save).toHaveBeenCalledTimes(1); + resolve({ ok: true, value: null }); + await vi.runAllTimersAsync(); + expect(save).toHaveBeenCalledTimes(2); + expect(save).toHaveBeenLastCalledWith('b', false); +}); + +test('identical text is not saved twice', async () => { + const autosave = make(); + autosave.schedule('a'); + await vi.advanceTimersByTimeAsync(750); + autosave.schedule('a'); + await vi.advanceTimersByTimeAsync(750); + expect(save).toHaveBeenCalledTimes(1); + expect(last()?.state).toBe('saved'); +}); + +test('flush saves pending text immediately with keepalive', async () => { + const autosave = make(); + autosave.schedule('a'); + await autosave.flush({ keepalive: true }); + expect(save).toHaveBeenCalledWith('a', true); + await vi.advanceTimersByTimeAsync(2000); + expect(save).toHaveBeenCalledTimes(1); +}); + +test('dispose cancels a pending save', async () => { + const autosave = make(); + autosave.schedule('a'); + autosave.dispose(); + await vi.advanceTimersByTimeAsync(2000); + expect(save).not.toHaveBeenCalled(); +}); + +test('ignoreFirst treats the initial render as already saved', async () => { + const autosave = createAutosave({ save, onStatus: (s) => statuses.push(s), ignoreFirst: true }); + autosave.schedule('initial'); + await vi.advanceTimersByTimeAsync(2000); + expect(save).not.toHaveBeenCalled(); + autosave.schedule('initial'); + await vi.advanceTimersByTimeAsync(2000); + expect(save).not.toHaveBeenCalled(); + autosave.schedule('edited'); + await vi.advanceTimersByTimeAsync(750); + expect(save).toHaveBeenCalledWith('edited', false); +}); diff --git a/apps/web/src/autosave.ts b/apps/web/src/autosave.ts new file mode 100644 index 0000000..1d9d656 --- /dev/null +++ b/apps/web/src/autosave.ts @@ -0,0 +1,112 @@ +import type { ClientResult } from './session-client.js'; + +export type SaveState = 'saved' | 'saving' | 'unsaved' | 'disabled'; + +export interface AutosaveStatus { + readonly state: SaveState; + readonly message: string; +} + +export interface Autosave { + schedule(text: string): void; + flush(options?: { readonly keepalive?: boolean }): Promise; + retry(): void; + dispose(): void; +} + +export interface AutosaveOptions { + readonly save: (text: string, keepalive: boolean) => Promise>; + readonly onStatus: (status: AutosaveStatus) => void; + readonly delayMs?: number; + /** Treat the first scheduled text (the initial render) as already saved. */ + readonly ignoreFirst?: boolean; +} + +const SAVED: AutosaveStatus = { state: 'saved', message: 'All changes saved' }; +const SAVING: AutosaveStatus = { state: 'saving', message: 'Saving…' }; +const FAILED: AutosaveStatus = { state: 'unsaved', message: 'Not saved — retrying on next change' }; +const CONFLICT: AutosaveStatus = { + state: 'unsaved', + message: 'This session changed elsewhere. Reload to continue.', +}; + +/** + * Debounced, single-flight autosave. In-memory state is never discarded: a failure only + * changes the reported status, and the newest text is always the one eventually saved. + */ +export function createAutosave(options: AutosaveOptions): Autosave { + const delay = options.delayMs ?? 750; + let pending: string | null = null; + let lastSaved: string | null = null; + let timer: ReturnType | null = null; + let inFlight = false; + let blocked = false; + let first = options.ignoreFirst === true; + let disposed = false; + + const clearTimer = () => { + if (timer !== null) clearTimeout(timer); + timer = null; + }; + + async function run(keepalive: boolean): Promise { + clearTimer(); + if (disposed || inFlight || pending === null) return; + if (pending === lastSaved) { + pending = null; + options.onStatus(SAVED); + return; + } + const text = pending; + pending = null; + inFlight = true; + options.onStatus(SAVING); + const result = await options.save(text, keepalive); + inFlight = false; + if (disposed) return; + if (result.ok) { + lastSaved = text; + if (pending !== null && pending !== lastSaved) { + await run(false); + return; + } + pending = null; + options.onStatus(SAVED); + return; + } + pending ??= text; + if (result.status === 404) { + blocked = true; + options.onStatus(CONFLICT); + } else { + options.onStatus(FAILED); + } + } + + return { + schedule(text) { + if (disposed) return; + if (first) { + first = false; + lastSaved = text; + return; + } + pending = text; + if (blocked || inFlight) return; + clearTimer(); + timer = setTimeout(() => void run(false), delay); + }, + flush(flushOptions = {}) { + if (blocked) return Promise.resolve(); + return run(flushOptions.keepalive === true); + }, + retry() { + blocked = false; + void run(false); + }, + dispose() { + disposed = true; + clearTimer(); + }, + }; +} diff --git a/apps/web/src/session-client.test.ts b/apps/web/src/session-client.test.ts new file mode 100644 index 0000000..2ee9b60 --- /dev/null +++ b/apps/web/src/session-client.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, test, vi } from 'vitest'; +import { + deleteSession, + getCurrent, + getSession, + listSessions, + renameSession, + resumeSession, + saveSandbox, + startNewSession, +} from './session-client.js'; + +const respond = (status: number, body?: unknown) => + vi.fn(() => + Promise.resolve(new Response(body === undefined ? null : JSON.stringify(body), { status })), + ); + +const id = `ses-${'a'.repeat(24)}`; + +describe('requests', () => { + test.each([ + ['getCurrent', () => getCurrent, [], 'GET', '/api/v1/sessions/current'], + ['listSessions', () => listSessions, [], 'GET', '/api/v1/sessions'], + ['getSession', () => getSession, [id], 'GET', `/api/v1/sessions/${id}`], + ['resumeSession', () => resumeSession, [id], 'POST', `/api/v1/sessions/${id}/resume`], + ['startNewSession', () => startNewSession, [], 'POST', '/api/v1/sessions/new'], + ['deleteSession', () => deleteSession, [id], 'DELETE', `/api/v1/sessions/${id}`], + ] as const)('%s uses %s %s', async (_name, pick, args, method, path) => { + const f = respond( + method === 'DELETE' ? 204 : 200, + method === 'DELETE' ? undefined : { sessions: [] }, + ); + await (pick() as (...a: unknown[]) => Promise)(...args, f); + const [url, init] = f.mock.calls[0]!; + expect(url).toBe(path); + expect(init?.method ?? 'GET').toBe(method); + expect(init?.credentials).toBe('same-origin'); + expect(new Headers(init?.headers).has('content-type')).toBe(false); + }); + + test('saveSandbox sends the raw document as JSON and supports keepalive', async () => { + const f = respond(200, { id }); + await saveSandbox(id, '{"format":"archwise-sandbox"}', f, { keepalive: true }); + const [url, init] = f.mock.calls[0]!; + expect(url).toBe(`/api/v1/sessions/${id}/sandbox`); + expect(init?.method).toBe('PUT'); + expect(init?.body).toBe('{"format":"archwise-sandbox"}'); + expect(init?.keepalive).toBe(true); + expect(new Headers(init?.headers).get('content-type')).toBe('application/json'); + }); + + test('renameSession sends a JSON label', async () => { + const f = respond(200, { id, label: 'New' }); + await renameSession(id, 'New', f); + const [, init] = f.mock.calls[0]!; + expect(init?.method).toBe('PATCH'); + expect(init?.body).toBe('{"label":"New"}'); + }); +}); + +describe('responses', () => { + test('parses successful JSON', async () => { + expect(await getCurrent(respond(200, { id, persisted: false, storeEnabled: true }))).toEqual({ + ok: true, + value: { id, persisted: false, storeEnabled: true }, + }); + expect(await listSessions(respond(200, { sessions: [{ id }] }))).toEqual({ + ok: true, + value: [{ id }], + }); + }); + + test('delete returns null on 204', async () => { + expect(await deleteSession(id, respond(204))).toEqual({ ok: true, value: null }); + }); + + test('non-2xx responses become typed failures', async () => { + expect(await getSession(id, respond(404, { error: 'not-found' }))).toEqual({ + ok: false, + status: 404, + error: 'not-found', + }); + expect(await saveSandbox(id, '{}', respond(500))).toEqual({ + ok: false, + status: 500, + error: 'HTTP 500', + }); + }); + + test('network errors never throw', async () => { + const f = vi.fn(() => Promise.reject(new TypeError('Failed to fetch'))); + expect(await getCurrent(f)).toEqual({ ok: false, status: 0, error: 'network' }); + }); +}); diff --git a/apps/web/src/session-client.ts b/apps/web/src/session-client.ts new file mode 100644 index 0000000..f5a0532 --- /dev/null +++ b/apps/web/src/session-client.ts @@ -0,0 +1,106 @@ +/** Typed client for the loopback session API. Never throws; failures are values. */ + +export interface CurrentSession { + readonly id: string | null; + readonly persisted: boolean; + readonly storeEnabled: boolean; +} + +export interface SessionSummary { + readonly id: string; + readonly label: string; + readonly createdAt: string; + readonly updatedAt: string; + readonly componentCount: number; + readonly hasSnapshots: boolean; + readonly baseIsCurrent: boolean; +} + +export interface SessionDetail extends SessionSummary { + readonly sandbox: string; + readonly view: unknown; +} + +export type ClientResult = + | { readonly ok: true; readonly value: T } + | { readonly ok: false; readonly status: number; readonly error: string }; + +type Fetch = typeof fetch; +const BASE = '/api/v1/sessions'; + +async function request( + f: Fetch, + path: string, + init: RequestInit & { readonly jsonBody?: string }, + map: (payload: unknown) => T, +): Promise> { + const { jsonBody, ...rest } = init; + let response: Response; + try { + response = await f(path, { + ...rest, + credentials: 'same-origin', + ...(jsonBody === undefined + ? {} + : { body: jsonBody, headers: { 'Content-Type': 'application/json' } }), + }); + } catch { + return { ok: false, status: 0, error: 'network' }; + } + if (response.status === 204) return { ok: true, value: map(null) }; + let payload: unknown; + try { + payload = await response.json(); + } catch { + payload = null; + } + if (!response.ok) { + const error = + typeof payload === 'object' && payload !== null && 'error' in payload + ? String(payload.error) + : `HTTP ${response.status}`; + return { ok: false, status: response.status, error }; + } + return { ok: true, value: map(payload) }; +} + +const identity = (payload: unknown): T => payload as T; + +export const getCurrent = (f: Fetch = fetch) => + request(f, `${BASE}/current`, {}, identity); + +export const listSessions = (f: Fetch = fetch) => + request(f, BASE, {}, (payload) => (payload as { sessions: SessionSummary[] }).sessions); + +export const getSession = (id: string, f: Fetch = fetch) => + request(f, `${BASE}/${id}`, {}, identity); + +export const resumeSession = (id: string, f: Fetch = fetch) => + request(f, `${BASE}/${id}/resume`, { method: 'POST' }, identity); + +export const startNewSession = (f: Fetch = fetch) => + request(f, `${BASE}/new`, { method: 'POST' }, identity); + +export const saveSandbox = ( + id: string, + text: string, + f: Fetch = fetch, + init: { readonly keepalive?: boolean } = {}, +) => + request( + f, + `${BASE}/${id}/sandbox`, + { method: 'PUT', jsonBody: text, ...(init.keepalive ? { keepalive: true } : {}) }, + identity, + ); + +export const renameSession = (id: string, label: string, f: Fetch = fetch) => + request( + f, + `${BASE}/${id}`, + { method: 'PATCH', jsonBody: JSON.stringify({ label }) }, + identity, + ); + +export const deleteSession = (id: string, f: Fetch = fetch) => + request(f, `${BASE}/${id}`, { method: 'DELETE' }, () => null); From b2f9803ed4f6b5ec7e03d2d836bde1d833d4ead3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Oliveira?= Date: Sun, 15 Nov 2026 21:05:46 -0300 Subject: [PATCH 4/7] feat(web): autosaved sessions, session list and resume in the Studio MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Signed-off-by: André Oliveira --- apps/web/src/App.svelte | 113 ++++++++++++++++++++++++- apps/web/src/ArchitectureCanvas.svelte | 30 ++++--- apps/web/src/SessionsPanel.svelte | 111 ++++++++++++++++++++++++ apps/web/src/session-view.test.ts | 46 ++++++++++ apps/web/src/session-view.ts | 16 ++++ apps/web/src/studio.css | 111 ++++++++++++++++++++++++ 6 files changed, 409 insertions(+), 18 deletions(-) create mode 100644 apps/web/src/SessionsPanel.svelte create mode 100644 apps/web/src/session-view.test.ts create mode 100644 apps/web/src/session-view.ts diff --git a/apps/web/src/App.svelte b/apps/web/src/App.svelte index a9ff846..159dbea 100644 --- a/apps/web/src/App.svelte +++ b/apps/web/src/App.svelte @@ -1,6 +1,18 @@ @@ -77,8 +162,19 @@
⬡ Archwise Architecture Studio - ● Local · Read-only project inspection +
+ {saveStatus.message} + {#if saveStatus.state === 'unsaved' && !saveStatus.message.includes('Reload')} + + {/if} + {#if storeEnabled} + + {/if} + ● Local · Read-only project inspection +
+