YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
evals: catch stale chat settings after overlapping navigation
louis90042a63d03e
diff --git a/evals/coding-agent/README.md b/evals/coding-agent/README.mdindex 0365200d0..dbd09d47c 100644--- a/evals/coding-agent/README.md+++ b/evals/coding-agent/README.md@@ -9,7 +9,7 @@ This is an agent eval suite, not a unit-test suite. Every case contains:- saved prompt, transcript, candidate patch, grader output, runtime fingerprint, and result;- repeated-trial reporting with success rate, `pass@k`, and `pass^k`.-The current app corpus contains 52 git-mined regressions. See+The current app corpus contains 56 git-mined regressions. See[DESIGN.md](./DESIGN.md) for the Anthropic guidance, source contract, andhistory-mining workflow. The companion website manifest uses this same harness.@@ -419,3 +419,23 @@ account, event and analytics ports are synthetic; mount effects do not execute.It does not prove rendered deletion controls, live account refresh, nativedurability, enforced isolation or model performance. Preset dependency deletionrecovery remains a separate case.++## Overlapping chat settings and preset outcomes++The `app-chat-overlapping-load-isolation` grader retains all thirteen original+hook/store outcomes and adds delayed-settings-read races. The saved reopen+target and emitted preset must belong to the newest chat after an older read+finishes. The old grader passed a variant with those guards removed; the two+new outcomes reject it. The historical parent fails three outcomes and preserves+twelve; the reference and selected current source pass all fifteen.++Run `bun test evals/coding-agent/calibrate-chat-overlap.test.js` with desktop+JavaScript dependencies installed. Calibration covers the parent, reference,+the original false pass, separate settings/preset bypasses, equivalent request+guard naming, missing source and preserved navigation behavior. The fixture+runs the actual React hook and chat store with synthetic disk, settings and+event ports; title generation is stubbed to prevent model/native execution.++This proves the selected delayed-read ordering, not native persistence, failures+or races within the settings writer, the complete rendered chat UI, real model+selection or enforced agent isolation. No model trial is implied.diff --git a/evals/coding-agent/calibrate-chat-overlap.test.js b/evals/coding-agent/calibrate-chat-overlap.test.jsnew file mode 100644index 000000000..b33e5e226--- /dev/null+++ b/evals/coding-agent/calibrate-chat-overlap.test.js@@ -0,0 +1,35 @@+// screenpipe — AI that knows everything you've seen, said, or heard+// https://screenpipe.com+import {afterAll,expect,test} from 'bun:test';+import {execFileSync,spawnSync} from 'node:child_process';+import {mkdtempSync,mkdirSync,readFileSync,writeFileSync,symlinkSync,rmSync} from 'node:fs';+import {resolve,join,dirname} from 'node:path';+import {tmpdir} from 'node:os';+const repo=resolve(import.meta.dir,'../..'),app='apps/screenpipe-app-tauri';+const item=JSON.parse(readFileSync(join(import.meta.dir,'cases.json'),'utf8')).cases.find(c=>c.id==='app-chat-overlapping-load-isolation');+const root=mkdtempSync(join(tmpdir(),'chat-overlap-')),hook=app+'/components/hooks/use-chat-conversations.ts';+const source=(ref=item.oracle_ref)=>execFileSync('git',['show',`${ref}:${hook}`],{cwd:repo,encoding:'utf8'});+afterAll(()=>rmSync(root,{recursive:true,force:true}));+function prepare(name,ref=item.oracle_ref){+ const cwd=join(root,name);mkdirSync(cwd);+ const paths=['components','lib','vitest.config.ts','vitest.setup.ts','tsconfig.json','scripts/bun-test-files.ts'].map(p=>app+'/'+p);+ execFileSync('tar',['-xf','-','-C',cwd],{input:execFileSync('git',['archive',ref,...paths],{cwd:repo,maxBuffer:64*1024*1024})});+ for(const f of item.grader.fixtures){const dest=join(cwd,f.destination_path);mkdirSync(dirname(dest),{recursive:true});writeFileSync(dest,readFileSync(join(import.meta.dir,f.local_path)));}+ symlinkSync(join(repo,app,'node_modules'),join(cwd,app,'node_modules'),'dir');return cwd;+}+function run(cwd){return spawnSync('node',['node_modules/vitest/vitest.mjs','run','--config','vitest.config.ts','lib/__tests__/save-conversation-race.test.tsx','--pool=forks','--poolOptions.forks.singleFork=true'],{cwd:join(cwd,app),encoding:'utf8',timeout:20000,env:{PATH:process.env.PATH,HOME:cwd,CI:'true',NODE_OPTIONS:'--localstorage-file=.eval-localstorage',NO_COLOR:'1'}});}+function fails(r){expect(r.error).toBeUndefined();expect(r.signal).toBeNull();expect(r.status).toBe(1);expect(r.stderr).toContain('AssertionError');expect(r.stderr).not.toMatch(/Cannot find module|Failed to (load|resolve import)|Unhandled/);}+function replace(s,a,b){expect(s.split(a)).toHaveLength(2);return s.replace(a,b);}+function mutant(name,s){const cwd=prepare(name);writeFileSync(join(cwd,hook),s);return run(cwd);}+function unguardedSettings(s){const start=s.indexOf(' // A temporary side chat must not become the launch-time restore target.',s.indexOf('const loadConversation = async'));const end=s.indexOf(' // ---- branchConversation ----',start);expect(start).toBeGreaterThan(0);expect(end).toBeGreaterThan(start);const body=s.slice(start,end);expect(body.split('if (!isLatestRequest()) return;')).toHaveLength(5);return s.slice(0,start)+body.replaceAll('if (!isLatestRequest()) return;','')+s.slice(end);}+test('historical parent fails3outcomes and preserves12',()=>{const r=run(prepare('parent',item.base_ref));fails(r);expect(r.stdout).toContain('3 failed | 12 passed');});+test('reference preserves all15outcomes',()=>{const r=run(prepare('reference'));expect(r.status).toBe(0);expect(r.stdout).toContain('15 passed');});+test('original false pass cannot overwrite settings and preset after late reads',()=>{const r=mutant('old-bypass',unguardedSettings(source()).replace('if (presetId && isLatestRequest())','if (presetId)'));fails(r);expect(r.stdout).toContain('2 failed | 13 passed');});+test('settings guard removal is independently rejected',()=>{const r=mutant('settings',unguardedSettings(source()));fails(r);expect(r.stdout).toContain('1 failed | 14 passed');});+test('a stale preset emitted before discarding a late settings result is rejected',()=>{+ const r=mutant('preset',replace(source(),'const freshSettings = await store.get<any>("settings");\n if (!isLatestRequest()) return;','const freshSettings = await store.get<any>("settings");\n if (!isLatestRequest()) { await emit("chat-preset-restore", { presetId: (conv as ChatConversation).presetId }); return; }'));fails(r);expect(r.stdout).toContain('1 failed | 14 passed');+});+test('equivalent request guard naming passes',()=>expect(mutant('renamed',source().replaceAll('isLatestRequest','stillCurrentNavigation').replaceAll('loadConversationRequestRef','navigationGenerationRef')).status).toBe(0));+test('skipping all navigation is rejected',()=>fails(mutant('no-op',replace(source(),'const loadConversation = async (conv: ChatConversation | ConversationMeta) => {','const loadConversation = async (conv: ChatConversation | ConversationMeta) => { return;'))));+test('unused good hook cannot rescue the old hook',()=>{const cwd=prepare('unused');writeFileSync(join(cwd,hook+'.unused.ts'),source());writeFileSync(join(cwd,hook),source(item.base_ref));fails(run(cwd));});+test('missing hook is a collection error',()=>{const cwd=prepare('missing');rmSync(join(cwd,hook));const r=run(cwd);expect(r.status).toBe(1);expect(r.stderr).toMatch(/Failed to (load|resolve import)|Cannot find module/);expect(r.stdout).toContain('no tests');});diff --git a/evals/coding-agent/cases.json b/evals/coding-agent/cases.jsonindex 6b9408cab..cdcedf395 100644--- a/evals/coding-agent/cases.json+++ b/evals/coding-agent/cases.json@@ -1,7 +1,7 @@{"schema_version": 1,"suite": "screenpipe-app-coding-agent-regressions",- "dataset_version": "2026-09-20.6",+ "dataset_version": "2026-09-20.7","suite_type": "regression","owner": "screenpipe engineering","policy": {@@ -784,9 +784,10 @@"grader": {"timeout_seconds": 420,"fixtures": [- { "source_path": "apps/screenpipe-app-tauri/lib/__tests__/save-conversation-race.test.tsx" }+ { "local_path": "graders/chat-overlapping-load.fixture.tsx",+ "destination_path": "apps/screenpipe-app-tauri/lib/__tests__/save-conversation-race.test.tsx" }],- "command": "cd apps/screenpipe-app-tauri && NODE_OPTIONS=--localstorage-file=.eval-localstorage bun x vitest run --config vitest.config.ts lib/__tests__/save-conversation-race.test.tsx"+ "command": "cd apps/screenpipe-app-tauri && NODE_OPTIONS=--localstorage-file=.eval-localstorage node node_modules/vitest/vitest.mjs run --config vitest.config.ts lib/__tests__/save-conversation-race.test.tsx --pool=forks --poolOptions.forks.singleFork=true"}},{diff --git a/evals/coding-agent/graders/chat-overlapping-load.fixture.tsx b/evals/coding-agent/graders/chat-overlapping-load.fixture.tsxnew file mode 100644index 000000000..2ea1fda54--- /dev/null+++ b/evals/coding-agent/graders/chat-overlapping-load.fixture.tsx@@ -0,0 +1,679 @@+// screenpipe — AI that knows everything you've seen, said, or heard+// https://screenpipe.com++/**+ * End-to-end-ish reproducer for PR #3600's race condition, driven through+ * the actual `useChatConversations` hook. This test invokes+ * `saveConversation` with the exact (messages, piSessionIdRef.current,+ * conversationId) tuple that exists during a mid-stream chat switch, and+ * asserts which id the disk write targets.+ *+ * The race (from use-chat-conversations.ts:702-850):+ *+ * loadConversation(B) {+ * piSessionIdRef.current = B // line 745, eager+ * setMessages(B's messages) // line 847, queued+ * setConversationId(B) // line 848, queued+ * setIsLoading(false) earlier at // line 733+ * piSessionSyncedRef.current = false // line 850, eager+ * }+ *+ * The isLoading: true→false transition fires the auto-save effect at+ * line 537, which calls saveConversation(messages) where `messages` is+ * the captured-by-closure OLD chat A's array. Inside saveConversation+ * (line 353):+ *+ * const convId = piSessionIdRef.current // = B (eager update)+ * || conversationId // = A (state still committing)+ * || crypto.randomUUID();+ *+ * → convId = B+ * → writes A's messages under B's file+ * → user opens chat B → sees A's content → reports "lost context"+ *+ * PR #3600's fix:+ * const convId = conversationId || piSessionIdRef.current || ...+ * → convId = A → save is correct.+ *+ * This test fails on the current (buggy) main branch and passes once the+ * fix is applied.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { renderHook, act } from "@testing-library/react";+import { useRef } from "react";+import {+ deleteCachedBrowserState,+ setCachedBrowserState,+} from "../browser-state-cache";++// ── Mocks ──────────────────────────────────────────────────────────────+// Capture every disk write so the test can assert (id, messages) pairs.+const saveCalls: Array<{+ id: string;+ messages: any[];+ browserState?: any;+ lastUserMessageAt?: number;+ lastViewedAt?: number;+ presetId?: string;+}> = [];+let pendingSaveGate: Promise<void> | null = null;+let notifySaveStarted: (() => void) | null = null;++vi.mock("@/lib/chat-storage", () => ({+ saveConversationFile: vi.fn(async (conv: any) => {+ saveCalls.push({+ id: conv.id,+ messages: conv.messages,+ browserState: conv.browserState,+ lastUserMessageAt: conv.lastUserMessageAt,+ lastViewedAt: conv.lastViewedAt,+ presetId: conv.presetId,+ });+ notifySaveStarted?.();+ notifySaveStarted = null;+ await pendingSaveGate;+ }),+ loadConversationFile: vi.fn(async () => null),+ deleteConversationFile: vi.fn(async () => undefined),+ invalidateConversationListCache: vi.fn(() => undefined),+ listConversations: vi.fn(async () => []),+ markConversationFileChanged: vi.fn(() => undefined),+ searchConversations: vi.fn(async () => []),+ migrateFromStoreBin: vi.fn(async () => undefined),+ conversationDedupIdentity: vi.fn(() => null),+ updateConversationFlags: vi.fn(async () => undefined),+ CHAT_HISTORY_INITIAL_LIMIT: 50,+}));++vi.mock("@tauri-apps/api/event", () => ({+ emit: vi.fn(async () => undefined),+ listen: vi.fn(async () => () => undefined),+}));++vi.mock("@/lib/utils/tauri", () => ({+ commands: {},+}));++vi.mock("@/lib/hooks/use-settings", () => ({+ getStore: vi.fn(async () => ({+ get: vi.fn(async () => ({})),+ set: vi.fn(async () => undefined),+ save: vi.fn(async () => undefined),+ })),+}));++vi.mock("@/lib/utils/generate-title-with-preset", () => ({ titleCreatedByAI: vi.fn(async () => null) }));++// ── Import under test (after mocks) ───────────────────────────────────+import { useChatConversations } from "../../components/hooks/use-chat-conversations";+import { loadConversationFile, updateConversationFlags } from "@/lib/chat-storage";+import { useChatStore } from "../stores/chat-store";++// Test harness: thin component that wires up the refs/state the hook+// needs, then exposes `saveConversation` for the test to call. Mirrors+// what standalone-chat.tsx does, minus the UI.+function useHarness(args: {+ initialMessages: any[];+ initialConversationId: string | null;+ initialPiSessionId: string;+ selectedPreset?: any;+ selectedPresetRef?: any;+}) {+ const messagesRef = useRef(args.initialMessages);+ const conversationIdRef = useRef<string | null>(args.initialConversationId);+ const piSessionIdRef = useRef(args.initialPiSessionId);+ const piSessionSyncedRef = useRef(false);+ const piStreamingTextRef = useRef("");+ const piMessageIdRef = useRef<string | null>(null);+ const piContentBlocksRef = useRef<any[]>([]);+ const inputRef = useRef<HTMLTextAreaElement | null>(null);++ const hook = useChatConversations({+ messages: messagesRef.current as any,+ setMessages: ((updater: any) => {+ messagesRef.current = typeof updater === "function" ? updater(messagesRef.current) : updater;+ }) as any,+ conversationId: conversationIdRef.current,+ setConversationId: ((updater: any) => {+ conversationIdRef.current = typeof updater === "function" ? updater(conversationIdRef.current) : updater;+ }) as any,+ setInput: vi.fn() as any,+ inputRef,+ isLoading: false,+ isStreaming: false,+ piStreamingTextRef,+ piMessageIdRef,+ piContentBlocksRef,+ piSessionSyncedRef,+ piSessionIdRef,+ setIsLoading: vi.fn() as any,+ setIsStreaming: vi.fn() as any,+ setPastedImages: vi.fn() as any,+ settings: { chatHistory: { historyEnabled: true } },+ inlineHistoryEnabled: false,+ selectedPreset: args.selectedPreset ?? null,+ selectedPresetRef: args.selectedPresetRef,+ });++ return { hook, messagesRef, conversationIdRef, piSessionIdRef };+}++beforeEach(() => {+ saveCalls.length = 0;+ pendingSaveGate = null;+ notifySaveStarted = null;+ deleteCachedBrowserState("chat-A");+ deleteCachedBrowserState("fresh-sid");+ useChatStore.setState({+ sessions: {},+ ephemeralSideConversationIds: {},+ currentId: null,+ panelSessionId: null,+ });+ vi.mocked(updateConversationFlags).mockResolvedValue(undefined);+});++afterEach(() => {+ vi.clearAllMocks();+});++describe("saveConversation race (PR #3600 / issue #3636 candidate)", () => {+ it("keeps temporary side conversations off disk, including a late post-close save", async () => {+ const messages = [+ { id: "u1", role: "user" as const, content: "temporary question", timestamp: 1 },+ { id: "a1", role: "assistant" as const, content: "temporary answer", timestamp: 2 },+ ];+ useChatStore.getState().actions.upsert({+ id: "temporary-side",+ title: "temporary side chat",+ preview: "temporary answer",+ status: "idle",+ messageCount: messages.length,+ createdAt: 1,+ updatedAt: 2,+ pinned: false,+ unread: false,+ draft: false,+ messages,+ ephemeral: true,+ sideConversation: true,+ sideConversationParentId: "source",+ });++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: messages,+ initialConversationId: "temporary-side",+ initialPiSessionId: "temporary-side",+ }),+ );++ await act(async () => {+ await result.current.hook.saveConversation(messages);+ });+ expect(saveCalls).toHaveLength(0);+ expect(loadConversationFile).not.toHaveBeenCalled();+ expect(useChatStore.getState().sessions["temporary-side"].messages).toEqual(messages);++ // Closing drops the heavy transcript, but the id tombstone survives long+ // enough to reject a debounced callback from the previous render.+ useChatStore.getState().actions.drop("temporary-side");+ await act(async () => {+ await result.current.hook.saveConversation(messages, {+ idOverride: "temporary-side",+ });+ });+ expect(saveCalls).toHaveLength(0);+ expect(loadConversationFile).not.toHaveBeenCalled();+ });++ it("writes A's messages under A's id during chat switch (PR #3600 fix)", async () => {+ // Set up the race condition state that exists for a single render+ // tick after `loadConversation(B)` has run:+ // - piSessionIdRef.current was eagerly updated to B (line 745)+ // - conversationId is still A (setConversationId(B) queued)+ // - messages is still A's messages (setMessages(B's msgs) queued)+ //+ // The (id, messages) pair sent to disk MUST stay consistent — A's+ // messages must go under A's id, not the ref's B. Pre-fix the save+ // wrote A's messages under B's file, silently corrupting B.+ const aMessages = [+ { id: "u1", role: "user" as const, content: "what's my codename?", timestamp: 1 },+ { id: "a1", role: "assistant" as const, content: "you said it's BANANA", timestamp: 2 },+ ];++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: aMessages,+ initialConversationId: "chat-A", // React state — old+ initialPiSessionId: "chat-B", // ref — eagerly switched+ }),+ );++ await act(async () => {+ await result.current.hook.saveConversation(aMessages);+ });++ expect(saveCalls).toHaveLength(1);+ const written = saveCalls[0];++ // The disk-write payload is A's messages.+ expect(written.messages.map((m) => m.id)).toEqual(["u1", "a1"]);++ // FIXED: convId follows conversationId (in lockstep with messages),+ // not the eager piSessionIdRef.+ expect(written.id).toBe("chat-A");+ expect(written.id).not.toBe("chat-B");+ });++ it("FIX FALLBACK: when conversationId is null (startNewConversation transient), ref is used", async () => {+ // During startNewConversation, setConversationId(null) → …setConversationId(newSid).+ // In the brief null window, the fallback must still pick the ref+ // so the save doesn't mint a fresh uuid and duplicate the conv.+ const messages = [{ id: "u1", role: "user" as const, content: "hello", timestamp: 1 }];++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: messages,+ initialConversationId: null,+ initialPiSessionId: "fresh-sid",+ }),+ );++ await act(async () => {+ await result.current.hook.saveConversation(messages);+ });++ expect(saveCalls).toHaveLength(1);+ expect(saveCalls[0].id).toBe("fresh-sid");+ });++ it("NO PHANTOM ID: falls back to store.currentId when conversationId and ref are both empty (#4719)", async () => {+ // Deepest null-id window: conversationId is null AND the ref hasn't been+ // reseeded yet. The save must adopt the last stable id the panel+ // published to the store — NOT mint a fresh uuid twin.+ useChatStore.setState({ currentId: "store-current-id" });+ const messages = [{ id: "u1", role: "user" as const, content: "hi", timestamp: 1 }];++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: messages,+ initialConversationId: null,+ initialPiSessionId: "", // ref transiently empty+ }),+ );++ await act(async () => {+ await result.current.hook.saveConversation(messages);+ });++ expect(saveCalls).toHaveLength(1);+ expect(saveCalls[0].id).toBe("store-current-id");+ });++ it("NO PHANTOM ID: skips the save entirely when no stable id exists (#4719)", async () => {+ // conversationId null, ref empty, store.currentId null → there is no+ // stable id to write under. Pre-fix this minted crypto.randomUUID() and+ // wrote a phantom twin file. Now it must write NOTHING.+ useChatStore.setState({ currentId: null });+ const messages = [{ id: "u1", role: "user" as const, content: "hi", timestamp: 1 }];++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: messages,+ initialConversationId: null,+ initialPiSessionId: "",+ }),+ );++ await act(async () => {+ await result.current.hook.saveConversation(messages);+ });++ expect(saveCalls).toHaveLength(0);+ });++ it("preserves browserState from the shadow cache when the disk file does not exist yet", async () => {+ const messages = [{ id: "u1", role: "user" as const, content: "hello", timestamp: 1 }];+ setCachedBrowserState("fresh-sid", {+ url: "https://example.com/browser-state-shadow",+ updatedAt: 1_234,+ width: 512,+ collapsed: true,+ });++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: messages,+ initialConversationId: null,+ initialPiSessionId: "fresh-sid",+ }),+ );++ await act(async () => {+ await result.current.hook.saveConversation(messages);+ });++ expect(saveCalls).toHaveLength(1);+ expect(saveCalls[0].browserState).toEqual({+ url: "https://example.com/browser-state-shadow",+ updatedAt: 1_234,+ width: 512,+ collapsed: true,+ });+ });++ it("recomputes lastUserMessageAt from the outgoing transcript instead of preserving a stale saved value", async () => {+ vi.mocked(loadConversationFile).mockResolvedValueOnce({+ id: "chat-A",+ title: "chat-A",+ createdAt: 1,+ updatedAt: 2,+ lastUserMessageAt: 1_000,+ messages: [],+ } as any);++ const messages = [+ { id: "u1", role: "user" as const, content: "old", timestamp: 1_000 },+ { id: "a1", role: "assistant" as const, content: "reply", timestamp: 1_200 },+ { id: "u2", role: "user" as const, content: "new", timestamp: 9_000 },+ ];++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: messages,+ initialConversationId: "chat-A",+ initialPiSessionId: "chat-A",+ }),+ );++ await act(async () => {+ await result.current.hook.saveConversation(messages);+ });++ expect(saveCalls).toHaveLength(1);+ expect(saveCalls[0].lastUserMessageAt).toBe(9_000);+ });++ it("persists the store's lastViewedAt watermark on save", async () => {+ useChatStore.getState().actions.upsert({+ id: "chat-A",+ title: "chat-A",+ preview: "",+ status: "idle",+ messageCount: 1,+ createdAt: 1,+ updatedAt: 2,+ pinned: false,+ unread: false,+ lastContentAt: 9_000,+ lastViewedAt: 8_500,+ });++ const messages = [+ { id: "u1", role: "user" as const, content: "hello", timestamp: 1_000 },+ { id: "a1", role: "assistant" as const, content: "reply", timestamp: 2_000 },+ ];++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: messages,+ initialConversationId: "chat-A",+ initialPiSessionId: "chat-A",+ }),+ );++ await act(async () => {+ await result.current.hook.saveConversation(messages);+ });++ expect(saveCalls).toHaveLength(1);+ expect(saveCalls[0].lastViewedAt).toBe(8_500);+ });++ it("resolves selectedPreset via ref when available to prevent stale closure on summary card click (#4820)", async () => {+ const selectedPresetRef = { current: { id: "argus", model: "argus-model", provider: "ollama" } as any };+ const messages = [+ { id: "u1", role: "user" as const, content: "hello", timestamp: 1_000 },+ ];++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: messages,+ initialConversationId: "chat-card",+ initialPiSessionId: "chat-card",+ selectedPreset: { id: "gpt-4o", model: "gpt-4o", provider: "openai" } as any, // Stale closure value+ selectedPresetRef, // Latest ref value+ }),+ );++ await act(async () => {+ await result.current.hook.saveConversation(messages);+ });++ expect(saveCalls).toHaveLength(1);+ expect(saveCalls[0].presetId).toBe("argus");+ });++ it("idOverride forces the save id (send path uses piSessionIdRef, not lagging conversationId) (#4719)", async () => {+ // The summary/todo card twin: at send time conversationId (state) lags the+ // dispatched session id. The send path passes idOverride so the disk file+ // (and its chat-conversation-saved emit) match the live store session,+ // instead of writing a second id the sidebar would upsert as a twin.+ const messages = [{ id: "u1", role: "user" as const, content: "hi", timestamp: 1 }];++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: messages,+ initialConversationId: "stale-conversation-id", // lagging state+ initialPiSessionId: "dispatched-session-id", // the real target+ }),+ );++ await act(async () => {+ await result.current.hook.saveConversation(messages, {+ idOverride: "dispatched-session-id",+ });+ });++ expect(saveCalls).toHaveLength(1);+ expect(saveCalls[0].id).toBe("dispatched-session-id");+ expect(saveCalls[0].id).not.toBe("stale-conversation-id");+ });++ it("a late first-turn save cannot restore an obsolete foreground conversation", async () => {+ // The automation-card send owns chat A and starts by making its first user+ // turn durable. While that disk write is pending, the user can switch to a+ // fresh chat B. Persistence must finish writing A without navigating the+ // panel back to A — saveConversation is storage, not foreground routing.+ let releaseSave!: () => void;+ pendingSaveGate = new Promise<void>((resolve) => {+ releaseSave = resolve;+ });+ const saveStarted = new Promise<void>((resolve) => {+ notifySaveStarted = resolve;+ });+ const firstTurn = [+ { id: "u1", role: "user" as const, content: "summarize my day", timestamp: 1 },+ ];++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: [],+ // Matches a first-send render whose setConversationId(A) has not+ // committed yet; idOverride still binds the durable write to A.+ initialConversationId: null,+ initialPiSessionId: "chat-A",+ }),+ );++ const pendingSave = result.current.hook.saveConversation(firstTurn, {+ idOverride: "chat-A",+ });+ await saveStarted;++ // A new-chat action wins foreground ownership while A is still saving.+ result.current.conversationIdRef.current = "chat-B";+ releaseSave();+ await act(async () => {+ await pendingSave;+ });++ expect(saveCalls).toHaveLength(1);+ expect(saveCalls[0].id).toBe("chat-A");+ expect(result.current.conversationIdRef.current).toBe("chat-B");+ });++ it("writes exactly ONE file for a single first turn — no twin (#4719)", async () => {+ // A single first user turn, with the panel id in lockstep across+ // conversationId / piSessionIdRef / store.currentId (the single-source-of-+ // truth invariant this PR enforces), must persist exactly one conversation+ // file under one id — never a second twin row.+ useChatStore.setState({ currentId: "turn-1", panelSessionId: "turn-1" });+ const firstTurn = [+ { id: "u1", role: "user" as const, content: "hello", timestamp: 1 },+ { id: "a1", role: "assistant" as const, content: "hi", timestamp: 2 },+ ];++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: firstTurn,+ initialConversationId: "turn-1",+ initialPiSessionId: "turn-1",+ }),+ );++ await act(async () => {+ await result.current.hook.saveConversation(firstTurn);+ });++ expect(saveCalls).toHaveLength(1);+ expect(saveCalls[0].id).toBe("turn-1");+ expect(new Set(saveCalls.map((c) => c.id)).size).toBe(1);+ });++ it("keeps the rendered transcript isolated and lets the newest overlapping load win", async () => {+ const messagesA = [+ { id: "a-user", role: "user" as const, content: "chat A", timestamp: 1 },+ { id: "a-agent", role: "assistant" as const, content: "answer A", timestamp: 2 },+ ];+ const messagesB = [+ { id: "b-user", role: "user" as const, content: "chat B", timestamp: 3 },+ ];+ const messagesC = [+ { id: "c-user", role: "user" as const, content: "chat C", timestamp: 4 },+ ];+ const seedSession = (id: string, title: string, sessionMessages: any[]) => {+ useChatStore.getState().actions.upsert({+ id,+ title,+ titleSource: "user",+ preview: "",+ status: "idle",+ messageCount: sessionMessages.length,+ messages: sessionMessages,+ createdAt: 1,+ updatedAt: 4,+ pinned: false,+ unread: false,+ });+ useChatStore.getState().actions.markHydrated(id);+ };+ seedSession("chat-A", "A", messagesA);+ seedSession("chat-B", "B", messagesB);+ seedSession("chat-C", "C", messagesC);+ useChatStore.getState().actions.setCurrent("chat-A");++ let releaseChatB!: () => void;+ const chatBGate = new Promise<void>((resolve) => {+ releaseChatB = resolve;+ });+ vi.mocked(updateConversationFlags).mockImplementation(async (id) => {+ if (id === "chat-B") await chatBGate;+ });++ const { result } = renderHook(() =>+ useHarness({+ initialMessages: messagesA,+ initialConversationId: "chat-A",+ initialPiSessionId: "chat-A",+ }),+ );++ const loadB = result.current.hook.loadConversation({+ id: "chat-B",+ title: "B",+ titleSource: "user",+ createdAt: 1,+ updatedAt: 3,+ messages: messagesB,+ } as any);+ await vi.waitFor(() =>+ expect(updateConversationFlags).toHaveBeenCalledWith(+ "chat-B",+ expect.objectContaining({ lastViewedAt: expect.any(Number) }),+ ),+ );++ // B has moved the eager Pi ref and is paused before its React commit. A+ // second request must still bind the rendered A messages to chat A, and C+ // must remain foreground even when B finishes last.+ await act(async () => {+ await result.current.hook.loadConversation({+ id: "chat-C",+ title: "C",+ titleSource: "user",+ createdAt: 1,+ updatedAt: 4,+ messages: messagesC,+ } as any);+ });+ releaseChatB();+ await act(async () => {+ await loadB;+ });++ expect(useChatStore.getState().sessions["chat-B"].messages).toEqual(messagesB);+ expect(result.current.messagesRef.current).toEqual(messagesC);+ expect(result.current.conversationIdRef.current).toBe("chat-C");+ expect(result.current.piSessionIdRef.current).toBe("chat-C");+ });+});++async function finishOlderSettingsReadLast() {+ const {getStore} = await import('@/lib/hooks/use-settings');+ const {emit} = await import('@tauri-apps/api/event');+ let release!: () => void;+ const gate = new Promise<void>(resolve => { release = resolve; });+ let reads = 0;+ let stored: any = {chatHistory:{historyEnabled:true,activeConversationId:'chat-A'}};+ const settingsStore = {+ get: vi.fn(async () => { reads++; if (reads===1) await gate; return structuredClone(stored); }),+ set: vi.fn(async (_key: string, value: any) => { stored=structuredClone(value); }),+ save: vi.fn(async () => undefined),+ };+ vi.mocked(getStore).mockResolvedValue(settingsStore);+ for (const id of ['chat-A','chat-B','chat-C']) {+ useChatStore.getState().actions.upsert({id,title:id,titleSource:'user',preview:'',status:'idle',messageCount:1,messages:[{id:id+'-message',role:'user',content:id,timestamp:1}],createdAt:1,updatedAt:1,pinned:false,unread:false});+ useChatStore.getState().actions.markHydrated(id);+ }+ useChatStore.getState().actions.setCurrent('chat-A');+ const {result}=renderHook(()=>useHarness({initialMessages:useChatStore.getState().sessions['chat-A'].messages,initialConversationId:'chat-A',initialPiSessionId:'chat-A'}));+ const load=(id:string)=>result.current.hook.loadConversation({id,title:id,createdAt:1,updatedAt:1,presetId:'preset-'+id,messages:useChatStore.getState().sessions[id].messages} as any);+ const older=load('chat-B');+ await vi.waitFor(()=>expect(settingsStore.get).toHaveBeenCalledTimes(1));+ await act(async()=>{await load('chat-C');});+ release(); await act(async()=>{await older;});+ return {stored,settingsStore,result,events:vi.mocked(emit).mock.calls.filter(call=>call[0]==='chat-preset-restore')};+}+it('older settings reads cannot change the durable reopen target after newer navigation',async()=>{+ const {stored,result}=await finishOlderSettingsReadLast();+ expect(result.current.conversationIdRef.current).toBe('chat-C');+ expect(stored.chatHistory.activeConversationId).toBe('chat-C');+});+it('older settings completion cannot restore a stale model preset',async()=>{+ const {events,result}=await finishOlderSettingsReadLast();+ expect(result.current.conversationIdRef.current).toBe('chat-C');+ expect(events.map(call=>call[1])).toEqual([{presetId:'preset-chat-C'}]);+});