Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(chat): ⌘M chat view for gemini (desktop + phone over relay)

review310c39a0e658
diff --git a/CLAUDE.md b/CLAUDE.md
index ccea29e57..fa943142d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1927,6 +1927,20 @@ else, and its context links must keep classifying across restarts).
in its frame) + Google's migration guide. It types and relaunches NOTHING, which is why a phrase
match is enough here where `resume-fallback.ts` needs three refusals. `AgentConfig.notice` carries
the one-line caveat to the menus/Dock tooltips; it is never read to decide behaviour.
+- **Gemini ⌘M chat view** (2026-09, `core/gemini-chat.ts`) — gemini is in `CHAT_CAPABLE` with its own
+ reader, routed in `readChatTranscript` via `capabilityAgentId` BEFORE anything claude-shaped and
+ located only by the header session id (`locateGemini`, which now reads just the header and honours
+ `GEMINI_CLI_HOME`). Its session file is an UPSERT log, not a message list: one id is rewritten in
+ full as tool results/tokens land, `$rewindTo` truncates, and `$set.messages` replaces the MODEL's
+ context at start, compression and rollback. The thread is the message records upserted by id with
+ rewinds honoured and **`$set.messages` ignored** — honouring it erases the thread at every
+ compression and shows the `<state_snapshot>` as the human's words. Not paged (a record depends on
+ earlier ones): one read under the 5 MB cap, `olderCursor: null`, like grok. Shows typed prompts
+ (`displayContent` over `@file` expansion; `<session_context>`/`<hook_context>` dropped per part),
+ replies, tool calls with results, `[info]`/`[warning]`/`[error]` notes and (paged) the model;
+ thinking is dropped. NOT supported: remote (SSH) nodes (`CHAT_LOCAL_ONLY` → "not supported yet"),
+ plan/question answer cards, the composer's model/effort labels. The phone gets it over the relay
+ unchanged; fixtures and exact rules: `src/shared/chat-fixtures/gemini/`, `docs/gemini-agent.md` §3.
- **Claude session context capacity (#818)** — the managed hook reports only
`CLAUDE_CODE_MAX_CONTEXT_TOKENS` from the effective Claude process environment (including
`--settings` env), never the GUI/server process environment. HookServer validates decimal safe
diff --git a/docs/gemini-agent.md b/docs/gemini-agent.md
index 753fa2208..88214331f 100644
--- a/docs/gemini-agent.md
+++ b/docs/gemini-agent.md
@@ -52,7 +52,7 @@ is the price of adding the next agent to the same list.
| `CONTEXT_LINK_CAPABLE` | **joined** (pre-branch) | A parser for gemini's event-sourced chat format plus a locator by sessionId (`handoff/locate.ts`'s `locateGemini`), and a discovery route — the marker block merged into `~/.gemini/GEMINI.md`. |
| `TRANSFER_SOURCE_CAPABLE` | **joined** (pre-branch) | The same native-transcript reader cross-agent transfer needs. |
| `CANVAS_CONTROL_CAPABLE` | **joined** (pre-branch) | The marker block in `~/.gemini/GEMINI.md` (gemini gets no skill — that is claude's discovery mechanism, which grok borrows). Membership is what sets `NODETERM_CANVAS_CONTROL` in the session env. |
-| `CHAT_CAPABLE` | not joined | The ⌘M `ChatPanel` renders **claude's** transcript `.jsonl`. Gemini's transcript is a different, event-sourced shape; the panel would need its own renderer. This list doubles as the "we can read and render this agent's transcript ourselves" fact — see the warning below. |
+| `CHAT_CAPABLE` | **joined 2026-09** | Its own reader, `core/gemini-chat.ts` (§3, "The ⌘M chat view's fold"), routed in `readChatTranscript` BEFORE anything claude-shaped (through `capabilityAgentId`, so a custom agent built on gemini reads it too) and located strictly by the session id in the file's header — never claude's `resolveTranscript`, whose cwd fallback would answer with a stranger's claude session. `CLAUDE_TRANSCRIPT_READABLE` stays claude-only, so the find bar and `context.ensure` are untouched. Local-only (`CHAT_LOCAL_ONLY`): a remote node answers "not supported yet". |
| `SUBAGENT_CAPABLE` | not joined | Subagent cards are driven by claude's `Agent`/`Task` tool correlation; gemini's equivalent vocabulary is not mapped. |
| `BRANCH_CAPABLE` | not joined | Branch sends claude's `/branch` and resumes by claude's session id; gemini has no counterpart. |
| `RECURRING_CAPABLE` | not joined | `/loop`, `/schedule`, `/cron` are detected from claude's `Skill` / `CronCreate` / `ScheduleWakeup` tool names. |
@@ -65,8 +65,9 @@ is the price of adding the next agent to the same list.
> rehydrated a codex/gemini node's meter from a **stranger's claude session** (wrong numerator, wrong
> denominator, then flapping against the correct tail), and the find bar indexed that session's
> messages as this node's hits. Fixed by a pure predicate, `readsClaudeTranscript`
-> (`src/renderer/lib/transcriptGates.ts`), which reuses `CHAT_CAPABLE` rather than adding a fourth
-> list that would mean the same thing. The **meter** stays on `hasUsage`; what a non-claude agent
+> (`src/renderer/lib/transcriptGates.ts`), which now reads `CLAUDE_TRANSCRIPT_READABLE` (claude only) —
+> it first reused `CHAT_CAPABLE`, and was split off when grok, then gemini, joined that list with
+> readers of their own. The **meter** stays on `hasUsage`; what a non-claude agent
> gives up is only the mount-time head start — its meter fills on the first hook event after mount
> instead of instantly. Correct-but-later beats instant-but-borrowed.
@@ -200,6 +201,36 @@ The one branch that does re-write history is the legacy `.json` → `.jsonl` **m
`pickGeminiTitle`'s docblock — described the `$set.messages` walk as *the resume mechanism*; it is
not. See §6.
+### The ⌘M chat view's fold (`core/gemini-chat.ts`)
+
+The paragraph above calls the file event-sourced; for the CHAT view the precise shape matters, and
+it was measured against 0.61.0's `ChatRecordingService` (`chunk-JDPZ4CE3.js`, `appendRecord`,
+`pushMessage`, `rewindTo`, `updateMessagesFromHistory`, and its own reader `loadConversationRecord`):
+
+- A **message record** (`{id, timestamp, type, content, displayContent?, thoughts?, tokens?, model?,
+ toolCalls?}`, `type` ∈ `user | gemini | info | warning | error`) is an **upsert**: the same id is
+ written again, in full, whenever the message changes — its tool calls added, their results landed
+ (`toolCalls[].result` = `functionResponse` parts), its tokens arrived. A tool's output is ALSO
+ recorded as its own `type:"user"` record of `functionResponse` parts.
+- `{$rewindTo: id}` deletes that message and everything after it.
+- `{$set: {messages}}` REPLACES the model's history: at session start (the `<session_context>`
+ preamble), at every compression (all turns re-minted under NEW ids, a `<state_snapshot>` summary
+ inserted as a user turn, older turns dropped) and when an aborted turn is rolled back.
+
+The chat thread is therefore the message records alone, upserted by id, with rewinds honoured and
+**`$set.messages` ignored** — it is what gemini will send next, not what was said, and honouring it
+would erase the thread at every compression and present the snapshot as the human's words. A rewind
+to an id the thread never held (a post-compression copy, or one before the 5 MB read cap) is ignored
+rather than wiping everything as gemini's own loader does. User bubbles prefer `displayContent` (the
+typed text, when an `@file` expanded `content`) and drop `<session_context>` / `<hook_context>` text
+PER PART (a BeforeAgent hook's context is appended beside the prompt). Thoughts are dropped; `info` /
+`warning` / `error` render as `[info] …` assistant notes. Because a record depends on earlier ones,
+the view does not page: one whole read under the 5 MB cap, `olderCursor: null`, like grok. The exact
+rules, and golden fixtures a port locks to, are in `src/shared/chat-fixtures/gemini/README.md`.
+
+`locateGemini` reads only each candidate's header line now (the view re-locates on every live
+reload) and honours `GEMINI_CLI_HOME`, the CLI's own home relocation.
+
---
## 4. The context meter: `tokens.input`, and gemini's own `tokenLimit()`
@@ -419,7 +450,7 @@ one stray keystroke.
| Rename write | **N/A** — gemini has no rename command (§6) | idem | idem |
| Permission mode | yes | yes (pure renderer + the flag) | **follow-up owed** — see §8 |
| In-place restart + cold-restore resume | yes | yes | N/A |
-| ⌘M transcript view (`ChatPanel`) | **not implemented for gemini** — `CHAT_CAPABLE` is claude-only; the panel parses claude's JSONL | idem | idem |
+| ⌘M transcript view (`ChatPanel`) | yes, local nodes (`core/gemini-chat.ts`); a remote (SSH) node says "not supported yet"; no plan/question answer cards and no composer model label (gemini's `/model` is an unmeasured dialog) | yes — `registerTranscriptIpc` is core, and the server runs on the host whose sessions it reads | yes over the relay (`chat.page` serves the desktop's parse; a remote node is "Could not read the transcript."); golden fixtures in `src/shared/chat-fixtures/gemini/` for a direct-SSH Swift port |
| Find bar's transcript index | **claude only** (`readsClaudeTranscript`); the terminal-buffer search works normally | idem | N/A |
| Context links | yes (`CONTEXT_LINK_CAPABLE`), marker block in `~/.gemini/GEMINI.md` | wired, **local-only** — `src/server/context-link.ts` calls `initContextLink(pty, {})` with no remote deps | N/A |
| Canvas control | yes, marker block + the sh+curl shim | **not wired** — `agent:control` has no server handler; pre-existing | N/A — no canvas |
@@ -561,4 +592,21 @@ SSH + surfaces
gradient, so the `currentColor` bloom is the LABEL colour, not its own ink — the light theme is
where that will look worst if it looks bad anywhere.
22. Kanban card + card modal: badges, the meter row and the 💬 comments panel on a gemini card.
+
+⌘M chat view
+23. ⌘M on a gemini node after a few turns with tool calls: prompts, answers and ONE chip per call
+ with its output; no thoughts, no `<session_context>` preamble. A turn in progress fills in live.
+24. `/compress` (or let it auto-compress), then ⌘M: the earlier turns are STILL there, followed by
+ "[info] Chat history compressed…", and no `<state_snapshot>` bubble appears as your words.
+25. Esc a turn mid-stream: the cancelled prompt stays, followed by the cancel note.
+26. `/rewind` to an earlier prompt: the rewound turns disappear from ⌘M. Then compress and rewind
+ again (the known limit: a rewind to a post-compression copy is ignored, so those turns stay).
+27. `@file` a file in a prompt: the bubble shows what you typed, not the file's body.
+28. Send from the ⌘M composer while gemini is idle: the text lands in gemini's prompt and submits
+ (bracketed paste into gemini's TUI); refused while RUNNING or NEEDS YOU.
+29. An SSH project's gemini node: ⌘M says "Reading a remote Gemini session's transcript isn't
+ supported yet." with no Retry; the phone says "Could not read the transcript."
+30. Phone Chat screen on a LOCAL gemini node over the relay: the same thread as ⌘M, the model
+ label under it.
+31. Close a gemini node, reopen its transcript from "Recently closed": it reads.
```
diff --git a/src/core/gemini-chat-fixtures.test.ts b/src/core/gemini-chat-fixtures.test.ts
new file mode 100644
index 000000000..b7ebd5038
--- /dev/null
+++ b/src/core/gemini-chat-fixtures.test.ts
@@ -0,0 +1,305 @@
+// Golden fixtures for gemini's chat view (`src/shared/chat-fixtures/gemini/`), the reference the
+// iOS Swift port locks to byte for byte — the same contract as the claude fixtures beside it
+// (`chat-fixtures.test.ts`), for gemini's reader (`core/gemini-chat.ts`).
+//
+// UPDATE_CHAT_FIXTURES=1 npx vitest run src/core/gemini-chat-fixtures.test.ts
+//
+// rewrites `gemini/inputs/` and `gemini/expected/`. Without the variable every file must already
+// equal what this code produces.
+//
+// Inputs are SYNTHETIC, built below from the record shapes measured against gemini-cli 0.61.0's
+// ChatRecordingService and on real session files — never slices of real ones (customer data).
+import { describe, it, expect, afterEach, vi } from 'vitest'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { chatFromGemini } from './gemini-chat'
+import { readChatTranscript } from './transcript-ipc'
+import { CHAT_PAGE_DEFAULT_BYTES } from '../shared/chat-page'
+
+const DIR = path.join(__dirname, '..', 'shared', 'chat-fixtures', 'gemini')
+const UPDATE = process.env.UPDATE_CHAT_FIXTURES === '1'
+if (UPDATE && process.env.CI) throw new Error('UPDATE_CHAT_FIXTURES must not be set in CI')
+
+// ── Synthetic records, in the measured shapes ────────────────────────────────────────────────────
+const SID = '3e7b9c21-4d5a-4f60-8b19-a2c3d4e5f607'
+const T0 = Date.parse('2026-09-28T10:00:00.000Z')
+const ts = (i: number): string => new Date(T0 + i * 1000).toISOString()
+
+type Rec = Record<string, unknown>
+const header = (extra: Rec = {}): Rec => ({
+ sessionId: SID,
+ projectHash: 'c0ffee'.padEnd(64, '0'),
+ startTime: ts(0),
+ lastUpdated: ts(0),
+ kind: 'main',
+ ...extra
+})
+/** A message record; `i` fixes its timestamp so the expected `at` is exact. */
+const m = (i: number, id: string, type: string, content: unknown, extra: Rec = {}): Rec => ({
+ id,
+ timestamp: ts(i),
+ type,
+ content,
+ ...extra
+})
+const tokens = { input: 1200, output: 40, cached: 800, thoughts: 60, tool: 0, total: 1300 }
+const thought = (i: number, subject: string, description: string): Rec => ({ subject, description, timestamp: ts(i) })
+const fr = (id: string, name: string, response: Rec): Rec => ({ functionResponse: { id, name, response } })
+const call = (id: string, name: string, args: unknown, extra: Rec = {}): Rec => ({
+ id,
+ name,
+ args,
+ status: 'success',
+ timestamp: ts(9),
+ displayName: name,
+ description: '',
+ renderOutputAsMarkdown: false,
+ ...extra
+})
+const lastUpdated = (i: number): Rec => ({ $set: { lastUpdated: ts(i) } })
+const jsonl = (...recs: unknown[]): string => recs.map((r) => (typeof r === 'string' ? r : JSON.stringify(r))).join('\n') + '\n'
+const PREAMBLE = '<session_context>\nThis is the Gemini CLI. We are setting up the context for our chat.\n</session_context>'
+
+const INPUTS: Record<string, string> = {
+ // A plain exchange: the session-start history sync (preamble), typed prompts in both content
+ // shapes, a model turn with thoughts + tokens + model, markdown and non-ASCII text.
+ 'plain-turns.jsonl': jsonl(
+ header(),
+ { $set: { messages: [m(0, 's0', 'user', [{ text: PREAMBLE }])], lastUpdated: ts(0) } },
+ m(1, 'u1', 'user', [{ text: 'Özet çıkar: **README** — 3 madde ✓' }]),
+ lastUpdated(1),
+ m(2, 'g1', 'gemini', '## Özet\n\n- bir\n- iki\n- üç\n\n```ts\nconst x = 1\n```', {
+ thoughts: [thought(2, 'Reading', 'The user wants a summary.')],
+ tokens,
+ model: 'gemini-3.5-flash'
+ }),
+ lastUpdated(2),
+ m(3, 'u2', 'user', 'a string content (older record shape)'),
+ m(4, 'u3', 'user', [{ text: 'first part' }, { text: 'second part' }]),
+ m(5, 'g2', 'gemini', [{ text: 'answer as a part list' }], { tokens, model: 'gemini-3.5-flash' })
+ ),
+
+ // The measured tool lifecycle: the call is recorded, its output arrives as a user turn of
+ // functionResponse parts, then the SAME message id is rewritten with the results. Plus every arg
+ // key gemini's tools declare, the caps, an error, display-only results and malformed entries.
+ 'tool-calls.jsonl': jsonl(
+ header(),
+ m(1, 'u1', 'user', [{ text: 'look around' }]),
+ m(2, 'g1', 'gemini', 'Let me look.', {
+ thoughts: [],
+ model: 'gemini-3.5-flash',
+ toolCalls: [call('c1', 'run_shell_command', { command: 'ls -la', description: 'List files', dir_path: '/srv' }, { status: 'executing' })]
+ }),
+ m(3, 'g1_response', 'user', [fr('c1', 'run_shell_command', { output: 'a.txt\nb.txt' })]),
+ m(2, 'g1', 'gemini', 'Let me look.', {
+ thoughts: [],
+ tokens,
+ model: 'gemini-3.5-flash',
+ toolCalls: [
+ call('c1', 'run_shell_command', { command: 'ls -la', description: 'List files', dir_path: '/srv' }, {
+ result: [fr('c1', 'run_shell_command', { output: 'total 2\na.txt\nb.txt\nc.txt\nd.txt' })],
+ resultDisplay: 'total 2\na.txt\nb.txt\nc.txt\nd.txt'
+ })
+ ]
+ }),
+ m(4, 'g2', 'gemini', '', {
+ model: 'gemini-3.5-flash',
+ toolCalls: [
+ call('c2', 'read_file', { file_path: 'src/app.ts', start_line: 1 }, { result: [fr('c2', 'read_file', { output: 'x'.repeat(520) })] }),
+ call('c3', 'list_directory', { dir_path: 'src' }, { result: [fr('c3', 'list_directory', { output: 'app.ts' })] }),
+ call('c4', 'glob', { pattern: '**/*.md' }, { resultDisplay: 'Found 2 matching file(s)' }),
+ call('c5', 'grep_search', { pattern: 'TODO', include_pattern: '*.ts' }, { resultDisplay: { summary: 'not text' } }),
+ call('c6', 'google_web_search', { query: 'gemini cli release notes' }),
+ call('c7', 'web_fetch', { prompt: 'summarize https://example.com' }),
+ call('c8', 'activate_skill', { name: 'pdf' }),
+ call('c9', 'update_topic', { title: 'Reading the repo', summary: 's', strategic_intent: 'i' }),
+ call('c10', 'write_todos', { todos: [] }, { description: 'Set 3 todo(s)' }),
+ call('c11', 'replace', { file_path: 'src/app.ts', old_string: 'a', new_string: 'b' }, {
+ status: 'error',
+ result: [fr('c11', 'replace', { error: 'Failed to edit: 0 occurrences found' })],
+ resultDisplay: { fileDiff: '--- a\n+++ b', fileName: 'app.ts' }
+ }),
+ call('c12', 'run_shell_command', { command: 'echo ' + 'y'.repeat(240) }),
+ { id: 'c13', args: {} },
+ 'not a call',
+ null
+ ]
+ })
+ ),
+
+ // Upserts (first position, last content) and rewinds: to a known id, and to one the thread never
+ // held (ignored and counted — gemini would wipe everything).
+ 'upsert-rewind.jsonl': jsonl(
+ header(),
+ m(1, 'u1', 'user', [{ text: 'keep this' }]),
+ m(2, 'g1', 'gemini', 'draft answer', { model: 'gemini-3.5-flash' }),
+ m(2, 'g1', 'gemini', 'draft answer', { model: 'gemini-3.5-flash', tokens }),
+ m(3, 'u2', 'user', [{ text: 'this gets rewound' }]),
+ m(4, 'g2', 'gemini', 'so does this', { model: 'gemini-2.5-pro' }),
+ { $rewindTo: 'u2' },
+ { $rewindTo: 'never-shown' },
+ m(5, 'u3', 'user', [{ text: 'asked again' }]),
+ m(6, 'g3', 'gemini', 'second try', { model: 'gemini-3.5-flash' })
+ ),
+
+ // `$set.messages` is the MODEL's context and never the thread: the session-start preamble, a
+ // compression (every turn re-minted under a new id, a <state_snapshot> summary inserted), and an
+ // aborted turn's rollback. Plus the metadata-only `$set` shapes.
+ 'history-sync.jsonl': jsonl(
+ header(),
+ { $set: { messages: [m(0, 's0', 'user', [{ text: PREAMBLE }])], lastUpdated: ts(0) } },
+ m(1, 'u1', 'user', [{ text: 'first question' }]),
+ m(2, 'g1', 'gemini', 'first answer', { model: 'gemini-3.5-flash' }),
+ m(3, 'i1', 'info', 'Chat history compressed from 91200 to 12400 tokens.'),
+ {
+ $set: {
+ messages: [
+ m(3, 'x0', 'user', [{ text: PREAMBLE }]),
+ m(3, 'x1', 'user', [{ text: '<state_snapshot>\n <overall_goal>SNAPSHOT</overall_goal>\n</state_snapshot>' }]),
+ m(3, 'x2', 'gemini', [{ text: 'Got it. Thanks for the additional context!' }])
+ ],
+ lastUpdated: ts(3)
+ }
+ },
+ m(4, 'u2', 'user', [{ text: 'a prompt I cancelled' }]),
+ m(5, 'i2', 'info', 'Request cancelled.'),
+ { $set: { messages: [m(3, 'x0', 'user', [{ text: PREAMBLE }])], lastUpdated: ts(5) } },
+ { $set: { summary: 'A session summary' } },
+ { $set: { memoryScratchpad: { notes: 'n' } } },
+ { $set: { directories: ['/srv/app'] } },
+ { $set: { sessionId: SID } },
+ m(6, 'u3', 'user', [{ text: 'after all that' }])
+ ),
+
+ // Harness text dropped per PART, what the user typed preferred over what was sent, thinking and
+ // non-text parts dropped.
+ 'harness-and-display.jsonl': jsonl(
+ header(),
+ m(1, 'u0', 'user', [{ text: PREAMBLE }]),
+ m(2, 'u1', 'user', [{ text: 'my prompt' }, { text: '<hook_context>added by a BeforeAgent hook</hook_context>' }]),
+ m(3, 'u2', 'user', [{ text: 'explain @src/app.ts' }, { text: '\n--- Content from referenced files ---' }, { text: 'FILE BODY' }], {
+ displayContent: [{ text: 'explain @src/app.ts' }]
+ }),
+ m(4, 'u3', 'user', [{ inlineData: { mimeType: 'image/png', data: 'iVBORw0KGgo=' } }, { text: 'what is in this image?' }]),
+ m(5, 'g1', 'gemini', '', { thoughts: [thought(5, 'Looking', 'at the image')], model: 'gemini-3.5-flash' }),
+ m(6, 'g2', 'gemini', [{ text: 'Binary content received. Proceeding with analysis.', thought: true, thoughtSignature: 'sig' }]),
+ m(7, 'i1', 'info', [{ inlineData: { mimeType: 'image/png', data: 'iVBORw0KGgo=' } }]),
+ m(8, 'g3', 'gemini', [{ text: '**Looking** at the image', thought: true }, { text: 'A cat.' }], { model: 'gemini-3.5-flash' })
+ ),
+
+ // The TUI's own notes, and everything that cannot be mapped (counted in `skipped`, never shown).
+ 'notes-and-junk.jsonl': jsonl(
+ { ...header(), messages: [m(1, 'h1', 'user', [{ text: 'carried in the header record' }])] },
+ m(2, 'i1', 'info', 'Switched to fallback model gemini-2.5-flash'),
+ m(3, 'w1', 'warning', [{ text: 'Approaching the context limit.' }]),
+ m(4, 'e1', 'error', '[API Error: 429 Resource exhausted]'),
+ m(5, 'i2', 'info', ''),
+ m(6, 'q1', 'mystery', 'an unknown message type'),
+ '{truncated line',
+ 'null',
+ '7',
+ '["an","array"]',
+ { unrelated: true },
+ { id: 11, type: 'user', content: 'a numeric id is not a message record' },
+ { id: 'u9', type: 'user', content: 'no timestamp at all' },
+ m(0, 'u10', 'user', 'an unparseable timestamp', { timestamp: 'yesterday' })
+ ),
+
+ // A REWRITTEN file (`rewriteConversationFile` after a history sync): model turns carry their calls
+ // as functionCall parts in `content` (next to thought parts), answered by a separate user record.
+ // When `toolCalls` is also present it wins and the parts are not duplicated.
+ 'function-call-content.jsonl': jsonl(
+ header(),
+ m(1, 'u1', 'user', [{ text: 'read it' }]),
+ m(2, 'g1', 'gemini', [
+ { text: '**Plan** read the file', thought: true },
+ { text: 'Reading.' },
+ { functionCall: { id: 'f1', name: 'read_file', args: { file_path: 'x.ts' } } }
+ ]),
+ m(3, 'g1_response', 'user', [fr('f1', 'read_file', { output: 'export const x = 1' })]),
+ m(4, 'g2', 'gemini', [{ functionCall: { id: 'f2', name: 'glob', args: { pattern: '*.ts' } } }], {
+ toolCalls: [call('f2', 'glob', { pattern: '*.ts' }, { result: [fr('f2', 'glob', { output: 'x.ts' })] })]
+ }),
+ m(5, 'g2_response', 'user', [fr('f2', 'glob', { output: 'a DIFFERENT late answer' })])
+ ),
+
+ // The model label: the newest model turn that states a usable one. A turn without one does not
+ // clear it, and a value over 100 UTF-16 units is not a model (50 × U+1F9EA = 100 units is kept).
+ 'model.jsonl': jsonl(
+ header(),
+ m(1, 'g1', 'gemini', 'one', { model: 'gemini-2.5-pro' }),
+ m(2, 'g2', 'gemini', 'two', { model: '🧪'.repeat(50) }),
+ m(3, 'g3', 'gemini', 'three'),
+ m(4, 'g4', 'gemini', 'four', { model: 'x'.repeat(101) }),
+ m(5, 'i1', 'info', 'an info record carrying a model', { model: 'not-a-model-turn' })
+ )
+}
+
+// ── Plumbing ─────────────────────────────────────────────────────────────────────────────────────
+const serialize = (x: unknown): string => JSON.stringify(x, null, 2) + '\n'
+const fixture = (rel: string): string => path.join(DIR, rel)
+
+function golden(rel: string, content: string): void {
+ const p = fixture(rel)
+ if (UPDATE) {
+ fs.mkdirSync(path.dirname(p), { recursive: true })
+ fs.writeFileSync(p, content)
+ return
+ }
+ expect(fs.existsSync(p), `${rel} is missing — run UPDATE_CHAT_FIXTURES=1`).toBe(true)
+ expect(fs.readFileSync(p, 'utf8'), rel).toBe(content)
+}
+
+afterEach(() => {
+ vi.unstubAllEnvs()
+})
+
+describe('gemini chat golden fixtures', () => {
+ it('inputs are what the synthetic builders produce (checked in, never real sessions)', () => {
+ for (const [name, body] of Object.entries(INPUTS)) golden(`inputs/${name}`, body)
+ })
+
+ it('no orphan files: inputs/ and expected/ hold exactly the generated set', () => {
+ const listing = (dir: string): string[] => (fs.existsSync(fixture(dir)) ? fs.readdirSync(fixture(dir)).sort() : [])
+ const expected = Object.keys(INPUTS).map((n) => n.replace(/\.jsonl$/, '.page.json')).sort()
+ if (UPDATE) {
+ for (const f of listing('expected')) if (!expected.includes(f)) fs.rmSync(fixture(`expected/${f}`))
+ for (const f of listing('inputs')) if (!(f in INPUTS)) fs.rmSync(fixture(`inputs/${f}`))
+ return
+ }
+ expect(listing('inputs')).toEqual(Object.keys(INPUTS).sort())
+ expect(listing('expected')).toEqual(expected)
+ expect(fs.readdirSync(DIR).sort()).toEqual(['README.md', 'expected', 'inputs'])
+ })
+
+ for (const name of Object.keys(INPUTS)) {
+ const base = name.replace(/\.jsonl$/, '')
+ it(`${base}: the served page matches expected/${base}.page.json`, async () => {
+ // Served through the REAL producer — the phone's `chat.page` path (`readChatTranscript`, paged,
+ // the default tail request) with the real locator over a scratch GEMINI_CLI_HOME — so the
+ // fixture pins what the wire carries, not a second implementation of it.
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-gemini-fixtures-'))
+ try {
+ const chats = path.join(home, '.gemini', 'tmp', 'fixture', 'chats')
+ fs.mkdirSync(chats, { recursive: true })
+ fs.copyFileSync(fixture(`inputs/${name}`), path.join(chats, `session-2026-09-28T10-00-${SID.slice(0, 8)}.jsonl`))
+ vi.stubEnv('GEMINI_CLI_HOME', home)
+ const page = await readChatTranscript({ sessionId: SID, agentId: 'gemini' }, { maxBytes: CHAT_PAGE_DEFAULT_BYTES }, {})
+ const parsed = chatFromGemini(fs.readFileSync(fixture(`inputs/${name}`), 'utf8'))
+ // The pure parser and the served page agree; the page adds only the paging constants.
+ const { skipped, model, messages } = parsed
+ expect(page).toStrictEqual({
+ messages,
+ found: true,
+ olderCursor: null,
+ unmatchedResults: [],
+ ...(model !== undefined ? { model } : {})
+ })
+ golden(`expected/${base}.page.json`, serialize({ page, skipped }))
+ } finally {
+ fs.rmSync(home, { recursive: true, force: true })
+ }
+ })
+ }
+})
diff --git a/src/core/gemini-chat.test.ts b/src/core/gemini-chat.test.ts
new file mode 100644
index 000000000..f44a84d5e
--- /dev/null
+++ b/src/core/gemini-chat.test.ts
@@ -0,0 +1,557 @@
+// The ⌘M chat view for gemini. Two things are pinned here and neither is cosmetic:
+//
+// - The FOLD. Gemini's session file is not a list of messages — it is an upsert log written by
+// its ChatRecordingService (gemini-cli 0.61.0): one message id is rewritten in full every time
+// its tool calls, results or tokens change; `$rewindTo` truncates; `$set.messages` REPLACES the
+// model's context (session start, compression, an aborted turn's rollback). Reading it line by
+// line would show every tool call three times; honouring `$set.messages` would make the thread
+// vanish at every compression.
+// - The ROUTE. A gemini node must never reach claude's `resolveTranscript`, whose cwd fallback
+// answers with the newest CLAUDE transcript in the directory — someone else's conversation — and
+// a remote gemini node must never be read from this machine's disk.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { chatFromGemini, readGeminiChatTranscript } from './gemini-chat'
+import { locateGemini } from './handoff/locate'
+import { readChatTranscript, registerTranscriptIpc } from './transcript-ipc'
+import { fakePlatform } from './platform-fake'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { IPC } from '../shared/ipc'
+import { canChat, readsClaudeShapedTranscript, setCustomAgentBaseResolver, chatReadsLocalOnly } from '../shared/agents/config'
+import type { ChatMessage, ChatTranscriptResult } from '../shared/types'
+
+const SID = '7c1f0a3e-5b2d-4e8f-9a61-2d4c8b0e6f13'
+const OTHER = '0d9e8f7a-6b5c-4d3e-8f21-1a2b3c4d5e6f'
+const T = '2026-09-28T10:00:00.000Z'
+const AT = Date.parse(T)
+
+type Rec = Record<string, unknown>
+const header = (sid = SID): Rec => ({
+ sessionId: sid,
+ projectHash: 'f'.repeat(64),
+ startTime: T,
+ lastUpdated: T,
+ kind: 'main'
+})
+const msg = (id: string, type: string, content: unknown, extra: Rec = {}): Rec => ({
+ id,
+ timestamp: T,
+ type,
+ content,
+ ...extra
+})
+const jsonl = (...recs: unknown[]): string => recs.map((r) => (typeof r === 'string' ? r : JSON.stringify(r))).join('\n') + '\n'
+const texts = (ms: ChatMessage[]): string[] =>
+ ms.map((m) => `${m.role}:${m.parts.map((p) => (p.kind === 'tool' ? `[${p.name}|${p.arg}|${p.result ?? ''}]` : p.text)).join('+')}`)
+
+describe('chatFromGemini — the fold', () => {
+ it('renders a typed prompt and the model answer, stamped with their own timestamps', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ msg('u1', 'user', [{ text: 'merhaba — ünicode ✓' }]),
+ { $set: { lastUpdated: T } },
+ msg('g1', 'gemini', 'selam', { model: 'gemini-3.5-flash', tokens: { input: 1, output: 1, total: 2 } })
+ )
+ )
+ expect(r.messages).toEqual([
+ { role: 'user', parts: [{ kind: 'text', text: 'merhaba — ünicode ✓' }], at: AT },
+ { role: 'assistant', parts: [{ kind: 'text', text: 'selam' }], at: AT }
+ ])
+ expect(r.skipped).toBe(0)
+ })
+
+ it('accepts a string user content (the legacy record shape)', () => {
+ expect(texts(chatFromGemini(jsonl(header(), msg('u1', 'user', 'plain string'))).messages)).toEqual(['user:plain string'])
+ })
+
+ it('a rewritten id keeps its FIRST position and its LAST content (gemini upserts, it does not append)', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ msg('u1', 'user', [{ text: 'q' }]),
+ msg('g1', 'gemini', '', { toolCalls: [{ id: 'c1', name: 'run_shell_command', args: { command: 'ls' }, status: 'executing' }] }),
+ msg('u2', 'user', [{ functionResponse: { id: 'c1', name: 'run_shell_command', response: { output: 'a.txt' } } }]),
+ msg('g1', 'gemini', '', {
+ toolCalls: [
+ {
+ id: 'c1',
+ name: 'run_shell_command',
+ args: { command: 'ls' },
+ status: 'success',
+ result: [{ functionResponse: { id: 'c1', name: 'run_shell_command', response: { output: 'a.txt\nb.txt' } } }]
+ }
+ ]
+ }),
+ msg('g2', 'gemini', 'two files')
+ )
+ )
+ // ONE tool part — not one per rewrite — carrying the final result.
+ expect(texts(r.messages)).toEqual(['user:q', 'assistant:[run_shell_command|ls|a.txt b.txt]', 'assistant:two files'])
+ })
+
+ it('$set.messages is the MODEL\'s context, never the thread: a compression does not erase what was said', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ // Session start: the environment preamble arrives only as a history sync.
+ { $set: { messages: [msg('s0', 'user', [{ text: '<session_context>\nThis is the Gemini CLI.' }])], lastUpdated: T } },
+ msg('u1', 'user', [{ text: 'first question' }]),
+ msg('g1', 'gemini', 'first answer'),
+ msg('i1', 'info', 'Chat history compressed from 9000 to 1200 tokens.'),
+ // Compression: every turn gets a NEW id, the older turns are gone from the model's view.
+ {
+ $set: {
+ messages: [
+ msg('x1', 'user', [{ text: '<state_snapshot>SUMMARY</state_snapshot>' }]),
+ msg('x2', 'gemini', [{ text: 'Got it. Thanks for the additional context!' }])
+ ]
+ }
+ },
+ msg('u2', 'user', [{ text: 'second question' }])
+ )
+ )
+ expect(texts(r.messages)).toEqual([
+ 'user:first question',
+ 'assistant:first answer',
+ 'assistant:[info] Chat history compressed from 9000 to 1200 tokens.',
+ 'user:second question'
+ ])
+ expect(JSON.stringify(r.messages)).not.toContain('SUMMARY')
+ expect(JSON.stringify(r.messages)).not.toContain('Got it')
+ expect(r.skipped).toBe(0)
+ })
+
+ it('an aborted turn\'s rollback sync does not delete the prompt the terminal still shows', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ msg('u1', 'user', [{ text: 'cancel me' }]),
+ msg('i1', 'info', 'Request cancelled.'),
+ { $set: { messages: [], lastUpdated: T } }
+ )
+ )
+ expect(texts(r.messages)).toEqual(['user:cancel me', 'assistant:[info] Request cancelled.'])
+ })
+
+ it('$rewindTo drops that message and everything after it', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ msg('u1', 'user', [{ text: 'keep' }]),
+ msg('g1', 'gemini', 'kept'),
+ msg('u2', 'user', [{ text: 'rewound' }]),
+ msg('g2', 'gemini', 'rewound answer'),
+ { $rewindTo: 'u2' },
+ msg('u3', 'user', [{ text: 'after' }])
+ )
+ )
+ expect(texts(r.messages)).toEqual(['user:keep', 'assistant:kept', 'user:after'])
+ })
+
+ it('a $rewindTo naming an id the thread never showed is ignored and counted, never a wipe', () => {
+ // gemini itself clears EVERYTHING on an unknown target; after a compression its targets are the
+ // new-id copies the thread deliberately does not show — a wipe would blank the whole thread.
+ const r = chatFromGemini(jsonl(header(), msg('u1', 'user', [{ text: 'still here' }]), { $rewindTo: 'x9' }))
+ expect(texts(r.messages)).toEqual(['user:still here'])
+ expect(r.skipped).toBe(1)
+ })
+
+ it('drops harness text per PART: the preamble and hook context, but never the prompt beside them', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ msg('u0', 'user', [{ text: '<session_context>\nToday is…' }]),
+ msg('u1', 'user', [{ text: 'my prompt' }, { text: '<hook_context>injected by a hook</hook_context>' }]),
+ msg('u2', 'user', ' <hook_context>only harness</hook_context>')
+ )
+ )
+ expect(texts(r.messages)).toEqual(['user:my prompt'])
+ })
+
+ it('shows what the user TYPED (displayContent), not the @-file expansion sent to the model', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ msg('u1', 'user', [{ text: 'explain @src/a.ts' }, { text: '--- Content from referenced files ---' }, { text: 'SECRET FILE BODY' }], {
+ displayContent: [{ text: 'explain @src/a.ts' }]
+ })
+ )
+ )
+ expect(texts(r.messages)).toEqual(['user:explain @src/a.ts'])
+ })
+
+ it('drops thinking — thoughts[], thought parts, and a thought-only turn — like claude\'s reader', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ msg('g1', 'gemini', '', { thoughts: [{ subject: 'Plan', description: 'hidden', timestamp: T }] }),
+ msg('g2', 'gemini', [{ text: '**Plan** hidden', thought: true }, { text: 'visible' }], {
+ thoughts: [{ subject: 'x', description: 'y', timestamp: T }]
+ }),
+ msg('g3', 'gemini', [{ text: 'Binary content received.', thought: true, thoughtSignature: 'sig' }])
+ )
+ )
+ expect(texts(r.messages)).toEqual(['assistant:visible'])
+ expect(JSON.stringify(r.messages)).not.toContain('hidden')
+ })
+
+ it('a pasted image or other non-text part is not a bubble of its own', () => {
+ const r = chatFromGemini(
+ jsonl(header(), msg('u1', 'user', [{ inlineData: { mimeType: 'image/png', data: 'AAAA' } }, { text: 'see image' }]))
+ )
+ expect(texts(r.messages)).toEqual(['user:see image'])
+ })
+
+ it('info / warning / error become assistant notes, never something the human said', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ msg('i1', 'info', 'note'),
+ msg('w1', 'warning', [{ text: 'careful' }]),
+ msg('e1', 'error', 'boom'),
+ msg('i2', 'info', '')
+ )
+ )
+ expect(r.messages.every((m) => m.role === 'assistant')).toBe(true)
+ expect(texts(r.messages)).toEqual(['assistant:[info] note', 'assistant:[warning] careful', 'assistant:[error] boom'])
+ })
+
+ it('counts, and never renders, what it cannot map', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ '{not json',
+ 'null',
+ '42',
+ '[1,2]',
+ { something: 'else' },
+ msg('m1', 'mystery', 'x'),
+ { id: 7, type: 'user', content: 'numeric id is not a message record' },
+ msg('u1', 'user', [{ text: 'fine' }])
+ )
+ )
+ expect(texts(r.messages)).toEqual(['user:fine'])
+ expect(r.skipped).toBe(7)
+ expect(JSON.stringify(r.messages)).not.toContain('mystery')
+ })
+
+ it('reads messages a header record carries (the older single-record shape)', () => {
+ const r = chatFromGemini(jsonl({ ...header(), messages: [msg('u1', 'user', [{ text: 'from header' }]), msg('g1', 'gemini', 'ok')] }))
+ expect(texts(r.messages)).toEqual(['user:from header', 'assistant:ok'])
+ })
+
+ it('omits `at` when the record states no parseable time — never a made-up one', () => {
+ const r = chatFromGemini(jsonl(header(), { id: 'u1', type: 'user', content: 'a' }, msg('u2', 'user', 'b', { timestamp: 'soon' })))
+ expect(r.messages.map((m) => 'at' in m)).toEqual([false, false])
+ })
+})
+
+describe('chatFromGemini — tool parts', () => {
+ const call = (args: unknown, extra: Rec = {}): Rec => ({ id: 'c', name: 'some_tool', args, status: 'success', ...extra })
+ const one = (tc: Rec): string => texts(chatFromGemini(jsonl(header(), msg('g', 'gemini', '', { toolCalls: [tc] }))).messages)[0]
+
+ it('names the arg the way the tool is keyed, in a fixed preference order', () => {
+ expect(one(call({ command: 'git status', description: 'd', dir_path: '/x' }))).toBe('assistant:[some_tool|git status|]')
+ expect(one(call({ file_path: '/a.ts', start_line: 1 }))).toBe('assistant:[some_tool|/a.ts|]')
+ expect(one(call({ dir_path: '/srv' }))).toBe('assistant:[some_tool|/srv|]')
+ expect(one(call({ pattern: '**/*.ts' }))).toBe('assistant:[some_tool|**/*.ts|]')
+ expect(one(call({ query: 'weather' }))).toBe('assistant:[some_tool|weather|]')
+ expect(one(call({ prompt: 'summarize https://x' }))).toBe('assistant:[some_tool|summarize https://x|]')
+ expect(one(call({ name: 'skill-a' }))).toBe('assistant:[some_tool|skill-a|]')
+ expect(one(call({ title: 'Topic', summary: 's' }))).toBe('assistant:[some_tool|Topic|]')
+ })
+
+ it('falls back to the call\'s own description, then to nothing', () => {
+ expect(one(call({ todos: [] }, { description: 'Update todo list' }))).toBe('assistant:[some_tool|Update todo list|]')
+ expect(one(call({ todos: [] }))).toBe('assistant:[some_tool||]')
+ expect(one(call(null))).toBe('assistant:[some_tool||]')
+ })
+
+ it('caps the arg at 200 UTF-16 units and names a nameless call "tool"', () => {
+ const long = 'x'.repeat(250)
+ const r = chatFromGemini(jsonl(header(), msg('g', 'gemini', '', { toolCalls: [{ id: 'c', args: { command: long } }] })))
+ const p = r.messages[0].parts[0]
+ expect(p.kind === 'tool' && p.name).toBe('tool')
+ expect(p.kind === 'tool' && p.arg.length).toBe(200)
+ })
+
+ it('summarizes the model-visible output: three lines, 500 units', () => {
+ const out = ['l1', 'l2', 'l3', 'l4'].join('\n')
+ expect(one(call({}, { result: [{ functionResponse: { id: 'c', name: 't', response: { output: out } } }] }))).toBe(
+ 'assistant:[some_tool||l1 l2 l3]'
+ )
+ const big = 'y'.repeat(600)
+ const r = chatFromGemini(
+ jsonl(header(), msg('g', 'gemini', '', { toolCalls: [call({}, { result: [{ functionResponse: { response: { output: big } } }] })] }))
+ )
+ const p = r.messages[0].parts[0]
+ expect(p.kind === 'tool' && p.result?.length).toBe(500)
+ })
+
+ it('an errored call shows its error; a call with only a display string shows that', () => {
+ expect(one(call({}, { status: 'error', result: [{ functionResponse: { response: { error: 'ENOENT: no such file' } } }] }))).toBe(
+ 'assistant:[some_tool||ENOENT: no such file]'
+ )
+ expect(one(call({}, { resultDisplay: 'Found 3 matches' }))).toBe('assistant:[some_tool||Found 3 matches]')
+ // A diff object is what the TUI draws, not text we can summarize — no result rather than JSON.
+ expect(one(call({}, { resultDisplay: { fileDiff: '--- a\n+++ b', fileName: 'a.ts' } }))).toBe('assistant:[some_tool||]')
+ })
+
+ it('keeps several calls of one turn in order after the turn\'s text', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ msg('g', 'gemini', 'Let me look.', {
+ toolCalls: [
+ { id: 'a', name: 'glob', args: { pattern: '*.md' } },
+ { id: 'b', name: 'read_file', args: { file_path: 'README.md' } }
+ ]
+ })
+ )
+ )
+ expect(texts(r.messages)).toEqual(['assistant:Let me look.+[glob|*.md|]+[read_file|README.md|]'])
+ })
+
+ it('a malformed toolCalls entry is skipped and counted', () => {
+ const r = chatFromGemini(jsonl(header(), msg('g', 'gemini', 'hi', { toolCalls: ['nope', null, { id: 'a', name: 'glob', args: { pattern: 'p' } }] })))
+ expect(texts(r.messages)).toEqual(['assistant:hi+[glob|p|]'])
+ expect(r.skipped).toBe(2)
+ })
+
+ it('a functionResponse-only user record is tool output: no bubble, result attached to its call', () => {
+ // A rewritten file (`rewriteConversationFile`) can carry a model turn whose calls live only in
+ // `content` as functionCall parts, answered by a separate user record.
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ msg('g', 'gemini', [{ text: 'checking' }, { functionCall: { id: 'f1', name: 'read_file', args: { file_path: 'x.ts' } } }]),
+ msg('g_response', 'user', [{ functionResponse: { id: 'f1', name: 'read_file', response: { output: 'export {}' } } }])
+ )
+ )
+ expect(texts(r.messages)).toEqual(['assistant:checking+[read_file|x.ts|export {}]'])
+ })
+
+ it('uses toolCalls over functionCall parts when a turn carries both, and a later response never overwrites', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ msg('g', 'gemini', [{ functionCall: { id: 'f1', name: 'read_file', args: { file_path: 'x.ts' } } }], {
+ toolCalls: [
+ { id: 'f1', name: 'read_file', args: { file_path: 'x.ts' }, result: [{ functionResponse: { response: { output: 'from toolCalls' } } }] }
+ ]
+ }),
+ msg('r', 'user', [{ functionResponse: { id: 'f1', response: { output: 'from response record' } } }])
+ )
+ )
+ expect(texts(r.messages)).toEqual(['assistant:[read_file|x.ts|from toolCalls]'])
+ })
+})
+
+describe('chatFromGemini — model', () => {
+ it('is the newest model turn that states one; a turn without one does not clear it', () => {
+ const r = chatFromGemini(
+ jsonl(
+ header(),
+ msg('g1', 'gemini', 'a', { model: 'gemini-2.5-pro' }),
+ msg('g2', 'gemini', 'b', { model: 'gemini-3.5-flash' }),
+ msg('g3', 'gemini', 'c')
+ )
+ )
+ expect(r.model).toBe('gemini-3.5-flash')
+ })
+
+ it('refuses a value longer than 100 UTF-16 units, and is ABSENT (the key) when nothing states one', () => {
+ expect('model' in chatFromGemini(jsonl(header(), msg('g', 'gemini', 'a', { model: 'm'.repeat(101) })))).toBe(false)
+ expect(chatFromGemini(jsonl(header(), msg('g', 'gemini', 'a', { model: 'm'.repeat(100) }))).model).toBe('m'.repeat(100))
+ expect('model' in chatFromGemini(jsonl(header(), msg('u', 'user', 'a')))).toBe(false)
+ })
+
+ it('never reads a model off an info/user record', () => {
+ expect('model' in chatFromGemini(jsonl(header(), msg('i', 'info', 'x', { model: 'nope' })))).toBe(false)
+ })
+})
+
+// ── Locating + routing ─────────────────────────────────────────────────────────────────────────
+let home: string
+beforeEach(() => {
+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-gemini-chat-'))
+ vi.spyOn(os, 'homedir').mockReturnValue(home)
+})
+afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllEnvs()
+ setCustomAgentBaseResolver(null)
+ resetPlatformForTests()
+ fs.rmSync(home, { recursive: true, force: true })
+})
+
+const writeGemini = (body: string, name = `session-2026-09-28T10-00-${SID.slice(0, 8)}.jsonl`, project = 'proj', root = home): string => {
+ const dir = path.join(root, '.gemini', 'tmp', project, 'chats')
+ fs.mkdirSync(dir, { recursive: true })
+ const p = path.join(dir, name)
+ fs.writeFileSync(p, body)
+ return p
+}
+const writeClaude = (body: string, sid = SID): void => {
+ const dir = path.join(home, '.claude', 'projects', '-srv-app')
+ fs.mkdirSync(dir, { recursive: true })
+ fs.writeFileSync(path.join(dir, `${sid}.jsonl`), body)
+}
+const claudeLines = (text: string): string =>
+ JSON.stringify({ type: 'user', message: { content: text } }) + '\n' +
+ JSON.stringify({ type: 'assistant', message: { content: [{ type: 'text', text: 'claude reply' }] } }) + '\n'
+
+describe('locateGemini', () => {
+ it('matches the header\'s session id exactly — never a neighbour in the same chats dir', async () => {
+ const mine = writeGemini(jsonl(header(SID), msg('u', 'user', 'mine')))
+ // Written LATER, same directory: a newest-file rule would pick it.
+ writeGemini(jsonl(header(OTHER), msg('u', 'user', 'theirs')), `session-2026-09-28T11-00-${OTHER.slice(0, 8)}.jsonl`)
+ expect(await locateGemini(SID)).toBe(mine)
+ expect(await locateGemini('00000000-0000-4000-8000-000000000000')).toBeUndefined()
+ })
+
+ it('reads only the header of each candidate, not the whole file', async () => {
+ // A miss visits every candidate, so the big neighbour is certainly examined.
+ const p = writeGemini(jsonl(header(OTHER), msg('u', 'user', 'z'.repeat(200_000))), 'session-other.jsonl')
+ const spy = vi.spyOn(fs.promises, 'readFile')
+ expect(await locateGemini(SID)).toBeUndefined()
+ expect(spy.mock.calls.map((c) => c[0])).not.toContain(p)
+ })
+
+ it('still finds a session whose header line is longer than the bounded head', async () => {
+ const mine = writeGemini(jsonl({ ...header(SID), summary: 's'.repeat(100_000) }, msg('u', 'user', 'x')))
+ expect(await locateGemini(SID)).toBe(mine)
+ })
+
+ it('honours GEMINI_CLI_HOME, the CLI\'s own home relocation', async () => {
+ const alt = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-gemini-home-'))
+ try {
+ const mine = writeGemini(jsonl(header(SID)), 'session-a.jsonl', 'proj', alt)
+ vi.stubEnv('GEMINI_CLI_HOME', alt)
+ expect(await locateGemini(SID)).toBe(mine)
+ } finally {
+ fs.rmSync(alt, { recursive: true, force: true })
+ }
+ })
+})
+
+describe('readGeminiChatTranscript', () => {
+ it('a paged read is one whole page: no keys, olderCursor null, no carried results, the model', async () => {
+ writeGemini(jsonl(header(), msg('u', 'user', 'hi'), msg('g', 'gemini', 'hello', { model: 'gemini-3.5-flash' })))
+ const res = await readGeminiChatTranscript({ sessionId: SID }, { before: null, maxBytes: 65536 })
+ expect(res).toEqual({
+ messages: [
+ { role: 'user', parts: [{ kind: 'text', text: 'hi' }], at: AT },
+ { role: 'assistant', parts: [{ kind: 'text', text: 'hello' }], at: AT }
+ ],
+ found: true,
+ olderCursor: null,
+ unmatchedResults: [],
+ model: 'gemini-3.5-flash'
+ })
+ expect(Object.keys(res)).toEqual(['messages', 'found', 'olderCursor', 'unmatchedResults', 'model'])
+ })
+
+ it('the legacy unpaged read is exactly {messages, found} — no model, no paging keys', async () => {
+ writeGemini(jsonl(header(), msg('g', 'gemini', 'hello', { model: 'gemini-3.5-flash' })))
+ const res = await readGeminiChatTranscript({ sessionId: SID }, null)
+ expect(Object.keys(res)).toEqual(['messages', 'found'])
+ })
+
+ it('no session id, or no such session: not found — and nothing else is read', async () => {
+ writeGemini(jsonl(header(OTHER), msg('u', 'user', 'theirs')))
+ expect(await readGeminiChatTranscript({ sessionId: undefined }, null)).toEqual({ messages: [], found: false })
+ expect(await readGeminiChatTranscript({ sessionId: SID }, { before: null, maxBytes: 65536 })).toEqual({
+ messages: [],
+ found: false,
+ olderCursor: null,
+ unmatchedResults: []
+ })
+ })
+
+ it('a REMOTE node is never read from this machine, even when a same-id file sits here', async () => {
+ writeGemini(jsonl(header(), msg('u', 'user', 'LOCAL NAMESAKE')))
+ const paged = await readGeminiChatTranscript({ sessionId: SID, remoteOnly: true }, { before: null, maxBytes: 65536 })
+ expect(paged).toEqual({ messages: [], found: false, olderCursor: null, unmatchedResults: [], unreadable: true })
+ const legacy = await readGeminiChatTranscript({ sessionId: SID, remoteOnly: true }, null)
+ expect(legacy).toEqual({ messages: [], found: false })
+ })
+
+ it('a file past the 5 MB cap is read from its tail, never refused', async () => {
+ const pad = msg('old', 'user', 'p'.repeat(6 * 1024 * 1024))
+ writeGemini(jsonl(header(), pad, msg('u', 'user', 'recent'), msg('g', 'gemini', 'newest')))
+ const res = await readGeminiChatTranscript({ sessionId: SID }, { before: null, maxBytes: 65536 })
+ expect(res.found).toBe(true)
+ expect(texts(res.messages)).toEqual(['user:recent', 'assistant:newest'])
+ })
+})
+
+describe('readChatTranscript routes gemini to its own reader', () => {
+ it('a gemini node is NOT handed the claude transcript for the same id or cwd', async () => {
+ // Both claude legs would answer: the exact-id file AND the cwd-newest fallback.
+ writeClaude(claudeLines('SOMEONE ELSE PRIVATE'))
+ for (const page of [null, { maxBytes: 65536 }]) {
+ const res = await readChatTranscript({ sessionId: SID, cwd: '/srv/app', agentId: 'gemini' }, page ?? undefined, {})
+ expect(res.found).toBe(false)
+ expect(JSON.stringify(res)).not.toContain('SOMEONE ELSE PRIVATE')
+ }
+ })
+
+ it('reads the gemini session when it exists', async () => {
+ writeClaude(claudeLines('SOMEONE ELSE PRIVATE'))
+ writeGemini(jsonl(header(), msg('u', 'user', 'from gemini')))
+ const res = await readChatTranscript({ sessionId: SID, cwd: '/srv/app', agentId: 'gemini' }, { maxBytes: 65536 }, {})
+ expect(texts(res.messages)).toEqual(['user:from gemini'])
+ expect(JSON.stringify(res)).not.toContain('SOMEONE ELSE PRIVATE')
+ })
+
+ it('a remote gemini node never reaches the claude remote leg or the local disk', async () => {
+ writeGemini(jsonl(header(), msg('u', 'user', 'LOCAL NAMESAKE')))
+ const readRemotePage = vi.fn(async () => ({ ok: true as const, data: Buffer.from('{}\n'), start: 0 }))
+ const readRemote = vi.fn(async () => 'x')
+ const res = await readChatTranscript(
+ { sessionId: SID, agentId: 'gemini', remoteOnly: true },
+ { maxBytes: 65536 },
+ { readRemotePage, readRemote }
+ )
+ expect(res.unreadable).toBe(true)
+ expect(res.messages).toEqual([])
+ expect(readRemotePage).not.toHaveBeenCalled()
+ expect(readRemote).not.toHaveBeenCalled()
+ })
+
+ it('a custom agent built on gemini reads gemini\'s transcript (the relay serves it through the base harness)', async () => {
+ setCustomAgentBaseResolver((id) => (id === 'custom:g' ? 'gemini' : undefined))
+ writeClaude(claudeLines('SOMEONE ELSE PRIVATE'))
+ writeGemini(jsonl(header(), msg('u', 'user', 'custom gemini')))
+ const res = await readChatTranscript({ sessionId: SID, cwd: '/srv/app', agentId: 'custom:g' }, { maxBytes: 65536 }, {})
+ expect(texts(res.messages)).toEqual(['user:custom gemini'])
+ })
+
+ it('the IPC channel applies the shell\'s remoteness to gemini too', async () => {
+ const f = fakePlatform()
+ initPlatform(f)
+ writeGemini(jsonl(header(), msg('u', 'user', 'LOCAL NAMESAKE')))
+ registerTranscriptIpc({ isRemoteNode: (id) => id === 'nt-remote' })
+ const read = (nodeId: string) =>
+ f.handlers[IPC.chatReadTranscript](SID, undefined, undefined, nodeId, 'gemini', { maxBytes: 65536 }) as Promise<ChatTranscriptResult>
+ expect((await read('nt-remote')).unreadable).toBe(true)
+ expect(texts((await read('nt-local')).messages)).toEqual(['user:LOCAL NAMESAKE'])
+ })
+})
+
+describe('capabilities', () => {
+ it('gemini renders in the chat view and is NOT readable by claude\'s resolver', () => {
+ expect(canChat('gemini')).toBe(true)
+ expect(readsClaudeShapedTranscript('gemini')).toBe(false)
+ })
+
+ it('gemini\'s reader is local-only, so an unreadable read of it can only mean "remote"', () => {
+ expect(chatReadsLocalOnly('gemini')).toBe(true)
+ expect(chatReadsLocalOnly('grok')).toBe(true)
+ expect(chatReadsLocalOnly('claude')).toBe(false)
+ })
+})
diff --git a/src/core/gemini-chat.ts b/src/core/gemini-chat.ts
new file mode 100644
index 000000000..d17e5ece3
--- /dev/null
+++ b/src/core/gemini-chat.ts
@@ -0,0 +1,303 @@
+// gemini's session file (`~/.gemini/tmp/<project>/chats/session-*.jsonl`) as the ⌘M panel's
+// structured messages — and, through the relay's `chat.page`, the phone's.
+//
+// The file is NOT a list of messages. Measured against gemini-cli 0.61.0's ChatRecordingService
+// (bundle `chunk-JDPZ4CE3.js`, `appendRecord` / `pushMessage` / `rewindTo` /
+// `updateMessagesFromHistory`, and its own reader `loadConversationRecord`), every line is one of:
+//
+// header {sessionId, projectHash, startTime, lastUpdated, kind, directories?, summary?}
+// — the first line; an older single-record shape also carried `messages`.
+// message {id, timestamp, type, content, displayContent?, …} — `type` is `user`, `gemini`,
+// `info`, `warning` or `error`. The SAME id is written again, in full, every time the
+// message changes (its tool calls are added, their results land, its tokens arrive):
+// an UPSERT, which keeps the message's first position.
+// $rewindTo {$rewindTo: id} — the user rewound: that message and everything after it are gone.
+// $set {$set: {lastUpdated | summary | directories | memoryScratchpad | sessionId |
+// messages}} — metadata, except `messages`, which REPLACES the model's history.
+//
+// That last one is the trap. `$set.messages` is written at session start (the `<session_context>`
+// preamble), on every compression (all turns re-minted under NEW ids, the older ones dropped, a
+// `<state_snapshot>` summary inserted as a user turn), and when an aborted turn is rolled back. It
+// is what gemini will SEND next time, not what was said: folding it the way gemini's own resume does
+// would make the whole thread vanish at every compression, show the model-facing snapshot as
+// something the human typed, and delete a cancelled prompt the terminal still shows. Every message
+// that was actually said is also appended as its own record, so the display log is those records
+// alone, upserted by id, with `$rewindTo` honoured — and `$set` never touches it.
+//
+// Why this does not page (claude pages by byte window): a record's meaning depends on records
+// before it — a tool result arrives as a later rewrite of an earlier message, and a rewind removes
+// earlier messages — so a byte window cannot be folded on its own. The file is read whole under
+// the same 5 MB cap claude's legacy read uses (`readCappedTail`), and returned as ONE page with
+// `olderCursor: null`, exactly like grok. Past the cap the fold starts at the tail: a message first
+// written before it appears where its first in-window rewrite is, and a rewind to a message before
+// it is ignored (see `rewind` below).
+import type { ChatMessage, ChatPart, ChatTranscriptResult } from '../shared/types'
+import type { ChatTranscriptPage } from '../shared/chat-page'
+import { CHAT_TOOL_ARG_MAX } from '../shared/chat-command'
+import { locateGemini } from './handoff/locate'
+import { readCappedTail } from './transcript-reader'
+
+/** Same caps as claude's reader (`summarizeResult` / `metaString` in transcript-reader.ts), in
+ * UTF-16 code units — kept equal so the three readers' parts look alike. */
+const TOOL_RESULT_LINES = 3
+const TOOL_RESULT_MAX = 500
+const CHAT_META_MAX_CHARS = 100
+
+/** Text parts that gemini itself wrote into a user turn, not the human: the environment preamble
+ * (`getInitialChatHistory`) and a hook's additionalContext, APPENDED as its own part beside the
+ * prompt (`fireBeforeAgentHookSafe`). The same prefixes gemini's `isIgnoredUserContent` skips.
+ * Dropped per PART — dropping the message would drop the prompt next to the hook's text. */
+const HARNESS_PREFIXES = ['<session_context>', '<hook_context>']
+
+/** Which argument names a call, per the parameter names gemini's tools declare (`command` for
+ * run_shell_command, `file_path` for read_file / write_file / replace, `dir_path` for
+ * list_directory, `pattern` for glob / grep_search, `query` for google_web_search, `prompt` for
+ * web_fetch, `name` for activate_skill, `title` for update_topic). First present string wins. */
+const ARG_KEYS = ['command', 'file_path', 'dir_path', 'path', 'pattern', 'query', 'prompt', 'name', 'title'] as const
+
+type Rec = Record<string, unknown>
+type ToolPart = Extract<ChatPart, { kind: 'tool' }>
+
+export interface GeminiChat {
+ messages: ChatMessage[]
+ /** The newest model turn's `model`. Absent (the key) when no turn states a usable one. */
+ model?: string
+ /** Records and entries we could not map — never rendered, never a crash. */
+ skipped: number
+}
+
+const isObj = (v: unknown): v is Rec => !!v && typeof v === 'object' && !Array.isArray(v)
+const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined)
+
+function isHarnessText(t: string): boolean {
+ const s = t.trimStart()
+ return HARNESS_PREFIXES.some((p) => s.startsWith(p))
+}
+
+/** A content value (string or Part[]) as its visible text parts: thoughts and harness text dropped,
+ * non-text parts (images, function calls/responses) ignored here. */
+function visibleTexts(content: unknown): string[] {
+ const raw: string[] = []
+ if (typeof content === 'string') raw.push(content)
+ else if (Array.isArray(content)) {
+ for (const p of content) {
+ if (!isObj(p) || p.thought === true) continue
+ const t = str(p.text)
+ if (t !== undefined) raw.push(t)
+ }
+ }
+ return raw.filter((t) => t.length > 0 && !isHarnessText(t))
+}
+
+function summarize(s: string): string {
+ return s.split('\n').slice(0, TOOL_RESULT_LINES).join(' ').slice(0, TOOL_RESULT_MAX)
+}
+
+/** What the model was given back: `functionResponse.response.output`, else its `error`. */
+function responseText(part: unknown): string | undefined {
+ const fr = isObj(part) && isObj(part.functionResponse) ? part.functionResponse : undefined
+ const resp = fr && isObj(fr.response) ? fr.response : undefined
+ if (!resp) return undefined
+ return str(resp.output) ?? str(resp.error)
+}
+
+function toolArg(args: unknown, description: unknown): string {
+ if (isObj(args)) {
+ for (const k of ARG_KEYS) {
+ const v = str(args[k])
+ if (v) return v.slice(0, CHAT_TOOL_ARG_MAX)
+ }
+ }
+ return (str(description) ?? '').slice(0, CHAT_TOOL_ARG_MAX)
+}
+
+function toolFromCall(c: Rec): ToolPart {
+ const part: ToolPart = { kind: 'tool', name: str(c.name) || 'tool', arg: toolArg(c.args, c.description) }
+ let out: string | undefined
+ if (Array.isArray(c.result)) {
+ for (const r of c.result) {
+ out = responseText(r)
+ if (out !== undefined) break
+ }
+ }
+ // `resultDisplay` is what the TUI drew. Only its string form is text; an object (a file diff) is
+ // not something to summarize, and rendering its JSON would be the raw-record failure.
+ out ??= str(c.resultDisplay)
+ const s = out === undefined ? '' : summarize(out)
+ if (s) part.result = s
+ return part
+}
+
+function lineTime(v: unknown): number | undefined {
+ if (typeof v !== 'string' || !v) return undefined
+ const t = Date.parse(v)
+ return Number.isFinite(t) ? t : undefined
+}
+
+/**
+ * Fold the records into the display log: message records upserted by id in first-seen order,
+ * `$rewindTo` honoured, everything else metadata. PURE.
+ */
+function foldRecords(buf: string): { log: Map<string, Rec>; skipped: number } {
+ const log = new Map<string, Rec>()
+ let skipped = 0
+ const upsert = (m: unknown): void => {
+ if (isObj(m) && typeof m.id === 'string') log.set(m.id, m)
+ }
+ for (const line of buf.split('\n')) {
+ if (!line.trim()) continue
+ let o: unknown
+ try {
+ o = JSON.parse(line)
+ } catch {
+ skipped++
+ continue
+ }
+ if (!isObj(o)) {
+ skipped++
+ continue
+ }
+ if (typeof o.$rewindTo === 'string') {
+ if (!log.has(o.$rewindTo)) {
+ // gemini clears EVERYTHING on an unknown target. Its targets after a compression are the
+ // re-minted copies this log deliberately does not hold, and past the read cap the target
+ // can sit before the window — a wipe would blank a thread that is really there.
+ skipped++
+ continue
+ }
+ let found = false
+ for (const id of [...log.keys()]) {
+ if (id === o.$rewindTo) found = true
+ if (found) log.delete(id)
+ }
+ } else if (typeof o.id === 'string') {
+ upsert(o)
+ } else if (isObj(o.$set)) {
+ // Metadata; `$set.messages` is the model's context, not the thread (see the file comment).
+ } else if (typeof o.sessionId === 'string' && typeof o.projectHash === 'string') {
+ if (Array.isArray(o.messages)) for (const m of o.messages) upsert(m)
+ } else {
+ skipped++
+ }
+ }
+ return { log, skipped }
+}
+
+/**
+ * Ordered bubbles for a gemini session. PURE — the golden fixtures in
+ * `src/shared/chat-fixtures/gemini/` pin its output byte for byte.
+ *
+ * - `user`: the text the human TYPED — `displayContent` when gemini recorded one (it does when the
+ * sent content differs, e.g. an `@file` expanded into the file's body), else `content`. A turn
+ * that is only tool output (`functionResponse` parts, which gemini records as a user turn) is not
+ * a bubble; its output is attached to the call it answers when that call has none yet.
+ * - `gemini`: its text, then one tool part per call — from `toolCalls` (the enriched record, with
+ * results), else from `functionCall` parts in `content` (a rewritten file carries those).
+ * Thoughts are dropped, as claude's reader drops thinking.
+ * - `info` / `warning` / `error`: the TUI's own notes (a compression, a cancel, an API error) —
+ * rendered on the assistant side prefixed `[info]` etc., never as something the human said.
+ */
+export function chatFromGemini(buf: string): GeminiChat {
+ const { log, skipped: foldSkipped } = foldRecords(buf)
+ let skipped = foldSkipped
+ const messages: ChatMessage[] = []
+ const toolById = new Map<string, ToolPart>()
+ let model: string | undefined
+ const push = (role: ChatMessage['role'], parts: ChatPart[], rec: Rec): void => {
+ if (!parts.length) return
+ const at = lineTime(rec.timestamp)
+ messages.push(at === undefined ? { role, parts } : { role, parts, at })
+ }
+ for (const rec of log.values()) {
+ switch (rec.type) {
+ case 'user': {
+ if (Array.isArray(rec.content)) {
+ for (const p of rec.content) {
+ if (!isObj(p) || !isObj(p.functionResponse)) continue
+ const id = str(p.functionResponse.id)
+ const tool = id ? toolById.get(id) : undefined
+ const out = responseText(p)
+ if (tool && tool.result === undefined && out) {
+ const s = summarize(out)
+ if (s) tool.result = s
+ }
+ }
+ }
+ const shown = rec.displayContent !== undefined ? visibleTexts(rec.displayContent) : []
+ const typed = shown.length ? shown : visibleTexts(rec.content)
+ push('user', typed.map((text) => ({ kind: 'text', text })), rec)
+ break
+ }
+ case 'gemini': {
+ const parts: ChatPart[] = visibleTexts(rec.content).map((text) => ({ kind: 'text', text }))
+ const calls = Array.isArray(rec.toolCalls) ? rec.toolCalls : []
+ if (calls.length) {
+ for (const c of calls) {
+ if (!isObj(c)) {
+ skipped++
+ continue
+ }
+ const part = toolFromCall(c)
+ parts.push(part)
+ const id = str(c.id)
+ if (id) toolById.set(id, part)
+ }
+ } else if (Array.isArray(rec.content)) {
+ for (const p of rec.content) {
+ if (!isObj(p) || !isObj(p.functionCall)) continue
+ const fc = p.functionCall
+ const part: ToolPart = { kind: 'tool', name: str(fc.name) || 'tool', arg: toolArg(fc.args, undefined) }
+ parts.push(part)
+ const id = str(fc.id)
+ if (id) toolById.set(id, part)
+ }
+ }
+ const m = str(rec.model)
+ if (m && m.length <= CHAT_META_MAX_CHARS) model = m
+ push('assistant', parts, rec)
+ break
+ }
+ case 'info':
+ case 'warning':
+ case 'error': {
+ const t = visibleTexts(rec.content).join('\n')
+ if (t) push('assistant', [{ kind: 'text', text: `[${rec.type}] ${t}` }], rec)
+ break
+ }
+ default:
+ skipped++
+ }
+ }
+ const out: GeminiChat = { messages, skipped }
+ if (model !== undefined) out.model = model
+ return out
+}
+
+/**
+ * The gemini leg of `chat:read-transcript` (routed in transcript-ipc.ts BEFORE anything
+ * claude-shaped runs). Local only: a remote node's session lives on its host and there is no remote
+ * reader for it yet, so `remoteOnly` answers `unreadable` (paged) / not-found (legacy) without
+ * touching this machine's disk — a same-id file here is a namesake, not the session.
+ *
+ * Located strictly by the session id in the file's header (`locateGemini`). There is no cwd leg:
+ * the newest session in a directory is whichever node spoke last, not this one.
+ */
+export async function readGeminiChatTranscript(
+ q: { sessionId?: string; remoteOnly?: boolean },
+ page: ChatTranscriptPage | null
+): Promise<ChatTranscriptResult> {
+ const paging = page ? { olderCursor: null, unmatchedResults: [] } : {}
+ if (q.remoteOnly) return page ? { messages: [], found: false, ...paging, unreadable: true } : { messages: [], found: false }
+ const p = q.sessionId ? await locateGemini(q.sessionId) : undefined
+ const buf = p ? await readCappedTail(p) : undefined
+ if (buf === undefined) return { messages: [], found: false, ...paging }
+ const chat = chatFromGemini(buf)
+ // `model` rides the PAGED result only, as on claude's reader; the legacy result stays
+ // `{messages, found}`.
+ return {
+ messages: chat.messages,
+ found: true,
+ ...paging,
+ ...(page && chat.model !== undefined ? { model: chat.model } : {})
+ }
+}
diff --git a/src/core/handoff/locate.ts b/src/core/handoff/locate.ts
index 3d9134931..9924fb4a6 100644
--- a/src/core/handoff/locate.ts
+++ b/src/core/handoff/locate.ts
@@ -38,8 +38,6 @@ export async function locateCodex(sessionId: string): Promise<string | undefined
return undefined
}
-// gemini: ~/.gemini/tmp/<proj>/chats/session-*.jsonl — find the file whose first-line
-// header sessionId equals the requested sessionId.
/**
* grok's transcript, from the session directory a hook told us about — DERIVED, never searched.
*
@@ -68,8 +66,33 @@ export async function locateGrok(sessionId: string): Promise<string | undefined>
}
}
+// gemini: <home>/.gemini/tmp/<proj>/chats/session-*.jsonl — find the file whose first-line
+// header sessionId equals the requested sessionId. `<home>` is `GEMINI_CLI_HOME` when set — the
+// CLI's own relocation (`homedir()` in its bundle) — else the OS home.
+//
+// Only the header is read: the ⌘M chat view locates on every live reload, and a session file grows
+// with every rewrite of a message, so reading every candidate whole cost the size of the project's
+// entire history per hook event. A header longer than the bounded head (it never is in practice —
+// sessionId comes first) falls back to the whole-file read, so nothing that resolved before stops
+// resolving.
+const GEMINI_HEAD_BYTES = 64 * 1024
+
+async function geminiHeaderLine(p: string): Promise<string> {
+ const fh = await fs.promises.open(p, 'r')
+ try {
+ const buf = Buffer.alloc(GEMINI_HEAD_BYTES)
+ const { bytesRead } = await fh.read(buf, 0, buf.length, 0)
+ const nl = buf.subarray(0, bytesRead).indexOf(0x0a)
+ if (nl >= 0) return buf.toString('utf8', 0, nl)
+ if (bytesRead < buf.length) return buf.toString('utf8', 0, bytesRead)
+ } finally {
+ await fh.close()
+ }
+ return (await fs.promises.readFile(p, 'utf8')).split('\n', 1)[0]
+}
+
export async function locateGemini(sessionId: string): Promise<string | undefined> {
- const tmp = path.join(os.homedir(), '.gemini', 'tmp')
+ const tmp = path.join(process.env.GEMINI_CLI_HOME || os.homedir(), '.gemini', 'tmp')
let projects: string[]
try {
projects = await fs.promises.readdir(tmp)
@@ -88,8 +111,7 @@ export async function locateGemini(sessionId: string): Promise<string | undefine
if (!f.endsWith('.jsonl')) continue
const p = path.join(chats, f)
try {
- const head = (await fs.promises.readFile(p, 'utf8')).split('\n', 1)[0]
- const o = JSON.parse(head) as { sessionId?: string }
+ const o = JSON.parse(await geminiHeaderLine(p)) as { sessionId?: string }
if (o.sessionId === sessionId) return p
} catch {
/* keep looking */
diff --git a/src/core/transcript-ipc.ts b/src/core/transcript-ipc.ts
index a58b6a080..1480579ea 100644
--- a/src/core/transcript-ipc.ts
+++ b/src/core/transcript-ipc.ts
@@ -15,6 +15,8 @@ import type { ChatTranscriptResult, TranscriptLine, TranscriptPresence } from '.
import { CHAT_PAGE_MAX_BYTES, normalizeChatPage, type ChatTranscriptPage } from '../shared/chat-page'
import { platform } from './platform'
import { chatMessagesFromGrok } from './grok-chat'
+import { readGeminiChatTranscript } from './gemini-chat'
+import { capabilityAgentId } from '../shared/agents/config'
import { locateGrok } from './handoff/locate'
import {
parseChatMessages,
@@ -238,6 +240,10 @@ export async function readChatTranscript(
? { messages: [], found: false, ...paging }
: { messages: chatMessagesFromGrok(buf), found: true, ...paging }
}
+ // Gemini, routed through the base harness so a custom agent built on it (which the relay serves)
+ // reads gemini's file too. Its own locator, keyed strictly on the session id in the file header —
+ // never claude's resolver, never a cwd — and local-only, like grok.
+ if (agentId && capabilityAgentId(agentId) === 'gemini') return readGeminiChatTranscript({ sessionId, remoteOnly }, page)
if (page) return readChatPage({ sessionId, cwd, accountId, nodeId, ...(remoteOnly ? { remoteOnly } : {}) }, page, deps)
const remote = deps.readRemote ? await deps.readRemote({ sessionId, cwd, accountId, nodeId }) : null
// A resolved-but-unreadable remote file is NOT "no conversation yet" — the read failed
diff --git a/src/main/remote/host-chat.test.ts b/src/main/remote/host-chat.test.ts
index e1221089b..dc972c879 100644
--- a/src/main/remote/host-chat.test.ts
+++ b/src/main/remote/host-chat.test.ts
@@ -67,7 +67,7 @@ describe('host-chat page', () => {
await expect(createHostChat(d).page('n1', {})).rejects.toThrow()
})
it('serves only chat-capable agents (resolved through the base harness), and reads nothing otherwise', async () => {
- for (const agentId of ['codex', 'gemini', undefined]) {
+ for (const agentId of ['codex', 'antigravity', undefined]) {
const d = deps({ lookupNode: () => ({ agentId, sessionId: 'sid-1' }) })
expect(await createHostChat(d).page('n1', {})).toBe('unsupported')
expect(d.readTranscript).not.toHaveBeenCalled()
@@ -80,6 +80,11 @@ describe('host-chat page', () => {
setCustomAgentBaseResolver(null)
}
})
+ it('serves gemini, handing its OWN agent id to the reader (which routes it off claude\'s resolver)', async () => {
+ const d = deps({ lookupNode: () => ({ agentId: 'gemini', sessionId: 'sid-1' }) })
+ expect(await createHostChat(d).page('n1', {})).toMatchObject({ version: 1 })
+ expect(d.readTranscript).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'gemini', sessionId: 'sid-1' }), {})
+ })
it('an absent page is the default paged tail, not the legacy read', async () => {
const d = deps()
await createHostChat(d).page('n1', undefined)
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 2bc3a415b..b6d719e42 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -22,6 +22,7 @@ import { E_UNSUPPORTED } from '@shared/rpc'
import { Spinner } from '../components/Spinner'
import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS, chatActivity, planLiveReload } from '../lib/chatLive'
import { sentCommand } from '@shared/chat-command'
+import { chatReadsLocalOnly } from '@shared/agents/config'
import { ChatLoadingStatus } from './ChatPanelFallback'
import { answerCardState, answerRebindPending, rebindRetryDelay, type BoundAnswerCard } from '../lib/chatAnswer'
import { AnswerControlsUpdating, PlanAnswerControls, QuestionAnswerControls } from './ChatAnswerControls'
@@ -87,14 +88,13 @@ interface ChatPanelProps {
type LoadState = 'loading' | 'ok' | 'missing' | 'unsupported' | 'remoteUnsupported' | 'error'
/**
- * An `unreadable` read of a GROK node can only be the remote case: core's grok leg is local-only
- * and answers a remote grok node (`remoteOnly`) with `unreadable` before touching anything, while
- * its local reader never sets the flag. So the agent alone names it — no renderer-side remoteness
- * guess, and no new field on the wire (the phone contract keeps `unreadable`). `=== 'grok'`
- * exactly, mirroring core's routing (`readChatTranscript` routes only the builtin id to grok's
- * reader). Retry cannot heal it, so it must not read as a transient failure.
+ * An `unreadable` read of a LOCAL-ONLY reader's node (grok, gemini — `CHAT_LOCAL_ONLY`) can only be
+ * the remote case: core's leg for those agents answers a remote node (`remoteOnly`) with
+ * `unreadable` before touching anything, while their local readers never set the flag. So the agent
+ * alone names it — no renderer-side remoteness guess, and no new field on the wire (the phone
+ * contract keeps `unreadable`). Retry cannot heal it, so it must not read as a transient failure.
*/
-const remoteGrokUnreadable = (agentId: string | undefined): boolean => agentId === 'grok'
+const remoteReaderUnsupported = (agentId: string | undefined): boolean => !!agentId && chatReadsLocalOnly(agentId)
const isUnsupported = (e: unknown): boolean =>
!!e && typeof e === 'object' && (e as { code?: string }).code === E_UNSUPPORTED
@@ -115,7 +115,8 @@ const EMPTY_TEXT: Record<LoadState, { title: string; detail?: string }> = {
title: "Transcripts can't be read on this surface.",
detail: 'Open this session on the desktop app to read its conversation.'
},
- remoteUnsupported: { title: "Reading a remote Grok session's transcript isn't supported yet." },
+ // `{agent}` is the node's own agent label (`agentLabel` below) — the case spans several agents.
+ remoteUnsupported: { title: "Reading a remote {agent} session's transcript isn't supported yet." },
error: {
title: "Couldn't read the transcript.",
detail: "The agent's host may not be reachable — Retry once it is."
@@ -338,7 +339,7 @@ export function ChatPanel({
setThread(emptyThread(identity))
// A read that FAILED (the host did not answer, a remote node with no reachable master)
// is not "no transcript": it gets the error copy, and ↻ is the way out.
- setLoadState(!res.unreadable ? 'missing' : remoteGrokUnreadable(agentId) ? 'remoteUnsupported' : 'error')
+ setLoadState(!res.unreadable ? 'missing' : remoteReaderUnsupported(agentId) ? 'remoteUnsupported' : 'error')
setHeldRead({ identity, pendingId: heldAtStart })
settleHeldReload(heldAtStart)
return
@@ -764,7 +765,7 @@ export function ChatPanel({
)}
{showEmpty && (
<div className="term-chat__empty">
- <div>{EMPTY_TEXT[loadState].title}</div>
+ <div>{EMPTY_TEXT[loadState].title.replace('{agent}', agentLabel)}</div>
{EMPTY_TEXT[loadState].detail && (
<div className="term-chat__empty-detail">{EMPTY_TEXT[loadState].detail}</div>
)}
diff --git a/src/renderer/nodes/ChatPanel.ux.test.tsx b/src/renderer/nodes/ChatPanel.ux.test.tsx
index 34aad4a52..d7ad602a4 100644
--- a/src/renderer/nodes/ChatPanel.ux.test.tsx
+++ b/src/renderer/nodes/ChatPanel.ux.test.tsx
@@ -250,6 +250,16 @@ describe('ChatPanel empty states', () => {
expect(host.querySelector('.term-chat__retry')).toBeNull()
})
+ it('an unreadable REMOTE gemini read names Gemini, not Grok, and offers no Retry', async () => {
+ await render({ agentId: 'gemini' })
+ await act(async () => {
+ pending[0].resolve({ messages: [], found: false, olderCursor: null, unmatchedResults: [], unreadable: true })
+ })
+ expect(msgs().textContent).toContain("Reading a remote Gemini session's transcript isn't supported yet.")
+ expect(msgs().textContent).not.toContain('Grok')
+ expect(host.querySelector('.term-chat__retry')).toBeNull()
+ })
+
it('a clean miss still says no transcript was found', async () => {
await render()
await act(async () => {
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index d58ae0867..5ed485555 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -293,7 +293,15 @@ export const USAGE_CAPABLE = ['claude', 'codex', 'gemini', 'grok'] as const
// newest CLAUDE transcript for that cwd. A grok node in this list would therefore show a stranger's
// conversation in its find bar and rehydrate its meter from it. That exact bug already happened once
// with codex and gemini; transcriptGates.ts documents it.
-export const CHAT_CAPABLE = ['claude', 'grok'] as const
+//
+// gemini joined in 2026-09 with its own reader (`core/gemini-chat.ts`): its session file is an upsert
+// log, not claude's shape, and it is located strictly by the session id in the file's header.
+export const CHAT_CAPABLE = ['claude', 'grok', 'gemini'] as const
+// CHAT_CAPABLE agents whose reader has NO remote leg: a remote (SSH) node's session lives on its
+// host, so core answers `unreadable` before touching anything — and the local reader never sets that
+// flag. So an unreadable read of one of these can only mean "remote, unsupported", and the ⌘M panel
+// names it from the agent alone rather than offering a Retry that can never succeed.
+export const CHAT_LOCAL_ONLY = ['grok', 'gemini'] as const
// Agents whose transcript CLAUDE's own resolver can locate and parse — the gate for everything that
// goes through `resolveTranscript` (the find bar's index, the meter's mount-time rehydration).
//
@@ -514,6 +522,7 @@ export const canBranch = (id: AgentId): boolean => includes(BRANCH_CAPABLE, id)
export const canContextLink = (id: AgentId): boolean => includes(CONTEXT_LINK_CAPABLE, id)
export const hasUsage = (id: AgentId): boolean => includes(USAGE_CAPABLE, id)
export const canChat = (id: AgentId): boolean => includes(CHAT_CAPABLE, id)
+export const chatReadsLocalOnly = (id: AgentId): boolean => includes(CHAT_LOCAL_ONLY, id)
/** Can CLAUDE's transcript resolver locate and parse this agent's conversation? Never widen this
* to mean "can we read this agent" — see CLAUDE_TRANSCRIPT_READABLE. */
export const readsClaudeShapedTranscript = (id: AgentId): boolean =>
diff --git a/src/shared/chat-fixtures/gemini/README.md b/src/shared/chat-fixtures/gemini/README.md
new file mode 100644
index 000000000..684ab401f
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/README.md
@@ -0,0 +1,151 @@
+# Gemini chat golden fixtures
+
+The reference outputs for the chat view's **gemini** reader (`src/core/gemini-chat.ts`), the same
+contract as the Claude fixtures one directory up: the TypeScript implementation is the reference,
+`nodeterm-ios` keeps a byte-identical copy of this directory, and a Swift port must reproduce every
+`expected/*.page.json` from the same input.
+
+Every input is **synthetic**, built by `src/core/gemini-chat-fixtures.test.ts` from record shapes
+measured against gemini-cli 0.61.0 (its `ChatRecordingService` in the installed bundle, and real
+session files on the author's machine). None is a slice of a real session. Do not add one.
+
+## Regenerate
+
+```sh
+UPDATE_CHAT_FIXTURES=1 npx vitest run src/core/gemini-chat-fixtures.test.ts
+```
+
+Without the variable, every file must equal what the code produces. Regenerating is refused when
+`CI` is set. After regenerating, refresh the iOS copy in the same change.
+
+## Layout
+
+| path | what it is |
+|---|---|
+| `inputs/<name>.jsonl` | A synthetic gemini session file (`~/.gemini/tmp/<project>/chats/session-*.jsonl`). |
+| `expected/<name>.page.json` | `{ page, skipped }`: the page the desktop serves for it, and the count of records it could not map. |
+
+`page` is exactly what `readChatTranscript` answers for a paged request (`{maxBytes: 262144}`) on a
+gemini node, which is what the relay's `chat.page` sends the phone. The test copies the input into a
+scratch `GEMINI_CLI_HOME` and reads it through the real locator, and it also checks that `page`
+equals the pure parser's output (`chatFromGemini`) plus the paging constants.
+
+Serialization is `JSON.stringify(value, null, 2) + "\n"`. Keys appear in the order the TS code builds
+them: page `messages`, `found`, `olderCursor`, `unmatchedResults`, then `model` when there is one;
+message `role`, `parts`, then `at`; tool part `kind`, `name`, `arg`, then `result`. Optional keys are
+**absent** when unset, never `null`.
+
+## One page, no paging
+
+A gemini session file is not paged, and never will be by byte window. It is an **upsert log**: the
+same message id is written again, in full, every time the message changes (its tool calls are added,
+their results land, its token counts arrive), and a `$rewindTo` record deletes earlier messages. A
+record's meaning depends on the records before it, so a window of bytes cannot be folded on its own.
+
+The reader therefore reads the whole file and answers ONE page: `olderCursor: null`,
+`unmatchedResults: []`, no message `key`, no tool part `id`. This is the same shape grok's reader
+answers. The read is capped at the last 5 MB (5242880 bytes, the Claude legacy cap, `readCappedTail`).
+Past the cap, the first partial line is dropped and the fold starts there. No fixture is that large;
+the behaviour is covered by a unit test that builds its file at run time.
+
+## The fold (the port must replicate this exactly)
+
+Split the file on `\n` and parse each non-blank line as JSON. Then, in file order:
+
+1. A line that does not parse, or parses to anything but a JSON object (`null`, a number, a string,
+ an array), is **skipped and counted**.
+2. `$rewindTo` is a string → a rewind. If that id is in the log, delete it and every message
+ inserted after it (insertion order). If it is NOT in the log, **ignore the record and count it**.
+ Gemini's own loader clears everything in that case. We do not: after a compression gemini's
+ targets are re-minted ids this log deliberately does not hold (rule 4), and past the 5 MB cap the
+ target can sit before the window, so a wipe would blank a thread that is really there.
+3. `id` is a string → a message record. **Upsert** it into the log by id: a new id is appended; a
+ known id keeps its first position and its content is replaced by this record.
+4. `$set` is an object → metadata. **Ignore it, including `$set.messages`.** `$set.messages` is the
+ model's context, rewritten at session start (the `<session_context>` preamble), on every
+ compression (all turns re-minted under new ids, older ones dropped, a `<state_snapshot>` summary
+ inserted as a user turn), and when an aborted turn is rolled back. Every message that was actually
+ said is also written as its own record, so honouring it would only make the thread vanish at each
+ compression, show the model-facing snapshot as something the human typed, and delete a cancelled
+ prompt the terminal still shows.
+5. `sessionId` and `projectHash` are both strings → the header. If it carries a `messages` array (an
+ older single-record shape), upsert each element that has a string `id`, in order.
+6. Anything else is **skipped and counted**.
+
+Rules 2 to 5 are tested in that order, exactly as gemini's `loadConversationRecord` tests them.
+
+## Rendering (the port must replicate this exactly)
+
+Walk the log in insertion order. `at` is `Date.parse(record.timestamp)` in epoch milliseconds when
+`timestamp` is a non-empty string that parses; otherwise the key is absent. A message that ends with
+no parts is not emitted.
+
+**Visible text** of a `content` / `displayContent` value: a string is one text; an array contributes
+the `text` of each element that is an object with a string `text` and without `thought: true`. Then
+drop every text that is empty, or whose `trimStart()` begins with `<session_context>` or
+`<hook_context>` (harness text; gemini appends a hook's context as its own part beside the prompt,
+so this is per PART, never per message). Everything else in a part array (`inlineData`, `fileData`,
+`functionCall`, `functionResponse`) contributes no text.
+
+**`type: "user"`**
+- First, for each `content` element with a `functionResponse` object: when its `id` names a tool part
+ already emitted that has **no** `result` yet, and the response text (below) is non-empty after
+ summarizing, set that tool's `result`. A later response never overwrites a result.
+- The bubble is the visible text of `displayContent` when that key is present and yields at least one
+ text, else the visible text of `content`. One text part per visible text, `role: "user"`.
+ (Gemini records `displayContent` when what was sent differs from what was typed, e.g. an `@file`
+ expanded into the file's body.) A turn of only `functionResponse` parts is tool output: no bubble.
+
+**`type: "gemini"`** → `role: "assistant"`. Parts: one text part per visible text of `content`,
+then tool parts:
+- If `toolCalls` is an array with at least one element: one tool part per element, in order. An
+ element that is not an object is **skipped and counted**. Otherwise:
+ - `name`: the call's `name` if a non-empty string, else `"tool"`.
+ - `arg`: the first non-empty string among `args.command`, `args.file_path`, `args.dir_path`,
+ `args.path`, `args.pattern`, `args.query`, `args.prompt`, `args.name`, `args.title` (when `args`
+ is an object), else the call's `description` string, else `""`. Then its first 200 UTF-16 units
+ (`String.prototype.slice(0, 200)`).
+ - `result`: the response text of the first element of `result` (an array) that has one (a
+ string, even an empty one, ends the search); when no element has one, `resultDisplay` when it is
+ a **string** (an object, e.g. a file diff, gives nothing). Summarized. Absent when that is empty.
+- Else, when `content` is an array: one tool part per element with a `functionCall` object, `name`
+ and `arg` from `functionCall.name` / `functionCall.args` by the same rules (no `description`
+ fallback), no `result` (a later user `functionResponse` may set it, rule above). This is the shape
+ of a rewritten file. When `toolCalls` is present these parts are NOT also emitted.
+- Tool parts are registered by their call id (`toolCalls[].id` / `functionCall.id`) for the
+ `functionResponse` rule above.
+- `thoughts` and `thought: true` parts are dropped, as Claude's reader drops thinking. A turn with
+ only thoughts emits nothing.
+
+**Response text** of a part: `functionResponse.response.output` if a string, else
+`functionResponse.response.error` if a string, else none.
+
+**Summarized**: split on `\n`, keep the first 3 lines joined by one space, then the first 500 UTF-16
+units. The same rule as Claude's `summarizeResult`.
+
+**`type: "info"`, `"warning"`, `"error"`** (the TUI's own notes: a compression, a cancel, an API
+error) → one assistant text part `"[<type>] " + <visible texts joined by "\n">`. Nothing when that
+text is empty. Never a user bubble.
+
+**Any other `type`** (including none) is **skipped and counted**.
+
+**`model`**: walking in the same order, every `type: "gemini"` record whose `model` is a string of 1
+to 100 UTF-16 units sets it. A record with no model, or an over-long one, leaves the previous value.
+Absent (the key) when none sets it. There is no `effort`: gemini records none.
+
+`skipped` = rule 1 lines + unknown `$rewindTo` targets + rule 6 records + unknown message types +
+non-object `toolCalls` elements. It is never sent over the wire; it exists so a port can prove it
+drops the same records.
+
+## What each fixture pins
+
+| fixture | pins |
+|---|---|
+| `plain-turns` | The session-start `$set.messages` preamble (never shown); typed prompts as a part array and as a string; two text parts in one user turn; a model turn with `thoughts`, `tokens` and `model` (thoughts dropped); markdown and non-ASCII text; a part-array model reply. |
+| `tool-calls` | The measured tool lifecycle: a call recorded as `executing`, its output as a user turn of `functionResponse` parts (no bubble), then the SAME id rewritten with results (one tool part, the final result, summarized to three lines). Every `arg` key, the `description` fallback, the 200-unit arg cap, the 500-unit result cap, an error response, a string `resultDisplay`, an object `resultDisplay` (no result), a nameless call (`"tool"`), and two non-object entries (skipped). |
+| `upsert-rewind` | A rewrite keeps the first position; `$rewindTo` a known id drops it and everything after; `$rewindTo` an unknown id is ignored and counted; `model` after a rewind comes from what remains. |
+| `history-sync` | `$set.messages` at session start, at a compression (re-minted ids, `<state_snapshot>`, the "Got it" turn) and at a cancelled turn's rollback: none of it shown, nothing erased; the metadata-only `$set` shapes (`summary`, `memoryScratchpad`, `directories`, `sessionId`); `info` notes. |
+| `harness-and-display` | A `<session_context>`-only user turn (no bubble); a `<hook_context>` part dropped beside the prompt it was appended to; `displayContent` preferred over an `@file`-expanded `content`; an image part beside text; a thoughts-only turn, a thought-part-only turn and an image-only `info` record (all emit nothing); a thought part beside visible text. |
+| `notes-and-junk` | A header carrying `messages`; `info` / `warning` / `error`; an empty `info`; and every skip: an unknown `type`, a torn line, `null`, a number, an array, an object that is no record kind, a numeric `id`. Missing and unparseable timestamps (no `at`). |
+| `function-call-content` | A rewritten file's model turns: `functionCall` parts in `content` beside thought parts, answered by a later user `functionResponse` record; a turn carrying both `toolCalls` and `functionCall` parts (`toolCalls` wins, no duplicate, the late response does not overwrite). |
+| `model` | Newest wins; a turn without a model keeps the previous; 50 × U+1F9EA (100 UTF-16 units) is kept; 101 units is ignored; an `info` record's `model` is never read. |
diff --git a/src/shared/chat-fixtures/gemini/expected/function-call-content.page.json b/src/shared/chat-fixtures/gemini/expected/function-call-content.page.json
new file mode 100644
index 000000000..43b563d0c
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/expected/function-call-content.page.json
@@ -0,0 +1,48 @@
+{
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "read it"
+ }
+ ],
+ "at": 1790589601000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Reading."
+ },
+ {
+ "kind": "tool",
+ "name": "read_file",
+ "arg": "x.ts",
+ "result": "export const x = 1"
+ }
+ ],
+ "at": 1790589602000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "glob",
+ "arg": "*.ts",
+ "result": "x.ts"
+ }
+ ],
+ "at": 1790589604000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": []
+ },
+ "skipped": 0
+}
diff --git a/src/shared/chat-fixtures/gemini/expected/harness-and-display.page.json b/src/shared/chat-fixtures/gemini/expected/harness-and-display.page.json
new file mode 100644
index 000000000..6fcdd167d
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/expected/harness-and-display.page.json
@@ -0,0 +1,51 @@
+{
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "my prompt"
+ }
+ ],
+ "at": 1790589602000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "explain @src/app.ts"
+ }
+ ],
+ "at": 1790589603000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "what is in this image?"
+ }
+ ],
+ "at": 1790589604000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "A cat."
+ }
+ ],
+ "at": 1790589608000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "gemini-3.5-flash"
+ },
+ "skipped": 0
+}
diff --git a/src/shared/chat-fixtures/gemini/expected/history-sync.page.json b/src/shared/chat-fixtures/gemini/expected/history-sync.page.json
new file mode 100644
index 000000000..dc92859aa
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/expected/history-sync.page.json
@@ -0,0 +1,71 @@
+{
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "first question"
+ }
+ ],
+ "at": 1790589601000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "first answer"
+ }
+ ],
+ "at": 1790589602000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[info] Chat history compressed from 91200 to 12400 tokens."
+ }
+ ],
+ "at": 1790589603000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "a prompt I cancelled"
+ }
+ ],
+ "at": 1790589604000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[info] Request cancelled."
+ }
+ ],
+ "at": 1790589605000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "after all that"
+ }
+ ],
+ "at": 1790589606000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "gemini-3.5-flash"
+ },
+ "skipped": 0
+}
diff --git a/src/shared/chat-fixtures/gemini/expected/model.page.json b/src/shared/chat-fixtures/gemini/expected/model.page.json
new file mode 100644
index 000000000..b288df128
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/expected/model.page.json
@@ -0,0 +1,61 @@
+{
+ "page": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "one"
+ }
+ ],
+ "at": 1790589601000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "two"
+ }
+ ],
+ "at": 1790589602000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "three"
+ }
+ ],
+ "at": 1790589603000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "four"
+ }
+ ],
+ "at": 1790589604000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[info] an info record carrying a model"
+ }
+ ],
+ "at": 1790589605000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪"
+ },
+ "skipped": 0
+}
diff --git a/src/shared/chat-fixtures/gemini/expected/notes-and-junk.page.json b/src/shared/chat-fixtures/gemini/expected/notes-and-junk.page.json
new file mode 100644
index 000000000..a977ccb41
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/expected/notes-and-junk.page.json
@@ -0,0 +1,68 @@
+{
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "carried in the header record"
+ }
+ ],
+ "at": 1790589601000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[info] Switched to fallback model gemini-2.5-flash"
+ }
+ ],
+ "at": 1790589602000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[warning] Approaching the context limit."
+ }
+ ],
+ "at": 1790589603000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[error] [API Error: 429 Resource exhausted]"
+ }
+ ],
+ "at": 1790589604000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "no timestamp at all"
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "an unparseable timestamp"
+ }
+ ]
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": []
+ },
+ "skipped": 7
+}
diff --git a/src/shared/chat-fixtures/gemini/expected/plain-turns.page.json b/src/shared/chat-fixtures/gemini/expected/plain-turns.page.json
new file mode 100644
index 000000000..3cceb7dec
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/expected/plain-turns.page.json
@@ -0,0 +1,65 @@
+{
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Özet çıkar: **README** — 3 madde ✓"
+ }
+ ],
+ "at": 1790589601000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "## Özet\n\n- bir\n- iki\n- üç\n\n```ts\nconst x = 1\n```"
+ }
+ ],
+ "at": 1790589602000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "a string content (older record shape)"
+ }
+ ],
+ "at": 1790589603000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "first part"
+ },
+ {
+ "kind": "text",
+ "text": "second part"
+ }
+ ],
+ "at": 1790589604000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "answer as a part list"
+ }
+ ],
+ "at": 1790589605000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "gemini-3.5-flash"
+ },
+ "skipped": 0
+}
diff --git a/src/shared/chat-fixtures/gemini/expected/tool-calls.page.json b/src/shared/chat-fixtures/gemini/expected/tool-calls.page.json
new file mode 100644
index 000000000..926b91e4a
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/expected/tool-calls.page.json
@@ -0,0 +1,107 @@
+{
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "look around"
+ }
+ ],
+ "at": 1790589601000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Let me look."
+ },
+ {
+ "kind": "tool",
+ "name": "run_shell_command",
+ "arg": "ls -la",
+ "result": "total 2 a.txt b.txt"
+ }
+ ],
+ "at": 1790589602000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "read_file",
+ "arg": "src/app.ts",
+ "result": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+ },
+ {
+ "kind": "tool",
+ "name": "list_directory",
+ "arg": "src",
+ "result": "app.ts"
+ },
+ {
+ "kind": "tool",
+ "name": "glob",
+ "arg": "**/*.md",
+ "result": "Found 2 matching file(s)"
+ },
+ {
+ "kind": "tool",
+ "name": "grep_search",
+ "arg": "TODO"
+ },
+ {
+ "kind": "tool",
+ "name": "google_web_search",
+ "arg": "gemini cli release notes"
+ },
+ {
+ "kind": "tool",
+ "name": "web_fetch",
+ "arg": "summarize https://example.com"
+ },
+ {
+ "kind": "tool",
+ "name": "activate_skill",
+ "arg": "pdf"
+ },
+ {
+ "kind": "tool",
+ "name": "update_topic",
+ "arg": "Reading the repo"
+ },
+ {
+ "kind": "tool",
+ "name": "write_todos",
+ "arg": "Set 3 todo(s)"
+ },
+ {
+ "kind": "tool",
+ "name": "replace",
+ "arg": "src/app.ts",
+ "result": "Failed to edit: 0 occurrences found"
+ },
+ {
+ "kind": "tool",
+ "name": "run_shell_command",
+ "arg": "echo yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
+ },
+ {
+ "kind": "tool",
+ "name": "tool",
+ "arg": ""
+ }
+ ],
+ "at": 1790589604000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "gemini-3.5-flash"
+ },
+ "skipped": 2
+}
diff --git a/src/shared/chat-fixtures/gemini/expected/upsert-rewind.page.json b/src/shared/chat-fixtures/gemini/expected/upsert-rewind.page.json
new file mode 100644
index 000000000..1ab6be345
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/expected/upsert-rewind.page.json
@@ -0,0 +1,51 @@
+{
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "keep this"
+ }
+ ],
+ "at": 1790589601000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "draft answer"
+ }
+ ],
+ "at": 1790589602000
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "asked again"
+ }
+ ],
+ "at": 1790589605000
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "second try"
+ }
+ ],
+ "at": 1790589606000
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "gemini-3.5-flash"
+ },
+ "skipped": 1
+}
diff --git a/src/shared/chat-fixtures/gemini/inputs/function-call-content.jsonl b/src/shared/chat-fixtures/gemini/inputs/function-call-content.jsonl
new file mode 100644
index 000000000..b1c7aee3f
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/inputs/function-call-content.jsonl
@@ -0,0 +1,6 @@
+{"sessionId":"3e7b9c21-4d5a-4f60-8b19-a2c3d4e5f607","projectHash":"c0ffee0000000000000000000000000000000000000000000000000000000000","startTime":"2026-09-28T10:00:00.000Z","lastUpdated":"2026-09-28T10:00:00.000Z","kind":"main"}
+{"id":"u1","timestamp":"2026-09-28T10:00:01.000Z","type":"user","content":[{"text":"read it"}]}
+{"id":"g1","timestamp":"2026-09-28T10:00:02.000Z","type":"gemini","content":[{"text":"**Plan** read the file","thought":true},{"text":"Reading."},{"functionCall":{"id":"f1","name":"read_file","args":{"file_path":"x.ts"}}}]}
+{"id":"g1_response","timestamp":"2026-09-28T10:00:03.000Z","type":"user","content":[{"functionResponse":{"id":"f1","name":"read_file","response":{"output":"export const x = 1"}}}]}
+{"id":"g2","timestamp":"2026-09-28T10:00:04.000Z","type":"gemini","content":[{"functionCall":{"id":"f2","name":"glob","args":{"pattern":"*.ts"}}}],"toolCalls":[{"id":"f2","name":"glob","args":{"pattern":"*.ts"},"status":"success","timestamp":"2026-09-28T10:00:09.000Z","displayName":"glob","description":"","renderOutputAsMarkdown":false,"result":[{"functionResponse":{"id":"f2","name":"glob","response":{"output":"x.ts"}}}]}]}
+{"id":"g2_response","timestamp":"2026-09-28T10:00:05.000Z","type":"user","content":[{"functionResponse":{"id":"f2","name":"glob","response":{"output":"a DIFFERENT late answer"}}}]}
diff --git a/src/shared/chat-fixtures/gemini/inputs/harness-and-display.jsonl b/src/shared/chat-fixtures/gemini/inputs/harness-and-display.jsonl
new file mode 100644
index 000000000..27695e31c
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/inputs/harness-and-display.jsonl
@@ -0,0 +1,9 @@
+{"sessionId":"3e7b9c21-4d5a-4f60-8b19-a2c3d4e5f607","projectHash":"c0ffee0000000000000000000000000000000000000000000000000000000000","startTime":"2026-09-28T10:00:00.000Z","lastUpdated":"2026-09-28T10:00:00.000Z","kind":"main"}
+{"id":"u0","timestamp":"2026-09-28T10:00:01.000Z","type":"user","content":[{"text":"<session_context>\nThis is the Gemini CLI. We are setting up the context for our chat.\n</session_context>"}]}
+{"id":"u1","timestamp":"2026-09-28T10:00:02.000Z","type":"user","content":[{"text":"my prompt"},{"text":"<hook_context>added by a BeforeAgent hook</hook_context>"}]}
+{"id":"u2","timestamp":"2026-09-28T10:00:03.000Z","type":"user","content":[{"text":"explain @src/app.ts"},{"text":"\n--- Content from referenced files ---"},{"text":"FILE BODY"}],"displayContent":[{"text":"explain @src/app.ts"}]}
+{"id":"u3","timestamp":"2026-09-28T10:00:04.000Z","type":"user","content":[{"inlineData":{"mimeType":"image/png","data":"iVBORw0KGgo="}},{"text":"what is in this image?"}]}
+{"id":"g1","timestamp":"2026-09-28T10:00:05.000Z","type":"gemini","content":"","thoughts":[{"subject":"Looking","description":"at the image","timestamp":"2026-09-28T10:00:05.000Z"}],"model":"gemini-3.5-flash"}
+{"id":"g2","timestamp":"2026-09-28T10:00:06.000Z","type":"gemini","content":[{"text":"Binary content received. Proceeding with analysis.","thought":true,"thoughtSignature":"sig"}]}
+{"id":"i1","timestamp":"2026-09-28T10:00:07.000Z","type":"info","content":[{"inlineData":{"mimeType":"image/png","data":"iVBORw0KGgo="}}]}
+{"id":"g3","timestamp":"2026-09-28T10:00:08.000Z","type":"gemini","content":[{"text":"**Looking** at the image","thought":true},{"text":"A cat."}],"model":"gemini-3.5-flash"}
diff --git a/src/shared/chat-fixtures/gemini/inputs/history-sync.jsonl b/src/shared/chat-fixtures/gemini/inputs/history-sync.jsonl
new file mode 100644
index 000000000..2b931fdd8
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/inputs/history-sync.jsonl
@@ -0,0 +1,14 @@
+{"sessionId":"3e7b9c21-4d5a-4f60-8b19-a2c3d4e5f607","projectHash":"c0ffee0000000000000000000000000000000000000000000000000000000000","startTime":"2026-09-28T10:00:00.000Z","lastUpdated":"2026-09-28T10:00:00.000Z","kind":"main"}
+{"$set":{"messages":[{"id":"s0","timestamp":"2026-09-28T10:00:00.000Z","type":"user","content":[{"text":"<session_context>\nThis is the Gemini CLI. We are setting up the context for our chat.\n</session_context>"}]}],"lastUpdated":"2026-09-28T10:00:00.000Z"}}
+{"id":"u1","timestamp":"2026-09-28T10:00:01.000Z","type":"user","content":[{"text":"first question"}]}
+{"id":"g1","timestamp":"2026-09-28T10:00:02.000Z","type":"gemini","content":"first answer","model":"gemini-3.5-flash"}
+{"id":"i1","timestamp":"2026-09-28T10:00:03.000Z","type":"info","content":"Chat history compressed from 91200 to 12400 tokens."}
+{"$set":{"messages":[{"id":"x0","timestamp":"2026-09-28T10:00:03.000Z","type":"user","content":[{"text":"<session_context>\nThis is the Gemini CLI. We are setting up the context for our chat.\n</session_context>"}]},{"id":"x1","timestamp":"2026-09-28T10:00:03.000Z","type":"user","content":[{"text":"<state_snapshot>\n <overall_goal>SNAPSHOT</overall_goal>\n</state_snapshot>"}]},{"id":"x2","timestamp":"2026-09-28T10:00:03.000Z","type":"gemini","content":[{"text":"Got it. Thanks for the additional context!"}]}],"lastUpdated":"2026-09-28T10:00:03.000Z"}}
+{"id":"u2","timestamp":"2026-09-28T10:00:04.000Z","type":"user","content":[{"text":"a prompt I cancelled"}]}
+{"id":"i2","timestamp":"2026-09-28T10:00:05.000Z","type":"info","content":"Request cancelled."}
+{"$set":{"messages":[{"id":"x0","timestamp":"2026-09-28T10:00:03.000Z","type":"user","content":[{"text":"<session_context>\nThis is the Gemini CLI. We are setting up the context for our chat.\n</session_context>"}]}],"lastUpdated":"2026-09-28T10:00:05.000Z"}}
+{"$set":{"summary":"A session summary"}}
+{"$set":{"memoryScratchpad":{"notes":"n"}}}
+{"$set":{"directories":["/srv/app"]}}
+{"$set":{"sessionId":"3e7b9c21-4d5a-4f60-8b19-a2c3d4e5f607"}}
+{"id":"u3","timestamp":"2026-09-28T10:00:06.000Z","type":"user","content":[{"text":"after all that"}]}
diff --git a/src/shared/chat-fixtures/gemini/inputs/model.jsonl b/src/shared/chat-fixtures/gemini/inputs/model.jsonl
new file mode 100644
index 000000000..82186a7ec
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/inputs/model.jsonl
@@ -0,0 +1,6 @@
+{"sessionId":"3e7b9c21-4d5a-4f60-8b19-a2c3d4e5f607","projectHash":"c0ffee0000000000000000000000000000000000000000000000000000000000","startTime":"2026-09-28T10:00:00.000Z","lastUpdated":"2026-09-28T10:00:00.000Z","kind":"main"}
+{"id":"g1","timestamp":"2026-09-28T10:00:01.000Z","type":"gemini","content":"one","model":"gemini-2.5-pro"}
+{"id":"g2","timestamp":"2026-09-28T10:00:02.000Z","type":"gemini","content":"two","model":"🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪"}
+{"id":"g3","timestamp":"2026-09-28T10:00:03.000Z","type":"gemini","content":"three"}
+{"id":"g4","timestamp":"2026-09-28T10:00:04.000Z","type":"gemini","content":"four","model":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}
+{"id":"i1","timestamp":"2026-09-28T10:00:05.000Z","type":"info","content":"an info record carrying a model","model":"not-a-model-turn"}
diff --git a/src/shared/chat-fixtures/gemini/inputs/notes-and-junk.jsonl b/src/shared/chat-fixtures/gemini/inputs/notes-and-junk.jsonl
new file mode 100644
index 000000000..536006f4b
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/inputs/notes-and-junk.jsonl
@@ -0,0 +1,14 @@
+{"sessionId":"3e7b9c21-4d5a-4f60-8b19-a2c3d4e5f607","projectHash":"c0ffee0000000000000000000000000000000000000000000000000000000000","startTime":"2026-09-28T10:00:00.000Z","lastUpdated":"2026-09-28T10:00:00.000Z","kind":"main","messages":[{"id":"h1","timestamp":"2026-09-28T10:00:01.000Z","type":"user","content":[{"text":"carried in the header record"}]}]}
+{"id":"i1","timestamp":"2026-09-28T10:00:02.000Z","type":"info","content":"Switched to fallback model gemini-2.5-flash"}
+{"id":"w1","timestamp":"2026-09-28T10:00:03.000Z","type":"warning","content":[{"text":"Approaching the context limit."}]}
+{"id":"e1","timestamp":"2026-09-28T10:00:04.000Z","type":"error","content":"[API Error: 429 Resource exhausted]"}
+{"id":"i2","timestamp":"2026-09-28T10:00:05.000Z","type":"info","content":""}
+{"id":"q1","timestamp":"2026-09-28T10:00:06.000Z","type":"mystery","content":"an unknown message type"}
+{truncated line
+null
+7
+["an","array"]
+{"unrelated":true}
+{"id":11,"type":"user","content":"a numeric id is not a message record"}
+{"id":"u9","type":"user","content":"no timestamp at all"}
+{"id":"u10","timestamp":"yesterday","type":"user","content":"an unparseable timestamp"}
diff --git a/src/shared/chat-fixtures/gemini/inputs/plain-turns.jsonl b/src/shared/chat-fixtures/gemini/inputs/plain-turns.jsonl
new file mode 100644
index 000000000..f8eda75b6
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/inputs/plain-turns.jsonl
@@ -0,0 +1,9 @@
+{"sessionId":"3e7b9c21-4d5a-4f60-8b19-a2c3d4e5f607","projectHash":"c0ffee0000000000000000000000000000000000000000000000000000000000","startTime":"2026-09-28T10:00:00.000Z","lastUpdated":"2026-09-28T10:00:00.000Z","kind":"main"}
+{"$set":{"messages":[{"id":"s0","timestamp":"2026-09-28T10:00:00.000Z","type":"user","content":[{"text":"<session_context>\nThis is the Gemini CLI. We are setting up the context for our chat.\n</session_context>"}]}],"lastUpdated":"2026-09-28T10:00:00.000Z"}}
+{"id":"u1","timestamp":"2026-09-28T10:00:01.000Z","type":"user","content":[{"text":"Özet çıkar: **README** — 3 madde ✓"}]}
+{"$set":{"lastUpdated":"2026-09-28T10:00:01.000Z"}}
+{"id":"g1","timestamp":"2026-09-28T10:00:02.000Z","type":"gemini","content":"## Özet\n\n- bir\n- iki\n- üç\n\n```ts\nconst x = 1\n```","thoughts":[{"subject":"Reading","description":"The user wants a summary.","timestamp":"2026-09-28T10:00:02.000Z"}],"tokens":{"input":1200,"output":40,"cached":800,"thoughts":60,"tool":0,"total":1300},"model":"gemini-3.5-flash"}
+{"$set":{"lastUpdated":"2026-09-28T10:00:02.000Z"}}
+{"id":"u2","timestamp":"2026-09-28T10:00:03.000Z","type":"user","content":"a string content (older record shape)"}
+{"id":"u3","timestamp":"2026-09-28T10:00:04.000Z","type":"user","content":[{"text":"first part"},{"text":"second part"}]}
+{"id":"g2","timestamp":"2026-09-28T10:00:05.000Z","type":"gemini","content":[{"text":"answer as a part list"}],"tokens":{"input":1200,"output":40,"cached":800,"thoughts":60,"tool":0,"total":1300},"model":"gemini-3.5-flash"}
diff --git a/src/shared/chat-fixtures/gemini/inputs/tool-calls.jsonl b/src/shared/chat-fixtures/gemini/inputs/tool-calls.jsonl
new file mode 100644
index 000000000..e9890d93d
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/inputs/tool-calls.jsonl
@@ -0,0 +1,6 @@
+{"sessionId":"3e7b9c21-4d5a-4f60-8b19-a2c3d4e5f607","projectHash":"c0ffee0000000000000000000000000000000000000000000000000000000000","startTime":"2026-09-28T10:00:00.000Z","lastUpdated":"2026-09-28T10:00:00.000Z","kind":"main"}
+{"id":"u1","timestamp":"2026-09-28T10:00:01.000Z","type":"user","content":[{"text":"look around"}]}
+{"id":"g1","timestamp":"2026-09-28T10:00:02.000Z","type":"gemini","content":"Let me look.","thoughts":[],"model":"gemini-3.5-flash","toolCalls":[{"id":"c1","name":"run_shell_command","args":{"command":"ls -la","description":"List files","dir_path":"/srv"},"status":"executing","timestamp":"2026-09-28T10:00:09.000Z","displayName":"run_shell_command","description":"","renderOutputAsMarkdown":false}]}
+{"id":"g1_response","timestamp":"2026-09-28T10:00:03.000Z","type":"user","content":[{"functionResponse":{"id":"c1","name":"run_shell_command","response":{"output":"a.txt\nb.txt"}}}]}
+{"id":"g1","timestamp":"2026-09-28T10:00:02.000Z","type":"gemini","content":"Let me look.","thoughts":[],"tokens":{"input":1200,"output":40,"cached":800,"thoughts":60,"tool":0,"total":1300},"model":"gemini-3.5-flash","toolCalls":[{"id":"c1","name":"run_shell_command","args":{"command":"ls -la","description":"List files","dir_path":"/srv"},"status":"success","timestamp":"2026-09-28T10:00:09.000Z","displayName":"run_shell_command","description":"","renderOutputAsMarkdown":false,"result":[{"functionResponse":{"id":"c1","name":"run_shell_command","response":{"output":"total 2\na.txt\nb.txt\nc.txt\nd.txt"}}}],"resultDisplay":"total 2\na.txt\nb.txt\nc.txt\nd.txt"}]}
+{"id":"g2","timestamp":"2026-09-28T10:00:04.000Z","type":"gemini","content":"","model":"gemini-3.5-flash","toolCalls":[{"id":"c2","name":"read_file","args":{"file_path":"src/app.ts","start_line":1},"status":"success","timestamp":"2026-09-28T10:00:09.000Z","displayName":"read_file","description":"","renderOutputAsMarkdown":false,"result":[{"functionResponse":{"id":"c2","name":"read_file","response":{"output":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}}}]},{"id":"c3","name":"list_directory","args":{"dir_path":"src"},"status":"success","timestamp":"2026-09-28T10:00:09.000Z","displayName":"list_directory","description":"","renderOutputAsMarkdown":false,"result":[{"functionResponse":{"id":"c3","name":"list_directory","response":{"output":"app.ts"}}}]},{"id":"c4","name":"glob","args":{"pattern":"**/*.md"},"status":"success","timestamp":"2026-09-28T10:00:09.000Z","displayName":"glob","description":"","renderOutputAsMarkdown":false,"resultDisplay":"Found 2 matching file(s)"},{"id":"c5","name":"grep_search","args":{"pattern":"TODO","include_pattern":"*.ts"},"status":"success","timestamp":"2026-09-28T10:00:09.000Z","displayName":"grep_search","description":"","renderOutputAsMarkdown":false,"resultDisplay":{"summary":"not text"}},{"id":"c6","name":"google_web_search","args":{"query":"gemini cli release notes"},"status":"success","timestamp":"2026-09-28T10:00:09.000Z","displayName":"google_web_search","description":"","renderOutputAsMarkdown":false},{"id":"c7","name":"web_fetch","args":{"prompt":"summarize https://example.com"},"status":"success","timestamp":"2026-09-28T10:00:09.000Z","displayName":"web_fetch","description":"","renderOutputAsMarkdown":false},{"id":"c8","name":"activate_skill","args":{"name":"pdf"},"status":"success","timestamp":"2026-09-28T10:00:09.000Z","displayName":"activate_skill","description":"","renderOutputAsMarkdown":false},{"id":"c9","name":"update_topic","args":{"title":"Reading the repo","summary":"s","strategic_intent":"i"},"status":"success","timestamp":"2026-09-28T10:00:09.000Z","displayName":"update_topic","description":"","renderOutputAsMarkdown":false},{"id":"c10","name":"write_todos","args":{"todos":[]},"status":"success","timestamp":"2026-09-28T10:00:09.000Z","displayName":"write_todos","description":"Set 3 todo(s)","renderOutputAsMarkdown":false},{"id":"c11","name":"replace","args":{"file_path":"src/app.ts","old_string":"a","new_string":"b"},"status":"error","timestamp":"2026-09-28T10:00:09.000Z","displayName":"replace","description":"","renderOutputAsMarkdown":false,"result":[{"functionResponse":{"id":"c11","name":"replace","response":{"error":"Failed to edit: 0 occurrences found"}}}],"resultDisplay":{"fileDiff":"--- a\n+++ b","fileName":"app.ts"}},{"id":"c12","name":"run_shell_command","args":{"command":"echo yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"},"status":"success","timestamp":"2026-09-28T10:00:09.000Z","displayName":"run_shell_command","description":"","renderOutputAsMarkdown":false},{"id":"c13","args":{}},"not a call",null]}
diff --git a/src/shared/chat-fixtures/gemini/inputs/upsert-rewind.jsonl b/src/shared/chat-fixtures/gemini/inputs/upsert-rewind.jsonl
new file mode 100644
index 000000000..3c70d5a84
--- /dev/null
+++ b/src/shared/chat-fixtures/gemini/inputs/upsert-rewind.jsonl
@@ -0,0 +1,10 @@
+{"sessionId":"3e7b9c21-4d5a-4f60-8b19-a2c3d4e5f607","projectHash":"c0ffee0000000000000000000000000000000000000000000000000000000000","startTime":"2026-09-28T10:00:00.000Z","lastUpdated":"2026-09-28T10:00:00.000Z","kind":"main"}
+{"id":"u1","timestamp":"2026-09-28T10:00:01.000Z","type":"user","content":[{"text":"keep this"}]}
+{"id":"g1","timestamp":"2026-09-28T10:00:02.000Z","type":"gemini","content":"draft answer","model":"gemini-3.5-flash"}
+{"id":"g1","timestamp":"2026-09-28T10:00:02.000Z","type":"gemini","content":"draft answer","model":"gemini-3.5-flash","tokens":{"input":1200,"output":40,"cached":800,"thoughts":60,"tool":0,"total":1300}}
+{"id":"u2","timestamp":"2026-09-28T10:00:03.000Z","type":"user","content":[{"text":"this gets rewound"}]}
+{"id":"g2","timestamp":"2026-09-28T10:00:04.000Z","type":"gemini","content":"so does this","model":"gemini-2.5-pro"}
+{"$rewindTo":"u2"}
+{"$rewindTo":"never-shown"}
+{"id":"u3","timestamp":"2026-09-28T10:00:05.000Z","type":"user","content":[{"text":"asked again"}]}
+{"id":"g3","timestamp":"2026-09-28T10:00:06.000Z","type":"gemini","content":"second try","model":"gemini-3.5-flash"}