Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Cmd-P finds and resumes Claude Code and Codex conversations Harness did not start (#380)

Dee85044f16529d
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index af629ca87..0881c77c4 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -1075,6 +1075,36 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
+ it('opens a harness on a conversation Harness did not start, and refuses what a resume cannot take', async () => {
+ const socket = new BackendSocket('token')
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:resume', {
+ sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true,
+ })
+ const inputs: Array<{ resumeSessionId?: string | null; cwd: string }> = []
+ socket.onCreateAgent = async (input) => {
+ inputs.push(input)
+ return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: 'It is open in another terminal or app.' }
+ }
+ const create = (requestId: string, extra: Record<string, unknown>) => socket.handleLocalFrame('local:resume', {
+ type: 'agent_create', payload: { requestId, engine: 'codex', cwd: '/work/cohorts', ...extra },
+ })
+ const reply = (requestId: string) => frames.find((frame) => (frame.payload as { requestId?: string }).requestId === requestId)?.payload
+ create('ok', { resumeSessionId: '01a0c4ad-de5e-7000-8000-000000000001' })
+ await vi.waitFor(() => expect(reply('ok')).toBeDefined())
+ expect(inputs[0]).toMatchObject({ resumeSessionId: '01a0c4ad-de5e-7000-8000-000000000001', cwd: '/work/cohorts' })
+ // What cli.ts said about it reaches the client as it was said.
+ expect(reply('ok')).toMatchObject({ error: 'SESSION_OPEN_ELSEWHERE', detail: 'It is open in another terminal or app.' })
+ create('shape', { resumeSessionId: '../../etc/passwd' })
+ create('prompt', { resumeSessionId: '01a0c4ad-de5e-7000-8000-000000000001', prompt: 'and then this' })
+ await vi.waitFor(() => expect(reply('prompt')).toBeDefined())
+ expect(reply('shape')).toMatchObject({ error: 'INVALID_SESSION' })
+ expect(reply('prompt')).toMatchObject({ error: 'INVALID_SESSION' })
+ expect(inputs).toHaveLength(1)
+ await socket.unregisterLocalClient('local:resume')
+ await socket.stop()
+ })
+
it('creates with approvals bypassed unless the client turns that off', async () => {
const socket = new BackendSocket('token')
const frames: Array<Record<string, unknown>> = []
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 6b955d046..234da8798 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -493,6 +493,10 @@ export class BackendSocket {
/** A mode from `PERMISSION_MODES` for this engine; null when the client sent only
* `bypassPermission`, which then decides. Validated here (`INVALID_PERMISSION_MODE`). */
permissionMode: string | null
+ /** A conversation Harness did not start, to open this harness ON: the engine resumes it, in its own
+ * folder (lib/sessionSearch/external.ts). Null for a new conversation. Shape-checked here; cli.ts
+ * checks it is one it found, not open elsewhere, and not already a harness. */
+ resumeSessionId?: string | null
}) =>
Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null
/** Called on `dsh_install` — cli.ts clones/sets up/doctors the harness and reports each phase. */
@@ -2338,6 +2342,18 @@ export class BackendSocket {
}
permissionMode = payload.permissionMode
}
+ // Opening a conversation Harness did not start: the engine resumes it, as it was. Nothing a new
+ // conversation is created with applies to it.
+ let resumeSessionId: string | null = null
+ if (payload.resumeSessionId !== undefined && payload.resumeSessionId !== null) {
+ if (typeof payload.resumeSessionId !== 'string' || !/^[A-Za-z0-9-]{8,80}$/.test(payload.resumeSessionId)) {
+ reply(type, requestId, { error: 'INVALID_SESSION', detail: 'resumeSessionId must be a session id' }); return
+ }
+ if (terminal || projectFolder || grid.state === 'ok' || model.state === 'ok' || dsh || prompt || agent) {
+ reply(type, requestId, { error: 'INVALID_SESSION', detail: 'a resumed conversation takes no new folder, grid, harness, prompt or agent' }); return
+ }
+ resumeSessionId = payload.resumeSessionId
+ }
const input = {
engine,
cwd: typeof cwd === 'string' ? cwd : terminal ? homedir() : '',
@@ -2350,6 +2366,7 @@ export class BackendSocket {
prompt,
name,
agent,
+ resumeSessionId,
}
const fingerprintInput = model.state === 'ok' ? { ...input, modelSelection: model.selection } : input
if (creationId !== undefined) {
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index be3747c8b..508a31c1c 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -94,6 +94,7 @@ import { createRetainExitedSession } from './lib/retainExitedSession.js'
import { repairClaudeCwd } from './lib/cwdRepair.js'
import { stoppedAgents } from './lib/stoppedAgents.js'
import { SessionSearchIndex, folderWords, type SearchSource } from './lib/sessionSearch/indexer.js'
+import { ExternalSessions, OpenSessions } from './lib/sessionSearch/external.js'
import { SessionSearchStore } from './lib/sessionSearch/store.js'
import { SESSION_SEARCH_FILE, searchCommand } from './lib/sessionSearch/command.js'
import { sweepWorktrees } from './lib/worktreeSweep.js'
@@ -121,7 +122,7 @@ import { ApiConnections } from './lib/apiConnections.js'
import { apiCommand, apiUsage } from './lib/apiCommand.js'
import { prepareApiInstructions } from './lib/apiInstructions.js'
import type { AgentDshContext } from './lib/agentFrame.js'
-import { basename } from 'node:path'
+import { basename, dirname as parentDir } from 'node:path'
import {
bypassPermissionActive,
permissionModeFromArgv,
@@ -2807,6 +2808,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Session search: every turn of every conversation on this machine, live and stopped, indexed from
// its transcript and searched by `session_search` (lib/sessionSearch/). Nothing leaves the machine
// but the hits for a query. A Node without `node:sqlite` has no index; the RPC then says so.
+ // Claude Code and Codex conversations on this machine that Harness did not start, found on disk
+ // so Cmd-P can find them and open one here; and which sessions a process has open right now.
+ const externalSessions = new ExternalSessions({ claudeProjectsDir: env.CLAUDE_PROJECTS_DIR, codexHome: env.CODEX_HOME })
+ const openSessions = new OpenSessions({ claudeHome: parentDir(env.CLAUDE_PROJECTS_DIR) })
const sessionSearch = (() => {
try {
const store = SessionSearchStore.open(join(env.ADAPTER_DATA_DIR, SESSION_SEARCH_FILE))
@@ -2816,22 +2821,38 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}
const index = new SessionSearchIndex({
store,
- sources: () => [...registry.list(), ...stoppedAgents.list()].flatMap((s): SearchSource[] => {
- const readHistory = s.transcriptPath ? undefined : databaseHistory(s)
- if (!s.sessionId || (!s.transcriptPath && !readHistory)) return []
- return [{
- agentId: s.agentId,
- sessionId: s.sessionId,
- engine: s.engine,
- transcriptPath: s.transcriptPath || null,
- header: [projectDisplayName(s), s.title, folderWords(s.cwd)].filter(Boolean).join(' · '),
- // Conversation stamps only (lib/agentFrame.ts lastActivityAt): the registry's own
- // updatedAt moves on every discovery pass.
- updatedAt: Math.max(s.lastTranscriptAt || 0, s.lastHookAt || 0) || s.boundAt || s.registeredAt || 0,
- readHistory,
- }]
- }),
+ sources: () => {
+ const own = [...registry.list(), ...stoppedAgents.list()]
+ const sources = own.flatMap((s): SearchSource[] => {
+ const readHistory = s.transcriptPath ? undefined : databaseHistory(s)
+ if (!s.sessionId || (!s.transcriptPath && !readHistory)) return []
+ return [{
+ agentId: s.agentId,
+ sessionId: s.sessionId,
+ engine: s.engine,
+ transcriptPath: s.transcriptPath || null,
+ header: [projectDisplayName(s), s.title, folderWords(s.cwd)].filter(Boolean).join(' · '),
+ // Conversation stamps only (lib/agentFrame.ts lastActivityAt): the registry's own
+ // updatedAt moves on every discovery pass.
+ updatedAt: Math.max(s.lastTranscriptAt || 0, s.lastHookAt || 0) || s.boundAt || s.registeredAt || 0,
+ readHistory,
+ }]
+ })
+ // Conversations Harness did not start — any Harness agent's, earlier ones included, are not.
+ const known = store.ownedSessionIds()
+ for (const s of own) if (s.sessionId) known.add(s.sessionId)
+ for (const e of externalSessions.list()) {
+ if (known.has(e.sessionId)) continue
+ sources.push({
+ agentId: '', sessionId: e.sessionId, engine: e.engine, transcriptPath: e.transcriptPath,
+ header: '', updatedAt: e.mtime, external: { cwd: e.cwd, origin: e.origin, title: e.title },
+ })
+ }
+ return sources
+ },
agents: () => [...registry.list(), ...stoppedAgents.list()].map((s) => s.agentId),
+ discover: () => externalSessions.scan(),
+ openSessions,
log: (line) => console.log(line),
})
index.start()
@@ -4956,8 +4977,37 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}
}
- backend.onCreateAgent = async ({ engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent }) => {
+ /**
+ * Whether a conversation Harness did not start can be opened here as a harness: one discovery found
+ * (looked for again if it is new), on this engine, not already a harness, and not open in a running
+ * process — a terminal or the engine's app that still has it would write it too.
+ */
+ const adoptableSession = async (sessionId: string, engine: AgentEngine): Promise<{ ok: true; cwd: string; title: string } | { ok: false; error: string; detail: string }> => {
+ if (registry.bySession(sessionId) || stoppedAgents.list().some((s) => s.sessionId === sessionId)) {
+ return { ok: false, error: 'SESSION_IN_HARNESS', detail: 'This conversation is already a harness here.' }
+ }
+ const found = externalSessions.get(sessionId) ?? (await externalSessions.scan(), externalSessions.get(sessionId))
+ if (!found) return { ok: false, error: 'SESSION_NOT_FOUND', detail: 'This conversation is no longer on this machine.' }
+ if (found.engine !== engine) return { ok: false, error: 'INVALID_ENGINE', detail: `This is a ${found.engine} conversation.` }
+ if ((await openSessions.fresh()).has(sessionId)) {
+ return { ok: false, error: 'SESSION_OPEN_ELSEWHERE', detail: 'It is open in another terminal or app. Close it there, then open it here.' }
+ }
+ // The Codex app keeps a thread in a folder of its own, which people tidy away.
+ if (!existsSync(found.cwd)) {
+ return { ok: false, error: 'SESSION_FOLDER_GONE', detail: `The folder it ran in is gone: ${found.cwd}` }
+ }
+ return { ok: true, cwd: found.cwd, title: found.title || sessionSearch?.session(sessionId)?.title || '' }
+ }
+
+ backend.onCreateAgent = async ({ engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, resumeSessionId }) => {
if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
+ // A conversation Harness did not start opens in its own folder, under its own title.
+ if (resumeSessionId) {
+ const adopted = await adoptableSession(resumeSessionId, engine)
+ if (!adopted.ok) return adopted
+ cwd = adopted.cwd
+ name = name ?? (adopted.title || null)
+ }
try {
if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }
} catch {
@@ -5099,7 +5149,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent) : [])]
// The first prompt is a launch option only — never part of `extraArgs`, which the registry row
// carries into a relaunch (engineLaunch.ts, `firstPrompt`).
- const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(prompt ? { firstPrompt: prompt } : {}), terminalHint: { machineName: terminalHintMachineName() } }
+ const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(prompt ? { firstPrompt: prompt } : {}), ...(resumeSessionId ? { resumeSessionId } : {}), terminalHint: { machineName: terminalHintMachineName() } }
const command = buildEngineCommandArgv(engine, launchOptions)
const argv = buildEngineLaunchArgv(engine, launchOptions)
// A tmux route is enough to stream its screen. Register it before looking for a process so both
diff --git a/cli/src/lib/sessionSearch/external.spec.ts b/cli/src/lib/sessionSearch/external.spec.ts
new file mode 100644
index 000000000..0432782fe
--- /dev/null
+++ b/cli/src/lib/sessionSearch/external.spec.ts
@@ -0,0 +1,127 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { ExternalSessions, OpenSessions, readClaudeHead, readCodexHead } from './external.js'
+
+const dirs: string[] = []
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+function home(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'external-sessions-'))
+ dirs.push(dir)
+ return dir
+}
+function write(path: string, lines: unknown[]): string {
+ mkdirSync(join(path, '..'), { recursive: true })
+ writeFileSync(path, lines.map((line) => typeof line === 'string' ? line : JSON.stringify(line)).join('\n') + '\n')
+ return path
+}
+
+const claudeLine = (sessionId: string, entrypoint: string, extra: Record<string, unknown> = {}) => ({
+ type: 'user', sessionId, cwd: '/work/dial', entrypoint, timestamp: '2026-09-20T10:00:00Z',
+ message: { role: 'user', content: 'fix the dial scroll' }, ...extra,
+})
+const codexMeta = (id: string, source: unknown, originator = 'codex-tui') => ({
+ timestamp: '2026-09-20T10:00:00Z', type: 'session_meta',
+ payload: { id, cwd: '/work/cohorts', originator, source, timestamp: '2026-09-20T10:00:00Z', base_instructions: 'x'.repeat(40_000) },
+})
+const A = '11111111-1111-4111-8111-111111111111'
+const B = '22222222-2222-4222-8222-222222222222'
+const C = '01a0c4ad-de5e-7000-8000-000000000001'
+const D = '01a0c4ad-de5e-7000-8000-000000000002'
+
+describe('what counts as a conversation a person started', () => {
+ it('reads Claude Code: a terminal or the Claude app, not a program or a sub-agent', async () => {
+ const dir = home()
+ const file = (name: string, lines: unknown[]) => write(join(dir, `${name}.jsonl`), lines)
+ // The first lines may carry no entrypoint: a title, a mode.
+ expect(await readClaudeHead(file('t', [{ type: 'permission-mode', permissionMode: 'auto' }, claudeLine(A, 'cli')])))
+ .toEqual({ sessionId: A, engine: 'claude', cwd: '/work/dial', origin: 'terminal' })
+ expect(await readClaudeHead(file('d', [claudeLine(A, 'claude-desktop')]))).toMatchObject({ origin: 'claude-app' })
+ expect(await readClaudeHead(file('s', [claudeLine(A, 'sdk-cli')]))).toBeNull()
+ expect(await readClaudeHead(file('x', [claudeLine(A, 'cli', { isSidechain: true })]))).toBeNull()
+ expect(await readClaudeHead(file('r', [claudeLine(A, 'cli', { cwd: 'relative/path' })]))).toBeNull()
+ expect(await readClaudeHead(file('e', [{ type: 'summary', summary: 'nothing else' }]))).toBeNull()
+ })
+
+ it('reads Codex: the terminal, the Codex app and the editors, not scripts or sub-agent threads', async () => {
+ const dir = home()
+ const file = (name: string, meta: unknown) => write(join(dir, `${name}.jsonl`), [meta, { type: 'event_msg', payload: {} }])
+ expect(await readCodexHead(file('cli', codexMeta(C, 'cli'))))
+ .toEqual({ sessionId: C, engine: 'codex', cwd: '/work/cohorts', origin: 'terminal' })
+ expect(await readCodexHead(file('app', codexMeta(C, 'vscode', 'Codex Desktop')))).toMatchObject({ origin: 'codex-app' })
+ expect(await readCodexHead(file('ide', codexMeta(C, 'vscode', 'codex_vscode')))).toMatchObject({ origin: 'editor' })
+ expect(await readCodexHead(file('exec', codexMeta(C, 'exec', 'codex_exec')))).toBeNull()
+ expect(await readCodexHead(file('sub', codexMeta(C, { subagent: { other: 'guardian' } })))).toBeNull()
+ })
+})
+
+describe('ExternalSessions', () => {
+ it("finds both engines' conversations, titles Codex's, skips sub-agents, and forgets deleted files", async () => {
+ const root = home()
+ const claude = join(root, '.claude', 'projects')
+ const codex = join(root, '.codex')
+ write(join(claude, '-work-dial', `${A}.jsonl`), [claudeLine(A, 'cli')])
+ write(join(claude, '-work-dial', `${B}.jsonl`), [claudeLine(B, 'sdk-cli')])
+ write(join(claude, '-work-dial', A, 'subagents', 'agent-1.jsonl'), [claudeLine(A, 'cli')])
+ write(join(codex, 'sessions', '2026', '09', '20', `rollout-2026-09-20T10-00-00-${C}.jsonl`), [codexMeta(C, 'cli')])
+ const archived = write(join(codex, 'archived_sessions', `rollout-2026-09-19T10-00-00-${D}.jsonl`), [codexMeta(D, 'vscode', 'Codex Desktop')])
+ write(join(codex, 'session_index.jsonl'), [
+ { id: C, thread_name: 'Old name', updated_at: '2026-09-20T10:00:00Z' },
+ { id: C, thread_name: 'Retention cohorts', updated_at: '2026-09-21T10:00:00Z' },
+ 'half a line',
+ ])
+ const sessions = new ExternalSessions({ claudeProjectsDir: claude, codexHome: codex })
+ const found = await sessions.scan()
+ expect(found.map((s) => [s.sessionId, s.engine, s.origin, s.title]).sort()).toEqual([
+ [C, 'codex', 'terminal', 'Retention cohorts'],
+ [D, 'codex', 'codex-app', ''],
+ [A, 'claude', 'terminal', ''],
+ ].sort())
+ expect(sessions.get(C)).toMatchObject({ cwd: '/work/cohorts', transcriptPath: expect.stringContaining(C) })
+
+ rmSync(archived)
+ await sessions.scan()
+ expect(sessions.get(D)).toBeUndefined()
+ expect(sessions.list()).toHaveLength(2)
+ })
+
+ it('shares one scan between callers, and finds nothing where nothing is', async () => {
+ const root = home()
+ const sessions = new ExternalSessions({ claudeProjectsDir: join(root, 'none'), codexHome: join(root, 'none') })
+ const [a, b] = [sessions.scan(), sessions.scan()]
+ expect(a).toBe(b)
+ expect(await a).toEqual([])
+ })
+})
+
+describe('OpenSessions', () => {
+ it('knows Claude sessions from their live process records, and Codex ones from open rollouts', async () => {
+ const root = home()
+ write(join(root, 'sessions', '101.json'), [{ pid: 101, sessionId: A }])
+ write(join(root, 'sessions', '102.json'), [{ pid: 102, sessionId: B }])
+ write(join(root, 'sessions', '103.json'), ['{ being written'])
+ let now = 1_000
+ let reads = 0
+ const open = new OpenSessions({
+ claudeHome: root,
+ alive: (pid) => pid === 101,
+ openRollouts: async () => { reads++; return [`/h/.codex/sessions/2026/09/20/rollout-2026-09-20T10-00-00-${C}.jsonl`] },
+ now: () => now,
+ maxAgeMs: 5_000,
+ })
+ expect(open.known().size).toBe(0)
+ const ids = await open.fresh()
+ expect([...ids].sort()).toEqual([A, C].sort())
+ expect(reads).toBe(1)
+ now += 1_000
+ await open.fresh()
+ expect(reads).toBe(1)
+ now += 10_000
+ await open.fresh()
+ expect(reads).toBe(2)
+ expect(open.known().has(C)).toBe(true)
+ })
+})
diff --git a/cli/src/lib/sessionSearch/external.ts b/cli/src/lib/sessionSearch/external.ts
new file mode 100644
index 000000000..841ea1080
--- /dev/null
+++ b/cli/src/lib/sessionSearch/external.ts
@@ -0,0 +1,264 @@
+/**
+ * Conversations on this machine that Harness did not start: Claude Code and Codex sessions run in a
+ * terminal or in their own desktop apps. Found where each engine keeps them, so Cmd-P can find them
+ * and open one in Harness (`agent_create` with `resumeSessionId`).
+ *
+ * Only what a person started, told apart by what each engine records at the top of the file:
+ * - Claude Code's `entrypoint`: `cli` (a terminal) or `claude-desktop` (the Claude app). `sdk-cli`
+ * is a program driving Claude — Harness's own summaries among them — and a sub-agent's file lives
+ * in a folder of its own.
+ * - Codex's `source`: `cli` (a terminal) or `vscode` (the Codex app, which says so in `originator`,
+ * and the editor extensions). `exec` is a script and a `subagent` source is another thread's helper.
+ *
+ * A file's first lines never change, so each file is read once, however often it is scanned.
+ */
+
+import { execFile } from 'node:child_process'
+import { open, readdir, readFile, stat } from 'node:fs/promises'
+import { join } from 'node:path'
+
+export type ExternalOrigin = 'terminal' | 'claude-app' | 'codex-app' | 'editor'
+export type ExternalEngine = 'claude' | 'codex'
+
+export interface ExternalSession {
+ sessionId: string
+ engine: ExternalEngine
+ transcriptPath: string
+ /** The folder it ran in, and so the folder it resumes in. */
+ cwd: string
+ origin: ExternalOrigin
+ /** Codex's thread name (`session_index.jsonl`); Claude's comes from the transcript as it is indexed. */
+ title: string
+ /** When the file last changed, epoch ms. */
+ mtime: number
+}
+
+type Head = Pick<ExternalSession, 'sessionId' | 'engine' | 'cwd' | 'origin'>
+
+/** How much of a file is read to classify it: a Claude file's first lines, a Codex file's first line. */
+const CLAUDE_HEAD_BYTES = 256 * 1024
+const CODEX_HEAD_BYTES = 1024 * 1024
+const SESSION_ID = /^[A-Za-z0-9-]{8,80}$/
+
+export interface ExternalSessionsOptions {
+ claudeProjectsDir: string
+ codexHome: string
+}
+
+export class ExternalSessions {
+ /** A verdict per file: its head, or null for a file that is not a person's conversation. */
+ private readonly heads = new Map<string, Head | null>()
+ private found: ExternalSession[] = []
+ private byId = new Map<string, ExternalSession>()
+ private scanning: Promise<ExternalSession[]> | null = null
+
+ constructor(private readonly opts: ExternalSessionsOptions) {}
+
+ /** What the last scan found, newest first. */
+ list(): readonly ExternalSession[] { return this.found }
+
+ get(sessionId: string): ExternalSession | undefined { return this.byId.get(sessionId) }
+
+ /** Looks again. One scan at a time: a second caller shares the one in progress. */
+ scan(): Promise<ExternalSession[]> {
+ this.scanning ??= this.scanOnce().finally(() => { this.scanning = null })
+ return this.scanning
+ }
+
+ private async scanOnce(): Promise<ExternalSession[]> {
+ const found: ExternalSession[] = []
+ const seen = new Set<string>()
+ const consider = async (path: string, read: (path: string) => Promise<Head | null>, title = (_id: string) => '') => {
+ seen.add(path)
+ const file = await stat(path).catch(() => null)
+ if (!file?.isFile()) return
+ let head = this.heads.get(path)
+ if (head === undefined) {
+ head = await read(path).catch(() => null)
+ this.heads.set(path, head)
+ }
+ if (head) found.push({ ...head, transcriptPath: path, title: title(head.sessionId), mtime: Math.floor(file.mtimeMs) })
+ // A first scan reads a thousand files: let the daemon breathe between them.
+ if (seen.size % 64 === 0) await new Promise<void>((resolve) => setImmediate(resolve))
+ }
+
+ for (const project of await entries(this.opts.claudeProjectsDir)) {
+ if (!project.isDirectory()) continue
+ const folder = join(this.opts.claudeProjectsDir, project.name)
+ // Only the project's own files: a sub-agent's are in a folder beneath it.
+ for (const file of await entries(folder)) {
+ if (file.isFile() && file.name.endsWith('.jsonl')) await consider(join(folder, file.name), readClaudeHead)
+ }
+ }
+
+ const titles = await codexTitles(join(this.opts.codexHome, 'session_index.jsonl'))
+ for (const path of [
+ ...await rollouts(join(this.opts.codexHome, 'sessions')),
+ ...await rollouts(join(this.opts.codexHome, 'archived_sessions')),
+ ]) await consider(path, readCodexHead, (id) => titles.get(id) ?? '')
+
+ for (const path of [...this.heads.keys()]) if (!seen.has(path)) this.heads.delete(path)
+ found.sort((a, b) => b.mtime - a.mtime)
+ this.found = found
+ this.byId = new Map(found.map((session) => [session.sessionId, session]))
+ return found
+ }
+}
+
+async function entries(dir: string) {
+ return readdir(dir, { withFileTypes: true }).catch(() => [])
+}
+
+/** Every rollout file under a Codex sessions folder (`YYYY/MM/DD/rollout-*.jsonl`), at any depth. */
+async function rollouts(dir: string): Promise<string[]> {
+ const out: string[] = []
+ const walk = async (at: string, depth: number): Promise<void> => {
+ for (const entry of await entries(at)) {
+ const path = join(at, entry.name)
+ if (entry.isDirectory() && depth < 4) await walk(path, depth + 1)
+ else if (entry.isFile() && entry.name.startsWith('rollout-') && entry.name.endsWith('.jsonl')) out.push(path)
+ }
+ }
+ await walk(dir, 0)
+ return out
+}
+
+async function readHead(path: string, bytes: number): Promise<string> {
+ const handle = await open(path, 'r')
+ try {
+ const buffer = Buffer.alloc(bytes)
+ const { bytesRead } = await handle.read(buffer, 0, bytes, 0)
+ return buffer.subarray(0, bytesRead).toString('utf8')
+ } finally {
+ await handle.close()
+ }
+}
+
+/** A Claude Code transcript's session, folder and entrypoint, from the first line that has them. */
+export async function readClaudeHead(path: string): Promise<Head | null> {
+ const text = await readHead(path, CLAUDE_HEAD_BYTES)
+ for (const line of text.split('\n')) {
+ if (!line.includes('"entrypoint"')) continue
+ let record: { sessionId?: unknown; cwd?: unknown; entrypoint?: unknown; isSidechain?: unknown }
+ try { record = JSON.parse(line) } catch { continue }
+ if (record.isSidechain === true) return null
+ const origin = record.entrypoint === 'cli' ? 'terminal' : record.entrypoint === 'claude-desktop' ? 'claude-app' : null
+ if (!origin) return null
+ if (typeof record.sessionId !== 'string' || !SESSION_ID.test(record.sessionId)) return null
+ if (typeof record.cwd !== 'string' || !record.cwd.startsWith('/')) return null
+ return { sessionId: record.sessionId, engine: 'claude', cwd: record.cwd, origin }
+ }
+ return null
+}
+
+/** A Codex rollout's session, folder and source, from its first line (`session_meta`). */
+export async function readCodexHead(path: string): Promise<Head | null> {
+ const text = await readHead(path, CODEX_HEAD_BYTES)
+ const newline = text.indexOf('\n')
+ if (newline < 0) return null
+ let record: { type?: unknown; payload?: { id?: unknown; cwd?: unknown; source?: unknown; originator?: unknown } }
+ try { record = JSON.parse(text.slice(0, newline)) } catch { return null }
+ const meta = record.payload
+ if (record.type !== 'session_meta' || !meta) return null
+ const origin = meta.source === 'cli' ? 'terminal'
+ : meta.source === 'vscode' ? (meta.originator === 'Codex Desktop' ? 'codex-app' : 'editor')
+ : null
+ if (!origin) return null
+ if (typeof meta.id !== 'string' || !SESSION_ID.test(meta.id)) return null
+ if (typeof meta.cwd !== 'string' || !meta.cwd.startsWith('/')) return null
+ return { sessionId: meta.id, engine: 'codex', cwd: meta.cwd, origin }
+}
+
+/** Codex's thread names: `session_index.jsonl`, one `{id, thread_name}` a line, the last one winning. */
+async function codexTitles(path: string): Promise<Map<string, string>> {
+ const titles = new Map<string, string>()
+ const text = await readFile(path, 'utf8').catch(() => '')
+ for (const line of text.split('\n')) {
+ try {
+ const record = JSON.parse(line) as { id?: unknown; thread_name?: unknown }
+ if (typeof record.id === 'string' && typeof record.thread_name === 'string' && record.thread_name.trim()) {
+ titles.set(record.id, record.thread_name.trim())
+ }
+ } catch { /* a line being written */ }
+ }
+ return titles
+}
+
+export interface OpenSessionsOptions {
+ /** `~/.claude`: running Claude Code processes each keep `sessions/<pid>.json` there. */
+ claudeHome: string
+ /** How long an answer is reused. */
+ maxAgeMs?: number
+ /** Whether a process is running; tests replace it. */
+ alive?: (pid: number) => boolean
+ /** The Codex rollouts open in a running process; tests replace it. */
+ openRollouts?: () => Promise<string[]>
+ now?: () => number
+}
+
+/**
+ * Which sessions are open in a running process right now, so Cmd-P does not open one a second time
+ * beside a terminal that still has it: both would write the same conversation.
+ *
+ * Claude Code says so itself — each running process keeps `~/.claude/sessions/<pid>.json` naming its
+ * session. Codex keeps no such record, but holds its rollout file open while it runs, so the
+ * operating system says which are (`lsof`).
+ */
+export class OpenSessions {
+ private answer: { at: number; ids: Set<string> } | null = null
+ private asking: Promise<Set<string>> | null = null
+
+ constructor(private readonly opts: OpenSessionsOptions) {}
+
+ /** The last answer, however old; empty before the first. Never waits. */
+ known(): ReadonlySet<string> {
+ const now = (this.opts.now ?? Date.now)()
+ if (!this.answer || now - this.answer.at > (this.opts.maxAgeMs ?? 5_000)) void this.fresh()
+ return this.answer?.ids ?? new Set()
+ }
+
+ /** An answer at most `maxAgeMs` old. */
+ fresh(): Promise<Set<string>> {
+ const now = (this.opts.now ?? Date.now)()
+ if (this.answer && now - this.answer.at <= (this.opts.maxAgeMs ?? 5_000)) return Promise.resolve(this.answer.ids)
+ this.asking ??= this.read().then((ids) => {
+ this.answer = { at: (this.opts.now ?? Date.now)(), ids }
+ return ids
+ }).finally(() => { this.asking = null })
+ return this.asking
+ }
+
+ private async read(): Promise<Set<string>> {
+ const ids = new Set<string>()
+ const alive = this.opts.alive ?? processAlive
+ const dir = join(this.opts.claudeHome, 'sessions')
+ for (const file of await entries(dir)) {
+ if (!file.isFile() || !file.name.endsWith('.json')) continue
+ try {
+ const record = JSON.parse(await readFile(join(dir, file.name), 'utf8')) as { pid?: unknown; sessionId?: unknown }
+ if (typeof record.pid === 'number' && typeof record.sessionId === 'string' && alive(record.pid)) ids.add(record.sessionId)
+ } catch { /* one being written, or gone */ }
+ }
+ for (const path of await (this.opts.openRollouts ?? openCodexRollouts)().catch(() => [])) {
+ const id = /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i.exec(path)?.[1]
+ if (id) ids.add(id)
+ }
+ return ids
+ }
+}
+
+function processAlive(pid: number): boolean {
+ try { process.kill(pid, 0); return true } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM' }
+}
+
+/** The rollout files Codex processes have open: `lsof` over processes named codex. */
+function openCodexRollouts(): Promise<string[]> {
+ return new Promise((resolve) => {
+ execFile('lsof', ['-n', '-P', '-Fn', '-c', 'codex', '-c', 'Codex'], { timeout: 3_000, maxBuffer: 8 * 1024 * 1024 }, (_error, stdout) => {
+ // lsof exits 1 when a name matches no process; what it printed is still the answer.
+ resolve(String(stdout ?? '').split('\n')
+ .filter((line) => line.startsWith('n') && line.includes('rollout-') && line.endsWith('.jsonl'))
+ .map((line) => line.slice(1)))
+ })
+ })
+}
diff --git a/cli/src/lib/sessionSearch/indexer.spec.ts b/cli/src/lib/sessionSearch/indexer.spec.ts
index 46bbebf77..9032a9e28 100644
--- a/cli/src/lib/sessionSearch/indexer.spec.ts
+++ b/cli/src/lib/sessionSearch/indexer.spec.ts
@@ -99,6 +99,48 @@ describe('SessionSearchIndex', () => {
expect(await index.tail('unknown')).toBeNull()
})
+ it("indexes a conversation Harness did not start under its own title, says if it is open, and drops it with its file", async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'session-search-external-'))
+ dirs.push(dir)
+ const titled = (type: string, key: string, title: string) => JSON.stringify({ type, [key]: title, sessionId: 'e1' }) + '\n'
+ const claudeFile = join(dir, 'e1.jsonl')
+ writeFileSync(claudeFile, prompt('why does the dial scroll jump', 0) + titled('ai-title', 'aiTitle', 'Dial scroll jump')
+ + answer('The delta is doubled.', 1) + titled('custom-title', 'customTitle', 'Dial fix') + titled('ai-title', 'aiTitle', 'Later AI title'))
+ const untitledFile = join(dir, 'e2.jsonl')
+ writeFileSync(untitledFile, prompt('compare retention\nby cohort please', 0) + answer('Day-7 is 35%.', 1))
+ const store = SessionSearchStore.open(':memory:')!
+ const open = new Set(['e1'])
+ let sources: SearchSource[] = [
+ { agentId: '', sessionId: 'e1', engine: 'claude', transcriptPath: claudeFile, header: '', updatedAt: 2, external: { cwd: '/work/dial', origin: 'terminal', title: '' } },
+ { agentId: '', sessionId: 'e2', engine: 'claude', transcriptPath: untitledFile, header: '', updatedAt: 1, external: { cwd: '/work/cohorts', origin: 'claude-app', title: '' } },
+ ]
+ const index = new SessionSearchIndex({
+ store, sources: () => sources, agents: () => [],
+ openSessions: { known: () => open, fresh: async () => open },
+ })
+ cleanups.push(() => { index.stop(); store.close() })
+ const settle = async () => {
+ index.sweep()
+ await vi.waitFor(() => { expect((index as unknown as { running: boolean }).running).toBe(false) })
+ }
+ await settle()
+ // The person's own title wins over Claude's; with none, the first ask, on one line.
+ expect(store.session('e1')).toMatchObject({ agentId: '', title: 'Dial fix', cwd: '/work/dial', origin: 'terminal' })
+ expect(store.session('e2')?.title).toBe('compare retention by cohort please')
+ // Found by its title, marked as not Harness's, and as open elsewhere.
+ const hit = index.search('dial fix').hits[0]
+ expect(hit).toMatchObject({ sessionId: 'e1', agentId: '', external: { title: 'Dial fix', cwd: '/work/dial', origin: 'terminal', open: true } })
+ expect(index.search('cohort').hits[0]).toMatchObject({ sessionId: 'e2', external: { origin: 'claude-app', open: false } })
+ const tail = await index.tail('e1')
+ expect(tail?.external).toEqual({ title: 'Dial fix', cwd: '/work/dial', origin: 'terminal', open: true })
+
+ // Its file gone, it leaves the index at the next sweep.
+ sources = sources.filter((source) => source.sessionId !== 'e2')
+ await settle()
+ expect(store.session('e2')).toBeUndefined()
+ expect(store.session('e1')).toBeDefined()
+ })
+
it('starts over when the transcript was rewritten shorter', async () => {
const { path, found, settle } = setup(prompt('first long conversation about cohorts and retention', 0) + answer('Done with the cohort table.', 1))
await settle()
diff --git a/cli/src/lib/sessionSearch/indexer.ts b/cli/src/lib/sessionSearch/indexer.ts
index fd2c8d246..f015028a5 100644
--- a/cli/src/lib/sessionSearch/indexer.ts
+++ b/cli/src/lib/sessionSearch/indexer.ts
@@ -38,6 +38,45 @@ export interface SearchSource {
* resume from.
*/
readHistory?: () => Promise<readonly LiveEvent[]>
+ /**
+ * A conversation Harness did not start (external.ts). Its `agentId` is empty and its header is made
+ * here, from its title and folder: the title the engine gave it (Codex's thread name here; Claude's
+ * read from its transcript as it is indexed), else what was first asked in it.
+ */
+ external?: { cwd: string; origin: string; title: string }
+}
+
+/** Claude Code's titles in a transcript: its own, and one the person gave (which wins). */
+const CLAUDE_TITLE = /"type":"(ai-title|custom-title)"/
+
+/** The title a Claude Code line gives, kept over [current] unless it is the person's own. */
+function claudeTitle(line: string, current: { title: string; custom: boolean } | null): { title: string; custom: boolean } | null {
+ try {
+ const record = JSON.parse(line) as { type?: unknown; aiTitle?: unknown; customTitle?: unknown }
+ if (record.type === 'custom-title' && typeof record.customTitle === 'string' && record.customTitle.trim()) {
+ return { title: record.customTitle, custom: true }
+ }
+ if (record.type === 'ai-title' && typeof record.aiTitle === 'string' && record.aiTitle.trim() && !current?.custom) {
+ return { title: record.aiTitle, custom: false }
+ }
+ } catch { /* not a title after all */ }
+ return current
+}
+
+/** A title as a header holds it: one line, not an essay. */
+function titleLine(text: string): string {
+ const line = text.replace(/\s+/g, ' ').trim()
+ return line.length > 80 ? `${line.slice(0, 79).trimEnd()}…` : line
+}
+
+function headerFor(source: SearchSource, title: string): string {
+ return source.external ? [title, folderWords(source.external.cwd)].filter(Boolean).join(' · ') : source.header
+}
+
+function externalFields(source: SearchSource, title: string): Pick<IndexedSession, 'title' | 'cwd' | 'origin'> {
+ return source.external
+ ? { title, cwd: source.external.cwd, origin: source.external.origin }
+ : { title: '', cwd: '', origin: '' }
}
export interface SessionSearchResult {
@@ -60,6 +99,13 @@ export interface SessionSearchIndexOptions {
*/
agents?: () => Iterable<string>
log?: (line: string) => void
+ /**
+ * Which sessions are open in a running process right now (external.ts `OpenSessions`), so a
+ * conversation Harness did not start says whether a terminal still has it. `known` never waits.
+ */
+ openSessions?: { known(): ReadonlySet<string>; fresh(): Promise<ReadonlySet<string>> }
+ /** Looks again for conversations Harness did not start, before each sweep lists its sources. */
+ discover?: () => Promise<unknown>
/** Between full sweeps. */
sweepEveryMs?: number
/** How long a pass may hold the thread before yielding. */
@@ -135,13 +181,25 @@ export class SessionSearchIndex {
/** Queue every known session, newest first; drop sessions whose agent no longer exists. */
sweep(): void {
+ if (this.stopped) return
+ if (this.opts.discover) {
+ // Which of them are open, looked at now: a search reads it without waiting.
+ void this.opts.openSessions?.fresh().catch(() => undefined)
+ void this.opts.discover().catch(() => undefined).then(() => this.sweepSources())
+ return
+ }
+ this.sweepSources()
+ }
+
+ private sweepSources(): void {
if (this.stopped) return
this.refreshSources(true)
const agents = new Set(this.opts.agents?.() ?? [...this.sources.values()].map((source) => source.agentId))
for (const sessionId of this.opts.store.sessionIds()) {
- // An agent's earlier sessions (before a /clear) stay findable while the agent exists.
+ // An agent's earlier sessions (before a /clear) stay findable while the agent exists; one
+ // Harness did not start, while its file does.
const indexed = this.opts.store.session(sessionId)
- if (indexed && !agents.has(indexed.agentId)) this.opts.store.removeSession(sessionId)
+ if (indexed && !agents.has(indexed.agentId) && !this.sources.has(sessionId)) this.opts.store.removeSession(sessionId)
}
const newest = [...this.sources.values()].sort((a, b) => b.updatedAt - a.updatedAt)
for (const source of newest) this.queue.add(source.sessionId)
@@ -151,6 +209,11 @@ export class SessionSearchIndex {
search(query: string, options: { limit?: number; from?: number; to?: number } = {}): SessionSearchResult {
const started = performance.now()
const hits = this.opts.store.search(query, options)
+ // Whether a terminal still has it, as last looked: a search never waits for a process table.
+ if (hits.some((hit) => hit.external) && this.opts.openSessions) {
+ const open = this.opts.openSessions.known()
+ for (const hit of hits) if (hit.external) hit.external.open = open.has(hit.sessionId)
+ }
const indexed = this.opts.store.counts().sessions
return { hits, indexed, pending: this.queue.size, tookMs: Math.round((performance.now() - started) * 10) / 10 }
}
@@ -177,7 +240,19 @@ export class SessionSearchIndex {
clearTimeout(timer)
}
}
- return this.opts.store.tail(sessionId, options)
+ const tail = this.opts.store.tail(sessionId, options)
+ const session = tail && this.opts.store.session(sessionId)
+ if (tail && session && !session.agentId) {
+ // A preview of a conversation Harness did not start says whether a terminal has it, as of now.
+ const open = await this.opts.openSessions?.fresh().catch(() => null)
+ tail.external = { title: session.title ?? '', cwd: session.cwd ?? '', origin: session.origin ?? '', open: open?.has(sessionId) ?? false }
+ }
+ return tail
+ }
+
+ /** What the index holds about one session. */
+ session(sessionId: string): IndexedSession | undefined {
+ return this.opts.store.session(sessionId)
}
/** Moves a session to the head of the queue. */
@@ -238,7 +313,8 @@ export class SessionSearchIndex {
if (!source.transcriptPath && source.readHistory) return this.historyPass(source, existing, dirty)
const normalize = source.transcriptPath ? lineNormalizer(source.engine, source.sessionId) : null
const file = source.transcriptPath && normalize ? await stat(source.transcriptPath).catch(() => null) : null
- const header = source.header
+ const knownTitle = source.external ? source.external.title || existing?.title || '' : ''
+ const header = headerFor(source, knownTitle)
if (!file || !source.transcriptPath || !normalize) {
// Nothing to read (a terminal, a database-backed engine, a missing file): its name is still findable.
if (existing?.header === header && existing.agentId === source.agentId) return
@@ -248,6 +324,7 @@ export class SessionSearchIndex {
size: existing?.size ?? 0, mtime: existing?.mtime ?? 0,
resumeOffset: existing?.resumeOffset ?? 0, resumeTurn: existing?.resumeTurn ?? 0,
lastAt: existing?.lastAt ?? (source.updatedAt || null), turns: 0,
+ ...externalFields(source, knownTitle),
}, NO_TURN_DELETE, [])
return
}
@@ -256,7 +333,7 @@ export class SessionSearchIndex {
const samePath = existing?.path === path
if (samePath && existing.size === file.size && existing.mtime === mtime) {
if (existing.header !== header || existing.agentId !== source.agentId) {
- store.writeSession({ ...existing, header, agentId: source.agentId }, NO_TURN_DELETE, [])
+ store.writeSession({ ...existing, header, agentId: source.agentId, ...externalFields(source, knownTitle) }, NO_TURN_DELETE, [])
}
return
}
@@ -266,24 +343,32 @@ export class SessionSearchIndex {
const fromTurn = resume ? existing.resumeTurn : 0
const collector = new TurnCollector(fromTurn)
let lastAt: number | null = null
+ let named: { title: string; custom: boolean } | null = null
this.sliceStart = performance.now()
const { end } = await forEachLine(path, from, async ({ text, offset }) => {
const at = lineTime(text) ?? lastAt
if (at !== null && (lastAt === null || at > lastAt)) lastAt = at
+ if (source.external && CLAUDE_TITLE.test(text)) named = claudeTitle(text, named)
collector.feed(normalize(text), offset, at)
await this.pace()
}, { skip: skipPredicate(source.engine), shouldStop: () => this.stopped })
if (this.stopped) return
const { closed, open } = collector.finish()
+ const turns = open ? [...closed, open] : closed
+ const firstAsk = fromTurn === 0 ? turns.find((turn) => turn.ask)?.ask ?? '' : ''
+ const title = source.external
+ ? titleLine(source.external.title || (named as { title: string } | null)?.title || existing?.title || firstAsk)
+ : ''
const session: IndexedSession = {
- sessionId: source.sessionId, agentId: source.agentId, engine: source.engine, path, header,
+ sessionId: source.sessionId, agentId: source.agentId, engine: source.engine, path,
+ header: headerFor(source, title),
size: file.size, mtime,
resumeOffset: open ? open.offset : end,
resumeTurn: open ? open.turn : collector.next,
lastAt: lastAt ?? (resume ? existing.lastAt : null) ?? mtime,
turns: 0,
+ ...externalFields(source, title),
}
- const turns = open ? [...closed, open] : closed
// A long session's first pass writes hundreds of rows. In one transaction that held the thread for
// 130 ms, so rows go in batches, each but the last saved as a pass that stopped at the next batch:
// a daemon stopped between them resumes there.
diff --git a/cli/src/lib/sessionSearch/store.ts b/cli/src/lib/sessionSearch/store.ts
index d0486552f..afefeac7a 100644
--- a/cli/src/lib/sessionSearch/store.ts
+++ b/cli/src/lib/sessionSearch/store.ts
@@ -16,7 +16,7 @@ import { chmodSync, existsSync, rmSync } from 'node:fs'
import { builtinSqlite } from '../sqliteRead.js'
import type { IndexedTurn } from './turns.js'
-const SCHEMA_VERSION = '7'
+const SCHEMA_VERSION = '8'
/** The row that holds a session's name, title and folder: searchable beside its turns. */
export const HEADER_TURN = -1
@@ -48,6 +48,23 @@ export interface IndexedSession {
resumeTurn: number
lastAt: number | null
turns: number
+ /**
+ * A conversation Harness did not start (lib/sessionSearch/external.ts), whose `agentId` is empty:
+ * its title (Codex's thread name, Claude's own title, else the first ask), the folder it resumes in,
+ * and where it ran. Empty for a Harness session.
+ */
+ title?: string
+ cwd?: string
+ origin?: string
+}
+
+/** What a hit on a conversation Harness did not start carries, so a client can show and resume it. */
+export interface ExternalHit {
+ title: string
+ cwd: string
+ origin: string
+ /** Open in a running process elsewhere (a terminal, the engine's app): not to be opened twice. */
+ open?: boolean
}
export interface SearchHit {
@@ -68,6 +85,8 @@ export interface SearchHit {
together: boolean
/** 0–1, higher is better: relevance blended with recency; comparable across machines. */
score: number
+ /** Set for a conversation Harness did not start; its `agentId` is then empty. */
+ external?: ExternalHit
}
// BM25 column weights: header (name/title/folder), what was asked, the answer, tool calls.
@@ -117,6 +136,8 @@ export interface SessionTail {
* continuation rows up, and it is what the session is doing now.
*/
lastAsk?: TailRow
+ /** For a conversation Harness did not start: what a hit on it carries, and whether it is open. */
+ external?: ExternalHit
}
/** What one preview page holds, and what a caller may ask for. */
@@ -314,7 +335,10 @@ export class SessionSearchStore {
resume_offset INTEGER NOT NULL,
resume_turn INTEGER NOT NULL,
last_at INTEGER,
- turns INTEGER NOT NULL
+ turns INTEGER NOT NULL,
+ title TEXT NOT NULL DEFAULT '',
+ cwd TEXT NOT NULL DEFAULT '',
+ origin TEXT NOT NULL DEFAULT ''
);
CREATE TABLE turns (
id INTEGER PRIMARY KEY,
@@ -368,13 +392,16 @@ export class SessionSearchStore {
}
/** Who each session belongs to and when it was last worked on, read once per change. */
- private meta: Map<string, { agentId: string; engine: string; lastAt: number | null }> | null = null
+ private meta: Map<string, SessionMeta> | null = null
- private sessionMeta(): Map<string, { agentId: string; engine: string; lastAt: number | null }> {
+ private sessionMeta(): Map<string, SessionMeta> {
if (!this.meta) {
- this.meta = new Map(this.statement('SELECT session_id, agent_id, engine, last_at FROM sessions').all().map((row) => [
+ this.meta = new Map(this.statement('SELECT session_id, agent_id, engine, last_at, title, cwd, origin FROM sessions').all().map((row) => [
row.session_id as string,
- { agentId: row.agent_id as string, engine: row.engine as string, lastAt: (row.last_at as number | null) ?? null },
+ {
+ agentId: row.agent_id as string, engine: row.engine as string, lastAt: (row.last_at as number | null) ?? null,
+ ...(row.agent_id ? {} : { external: { title: String(row.title ?? ''), cwd: String(row.cwd ?? ''), origin: String(row.origin ?? '') } }),
+ },
]))
}
return this.meta
@@ -433,6 +460,11 @@ export class SessionSearchStore {
return tail
}
+ /** Sessions the index files under a Harness agent, earlier ones (before a `/clear`) included. */
+ ownedSessionIds(): Set<string> {
+ return new Set(this.statement("SELECT session_id FROM sessions WHERE agent_id != ''").all().map((row) => row.session_id as string))
+ }
+
sessionIds(): string[] {
return this.statement('SELECT session_id FROM sessions').all().map((row) => row.session_id as string)
}
@@ -451,10 +483,11 @@ export class SessionSearchStore {
for (const turn of turns) insert.run(session.sessionId, turn.turn, turn.at, '', turn.ask, turn.answer, turn.tools)
const count = this.statement('SELECT count(*) AS n FROM turns WHERE session_id = ? AND turn >= 0').get(session.sessionId)?.n as number
this.statement(`INSERT OR REPLACE INTO sessions
- (session_id, agent_id, engine, path, header, size, mtime, resume_offset, resume_turn, last_at, turns)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
+ (session_id, agent_id, engine, path, header, size, mtime, resume_offset, resume_turn, last_at, turns, title, cwd, origin)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
session.sessionId, session.agentId, session.engine, session.path, session.header, session.size,
session.mtime, session.resumeOffset, session.resumeTurn, session.lastAt, count,
+ session.title ?? '', session.cwd ?? '', session.origin ?? '',
)
})
}
@@ -632,6 +665,7 @@ export class SessionSearchStore {
snippet,
together: match.together,
score: Math.round(score * 1000) / 1000,
+ ...externalOf(session),
}
})
}
@@ -692,6 +726,7 @@ export class SessionSearchStore {
snippet: clipAsk(asked || String(row.answer ?? '')),
together: true,
score: Math.round(Math.pow(0.5, Math.max(0, now - at) / 86_400_000 / RECENCY_HALF_LIFE_DAYS) * 1000) / 1000,
+ ...externalOf(session),
})
}
return hits
@@ -723,5 +758,16 @@ function toSession(row: Record<string, unknown>): IndexedSession {
resumeTurn: row.resume_turn as number,
lastAt: (row.last_at as number | null) ?? null,
turns: row.turns as number,
+ title: String(row.title ?? ''),
+ cwd: String(row.cwd ?? ''),
+ origin: String(row.origin ?? ''),
}
}
+
+type SessionMeta = { agentId: string; engine: string; lastAt: number | null; external?: ExternalHit }
+
+/** The fields a hit on a session Harness did not start adds. */
+function externalOf(session: SessionMeta): { external: ExternalHit } | Record<string, never> {
+ // A copy: a search marks whether it is open, and the cache it came from outlives the search.
+ return session.external ? { external: { ...session.external } } : {}
+}
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 9cb2414d0..24bd67fad 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -2450,19 +2450,23 @@ class _SwarmScreenState extends State<SwarmScreen> {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(failure.message),
- action: SnackBarAction(
- label: 'Start New Conversation',
- onPressed: () => _openNewHarness(
- machineId: row.machineId!,
- engine: agent?.dsh ?? agent?.engine,
- folder: agent?.project?.cwd,
- swarmId: app.swarms.any((tab) => tab.id == target)
- ? target
- : app.activeSwarmId,
- placement: placement,
- task: '',
- ),
- ),
+ // A conversation Harness did not start says what stopped it (open in
+ // a terminal, gone); a new, empty one is not what was asked for.
+ action: row.external != null
+ ? null
+ : SnackBarAction(
+ label: 'Start New Conversation',
+ onPressed: () => _openNewHarness(
+ machineId: row.machineId!,
+ engine: agent?.dsh ?? agent?.engine,
+ folder: agent?.project?.cwd,
+ swarmId: app.swarms.any((tab) => tab.id == target)
+ ? target
+ : app.activeSwarmId,
+ placement: placement,
+ task: '',
+ ),
+ ),
),
);
}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index a9d014ce4..c145ff5ea 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -7296,7 +7296,6 @@ class AppNotifier extends ChangeNotifier {
AgentCreationAttempt? attempt,
HarnessPlacement? placement,
}) {
- final creation = attempt ?? AgentCreationAttempt();
final choices = <String, dynamic>{
'engine': engine,
if (projectFolder == null && folder != null) 'cwd': folder,
@@ -7326,6 +7325,55 @@ class AppNotifier extends ChangeNotifier {
// same refusal for an engine that has no such thing (`AGENT_UNSUPPORTED`).
'agent': ?agent,
};
+ return _create(
+ machineId,
+ choices,
+ projectFolder: projectFolder,
+ dsh: dsh,
+ swarmId: swarmId,
+ split: split,
+ attempt: attempt,
+ placement: placement,
+ );
+ }
+
+ /// A Claude Code or Codex conversation Harness did not start, opened as a
+ /// harness that resumes it, in its own folder (Cmd-P, `ExternalSessionRef`).
+ /// The machine refuses one open elsewhere, already a harness, or whose folder
+ /// is gone, and says why. Null when it started; otherwise what to tell the
+ /// person.
+ Future<String?> resumeConversation(
+ String machineId, {
+ required String engine,
+ required String folder,
+ required String sessionId,
+ String? name,
+ String? swarmId,
+ HarnessPlacement? placement,
+ }) => _create(
+ machineId,
+ {
+ 'engine': engine,
+ 'cwd': folder,
+ 'bypassPermission': true,
+ 'name': ?name,
+ 'resumeSessionId': sessionId,
+ },
+ swarmId: swarmId,
+ placement: placement,
+ );
+
+ Future<String?> _create(
+ String machineId,
+ Map<String, dynamic> choices, {
+ ProjectFolderRequest? projectFolder,
+ String? dsh,
+ String? swarmId,
+ PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
+ }) {
+ final creation = attempt ?? AgentCreationAttempt();
if (creation._choices != null &&
(creation._machineId != machineId ||
creation._projectFolder?.isGenerated !=
@@ -7438,6 +7486,14 @@ class AppNotifier extends ChangeNotifier {
'This engine cannot be opened as that named agent on $machine.',
'INVALID_PERMISSION_MODE' =>
'This engine has no such permission mode on $machine.',
+ // Opening a conversation Harness did not start (`resumeSessionId`). The
+ // machine says what stopped it: open elsewhere, already a harness, gone.
+ 'SESSION_OPEN_ELSEWHERE' ||
+ 'SESSION_IN_HARNESS' ||
+ 'SESSION_NOT_FOUND' ||
+ 'SESSION_FOLDER_GONE' ||
+ 'INVALID_SESSION' =>
+ detail ?? 'Could not open that conversation on $machine.',
// A daemon that predates the terminal engine refuses it by name; the
// fix is the same one the other UNSUPPORTED codes ask for.
'INVALID_ENGINE' =>
@@ -7641,6 +7697,12 @@ class AppNotifier extends ChangeNotifier {
'GRID_CONFIG_FAILED',
'UNSUPPORTED_ON_REMOTE',
'UNSUPPORTED',
+ // A conversation Harness did not start, refused before its pane opens.
+ 'SESSION_OPEN_ELSEWHERE',
+ 'SESSION_IN_HARNESS',
+ 'SESSION_NOT_FOUND',
+ 'SESSION_FOLDER_GONE',
+ 'INVALID_SESSION',
};
if (refusedBeforeLaunch.contains(failure.code)) {
if (failure.code == 'INVALID_CWD' && choices['projectSource'] != null) {
diff --git a/desktop/lib/state/session_content_search.dart b/desktop/lib/state/session_content_search.dart
index 6682f5a34..7f5898dec 100644
--- a/desktop/lib/state/session_content_search.dart
+++ b/desktop/lib/state/session_content_search.dart
@@ -3,7 +3,8 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import 'search_when.dart';
-import 'swarm_navigation.dart' show agentDestinationId;
+import 'swarm_navigation.dart'
+ show ExternalSessionRef, agentDestinationId, externalDestinationId;
/// Where a machine's daemon marks each matched word in a snippet.
const kSnippetMarkOpen = '\u0002';
@@ -25,10 +26,18 @@ class SessionContentHit {
this.position = 0,
this.turn = 0,
this.at,
+ this.lastAt,
+ this.external,
});
final String machineId, agentId, sessionId;
+ /// A conversation Harness did not start, whose [agentId] is empty.
+ final ExternalSessionRef? external;
+
+ /// When the session was last worked on.
+ final DateTime? lastAt;
+
/// `ask`, `answer`, `tools` or `name`: which part of the turn matched.
final String field;
@@ -51,7 +60,9 @@ class SessionContentHit {
/// When the matching turn happened, when the transcript says.
final DateTime? at;
- String get destinationId => agentDestinationId(machineId, agentId);
+ String get destinationId => external == null
+ ? agentDestinationId(machineId, agentId)
+ : externalDestinationId(machineId, sessionId);
/// The snippet as plain text, marks removed.
String get plainSnippet => snippet
@@ -67,11 +78,15 @@ class SessionContentHit {
final agentId = raw['agentId'];
final sessionId = raw['sessionId'];
final snippet = raw['snippet'];
- if (agentId is! String || agentId.isEmpty || sessionId is! String) {
+ final external = _external(raw, sessionId);
+ if (agentId is! String ||
+ (agentId.isEmpty && external == null) ||
+ sessionId is! String) {
return null;
}
final score = raw['score'];
final at = raw['at'];
+ final lastAt = raw['lastAt'];
final turn = raw['turn'];
return SessionContentHit(
machineId: machineId,
@@ -88,6 +103,30 @@ class SessionContentHit {
position: position,
turn: turn is int ? turn : 0,
at: at is int ? DateTime.fromMillisecondsSinceEpoch(at) : null,
+ lastAt: lastAt is int ? DateTime.fromMillisecondsSinceEpoch(lastAt) : null,
+ external: agentId.isEmpty ? external : null,
+ );
+ }
+
+ /// A hit on a conversation Harness did not start: the daemon says where it
+ /// resumes and where it ran. Null when the hit is a harness's.
+ static ExternalSessionRef? _external(Map raw, Object? sessionId) {
+ final external = raw['external'];
+ final engine = raw['engine'];
+ if (external is! Map || sessionId is! String || engine is! String) {
+ return null;
+ }
+ final cwd = external['cwd'];
+ if (cwd is! String || !cwd.startsWith('/')) return null;
+ final title = external['title'];
+ final origin = external['origin'];
+ return ExternalSessionRef(
+ sessionId: sessionId,
+ engine: engine,
+ cwd: cwd,
+ origin: origin is String ? origin : 'terminal',
+ title: title is String ? title : '',
+ open: external['open'] == true,
);
}
diff --git a/desktop/lib/state/session_tail.dart b/desktop/lib/state/session_tail.dart
index 54a5f9792..b6cf5a2b5 100644
--- a/desktop/lib/state/session_tail.dart
+++ b/desktop/lib/state/session_tail.dart
@@ -52,6 +52,7 @@ class SessionTail {
required this.total,
required this.fetchedAt,
this.lastAsk,
+ this.openElsewhere = false,
});
final List<SessionTailRow> rows;
@@ -63,6 +64,10 @@ class SessionTail {
/// rows up, and it is what the session is doing now.
final SessionTailRow? lastAsk;
+ /// For a conversation Harness did not start: open in a running process
+ /// elsewhere, as its machine found when it answered.
+ final bool openElsewhere;
+
static SessionTail? fromReply(Map<String, dynamic> reply, DateTime now) {
final rows = reply['rows'];
if (rows is! List) return null;
@@ -72,6 +77,9 @@ class SessionTail {
total: reply['total'] is int ? reply['total'] as int : rows.length,
fetchedAt: now,
lastAsk: SessionTailRow.fromJson(reply['lastAsk']),
+ openElsewhere:
+ reply['external'] is Map &&
+ (reply['external'] as Map)['open'] == true,
);
}
}
@@ -173,6 +181,7 @@ class SessionTails extends ChangeNotifier {
total: page.total,
fetchedAt: page.fetchedAt,
lastAsk: page.lastAsk,
+ openElsewhere: page.openElsewhere,
),
);
}
@@ -207,6 +216,7 @@ class SessionTails extends ChangeNotifier {
total: current.total,
fetchedAt: current.fetchedAt,
lastAsk: current.lastAsk,
+ openElsewhere: current.openElsewhere,
),
);
} finally {
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
index 4ff08b519..26fecbb05 100644
--- a/desktop/lib/state/swarm_navigation.dart
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -4,7 +4,7 @@ import 'dart:async';
import 'dart:convert';
import 'package:collection/collection.dart' show compareNatural;
-import 'package:flutter/foundation.dart' show listEquals, setEquals;
+import 'package:flutter/foundation.dart' show immutable, listEquals, setEquals;
import '../core/fuzzy_match.dart';
import '../core/local_key_value_store.dart';
@@ -239,6 +239,42 @@ class SwarmNavigationHistory {
}
}
+/// A Claude Code or Codex conversation Harness did not start, on one machine:
+/// run in a terminal or in the engine's own app, found on disk by that
+/// machine's daemon (cli/src/lib/sessionSearch/external.ts). Cmd-P shows one
+/// when a search matches it, and opens it as a new harness resuming it.
+@immutable
+class ExternalSessionRef {
+ const ExternalSessionRef({
+ required this.sessionId,
+ required this.engine,
+ required this.cwd,
+ required this.origin,
+ this.title = '',
+ this.open = false,
+ });
+
+ final String sessionId, engine, cwd, title;
+
+ /// `terminal`, `claude-app`, `codex-app` or `editor`.
+ final String origin;
+
+ /// Open in a running process elsewhere: opening it here too would have two
+ /// processes writing one conversation.
+ final bool open;
+
+ /// Where it ran, as a person says it.
+ String get originLabel => switch (origin) {
+ 'claude-app' => 'Claude app',
+ 'codex-app' => 'Codex app',
+ 'editor' => 'editor',
+ _ => 'terminal',
+ };
+}
+
+String externalDestinationId(String machineId, String sessionId) =>
+ 'external:$machineId:$sessionId';
+
/// A searchable snapshot. Resolving a result again at activation prevents live
/// discovery or a closed tab from redirecting an action to unrelated work.
class SwarmDestination {
@@ -270,6 +306,7 @@ class SwarmDestination {
this.isStore = false,
this.isCreate = false,
this.task,
+ this.external,
Iterable<String?> searchFields = const [],
int titleFields = 1,
}) : fields = [
@@ -323,11 +360,18 @@ class SwarmDestination {
/// What the create row would start the new harness on: what was typed.
final String? task;
+
+ /// A conversation Harness did not start; opening it resumes it as a harness.
+ final ExternalSessionRef? external;
final bool current;
final List<String> fields;
bool get isProject => projectId != null;
bool get isMachine =>
- agentId == null && machineId != null && !isProject && !isModel;
+ agentId == null &&
+ machineId != null &&
+ !isProject &&
+ !isModel &&
+ external == null;
bool get isGroup => isProject || isMachine;
bool get isSwarm =>
agentId == null &&
@@ -336,7 +380,8 @@ class SwarmDestination {
!isCreate &&
!isModel &&
!isStoreEntry &&
- pickerQuery == null;
+ pickerQuery == null &&
+ external == null;
bool get hasView => swarmId != null;
}
@@ -794,6 +839,23 @@ Future<bool> activateSwarmSearchSelection(
HarnessPlacement? placement,
}) async {
final destination = selection.destination;
+ if (destination.external case final external?) {
+ final machineId = destination.machineId;
+ if (machineId == null || split != null) return false;
+ // A new harness that resumes it, in its own folder: the machine refuses one
+ // that is open elsewhere, or already a harness, and says so.
+ final error = await app.resumeConversation(
+ machineId,
+ engine: external.engine,
+ folder: external.cwd,
+ sessionId: external.sessionId,
+ name: external.title.isEmpty ? null : external.title,
+ swarmId: destinationSwarmId,
+ placement: placement ?? HarnessPlacement.currentTab,
+ );
+ if (error != null) throw SwarmResumeFailure(destination, error);
+ return true;
+ }
if (placement != null) {
final machineId = destination.machineId;
final agentId = destination.agentId;
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 08f80d63f..dd0a9b2f8 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -1176,6 +1176,29 @@ class SwarmSearchController extends ChangeNotifier {
..._heldRows.values.where((row) => !present.contains(row.id)),
];
}
+ // Conversations Harness did not start, found by what was said in them: a
+ // row only while a search matches one, never in the list as it opens.
+ if (byActivity &&
+ _contentQuery.isNotEmpty &&
+ scopedBranch == null &&
+ _groupScope == null &&
+ split == null) {
+ final present = {for (final row in candidates) row.id};
+ candidates = [
+ ...candidates,
+ for (final hit
+ in _content?.hitsFor(_contentQuery).values ??
+ const <SessionContentHit>[])
+ if (hit.external case final external?
+ when !present.contains(hit.destinationId))
+ externalSessionDestination(
+ hit,
+ external,
+ machineLabel:
+ app.stateOf(hit.machineId)?.machine.displayName ?? '',
+ ),
+ ];
+ }
total = candidates.length;
rows = isCommandMode
? _recentFirst(rankSwarmDestinations(availableCommands, commandQuery))
@@ -1508,6 +1531,23 @@ class SwarmSearchController extends ChangeNotifier {
/// Read live state at activation too: a rendered row can outlive a disconnect.
String? sessionUnavailable(SwarmDestination? row) {
+ if (row?.external case final external?) {
+ // Short: it is a row's note. The preview says what to do about it. Its
+ // preview's answer is the fresher, when there is one.
+ final previewed = app.sessionTails.read((
+ machineId: row!.machineId ?? '',
+ sessionId: external.sessionId,
+ ));
+ if (external.open || previewed?.openElsewhere == true) {
+ return external.origin == 'terminal'
+ ? 'Open in another terminal'
+ : 'Open in the ${external.originLabel}';
+ }
+ final machine = app.stateOf(row.machineId ?? '');
+ return machine == null || machine.nodeOnline == false
+ ? 'Its machine is offline.'
+ : null;
+ }
if (!setupLayout || row?.agentId == null) return null;
final machine = app.stateOf(row!.machineId!);
final agent = machine?.agents
@@ -1554,29 +1594,43 @@ class SwarmSearchController extends ChangeNotifier {
bool alreadyHere(SwarmDestination row) =>
adding && row.agentId != null && _presentIds.contains(row.id);
- bool canAdd(SwarmDestination? row) =>
- !navigating &&
- history == null &&
- row != null &&
- sessionUnavailable(row) == null &&
- !row.isCommand &&
- !row.isModel &&
- !row.isStoreEntry &&
- row.closedId == null &&
- (placement == null || row.agentId != null) &&
- (placement != null && alreadyHere(row) ||
- _hasMissing(row) &&
- (split == null || row.agentId != null) &&
- (split == null || app.isPaneSplitCurrent(split!)) &&
- (placement == HarnessPlacement.newTab ||
- app.swarms.any(
- (swarm) =>
- swarm.id == targetId &&
- !swarm.isStore &&
- !swarm.isOrchestrator &&
- swarm.panes.length + _missingCount(row) <=
- AppNotifier.maxPanes,
- )));
+ bool canAdd(SwarmDestination? row) => row?.external != null
+ // A conversation Harness did not start becomes a new harness: room for
+ // one more pane, or a tab of its own.
+ ? !navigating &&
+ history == null &&
+ split == null &&
+ sessionUnavailable(row) == null &&
+ (placement == HarnessPlacement.newTab ||
+ app.swarms.any(
+ (swarm) =>
+ swarm.id == targetId &&
+ !swarm.isStore &&
+ !swarm.isOrchestrator &&
+ swarm.panes.length < AppNotifier.maxPanes,
+ ))
+ : !navigating &&
+ history == null &&
+ row != null &&
+ sessionUnavailable(row) == null &&
+ !row.isCommand &&
+ !row.isModel &&
+ !row.isStoreEntry &&
+ row.closedId == null &&
+ (placement == null || row.agentId != null) &&
+ (placement != null && alreadyHere(row) ||
+ _hasMissing(row) &&
+ (split == null || row.agentId != null) &&
+ (split == null || app.isPaneSplitCurrent(split!)) &&
+ (placement == HarnessPlacement.newTab ||
+ app.swarms.any(
+ (swarm) =>
+ swarm.id == targetId &&
+ !swarm.isStore &&
+ !swarm.isOrchestrator &&
+ swarm.panes.length + _missingCount(row) <=
+ AppNotifier.maxPanes,
+ )));
SwarmSearchSelection? addHere() => adding || isGroupMode || isHelpMode
? submit()
@@ -1616,3 +1670,43 @@ class SwarmSearchController extends ChangeNotifier {
super.dispose();
}
}
+
+/// A Cmd-P row for a conversation Harness did not start, from the hit that
+/// found it: its title (or what was first asked), the engine and where it ran.
+SwarmDestination externalSessionDestination(
+ SessionContentHit hit,
+ ExternalSessionRef external, {
+ String machineLabel = '',
+}) {
+ final engine = switch (external.engine) {
+ 'claude' => 'Claude Code',
+ 'codex' => 'Codex',
+ final other => other,
+ };
+ final folder =
+ external.cwd.split('/').where((part) => part.isNotEmpty).lastOrNull ??
+ external.cwd;
+ final detail = [
+ engine,
+ external.originLabel,
+ folder,
+ 'not in Harness',
+ ].join(' · ');
+ return SwarmDestination(
+ id: hit.destinationId,
+ title: external.title.isEmpty ? 'Untitled conversation' : external.title,
+ detail: detail,
+ terminalDetail: [
+ detail,
+ if (machineLabel.isNotEmpty) machineLabel,
+ ].join(' · '),
+ lastActivityAt: hit.lastAt ?? hit.at,
+ swarmId: null,
+ current: false,
+ machineId: hit.machineId,
+ machineLabel: machineLabel,
+ engine: external.engine,
+ external: external,
+ searchFields: [folder, external.cwd, engine],
+ );
+}
diff --git a/desktop/lib/widgets/swarm_search_preview.dart b/desktop/lib/widgets/swarm_search_preview.dart
index f96c98361..678eecfc2 100644
--- a/desktop/lib/widgets/swarm_search_preview.dart
+++ b/desktop/lib/widgets/swarm_search_preview.dart
@@ -70,6 +70,16 @@ class SwarmSearchPreview extends StatefulWidget {
State<SwarmSearchPreview> createState() => _SwarmSearchPreviewState();
}
+/// The conversation an external row previews: its own, on its machine.
+SessionTailKey? _externalKey(SwarmDestination row) =>
+ switch ((row.external, row.machineId)) {
+ (final external?, final machineId?) => (
+ machineId: machineId,
+ sessionId: external.sessionId,
+ ),
+ _ => null,
+ };
+
/// The session a single-agent row previews the end of: the agent's current
/// one, which is what opening the row shows.
SessionTailKey? _tailKey(_PreviewAgent item) => switch (item.agent.sessionId) {
@@ -148,6 +158,10 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
], prioritize: true);
// The next rows' latest turns, so arrowing down finds them ready.
for (final neighbor in neighbors) {
+ if (_externalKey(neighbor) case final key?) {
+ app.sessionTails.want(key);
+ continue;
+ }
final items = _agents(app, neighbor);
if (neighbor.isGroup || items.length != 1) continue;
if (_tailKey(items.single) case final key?) app.sessionTails.want(key);
@@ -156,12 +170,115 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
}
void _wantTail(SwarmDestination row) {
+ if (_externalKey(row) case final key?) {
+ app.sessionTails.want(key);
+ return;
+ }
final items = _agents(app, row);
if (row.isGroup || items.length != 1) return;
final item = items.single;
if (_tailKey(item) case final key?) app.sessionTails.want(key);
}
+ /// A conversation Harness did not start: what it is and where it ran, then
+ /// its latest turns from the bottom up, as any session's.
+ Widget _external(
+ SwarmDestination row,
+ ExternalSessionRef external,
+ EdgeInsets padding,
+ Size cell,
+ TerminalTheme theme,
+ ) {
+ final terminal = widget.terminal;
+ final muted = terminal
+ ? terminalContentStyle(color: theme.foreground.withValues(alpha: .54))
+ : _muted;
+ final body = terminal
+ ? terminalContentStyle(color: theme.foreground)
+ : _body;
+ final warning = terminal ? theme.yellow : const Color(0xffe9bf79);
+ final gap = terminal ? cell.height : 12.0;
+ final key = _externalKey(row)!;
+ final tail = app.sessionTails.read(key);
+ final open = tail?.openElsewhere ?? external.open;
+ final header = Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ row.title,
+ style: terminal
+ ? body
+ : AppType.monoLabel(fontWeight: FontWeight.w600, height: 1.25),
+ ),
+ Text(row.detail, style: muted),
+ Text(
+ [
+ external.cwd,
+ if (row.machineLabel.isNotEmpty) row.machineLabel,
+ ].join(' · '),
+ style: muted,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ if (open)
+ Padding(
+ padding: EdgeInsets.only(top: gap * .5),
+ child: Text(
+ '${widget.search.sessionUnavailable(row) ?? 'Open elsewhere'}. '
+ 'Close it there to open it here.',
+ style: muted.copyWith(color: warning),
+ ),
+ ),
+ ],
+ );
+ if (tail == null || tail.rows.isEmpty) {
+ _scroll.reversed = false;
+ final found = widget.search.contentHitFor(row.id);
+ return SingleChildScrollView(
+ key: ValueKey('preview-content:${row.id}'),
+ controller: _scroll,
+ padding: padding,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ header,
+ if (found != null) ...[
+ SizedBox(height: gap),
+ SessionSnippetText(found, style: body, maxLines: null),
+ ],
+ ],
+ ),
+ );
+ }
+ _scroll.reversed = true;
+ return Column(
+ key: ValueKey('preview-content:${row.id}'),
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: padding.copyWith(bottom: gap),
+ child: header,
+ ),
+ Expanded(
+ child: SessionTailView(
+ tail: tail,
+ tails: app.sessionTails,
+ tailKey: key,
+ controller: _scroll,
+ words: [
+ for (final word in widget.search.wordsQuery.split(RegExp(r'\s+')))
+ if (word.length > 1) word,
+ ],
+ body: body,
+ muted: muted,
+ gap: gap,
+ padding: padding.copyWith(top: 0),
+ ),
+ ),
+ ],
+ );
+ }
+
/// One agent's preview: its session's latest turns from the bottom up when
/// its machine can say them, else the excerpts the live agent keeps.
Widget _single(
@@ -337,6 +454,16 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
),
);
}
+ if (row.external case final external?) {
+ final content = _external(row, external, padding, cell, theme);
+ return Semantics(
+ container: true,
+ label: 'Conversation preview',
+ child: _scroll.reversed
+ ? content
+ : Scrollbar(controller: _scroll, child: content),
+ );
+ }
final agents = _agents(app, row);
if (row.isGroup || agents.length != 1) _scroll.reversed = false;
final content = row.isGroup || agents.length != 1
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index 1c1489b40..3f4a59627 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -1419,10 +1419,16 @@ class _SearchRowContentState extends State<_SearchRowContent> {
),
] else if (widget.unavailableReason case final reason?) ...[
SizedBox(width: cell.width * 2),
- Text(
- reason,
- maxLines: 1,
- style: terminalContentStyle(color: muted),
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: constraints.maxWidth * .4,
+ ),
+ child: Text(
+ reason,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: terminalContentStyle(color: muted),
+ ),
),
] else if (row.shortcut case final shortcut?) ...[
SizedBox(width: cell.width * 2),
diff --git a/desktop/test/session_content_search_test.dart b/desktop/test/session_content_search_test.dart
index b62cc51e7..dfbb9edc8 100644
--- a/desktop/test/session_content_search_test.dart
+++ b/desktop/test/session_content_search_test.dart
@@ -99,6 +99,53 @@ void main() {
expect(SessionContentHit.listFromReply('m', {'error': 'X'}), isEmpty);
});
+ test('reads a conversation Harness did not start, and refuses one it cannot resume', () {
+ final hits = SessionContentHit.listFromReply('m', {
+ 'hits': [
+ {
+ 'agentId': '',
+ 'sessionId': '01a0c4ad-de5e-7000-8000-000000000001',
+ 'engine': 'codex',
+ 'field': 'ask',
+ 'snippet': 'compare ${_o}retention$_c',
+ 'score': .8,
+ 'lastAt': 1790000000000,
+ 'external': {
+ 'title': 'Retention cohorts',
+ 'cwd': '/work/cohorts',
+ 'origin': 'codex-app',
+ 'open': true,
+ },
+ },
+ // No folder to resume in, and no engine to resume with: not a row.
+ {
+ 'agentId': '',
+ 'sessionId': 's2',
+ 'engine': 'claude',
+ 'external': {'title': 'x'},
+ },
+ {
+ 'agentId': '',
+ 'sessionId': 's3',
+ 'external': {'cwd': '/work'},
+ },
+ {'agentId': '', 'sessionId': 's4'},
+ ],
+ });
+ expect(hits, hasLength(1));
+ final hit = hits.single;
+ expect(
+ hit.destinationId,
+ externalDestinationId('m', '01a0c4ad-de5e-7000-8000-000000000001'),
+ );
+ expect(hit.lastAt, DateTime.fromMillisecondsSinceEpoch(1790000000000));
+ expect(hit.external!.engine, 'codex');
+ expect(hit.external!.cwd, '/work/cohorts');
+ expect(hit.external!.title, 'Retention cohorts');
+ expect(hit.external!.originLabel, 'Codex app');
+ expect(hit.external!.open, isTrue);
+ });
+
test('snippet runs bold exactly the marked words', () {
expect(snippetRuns('a ${_o}dial$_c and ${_o}scroll$_c.'), [
(text: 'a ', matched: false),
diff --git a/desktop/test/session_search_rendering_test.dart b/desktop/test/session_search_rendering_test.dart
index e0cdac1cb..c7ca10b66 100644
--- a/desktop/test/session_search_rendering_test.dart
+++ b/desktop/test/session_search_rendering_test.dart
@@ -301,14 +301,170 @@ void main() {
await tester.pumpWidget(const SizedBox());
},
);
+
+ testWidgets(
+ 'a conversation Harness did not start is found, previewed, and opened as a harness resuming it',
+ (tester) async {
+ const session = '01a0c4ad-de5e-7000-8000-000000000001';
+ const busy = '01a0c4ad-de5e-7000-8000-000000000002';
+ Map<String, dynamic> external(String id, {required bool open}) => {
+ 'agentId': '',
+ 'sessionId': id,
+ 'engine': 'codex',
+ 'field': 'ask',
+ 'snippet':
+ 'compare ${kSnippetMarkOpen}retention$kSnippetMarkClose by cohort',
+ 'together': true,
+ 'score': .9,
+ 'lastAt': DateTime.now()
+ .subtract(const Duration(days: 2))
+ .millisecondsSinceEpoch,
+ 'external': {
+ 'title': open ? 'Retention, still open' : 'Retention cohorts',
+ 'cwd': '/work/cohorts',
+ 'origin': open ? 'terminal' : 'codex-app',
+ 'open': open,
+ },
+ };
+ final connection = TailConnection(
+ {
+ 'retention cohorts': [
+ external(session, open: false),
+ external(busy, open: true),
+ ],
+ },
+ tail: (payload) => {
+ 'rows': [
+ {
+ 'turn': 0,
+ 'at': DateTime.now()
+ .subtract(const Duration(days: 2))
+ .millisecondsSinceEpoch,
+ 'ask': 'compare retention by cohort',
+ 'answer': 'Day-7 retention is 35%.',
+ 'tools': '',
+ },
+ ],
+ 'hasMore': false,
+ 'total': 1,
+ 'external': {'open': payload['sessionId'] == busy},
+ },
+ create: (payload) => {
+ 'creationId': payload['creationId'],
+ 'state': 'failed',
+ 'failure': {
+ 'code': 'SESSION_OPEN_ELSEWHERE',
+ 'detail': 'It is open in another terminal or app. Close it there, then open it here.',
+ },
+ },
+ );
+ final app = createApp(
+ connected: true,
+ connectionForTest: (_) => connection,
+ );
+ final map = MemoryKeymap();
+ final projects = SwarmProjectStore();
+ addTearDown(map.dispose);
+ addTearDown(projects.dispose);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 800);
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (_, child) => grid.BrightnessScope(
+ child: KeymapProvider(keymap: map, child: child!),
+ ),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: false,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ await openHarnessPicker(tester);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'retention cohorts',
+ );
+ for (var i = 0; i < 4; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ // Found by what was said in it, as a row of its own.
+ final row = search.rows.firstWhere(
+ (row) => row.external?.sessionId == session,
+ );
+ expect(row.title, 'Retention cohorts');
+ expect(row.detail, 'Codex · Codex app · cohorts · not in Harness');
+ expect(search.canSubmit(row), isTrue);
+ final open = search.rows.firstWhere(
+ (row) => row.external?.sessionId == busy,
+ );
+ expect(search.canSubmit(open), isFalse);
+ expect(
+ search.sessionUnavailable(open),
+ contains('Open in another terminal'),
+ );
+
+ // Previewed like any session: what it is, where it ran, its latest turn.
+ while (search.selected?.id != row.id) {
+ search.move(1);
+ }
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.pump(const Duration(milliseconds: 50));
+ expect(
+ find.text('Codex · Codex app · cohorts · not in Harness'),
+ findsWidgets,
+ );
+ expect(
+ find.textContaining('Day-7 retention is 35%', findRichText: true),
+ findsOneWidget,
+ );
+
+ // Enter opens a harness resuming it; the machine's refusal is said as it said it.
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(connection.creates, hasLength(1));
+ expect(
+ connection.creates.single,
+ containsPair('resumeSessionId', session),
+ );
+ expect(connection.creates.single, containsPair('engine', 'codex'));
+ expect(connection.creates.single, containsPair('cwd', '/work/cohorts'));
+ expect(
+ connection.creates.single,
+ containsPair('name', 'Retention cohorts'),
+ );
+ expect(
+ find.text(
+ 'It is open in another terminal or app. Close it there, then open it here.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('Start New Conversation'), findsNothing);
+
+ app.dispose();
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
}
/// A machine that searches and previews: `session_tail` answered by [tail].
class TailConnection extends SearchConnection {
- TailConnection(super.answers, {required this.tail});
+ TailConnection(super.answers, {required this.tail, this.create});
final Map<String, dynamic> Function(Map<String, dynamic> payload) tail;
+ /// How `agent_create` is answered; each payload is kept in [creates].
+ final Map<String, dynamic> Function(Map<String, dynamic> payload)? create;
+ final creates = <Map<String, dynamic>>[];
+
@override
Future<Map<String, dynamic>> request(
String type, {
@@ -316,6 +472,10 @@ class TailConnection extends SearchConnection {
Duration timeout = const Duration(seconds: 20),
}) async {
if (type == 'session_tail') return tail(payload);
+ if (type == 'agent_create' && create != null) {
+ creates.add(payload);
+ return create!(payload);
+ }
return super.request(type, payload: payload, timeout: timeout);
}
}
diff --git a/docs/research/2026-09-26-session-search.md b/docs/research/2026-09-26-session-search.md
index 2b28589ca..d63171c43 100644
--- a/docs/research/2026-09-26-session-search.md
+++ b/docs/research/2026-09-26-session-search.md
@@ -280,6 +280,35 @@ socket, about 0.4 s from another machine over the relay.
dropped: they were never said in the conversation. Schema 7 rebuilds each index once.
- Group rows, and machines whose CLI predates `session_tail`, keep the excerpt preview.
+## Conversations Harness did not start
+
+⌘P also finds Claude Code and Codex conversations run in a terminal or in the engines' own apps, and
+Enter opens one as a harness resuming it (`lib/sessionSearch/external.ts`).
+
+- **Found on disk.** Every local Codex session, whether from the terminal, the Codex app or a
+ script, is a rollout under `~/.codex/sessions/YYYY/MM/DD/`. Its first line says who wrote it:
+ `source` `cli` (terminal) or `vscode` (the Codex app, `originator` "Codex Desktop", and the
+ editors). Thread names are in `~/.codex/session_index.jsonl`. Claude Code's are under
+ `~/.claude/projects/<folder>/`, with `entrypoint` `cli` or `claude-desktop`. Claude's title is
+ the latest `ai-title` in the transcript, unless the person renamed it (`custom-title`).
+- **Only what a person started.** Codex `exec` runs (scripts), sub-agent threads, and Claude's
+ `sdk-cli` sessions (programs, Harness's own summaries among them) are left out. On one machine:
+ about 210 of 1,227 files, plus a session any Harness agent already has is skipped.
+- **Shown only when a search matches one**, marked `not in Harness`, and previewed like any session.
+- **Open elsewhere** is known exactly. A running Claude Code keeps `~/.claude/sessions/<pid>.json`
+ naming its session, and a running Codex holds its rollout open (`lsof`). ⌘P will not open one
+ that is still open, and the daemon checks again before it resumes.
+- **Resuming** is `agent_create` with `resumeSessionId`: a new pane runs `claude --resume <id>` or
+ `codex resume <id>` in the session's own folder, named after its title. It is refused if the
+ session is open elsewhere, is already a harness, or its folder is gone (Codex app threads live in
+ folders people tidy away).
+- ChatGPT conversations and Codex cloud tasks are not on disk, so they cannot be found.
+
+Checked on one machine's real folders through a sandboxed daemon: the Codex app's threads and
+terminal sessions were found by what was said in them. A session open in a terminal was refused.
+Stand-in engines confirmed the resume launch (`codex resume <id>`, `claude --resume <id>`, each in
+its session's folder); no real conversation was touched.
+
## Protocol
`session_search { query, limit, from?, to? }` → `{ hits: [{ agentId, sessionId, engine, turn, at,
@@ -304,8 +333,6 @@ index the daemon owns.
## Not yet
-- **Sessions started outside Harness** (plain `claude`, `codex`) could be indexed too, so any past
- conversation on the machine can be found and resumed.
- **Untitled sessions** ("Claude harness 9-26 13:41") are now found by their content, but a
generated title from the first ask would help the name match as well.
- **A natural-language "ask" mode** for fuzzy memory ("the one last week where we fixed dial