| 1 | import React, { useState } from "react"; |
| 2 | import { createRoot } from "react-dom/client"; |
| 3 | import { useController } from "../src/lib/useController"; |
| 4 | import { projectSessionRowKey } from "../src/lib/projectSessionIdentity"; |
| 5 | import { mergeProjectTopicPage, projectTreeWithoutTopics } from "../src/lib/projectTreeTopic"; |
| 6 | import { createSessionLifecycleFences } from "../src/lib/sessionLifecycleFences"; |
| 7 | import { installDesktopHostStub } from "../src/__tests__/desktopHostStub"; |
| 8 | import { meta, tabMeta } from "../src/__tests__/helpers/sessionSwitchFixtures"; |
| 9 | import type { ProjectNode } from "../src/lib/types"; |
| 10 | import type { FollowRequest, TranscriptFollowResponse } from "../src/generated/desktopContract.generated"; |
| 11 | |
| 12 | function deferred() { |
| 13 | let resolve!: () => void; |
| 14 | const promise = new Promise<void>(done => { resolve = done; }); |
| 15 | return { promise, resolve }; |
| 16 | } |
| 17 | let current = "initial", epoch = "initial-epoch", committed = true; |
| 18 | let releaseOpen = deferred(), releaseBaseline = deferred(); |
| 19 | let reads = 0, premature = 0; |
| 20 | const metadata = () => meta({ session: { hostId: "local", sessionId: current }, sessionPath: `session-id:${current}`, |
| 21 | sessionGeneration: 1, runtime: { phase: "ready", epoch } }); |
| 22 | const stub = installDesktopHostStub({ |
| 23 | RegisterNavigationIntent: async () => {}, |
| 24 | ListTabs: async () => [tabMeta({ ...metadata(), active: true })], MetaForTab: async () => metadata(), |
| 25 | ReplayPendingPrompts: async () => {}, ReplayPendingPromptsForTab: async () => {}, |
| 26 | ContextUsageForTab: async () => ({ used: 0, window: 100, sessionTokens: 0 }), |
| 27 | EffortForTab: async () => ({ supported: false, current: "auto", levels: [] }), |
| 28 | BalanceForTab: async () => ({ available: false, display: "" }), JobsForTab: async () => [], |
| 29 | CheckpointsForTab: async () => [], ForkTargetsForTab: async () => ({ targets: [], verifiable: false }), |
| 30 | OpenSession: async (ref: { sessionId: string }) => { |
| 31 | current = ref.sessionId; epoch = `${current}-epoch`; committed = false; |
| 32 | stub.emit("runtime:rebuilt", "tab-a", epoch); |
| 33 | stub.emit("runtime:rebuilt", "tab-a", epoch); |
| 34 | stub.emit("agent:ready", "tab-a"); |
| 35 | await releaseOpen.promise; |
| 36 | committed = true; |
| 37 | }, |
| 38 | TranscriptFollowForTab: async (_tab: string, request: FollowRequest): Promise<TranscriptFollowResponse> => { |
| 39 | if (request.close) return { protocolVersion: 2, subscription: request.subscription, changes: [], resetRequired: false }; |
| 40 | if (request.subscription) return new Promise(() => {}); |
| 41 | const id = current; |
| 42 | if (id !== "initial") reads++; |
| 43 | if (!committed) { premature++; throw new Error("runtime changed while following transcript"); } |
| 44 | if (id !== "initial") await releaseBaseline.promise; |
| 45 | return { protocolVersion: 2, subscription: `${id}-${reads}`, changes: [], resetRequired: false, |
| 46 | snapshot: { protocolVersion: 1, snapshotId: id, identity: { sessionId: id, runtimeEpoch: epoch, rewriteEpoch: 0, headId: "" }, |
| 47 | projectionRevision: 1, coveredThroughSeq: 1, durableSeq: 1, records: [], activeRecords: [], activeAttempts: [], |
| 48 | runtime: { status: "completed", pendingEvents: [], samplingCount: 0, toolCount: 0 }, |
| 49 | before: 0, hasOlder: false, totalRecords: 0, totalTurns: 0, stale: false }, |
| 50 | history: { status: "ready", snapshotSequence: 1, coverageSequence: 1, generation: id, totalTurns: 0, |
| 51 | hasOlder: false, hasNewer: false, messages: [] } }; |
| 52 | }, |
| 53 | }); |
| 54 | const source: ProjectNode = { key: "legacy", kind: "global_topic", label: "Imported history", |
| 55 | source: { hostId: "local", sourceKey: "browser-source", path: "/history.jsonl" } }; |
| 56 | const original: ProjectNode = { key: "original", kind: "global_topic", label: "Imported history", |
| 57 | session: { hostId: "local", sessionId: "original" }, identityAliases: ["source\0local\0browser-source"] }; |
| 58 | const reviewed: ProjectNode = { ...original, key: "reviewed", session: { hostId: "local", sessionId: "reviewed" } }; |
| 59 | const other: ProjectNode = { key: "other", kind: "global_topic", label: "Other session", session: { hostId: "local", sessionId: "other" } }; |
| 60 | const fences = createSessionLifecycleFences(); |
| 61 | |
| 62 | function Fixture() { |
| 63 | const controller = useController(); |
| 64 | const [cycle, setCycle] = useState(-1); |
| 65 | const [status, setStatus] = useState("idle"); |
| 66 | const [result, setResult] = useState({ reads: 0, premature: 0, elapsed: 0 }); |
| 67 | const pages = cycle < 0 ? [source] : cycle % 2 |
| 68 | ? mergeProjectTopicPage([other, reviewed], [original], true) |
| 69 | : mergeProjectTopicPage([original], [reviewed], true); |
| 70 | const rows = projectTreeWithoutTopics(pages, fences.keys()); |
| 71 | return <main style={{ fontFamily: "system-ui", padding: 32 }}> |
| 72 | <h1>Session navigation and sidebar regression</h1> |
| 73 | <p>Shared-source sessions remain separate through repeated catalog refreshes.</p> |
| 74 | <button onClick={() => setCycle(value => value + 1)}>Refresh list</button> |
| 75 | <button onClick={() => { fences.archive(original, { lifecycleGeneration: 1, operationId: "archive-original" }); setCycle(value => value + 2); }}>Archive original</button> |
| 76 | <button onClick={() => { fences.observeDirectory([{ ...reviewed, lifecycleGeneration: 99 }]); setCycle(value => value + 2); }}>Refresh sibling</button> |
| 77 | <button onClick={() => { fences.observeDirectory([{ ...original, lifecycleGeneration: 2 }]); setCycle(value => value + 2); }}>Restore original</button> |
| 78 | <ul>{rows.map(row => <li key={projectSessionRowKey(row)} data-session={row.session?.sessionId ?? "source"}>{row.label}</li>)}</ul> |
| 79 | <button disabled={status === "opening" || !controller.state.meta?.ready} onClick={() => { |
| 80 | const startedAt = performance.now(); |
| 81 | reads = 0; premature = 0; releaseOpen = deferred(); releaseBaseline = deferred(); setStatus("opening"); |
| 82 | const intent = controller.noteNavigationIntent(); |
| 83 | void controller.openCanonicalSession({ hostId: "local", sessionId: `target-${intent}` }, intent).then(() => { |
| 84 | setResult({ reads, premature, elapsed: performance.now() - startedAt }); setStatus("ready"); |
| 85 | }, () => setStatus("failed")); |
| 86 | }}>Open session</button> |
| 87 | <button onClick={() => releaseOpen.resolve()}>Commit binding</button> |
| 88 | <button onClick={() => releaseBaseline.resolve()}>Deliver baseline</button> |
| 89 | <button onClick={() => { |
| 90 | stub.emit("runtime:rebuilt", "tab-a", epoch); stub.emit("agent:ready", "tab-a"); |
| 91 | setResult(value => ({ ...value, reads, premature })); |
| 92 | }}>Replay notifications</button> |
| 93 | <output data-status={status} data-reads={reads} data-premature={premature} data-cycle={cycle}> |
| 94 | {JSON.stringify({ status, ...result })} |
| 95 | </output> |
| 96 | </main>; |
| 97 | } |
| 98 | createRoot(document.getElementById("root")!).render(<Fixture />); |
| 99 |