From e9cb969a94b238a8b1686221b946129c30479c6c Mon Sep 17 00:00:00 2001 From: Merge Sim Date: Mon, 7 Sep 2026 10:20:59 -0700 Subject: [PATCH 01/13] refactor(agents): extract the title name-anchoring vocabulary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pure move, no behaviour change. The name tokens, display labels and the bare-name/whole-title resolvers come out of agent-title-evidence.ts into agent-title-name-anchoring.ts so more than one predicate can resolve a name to an agent through the same implementation rather than by convention. Nothing is added or reworded on the way out; the extracted functions are unchanged and simply exported. Verified by the existing suites: the title, identity and sidebar tests all pass untouched. The identity ratchet moves with it — titleHasAgentName's two parser-implementation callsites now live in the new module — so this commit is green on its own rather than leaving the ratchet red until the next one. --- src/shared/agent-title-evidence.ts | 114 ++--------------- src/shared/agent-title-name-anchoring.ts | 119 ++++++++++++++++++ .../pane-agent-identity-inventory.test.ts | 2 +- 3 files changed, 128 insertions(+), 107 deletions(-) create mode 100644 src/shared/agent-title-name-anchoring.ts diff --git a/src/shared/agent-title-evidence.ts b/src/shared/agent-title-evidence.ts index 8f212b5c75d5..0cf5f941bfeb 100644 --- a/src/shared/agent-title-evidence.ts +++ b/src/shared/agent-title-evidence.ts @@ -1,18 +1,21 @@ import { - AGY_AGENT_NAME_RE, CLAUDE_IDLE, - DROID_AGENT_NAME_RE, GEMINI_IDLE, GEMINI_PERMISSION, GEMINI_SILENT_WORKING, GEMINI_WORKING, - HERMES_AGENT_NAME_RE, containsAgentSpinnerGlyph, isClaudeIdentityFrameSegment, isClaudeManagementTitle, - isCursorNativeAgentTitle, - titleHasAgentName + isCursorNativeAgentTitle } from './agent-title-core' +import { + DISPLAY_LABELS, + agentForBareName, + agentForWholeTitle, + namesIn, + stripBareNameDecoration +} from './agent-title-name-anchoring' import { isOpenCodeNativeTitle } from './opencode-terminal-title' import { stripLeadingAgentTitleDecorationOrEmpty } from './agent-title-decoration' import { getPiCompatibleSyntheticAgentLabel } from './pi-compatible-synthetic-title' @@ -21,7 +24,6 @@ import { SYNTHETIC_AGENT_TITLE_PROFILES } from './synthetic-agent-title' import type { TuiAgent } from './tui-agent' -import { TUI_AGENT_DISPLAY_NAMES } from './tui-agent-display-names' /** * Order-independent identity evidence from a terminal title. @@ -57,48 +59,6 @@ export type AgentTitleEvidence = { readonly reason: AgentTitleEvidenceReason } -/** Names matched as whole tokens, paired with the agent each identifies. */ -const NAME_TOKENS: readonly (readonly [string, TuiAgent])[] = [ - ['claude', 'claude'], - ['openclaude', 'openclaude'], - ['codex', 'codex'], - ['copilot', 'copilot'], - ['cursor', 'cursor'], - ['gemini', 'gemini'], - ['antigravity', 'antigravity'], - ['opencode', 'opencode'], - ['mimo', 'mimo-code'], - ['openclaw', 'openclaw'], - ['aider', 'aider'], - ['grok', 'grok'], - ['devin', 'devin'] -] - -/** Agents whose name is matched by a dedicated pattern rather than a plain token. */ -const PATTERN_NAMES: readonly (readonly [RegExp, TuiAgent])[] = [ - [AGY_AGENT_NAME_RE, 'antigravity'], - [DROID_AGENT_NAME_RE, 'droid'], - [HERMES_AGENT_NAME_RE, 'hermes'] -] - -/** Catalog labels known to be emitted as terminal titles, not merely presented in Orca's UI. */ -const EMITTED_DISPLAY_LABEL_AGENTS = [ - 'claude-agent-teams', - 'mimo-code', - 'prime-agent', - 'command-code', - 'copilot' -] as const satisfies readonly TuiAgent[] - -const DISPLAY_LABELS = [ - ...EMITTED_DISPLAY_LABEL_AGENTS.map( - (agent) => [TUI_AGENT_DISPLAY_NAMES[agent].toLowerCase(), agent] as const - ), - ['claude code', 'claude'], - ['gemini cli', 'gemini'], - ['agent teams', 'claude-agent-teams'] -] satisfies readonly (readonly [string, TuiAgent])[] - const GEMINI_GLYPHS = [GEMINI_WORKING, GEMINI_SILENT_WORKING, GEMINI_IDLE, GEMINI_PERMISSION] const ANTIGRAVITY_MODEL_TITLE_RE = /^(?:agy|antigravity)(?:\s*[·—:-]\s*|\s+)gemini\s+\d/i @@ -108,7 +68,6 @@ const ANTIGRAVITY_MODEL_TITLE_RE = /^(?:agy|antigravity)(?:\s*[·—:-]\s*|\s+)g * worktree name (`review-14600-codex`), which is a directory, not an owner declaration. */ const OWNER_SUFFIX_RE = /\s-\s+([A-Za-z][\w-]*)\s*$/ -const WINDOWS_LAUNCHER_SUFFIX_RE = /\.(?:exe|cmd|bat|ps1)$/i const WRAPPER_SEPARATOR = ' | ' const MAX_WRAPPER_EVIDENCE_SEGMENTS = 8 const RESERVED_OWNER_IDS: ReadonlyMap = new Map([ @@ -135,63 +94,6 @@ function getEvidenceTitleSegments(title: string): string[] { return segments } -function namesIn(text: string): TuiAgent[] { - const found = new Set() - for (const [token, agent] of NAME_TOKENS) { - if (titleHasAgentName(text, token)) { - found.add(agent) - } - } - for (const [pattern, agent] of PATTERN_NAMES) { - if (pattern.test(text)) { - found.add(agent) - } - } - return [...found] -} - -function stripBareNameDecoration(text: string): string { - return text - .trim() - .replace(/^[^\p{L}\p{N}]+/u, '') - .replace(/[^\p{L}\p{N}]+$/u, '') -} - -function agentForBareName(text: string): TuiAgent | null { - const trimmed = text.trim() - if (!trimmed || /[\\/]/.test(trimmed)) { - return null - } - const stripped = stripBareNameDecoration(trimmed) - // Why labels too: an agent may write its own display name as the entire title (`⠐ Claude Code`). - // That is the same claim as a bare token, just spelled the way the vendor spells it. - const label = DISPLAY_LABELS.find(([text]) => text === stripped.toLowerCase()) - if (label) { - return label[1] - } - const bareToken = stripped.replace(WINDOWS_LAUNCHER_SUFFIX_RE, '') - const names = namesIn(bareToken) - // Why the length check: the remainder must BE the name, not merely contain it. "agy" anchors; - // "fix the agy hook" does not, and neither does a hyphenated worktree name like "codex-split". - return names.length === 1 && /^[\p{L}\p{N}]+$/u.test(bareToken) ? names[0] : null -} - -function agentForWholeTitle(text: string): TuiAgent | null { - const trimmed = text.trim() - if (!trimmed || /[\\/]/.test(trimmed)) { - return null - } - const stripped = stripBareNameDecoration(trimmed) - const label = DISPLAY_LABELS.find(([text]) => text === stripped.toLowerCase()) - if (label) { - return label[1] - } - if (!WINDOWS_LAUNCHER_SUFFIX_RE.test(stripped)) { - return null - } - return agentForBareName(stripped) -} - function agentForOwnerSuffix(text: string): TuiAgent | null { const normalized = text.trim().toLowerCase() return RESERVED_OWNER_IDS.get(normalized) ?? agentForBareName(text) diff --git a/src/shared/agent-title-name-anchoring.ts b/src/shared/agent-title-name-anchoring.ts new file mode 100644 index 000000000000..728a8cd62d72 --- /dev/null +++ b/src/shared/agent-title-name-anchoring.ts @@ -0,0 +1,119 @@ +import { + AGY_AGENT_NAME_RE, + DROID_AGENT_NAME_RE, + HERMES_AGENT_NAME_RE, + titleHasAgentName +} from './agent-title-core' +import type { TuiAgent } from './tui-agent' +import { TUI_AGENT_DISPLAY_NAMES } from './tui-agent-display-names' + +/** + * The vocabulary that maps a piece of title text to the agent it names, and the position tests + * that decide whether that text NAMES the agent or merely mentions it. + * + * Split out of agent-title-evidence.ts so the evidence parser and `titlePresentsAgent` resolve + * names through one implementation. They ask different questions — "who does this title name" + * versus "does this title present THIS agent" — and the whole class of bug in #8940/#14937 comes + * from those questions drifting apart, so the part they agree on lives in exactly one place. + */ + +const WINDOWS_LAUNCHER_SUFFIX_RE = /\.(?:exe|cmd|bat|ps1)$/i + +/** Names matched as whole tokens, paired with the agent each identifies. */ +const NAME_TOKENS: readonly (readonly [string, TuiAgent])[] = [ + ['claude', 'claude'], + ['openclaude', 'openclaude'], + ['codex', 'codex'], + ['copilot', 'copilot'], + ['cursor', 'cursor'], + ['gemini', 'gemini'], + ['antigravity', 'antigravity'], + ['opencode', 'opencode'], + ['mimo', 'mimo-code'], + ['openclaw', 'openclaw'], + ['aider', 'aider'], + ['grok', 'grok'], + ['devin', 'devin'] +] + +/** Agents whose name is matched by a dedicated pattern rather than a plain token. */ +const PATTERN_NAMES: readonly (readonly [RegExp, TuiAgent])[] = [ + [AGY_AGENT_NAME_RE, 'antigravity'], + [DROID_AGENT_NAME_RE, 'droid'], + [HERMES_AGENT_NAME_RE, 'hermes'] +] + +/** Catalog labels known to be emitted as terminal titles, not merely presented in Orca's UI. */ +const EMITTED_DISPLAY_LABEL_AGENTS = [ + 'claude-agent-teams', + 'mimo-code', + 'prime-agent', + 'command-code', + 'copilot' +] as const satisfies readonly TuiAgent[] + +export const DISPLAY_LABELS = [ + ...EMITTED_DISPLAY_LABEL_AGENTS.map( + (agent) => [TUI_AGENT_DISPLAY_NAMES[agent].toLowerCase(), agent] as const + ), + ['claude code', 'claude'], + ['gemini cli', 'gemini'], + ['agent teams', 'claude-agent-teams'] +] satisfies readonly (readonly [string, TuiAgent])[] + +export function namesIn(text: string): TuiAgent[] { + const found = new Set() + for (const [token, agent] of NAME_TOKENS) { + if (titleHasAgentName(text, token)) { + found.add(agent) + } + } + for (const [pattern, agent] of PATTERN_NAMES) { + if (pattern.test(text)) { + found.add(agent) + } + } + return [...found] +} + +export function stripBareNameDecoration(text: string): string { + return text + .trim() + .replace(/^[^\p{L}\p{N}]+/u, '') + .replace(/[^\p{L}\p{N}]+$/u, '') +} + +export function agentForBareName(text: string): TuiAgent | null { + const trimmed = text.trim() + if (!trimmed || /[\\/]/.test(trimmed)) { + return null + } + const stripped = stripBareNameDecoration(trimmed) + // Why labels too: an agent may write its own display name as the entire title (`⠐ Claude Code`). + // That is the same claim as a bare token, just spelled the way the vendor spells it. + const label = DISPLAY_LABELS.find(([text]) => text === stripped.toLowerCase()) + if (label) { + return label[1] + } + const bareToken = stripped.replace(WINDOWS_LAUNCHER_SUFFIX_RE, '') + const names = namesIn(bareToken) + // Why the length check: the remainder must BE the name, not merely contain it. "agy" anchors; + // "fix the agy hook" does not, and neither does a hyphenated worktree name like "codex-split". + return names.length === 1 && /^[\p{L}\p{N}]+$/u.test(bareToken) ? names[0] : null +} + +export function agentForWholeTitle(text: string): TuiAgent | null { + const trimmed = text.trim() + if (!trimmed || /[\\/]/.test(trimmed)) { + return null + } + const stripped = stripBareNameDecoration(trimmed) + const label = DISPLAY_LABELS.find(([text]) => text === stripped.toLowerCase()) + if (label) { + return label[1] + } + if (!WINDOWS_LAUNCHER_SUFFIX_RE.test(stripped)) { + return null + } + return agentForBareName(stripped) +} diff --git a/src/shared/pane-agent-identity-inventory.test.ts b/src/shared/pane-agent-identity-inventory.test.ts index 7de6b14f1c78..bcef48b52296 100644 --- a/src/shared/pane-agent-identity-inventory.test.ts +++ b/src/shared/pane-agent-identity-inventory.test.ts @@ -120,8 +120,8 @@ const INVENTORY: readonly InventoryGroup[] = [ 'src/shared/agent-detection.ts', 'src/shared/agent-name-token-match.ts', ['src/shared/agent-title-core.ts', 4], - ['src/shared/agent-title-evidence.ts', 2], ['src/shared/agent-title-identity.ts', 11], + ['src/shared/agent-title-name-anchoring.ts', 2], ['src/shared/terminal-title-agent-type.ts', 14] ] }, From af3f9d91e756d42b3a5bdcc6ed4b35ca928a01f0 Mon Sep 17 00:00:00 2001 From: Merge Sim Date: Mon, 7 Sep 2026 10:21:34 -0700 Subject: [PATCH 02/13] fix(agents): stop a foreign agent name in task text from taking a pane MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Claude pane's WORKING title is a bare braille spinner plus task text, so any agent name inside that text resolved the title to a committed foreign identity. The guard that fixed the mirror-image bug was written for the Claude label only, so every other name short-circuited above it and took the pane from its owner — the tab icon in use-tab-agent.ts, and the sidebar/dashboard row in worktree-title-derived-agent-rows.ts, which never consulted the owner at all. Make the rule agent-neutral in both directions: a title may only take a pane from a known owner when it PRESENTS that agent, never when the name merely occurs in free-form task text. titlePresentsAgent sits beside collectAgentTitleEvidence and resolves names through the vocabulary they now share. It differs from the parser in one respect: the parser asks who a title names given no owner, so it must refuse anything a task sentence could forge; this predicate is told which agent to check, so it also accepts that one name in an identity POSITION — the whole undecorated remainder, or the head of a `Name:` frame. The colon is what separates `Codex: fix cursor offsets` from `Claude Code compare Opencode`. resolveTabAgentFromSignals exists twice, already drifted in owner handling. useTabAgent calls the copy in use-tab-agent.ts, which is what paints the tab icon; every existing test imports the copy in tab-agent-from-signals.ts. Both are fixed, and the new suite runs its whole contract through both so a future divergence fails instead of hiding. --- .../worktree-title-derived-agent-rows.test.ts | 84 ++++++++++++ .../worktree-title-derived-agent-rows.ts | 17 ++- ...tab-agent-foreign-name-title-guard.test.ts | 121 ++++++++++++++++++ .../src/lib/tab-agent-from-signals.ts | 13 +- src/renderer/src/lib/use-tab-agent.ts | 13 +- src/shared/agent-title-evidence.test.ts | 47 ++++++- src/shared/agent-title-evidence.ts | 46 +++++++ 7 files changed, 319 insertions(+), 22 deletions(-) create mode 100644 src/renderer/src/lib/tab-agent-foreign-name-title-guard.test.ts diff --git a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts index c5de2eb18139..af7d405b2abd 100644 --- a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts +++ b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts @@ -4,6 +4,11 @@ import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/ter import type { TuiAgent } from '../../../../shared/tui-agent' import { makePaneKey } from '../../../../shared/stable-pane-id' import { buildWorktreeAgentRows } from './worktree-agent-rows' +import { + resolveAgentTypeFromTerminalTitle, + resolveTitleDerivedAgentType +} from './worktree-title-derived-agent-rows' +import { resolveRowAgentType } from './worktree-agent-row-type' const LEAF_ID_1 = '77777777-7777-4777-8777-777777777777' const LEAF_ID_2 = '88888888-8888-4888-8888-888888888888' @@ -382,3 +387,82 @@ describe('buildTitleDerivedAgentRows', () => { expect(rows).toHaveLength(0) }) }) + +/** + * #14938: the owner guard below `resolveTitleDerivedAgentType`'s early return was only ever + * reached for the Claude label, so a Claude pane working on a task whose text names another agent + * was listed as that agent's row — label, icon and agentType. + */ +describe('a foreign name in a Claude pane task title', () => { + const FOREIGN_NAME_TASK_TITLES = [ + '⠋ Fix the codex plugin launcher', + '⠋ add grok support to the tab bar', + '⠋ port the gemini status parser' + ] + + it('does not hand the row to the named agent', () => { + for (const title of FOREIGN_NAME_TASK_TITLES) { + const rows = buildWorktreeAgentRows({ + tabs: [makeTab('tab-1', { launchAgent: 'claude' })], + entries: [], + retained: [], + runtimePaneTitlesByTabId: { 'tab-1': { 1: title } }, + ptyIdsByTabId: { 'tab-1': ['pty-claude'] }, + terminalLayoutsByTabId: { 'tab-1': makeSingleLayout(LEAF_ID_1) }, + now: 2000 + }) + expect(rows.map((row) => row.agentType)).toEqual(['claude']) + } + }) + + it('declines at both title resolvers so the caller can fall back to the owner', () => { + expect( + resolveTitleDerivedAgentType('⠋ Fix the codex plugin launcher', 'Codex', 'claude') + ).toBeNull() + expect( + resolveAgentTypeFromTerminalTitle('⠋ Fix the codex plugin launcher', 'claude') + ).toBeNull() + }) + + // #14938 named this consumer specifically: it passes tab.launchAgent as the owner the guard used + // to discard, so a hook row with a missing or 'unknown' agentType flipped to the named agent too. + it('keeps resolveRowAgentType on the launch owner for an unknown-typed hook row', () => { + const entry = { + paneKey: makePaneKey('tab-1', LEAF_ID_1), + state: 'working', + prompt: 'x', + updatedAt: 0, + stateStartedAt: 0, + stateHistory: [], + agentType: 'unknown', + terminalTitle: '⠋ Fix the codex plugin launcher' + } as unknown as Parameters[0] + expect(resolveRowAgentType(entry, makeTab('tab-1', { launchAgent: 'claude' }))).toBe('claude') + }) + + // The reverse direction, which #8940 already guarded. Both directions are now one rule; this is + // the assertion that fails if the guard is ever made one-way again. + it('is symmetric with the Claude-token-in-foreign-task-text direction', () => { + expect( + resolveTitleDerivedAgentType('⠋ port the claude hook installer', 'Claude Code', 'codex') + ).toBeNull() + expect( + resolveTitleDerivedAgentType('⠋ Fix the codex plugin launcher', 'Codex', 'claude') + ).toBeNull() + }) + + it('still accepts a genuine identity frame on a reused pane', () => { + expect(resolveTitleDerivedAgentType('⠋ Codex', 'Codex', 'claude')).toBe('codex') + expect(resolveTitleDerivedAgentType('⠋ Codex: fix cursor offsets', 'Codex', 'claude')).toBe( + 'codex' + ) + expect(resolveTitleDerivedAgentType('⠋ Claude Code', 'Claude Code', 'codex')).toBe('claude') + }) + + // Non-discriminating: an unowned pane has nothing to protect, so the title answers either way. + it('still answers from the title when the pane has no known owner', () => { + expect(resolveTitleDerivedAgentType('⠋ Fix the codex plugin launcher', 'Codex', null)).toBe( + 'codex' + ) + }) +}) diff --git a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts index 08c0d27b9e74..f7d7a7404398 100644 --- a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts @@ -21,7 +21,8 @@ import { type CompatibleAgentOwnerOptions } from '../../../../shared/agent-title-owner' import { resolvePaneAgentOwner } from '../../../../shared/pane-agent-owner' -import { isClaudeIdentityFrameTitle } from '../../../../shared/terminal-title-agent-type' +import { titlePresentsAgent } from '../../../../shared/agent-title-evidence' +import type { TuiAgent } from '../../../../shared/tui-agent' /** Fixed, not per-process: title rows are a pure projection of the current title, so they are * comparable across restarts in a way a sequenced authority's rows are not. Ordering against @@ -32,7 +33,7 @@ const EMPTY_RUNTIME_TITLES: Record> = {} const EMPTY_LIVE_PTY_IDS: Record = {} const EMPTY_TERMINAL_LAYOUTS: Record = {} -const TITLE_AGENT_LABEL_TO_TYPE: Record = { +const TITLE_AGENT_LABEL_TO_TYPE: Record = { 'Claude Code': 'claude', OpenClaude: 'openclaude', Codex: 'codex', @@ -231,19 +232,21 @@ export function resolveTitleDerivedAgentType( ownerAgentType?: AgentType | null ): AgentType | null { const agentType = TITLE_AGENT_LABEL_TO_TYPE[label] ?? 'unknown' - if (agentType !== 'claude') { + if (agentType === 'unknown') { return agentType } // Why: Claude's task-title spinner heuristic has no provider identity. In // split panes it can match arbitrary terminal spinners, so sidebar rows only // accept Claude when the title itself names Claude. - if (!CLAUDE_AGENT_TOKEN_RE.test(title)) { + if (agentType === 'claude' && !CLAUDE_AGENT_TOKEN_RE.test(title)) { return null } - // Why: a "claude" word inside another agent's task text is a mention, not identity. - // Only a title that PRESENTS Claude may take a pane away from its known owner (#8940). + // Why: a name inside another agent's task text is a mention, not identity. Only a title that + // PRESENTS that agent may take a pane away from its known owner (#8940). Agent-neutral on + // purpose: while this was scoped to Claude, every other name in a Claude pane's task text + // short-circuited above the guard and took the row. const owner = ownerAgentType && ownerAgentType !== 'unknown' ? ownerAgentType : null - if (owner && owner !== 'claude' && !isClaudeIdentityFrameTitle(title)) { + if (owner && owner !== agentType && !titlePresentsAgent(title, agentType)) { return null } return agentType diff --git a/src/renderer/src/lib/tab-agent-foreign-name-title-guard.test.ts b/src/renderer/src/lib/tab-agent-foreign-name-title-guard.test.ts new file mode 100644 index 000000000000..82caa3ef1329 --- /dev/null +++ b/src/renderer/src/lib/tab-agent-foreign-name-title-guard.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from 'vitest' +import { resolveTabAgentFromSignals as resolveFromSignalsModule } from './tab-agent-from-signals' +import { resolveTabAgentFromSignals as resolveFromHookModule } from './use-tab-agent' + +/** + * #14937: a Claude pane's WORKING title is a bare braille spinner plus task text, so any agent + * name in that text used to resolve the title to a committed foreign identity and take the pane + * from its Claude owner. The guard that fixed the mirror-image bug (#8940) was written for the + * Claude label only, so every other name short-circuited above it. + * + * Both copies are exercised on purpose: `useTabAgent` (the tab-bar icon) calls the copy in + * use-tab-agent.ts, while open-tab-occupant-agent.ts and the rest of these suites call the copy in + * tab-agent-from-signals.ts. They are separate implementations of the same contract. + */ +const RESOLVERS = [ + ['tab-agent-from-signals', resolveFromSignalsModule], + ['use-tab-agent', resolveFromHookModule] +] as const + +const FOREIGN_NAME_TASK_TITLES = [ + '⠋ Fix the codex plugin launcher', + '⠙ Investigate why codex hangs on Windows', + '⠹ compare codex and claude output', + '⠋ add grok support to the tab bar', + '⠋ port the gemini status parser', + '⠋ review copilot suggestions' +] + +describe.each(RESOLVERS)('%s: a foreign name in task text is a mention', (_name, resolve) => { + it('keeps a Claude-owned pane Claude with no live hook', () => { + for (const title of FOREIGN_NAME_TASK_TITLES) { + expect( + resolve({ + hasObservedAgentSignal: true, + isRemote: false, + title, + hookAgent: null, + launchAgent: 'claude' + }) + ).toBe('claude') + } + }) + + it('keeps a Claude-owned pane Claude with a completed hook, and on a remote pane', () => { + const title = '⠋ Fix the codex plugin launcher' + expect( + resolve({ + hasObservedAgentSignal: true, + isRemote: false, + title, + hookAgent: null, + focusedCompletedHookAgent: 'claude', + launchAgent: 'claude' + }) + ).toBe('claude') + expect( + resolve({ + hasObservedAgentSignal: true, + isRemote: true, + title, + hookAgent: null, + launchAgent: 'claude' + }) + ).toBe('claude') + }) + + // Non-discriminating on its own — it passes before the fix too. Kept as the control that shows + // why users experienced this as random: a live hook always outranked the title. + it('was already correct while a live hook existed', () => { + expect( + resolve({ + hasObservedAgentSignal: true, + isRemote: false, + title: '⠋ Fix the codex plugin launcher', + hookAgent: 'claude', + launchAgent: 'claude' + }) + ).toBe('claude') + }) + + // The guard must stay agent-neutral in BOTH directions. This is the assertion that fails if + // someone reintroduces a one-way guard: #8940's direction and #14937's direction are one rule. + it('still lets a genuine identity frame reclaim a reused pane, both directions', () => { + expect( + resolve({ + hasObservedAgentSignal: true, + isRemote: false, + title: '✳ Claude Code', + hookAgent: null, + launchAgent: 'opencode' + }) + ).toBe('claude') + expect( + resolve({ + hasObservedAgentSignal: true, + isRemote: false, + title: '⠋ Codex', + hookAgent: null, + launchAgent: 'claude' + }) + ).toBe('codex') + }) + + it('keeps an OpenCode pane OpenCode when its task text mentions Claude (#8940)', () => { + for (const title of [ + 'OC | ⠋ ask claude about this', + '⠋ use Claude Sonnet', + '⠋ port the claude prompt' + ]) { + expect( + resolve({ + hasObservedAgentSignal: true, + isRemote: false, + title, + hookAgent: null, + launchAgent: 'opencode' + }) + ).toBe('opencode') + } + }) +}) diff --git a/src/renderer/src/lib/tab-agent-from-signals.ts b/src/renderer/src/lib/tab-agent-from-signals.ts index d4f5403b379e..1cc3f5fc8c20 100644 --- a/src/renderer/src/lib/tab-agent-from-signals.ts +++ b/src/renderer/src/lib/tab-agent-from-signals.ts @@ -1,8 +1,6 @@ import { isShellProcess } from '../../../shared/agent-detection' -import { - isClaudeIdentityFrameTitle, - resolveExplicitTerminalTitleAgentType -} from '../../../shared/terminal-title-agent-type' +import { resolveExplicitTerminalTitleAgentType } from '../../../shared/terminal-title-agent-type' +import { titlePresentsAgent } from '../../../shared/agent-title-evidence' import { resolveCompatibleAgentTypeForOwner, shareCompatibleTitleIdentityGroup @@ -119,10 +117,11 @@ export function resolveTabAgentFromSignals(args: { const explicitTitleAgent = resolveSignalAgentForLaunchOwner(rawTitleAgent, owner, ownerIsLaunch) const priorIdentity = idleFocusedIdentity ?? launchAgent const nativeOpenCodeTitle = explicitTitleAgent === 'opencode' && isOpenCodeNativeTitle(args.title) - // Why: a "claude" token in another agent's task text is a mention, not identity, so it must - // not take a pane from its known owner — only a title that PRESENTS Claude may (#8940). + // Why: a name inside another agent's task text is a mention, not identity, so it must not take + // a pane from its known owner — only a title that PRESENTS that agent may (#8940). The rule is + // agent-neutral: scoping it to Claude let every other name in Claude's task text steal the pane. const titleClaimsIdentity = - explicitTitleAgent !== 'claude' || isClaudeIdentityFrameTitle(args.title) + explicitTitleAgent === null || titlePresentsAgent(args.title, explicitTitleAgent) // Why: native OpenCode titles can reclaim stale launch intent before any observed hook signal. // Raw title group, not the fallback-rewritten agent: inferred Pi owners would otherwise treat an OMP wrapper title as a different identity. const titleReclaimsReusedPane = diff --git a/src/renderer/src/lib/use-tab-agent.ts b/src/renderer/src/lib/use-tab-agent.ts index 21c00f4cc37e..3e2b15f811b2 100644 --- a/src/renderer/src/lib/use-tab-agent.ts +++ b/src/renderer/src/lib/use-tab-agent.ts @@ -12,10 +12,8 @@ import { resolveSiblingRetainedTabAgent, resolveSiblingTabAgent } from './tab-agent' -import { - isClaudeIdentityFrameTitle, - resolveExplicitTerminalTitleAgentType -} from '../../../shared/terminal-title-agent-type' +import { resolveExplicitTerminalTitleAgentType } from '../../../shared/terminal-title-agent-type' +import { titlePresentsAgent } from '../../../shared/agent-title-evidence' import { resolveCompatibleAgentTypeForOwner } from '../../../shared/agent-title-owner' import { isOpenCodeNativeTitle } from '../../../shared/opencode-terminal-title' import { resolvePaneAgentOwner } from '../../../shared/pane-agent-owner' @@ -119,10 +117,11 @@ export function resolveTabAgentFromSignals(args: { ) const priorIdentity = idleFocusedIdentity ?? launchAgent const nativeOpenCodeTitle = explicitTitleAgent === 'opencode' && isOpenCodeNativeTitle(args.title) - // Why: a "claude" token in another agent's task text is a mention, not identity, so it must - // not take a pane from its known owner — only a title that PRESENTS Claude may (#8940). + // Why: a name inside another agent's task text is a mention, not identity, so it must not take + // a pane from its known owner — only a title that PRESENTS that agent may (#8940). The rule is + // agent-neutral: scoping it to Claude let every other name in Claude's task text steal the pane. const titleClaimsIdentity = - explicitTitleAgent !== 'claude' || isClaudeIdentityFrameTitle(args.title) + explicitTitleAgent === null || titlePresentsAgent(args.title, explicitTitleAgent) // Why: native OpenCode titles can reclaim stale launch intent before any observed hook signal. const titleReclaimsReusedPane = priorIdentity !== null && diff --git a/src/shared/agent-title-evidence.test.ts b/src/shared/agent-title-evidence.test.ts index 66840fe540d9..1e612473d5e8 100644 --- a/src/shared/agent-title-evidence.test.ts +++ b/src/shared/agent-title-evidence.test.ts @@ -5,7 +5,7 @@ import { GEMINI_SILENT_WORKING, GEMINI_WORKING } from './agent-title-core' -import { collectAgentTitleEvidence } from './agent-title-evidence' +import { collectAgentTitleEvidence, titlePresentsAgent } from './agent-title-evidence' const agentFor = (title: string) => collectAgentTitleEvidence(title).agent const reasonFor = (title: string) => collectAgentTitleEvidence(title).reason @@ -353,3 +353,48 @@ describe('collectAgentTitleEvidence', () => { expect(agentFor(' | ')).toBeNull() }) }) + +describe('titlePresentsAgent', () => { + // #14937/#14938: the gate a title must pass before it may take a pane from a known owner. + it('rejects a name that only appears inside task text', () => { + expect(titlePresentsAgent('⠋ Fix the codex plugin launcher', 'codex')).toBe(false) + expect(titlePresentsAgent('⠙ Investigate why codex hangs on Windows', 'codex')).toBe(false) + expect(titlePresentsAgent('⠋ add grok support to the tab bar', 'grok')).toBe(false) + expect(titlePresentsAgent('⠋ port the gemini status parser', 'gemini')).toBe(false) + expect(titlePresentsAgent('⠋ review copilot suggestions', 'copilot')).toBe(false) + expect(titlePresentsAgent('⠋ refactor the aider bridge', 'aider')).toBe(false) + }) + + it('accepts a name in the identity position', () => { + expect(titlePresentsAgent('⠋ Codex', 'codex')).toBe(true) + expect(titlePresentsAgent('⠋ Codex: fix cursor offsets', 'codex')).toBe(true) + expect(titlePresentsAgent('Codex ready', 'codex')).toBe(true) + expect(titlePresentsAgent('Codex - action required', 'codex')).toBe(true) + expect(titlePresentsAgent('⠋ Claude Code', 'claude')).toBe(true) + expect(titlePresentsAgent('zsh | ⠋ Claude Code', 'claude')).toBe(true) + }) + + it('answers only for the agent asked about', () => { + expect(titlePresentsAgent('⠋ Codex', 'claude')).toBe(false) + expect(titlePresentsAgent('⠋ Claude Code', 'codex')).toBe(false) + }) + + // The one intentional divergence from collectAgentTitleEvidence, pinned so it cannot re-drift. + // The parser files '⠋ Codex' as free text because codex sets synthesizeWorkingTitle: false in + // synthetic-agent-title.ts — Codex emits its own working titles, so Orca never synthesizes one + // for the parser to anchor against. This predicate is asked about ONE named agent rather than + // inferring it, so a name in the identity position is enough. Keeping the two in agreement here + // would break the pinned '⠋ Codex: fix cursor offsets' => codex assertion in + // terminal-title-agent-type.test.ts, and would demote real Codex frames on hookless SSH panes. + it('diverges from the evidence parser only for a bare frame it files as free text', () => { + expect(collectAgentTitleEvidence('⠋ Codex').reason).toBe('free-text-only') + expect(collectAgentTitleEvidence('⠋ Codex').agent).toBeNull() + expect(titlePresentsAgent('⠋ Codex', 'codex')).toBe(true) + }) + + // Task text that merely opens with a name is still task text: the colon is the frame marker. + it('rejects a name trailed by task text with no frame separator', () => { + expect(titlePresentsAgent('. Claude Code compare Opencode', 'claude')).toBe(false) + expect(titlePresentsAgent('⠋ Codex plugin launcher rewrite', 'codex')).toBe(false) + }) +}) diff --git a/src/shared/agent-title-evidence.ts b/src/shared/agent-title-evidence.ts index 0cf5f941bfeb..689df175272c 100644 --- a/src/shared/agent-title-evidence.ts +++ b/src/shared/agent-title-evidence.ts @@ -17,6 +17,7 @@ import { stripBareNameDecoration } from './agent-title-name-anchoring' import { isOpenCodeNativeTitle } from './opencode-terminal-title' +import { memoizeTitleClassification } from './terminal-title-classification-memo' import { stripLeadingAgentTitleDecorationOrEmpty } from './agent-title-decoration' import { getPiCompatibleSyntheticAgentLabel } from './pi-compatible-synthetic-title' import { @@ -264,3 +265,48 @@ export function collectAgentTitleEvidence(title: string): AgentTitleEvidence { reason: freeTextNames.length > 0 ? 'free-text-only' : 'no-evidence' } } + +/** Pure in `title`; the tab strip asks this per pane per render, so keep it off the regex ladder. */ +const collectMemoizedAgentTitleEvidence = memoizeTitleClassification(collectAgentTitleEvidence) + +/** + * Whether a segment puts `agent`'s name in an identity POSITION: the whole undecorated remainder, + * or the head of a `Name:` frame. + */ +function segmentPresentsAgentByPosition(segment: string, agent: TuiAgent): boolean { + const undecorated = stripLeadingAgentTitleDecorationOrEmpty(segment).trim() + if (!undecorated) { + return false + } + if (agentForBareName(undecorated) === agent) { + return true + } + // Why the colon specifically: it is what separates `Codex: fix cursor offsets` — a frame and + // then its task — from `Claude Code compare Opencode`, one sentence that happens to open with + // a name. Without it, any task text beginning with an agent's name would read as identity. + const frameEnd = undecorated.indexOf(':') + return frameEnd > 0 && agentForBareName(undecorated.slice(0, frameEnd)) === agent +} + +/** + * Whether `title` PRESENTS `agent` as the pane's identity rather than merely mentioning it. This + * is the gate a title must pass before it may take a pane away from a known owner (#8940) — for + * every agent, not only Claude. + * + * Deliberate, test-pinned divergence from `collectAgentTitleEvidence`: the parser answers "who + * does this title name, given no owner", so it must refuse any name an ordinary task sentence + * could forge. Here the agent is supplied rather than inferred, so the title need only put that + * one name in an identity position. That admits `⠋ Codex`, which the parser files as + * `free-text-only` because codex sets `synthesizeWorkingTitle: false` in synthetic-agent-title.ts + * — Codex emits its own working titles, so Orca never synthesizes one for the parser to anchor + * against. Task text still cannot pass: `⠋ Fix the codex plugin launcher` puts the name + * mid-sentence, and `. Claude Code compare Opencode` trails task text past it. + */ +export function titlePresentsAgent(title: string, agent: TuiAgent): boolean { + if (collectMemoizedAgentTitleEvidence(title).anchoredNames.includes(agent)) { + return true + } + return getEvidenceTitleSegments(title).some((segment) => + segmentPresentsAgentByPosition(segment, agent) + ) +} From 5fad753cca45a32da6a9e87888e98aedd2c58326 Mon Sep 17 00:00:00 2001 From: Merge Sim Date: Mon, 7 Sep 2026 10:27:05 -0700 Subject: [PATCH 03/13] fix(agents): let the title label map admit a missing label MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Narrowing the map's value type to TuiAgent surfaced an inaccuracy that was always there: noUncheckedIndexedAccess is off, so indexing Record types every lookup as a hit, and `label` is arbitrary text parsed off a terminal title. The compiler concluded the `?? 'unknown'` fallback was unreachable and the unknown-label comparison impossible. The runtime disagrees — the map carries a fixed set of ~10 labels and misses everything else. Deleting the branch would return undefined where the function returns 'unknown' today, so the type is what is wrong. Partial> makes absence expressible and leaves behaviour unchanged. Pinned by a test, since nothing else forced the map to be honest about this. --- .../sidebar/worktree-title-derived-agent-rows.test.ts | 10 ++++++++++ .../sidebar/worktree-title-derived-agent-rows.ts | 5 ++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts index af7d405b2abd..66123c460cde 100644 --- a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts +++ b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts @@ -465,4 +465,14 @@ describe('a foreign name in a Claude pane task title', () => { 'codex' ) }) + + // The label map is missing every label outside its fixed set, so the unknown-label branch is + // live at runtime. Nothing said so in the types until the value type was narrowed to TuiAgent, + // and deleting the branch on the compiler's advice would return undefined here instead. + it('returns unknown for a label the map does not carry', () => { + expect(resolveTitleDerivedAgentType('⠋ Something Else', 'Something Else', null)).toBe('unknown') + expect(resolveTitleDerivedAgentType('⠋ Something Else', 'Something Else', 'claude')).toBe( + 'unknown' + ) + }) }) diff --git a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts index f7d7a7404398..9aef081d8206 100644 --- a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts @@ -33,7 +33,10 @@ const EMPTY_RUNTIME_TITLES: Record> = {} const EMPTY_LIVE_PTY_IDS: Record = {} const EMPTY_TERMINAL_LAYOUTS: Record = {} -const TITLE_AGENT_LABEL_TO_TYPE: Record = { +// Partial, not Record: `label` is arbitrary text parsed off a terminal title, so a lookup misses +// for anything outside this fixed set and the `?? 'unknown'` below is live. Without `Partial` the +// index type promises a hit that the runtime does not, and the unknown-label guard reads as dead. +const TITLE_AGENT_LABEL_TO_TYPE: Partial> = { 'Claude Code': 'claude', OpenClaude: 'openclaude', Codex: 'codex', From fa42ea4c289eec30fe867f63d96d8c62fd03f6ee Mon Sep 17 00:00:00 2001 From: Merge Sim Date: Mon, 7 Sep 2026 12:04:09 -0700 Subject: [PATCH 04/13] fix(agents): let an agent's own sigil still present it against an owner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit titlePresentsAgent read only anchoredNames, so it missed the evidence class the parser ranks highest: a vendor marker, the sigil an agent emits itself and task text cannot forge. Gemini's four glyphs and Cursor's native literal are markers, not anchored names, so every Gemini working, idle and permission title — and Cursor's literal — failed the gate and the pane stayed on its previous owner. Run Claude, let it finish, run gemini in the same pane: tab and sidebar both stayed Claude. The bug this change exists to fix, mirrored. Admitting the whole vendor class would have reintroduced #8940 the other way, because Claude's '. ', '* ' and idle sigil are generic — OpenCode emits them too — so they prove activity, not identity. hasGenericClaudeStatusPrefix already modelled that distinction inside terminal-title-agent-type.ts; it moves to agent-title-core.ts so both callers share the one definition. Not isGenericClaudeStatusClaim, which is that model plus a clause for a different question: it treats a 'claude' token as upgrading a generic prefix into a real claim, which is right when asking whether a title may MINT Claude identity and wrong when asking whether it PRESENTS Claude. Applied here it would have let ". port the claude prompt" reclaim an OpenCode pane. The predicate is now one memoized set per title rather than a memoized first line and an uncached scan, so the common path — a title presenting nobody — no longer re-runs the name matchers over every wrapper segment on each render. --- .../worktree-title-derived-agent-rows.test.ts | 33 ++++++++ ...tab-agent-foreign-name-title-guard.test.ts | 64 ++++++++++++++++ src/shared/agent-title-core.ts | 15 ++++ src/shared/agent-title-evidence.test.ts | 30 ++++++++ src/shared/agent-title-evidence.ts | 75 +++++++++++-------- src/shared/terminal-title-agent-type.ts | 16 ++-- 6 files changed, 191 insertions(+), 42 deletions(-) diff --git a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts index 66123c460cde..dfaf1d687fd4 100644 --- a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts +++ b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts @@ -466,6 +466,39 @@ describe('a foreign name in a Claude pane task title', () => { ) }) + // A vendor marker is the agent's own sigil, so it must still take the row from a prior owner. + // Reading only anchoredNames printed a Claude row, with a Claude label, for a live Gemini pane. + it('lets a vendor-marker title take the row from a prior owner', () => { + expect( + resolveTitleDerivedAgentType('\u2726 Analyzing the repository', 'Gemini CLI', 'claude') + ).toBe('gemini') + expect(resolveTitleDerivedAgentType('\u25c7 waiting', 'Gemini CLI', 'claude')).toBe('gemini') + const rows = buildWorktreeAgentRows({ + tabs: [makeTab('tab-1', { launchAgent: 'claude' })], + entries: [], + retained: [], + runtimePaneTitlesByTabId: { 'tab-1': { 1: '\u2726 Analyzing the repository' } }, + ptyIdsByTabId: { 'tab-1': ['pty-gemini'] }, + terminalLayoutsByTabId: { 'tab-1': makeSingleLayout(LEAF_ID_1) }, + now: 2000 + }) + expect(rows.map((row) => [row.agentType, row.entry.prompt])).toEqual([['gemini', 'Gemini CLI']]) + }) + + // #10258: Cursor's status-less native literal still identifies the pane, even against an owner. + it('lets the native cursor literal take the row from a prior owner', () => { + const rows = buildWorktreeAgentRows({ + tabs: [makeTab('tab-1', { launchAgent: 'claude' })], + entries: [], + retained: [], + runtimePaneTitlesByTabId: { 'tab-1': { 1: 'Cursor Agent' } }, + ptyIdsByTabId: { 'tab-1': ['pty-cursor'] }, + terminalLayoutsByTabId: { 'tab-1': makeSingleLayout(LEAF_ID_1) }, + now: 2000 + }) + expect(rows.map((row) => row.agentType)).toEqual(['cursor']) + }) + // The label map is missing every label outside its fixed set, so the unknown-label branch is // live at runtime. Nothing said so in the types until the value type was narrowed to TuiAgent, // and deleting the branch on the compiler's advice would return undefined here instead. diff --git a/src/renderer/src/lib/tab-agent-foreign-name-title-guard.test.ts b/src/renderer/src/lib/tab-agent-foreign-name-title-guard.test.ts index 82caa3ef1329..c588c9822572 100644 --- a/src/renderer/src/lib/tab-agent-foreign-name-title-guard.test.ts +++ b/src/renderer/src/lib/tab-agent-foreign-name-title-guard.test.ts @@ -101,6 +101,70 @@ describe.each(RESOLVERS)('%s: a foreign name in task text is a mention', (_name, ).toBe('codex') }) + // The mirror of this PR's own bug, and the regression the first cut of it shipped: a vendor + // marker is the agent's OWN sigil, which task text cannot forge, so it must still reclaim a + // pane from a prior owner. Gemini's four glyphs and Cursor's native literal are markers, not + // anchored names, so a predicate reading only anchoredNames strands a real Gemini pane on its + // previous Claude owner. + it('lets a vendor-marker title reclaim a pane from a prior owner', () => { + for (const title of [ + '\u2726 Analyzing the repository', + '\u23f2 thinking', + '\u25c7 waiting', + '\u270b approve this edit' + ]) { + expect( + resolve({ + hasObservedAgentSignal: true, + isRemote: false, + title, + hookAgent: null, + launchAgent: 'claude' + }) + ).toBe('gemini') + expect( + resolve({ + hasObservedAgentSignal: true, + isRemote: false, + title, + hookAgent: null, + focusedCompletedHookAgent: 'claude', + launchAgent: 'claude' + }) + ).toBe('gemini') + } + // #10258: the native literal is deliberately status-less but still identifies a live pane. + expect( + resolve({ + hasObservedAgentSignal: true, + isRemote: false, + title: 'cursor agent', + hookAgent: null, + launchAgent: 'claude' + }) + ).toBe('cursor') + }) + + // Claude's decorations are the exception, and the reason the vendor class cannot be admitted + // wholesale: OpenCode emits '. ' and '* ' too, so they prove activity, not identity. + it('does not let a generic Claude status prefix reclaim a pane', () => { + for (const title of [ + '. port the claude prompt', + '. ship it with claude', + '. Compare Opencode Vs Orca' + ]) { + expect( + resolve({ + hasObservedAgentSignal: true, + isRemote: false, + title, + hookAgent: null, + launchAgent: 'opencode' + }) + ).toBe('opencode') + } + }) + it('keeps an OpenCode pane OpenCode when its task text mentions Claude (#8940)', () => { for (const title of [ 'OC | ⠋ ask claude about this', diff --git a/src/shared/agent-title-core.ts b/src/shared/agent-title-core.ts index 3d0bdbc0feb5..e339dbf6dc2f 100644 --- a/src/shared/agent-title-core.ts +++ b/src/shared/agent-title-core.ts @@ -149,6 +149,21 @@ export function isCursorNativeAgentTitle(title: string): boolean { return title.trim().toLowerCase() === CURSOR_NATIVE_TITLE_LOWER } +/** + * Claude's bare status decorations. Generic on purpose: OpenCode emits '. ' and '* ' too (#8940) + * and several agents animate a spinner, so these prove a pane is ACTIVE, never which agent it is. + * Callers asking an identity question must not read one as a Claude vendor emission. + */ +export function hasGenericClaudeStatusPrefix(title: string): boolean { + return ( + containsAgentSpinnerGlyph(title) || + title.startsWith(`${CLAUDE_IDLE} `) || + title === CLAUDE_IDLE || + title.startsWith('. ') || + title.startsWith('* ') + ) +} + const CLAUDE_IDENTITY_FRAME_RE = /^claude(?: code)?(?:\s+(?:ready|idle|done|working|thinking|running))?(?:\s*-\s*action required)?$/ diff --git a/src/shared/agent-title-evidence.test.ts b/src/shared/agent-title-evidence.test.ts index 1e612473d5e8..f27507e26df2 100644 --- a/src/shared/agent-title-evidence.test.ts +++ b/src/shared/agent-title-evidence.test.ts @@ -392,6 +392,36 @@ describe('titlePresentsAgent', () => { expect(titlePresentsAgent('⠋ Codex', 'codex')).toBe(true) }) + // The OTHER direction of the divergence. The parser resolves a lone vendor marker to its agent, + // including Claude's generic status decorations; this predicate must not, or a '. '-prefixed + // OpenCode task title would reclaim the pane #8940 exists to protect. Pinned because leaving + // this direction unguarded is exactly how the first cut of this change shipped a regression. + it('diverges the other way: a generic Claude status prefix is not identity', () => { + for (const title of [ + '. port the claude prompt', + '. ship it with claude', + '\u2733 investigating startup' + ]) { + expect(collectAgentTitleEvidence(title).agent).toBe('claude') + expect(collectAgentTitleEvidence(title).reason).toBe('vendor-marker') + expect(titlePresentsAgent(title, 'claude')).toBe(false) + } + }) + + // But an agent's OWN sigil is identity, and must survive: these are the titles a real Gemini or + // Cursor pane paints, and refusing them stranded the pane on its previous owner. + it('accepts a vendor marker that is the agent own sigil', () => { + for (const title of [ + '\u2726 Analyzing the repository', + '\u23f2 thinking', + '\u25c7 waiting', + '\u270b approve this edit' + ]) { + expect(titlePresentsAgent(title, 'gemini')).toBe(true) + } + expect(titlePresentsAgent('cursor agent', 'cursor')).toBe(true) + }) + // Task text that merely opens with a name is still task text: the colon is the frame marker. it('rejects a name trailed by task text with no frame separator', () => { expect(titlePresentsAgent('. Claude Code compare Opencode', 'claude')).toBe(false) diff --git a/src/shared/agent-title-evidence.ts b/src/shared/agent-title-evidence.ts index 689df175272c..b8d9eb8c7aec 100644 --- a/src/shared/agent-title-evidence.ts +++ b/src/shared/agent-title-evidence.ts @@ -6,6 +6,7 @@ import { GEMINI_WORKING, containsAgentSpinnerGlyph, isClaudeIdentityFrameSegment, + hasGenericClaudeStatusPrefix, isClaudeManagementTitle, isCursorNativeAgentTitle } from './agent-title-core' @@ -266,47 +267,59 @@ export function collectAgentTitleEvidence(title: string): AgentTitleEvidence { } } -/** Pure in `title`; the tab strip asks this per pane per render, so keep it off the regex ladder. */ -const collectMemoizedAgentTitleEvidence = memoizeTitleClassification(collectAgentTitleEvidence) - /** - * Whether a segment puts `agent`'s name in an identity POSITION: the whole undecorated remainder, - * or the head of a `Name:` frame. + * Every agent a title PRESENTS, as opposed to merely mentions. Memoized as a set rather than + * per-agent: both tab-strip resolvers ask this per pane on every render, and the positional scan + * below runs the name matchers over each wrapper segment. */ -function segmentPresentsAgentByPosition(segment: string, agent: TuiAgent): boolean { - const undecorated = stripLeadingAgentTitleDecorationOrEmpty(segment).trim() - if (!undecorated) { - return false +const titlePresentedAgents = memoizeTitleClassification((title: string): ReadonlySet => { + const evidence = collectAgentTitleEvidence(title) + const presented = new Set(evidence.anchoredNames) + + for (const marker of evidence.vendorMarkers) { + // Why Claude's marker is excluded and Gemini's and Cursor's are not: a vendor marker is + // unforgeable only when it is the agent's OWN sigil. Claude's status decorations are generic — + // OpenCode emits '. ' and '* ' too (#8940) — so they prove activity, not identity. A title + // that really does present Claude carries an identity frame, which is already anchored above. + if (marker !== 'claude' || !hasGenericClaudeStatusPrefix(title)) { + presented.add(marker) + } } - if (agentForBareName(undecorated) === agent) { - return true + + for (const segment of getEvidenceTitleSegments(title)) { + // A name in the identity position: the whole undecorated remainder, or the head of a `Name:` + // frame. The colon is what separates `Codex: fix cursor offsets` from `Claude Code compare + // Opencode`, one sentence that happens to open with a name. + const undecorated = stripLeadingAgentTitleDecorationOrEmpty(segment).trim() + const frameEnd = undecorated.indexOf(':') + const positional = + agentForBareName(undecorated) ?? + (frameEnd > 0 ? agentForBareName(undecorated.slice(0, frameEnd)) : null) + if (positional) { + presented.add(positional) + } } - // Why the colon specifically: it is what separates `Codex: fix cursor offsets` — a frame and - // then its task — from `Claude Code compare Opencode`, one sentence that happens to open with - // a name. Without it, any task text beginning with an agent's name would read as identity. - const frameEnd = undecorated.indexOf(':') - return frameEnd > 0 && agentForBareName(undecorated.slice(0, frameEnd)) === agent -} + + return presented +}) /** * Whether `title` PRESENTS `agent` as the pane's identity rather than merely mentioning it. This * is the gate a title must pass before it may take a pane away from a known owner (#8940) — for * every agent, not only Claude. * - * Deliberate, test-pinned divergence from `collectAgentTitleEvidence`: the parser answers "who - * does this title name, given no owner", so it must refuse any name an ordinary task sentence - * could forge. Here the agent is supplied rather than inferred, so the title need only put that - * one name in an identity position. That admits `⠋ Codex`, which the parser files as - * `free-text-only` because codex sets `synthesizeWorkingTitle: false` in synthetic-agent-title.ts - * — Codex emits its own working titles, so Orca never synthesizes one for the parser to anchor - * against. Task text still cannot pass: `⠋ Fix the codex plugin launcher` puts the name - * mid-sentence, and `. Claude Code compare Opencode` trails task text past it. + * This is NOT collectAgentTitleEvidence with a different signature; the two answer different + * questions and diverge in BOTH directions, each pinned by test: + * + * more permissive — the parser asks who a title names given no owner, so it must refuse any name + * an ordinary sentence could forge. Here the agent is supplied rather than inferred, so a name in + * the identity POSITION is enough. That admits `⠋ Codex`, which the parser files as + * `free-text-only` because codex sets `synthesizeWorkingTitle: false` in synthetic-agent-title.ts. + * + * less permissive — the parser resolves a lone vendor marker to its agent, including Claude's + * generic status decorations. Those are not identity here, or a `. `-prefixed OpenCode task title + * would reclaim the pane it was #8940's whole point to protect. */ export function titlePresentsAgent(title: string, agent: TuiAgent): boolean { - if (collectMemoizedAgentTitleEvidence(title).anchoredNames.includes(agent)) { - return true - } - return getEvidenceTitleSegments(title).some((segment) => - segmentPresentsAgentByPosition(segment, agent) - ) + return titlePresentedAgents(title).has(agent) } diff --git a/src/shared/terminal-title-agent-type.ts b/src/shared/terminal-title-agent-type.ts index 4a000f8be9b8..91501c8ee141 100644 --- a/src/shared/terminal-title-agent-type.ts +++ b/src/shared/terminal-title-agent-type.ts @@ -4,7 +4,11 @@ import { HERMES_AGENT_NAME_RE, titleHasAgentName } from './agent-name-token-match' -import { containsAgentSpinnerGlyph, isCursorAgentTitle } from './agent-title-core' +import { + containsAgentSpinnerGlyph, + isCursorAgentTitle, + hasGenericClaudeStatusPrefix +} from './agent-title-core' import { isOpenCodeNativeTitle } from './opencode-terminal-title' import { getPiCompatibleSyntheticAgentLabel, @@ -241,16 +245,6 @@ const TITLE_LABEL_TO_AGENT: Partial> = { OMP: 'omp' } -function hasGenericClaudeStatusPrefix(title: string): boolean { - return ( - containsAgentSpinnerGlyph(title) || - title.startsWith('✳ ') || - title === '✳' || - title.startsWith('. ') || - title.startsWith('* ') - ) -} - export { isClaudeIdentityFrameTitle } from './agent-title-core' function isGenericClaudeStatusClaim(title: string, titleAgent: TuiAgent | null): boolean { From 48eea762257529269ddb5e7ab9a1a35237db7222 Mon Sep 17 00:00:00 2001 From: Merge Sim Date: Mon, 7 Sep 2026 12:37:41 -0700 Subject: [PATCH 05/13] fix(agents): gate on one identity-frame grammar, ratcheted against the corpus MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two review rounds found the same class of defect: the gate was a second model of "does this title present an agent", poorer than the model its callers use. Round 1 missed an evidence class, round 2 missed four whole ROUTES in a different function. A third patch would have bought the fifth route. getAgentLabel mints identity through routes the evidence parser cannot express, because titleHasAgentName asks whether a name occurs ANYWHERE and never where. One Codex branch therefore serves both 'codex working' and the mid-sentence mention this change exists to reject. Route identity cannot separate them; the gate genuinely needs position information the resolver discards. So the models cannot be collapsed. What they can be is one GRAMMAR plus an enforced agreement: agentForIdentityFrame generalizes what isClaudeIdentityFrameSegment has always described — a name, an optional status word, an optional '- action required' — which was agent-neutral in shape and applied only to Claude. That was the same one-way-guard mistake as the original bug, one level down. Generalized, it covers every minting route: bare names, 'Codex: ...', em-dash frames, name plus status, Windows launcher forms, '|'-headed titles and Pi's native format. The positional and vendor-marker rules fold into it rather than stacking beside it. terminal-title-pane-claim-corpus.test.ts is the enforcement. It sweeps the whole classification corpus, and any title getAgentLabel still mints an identity from must remain able to claim a pane. Shared code cannot enforce this because the two models legitimately differ; the corpus can, and it names the offending title when a future route is added. Corpus: 14 lost claims before this commit, 0 after. One intended gain, 'claude.bat working', listed and explained in the ratchet: the old gate accepted 'aider.ps1 ready' for aider and refused the identical form for Claude purely because the guard was Claude-only. --- ...tab-agent-foreign-name-title-guard.test.ts | 24 ++++ .../lib/tab-agent-pane-claim-corpus.test.ts | 77 ++++++++++++ src/shared/agent-title-evidence.ts | 41 +++---- src/shared/agent-title-name-anchoring.ts | 41 +++++++ .../terminal-title-pane-claim-corpus.test.ts | 115 ++++++++++++++++++ 5 files changed, 277 insertions(+), 21 deletions(-) create mode 100644 src/renderer/src/lib/tab-agent-pane-claim-corpus.test.ts create mode 100644 src/shared/terminal-title-pane-claim-corpus.test.ts diff --git a/src/renderer/src/lib/tab-agent-foreign-name-title-guard.test.ts b/src/renderer/src/lib/tab-agent-foreign-name-title-guard.test.ts index c588c9822572..2826975ded1a 100644 --- a/src/renderer/src/lib/tab-agent-foreign-name-title-guard.test.ts +++ b/src/renderer/src/lib/tab-agent-foreign-name-title-guard.test.ts @@ -165,6 +165,30 @@ describe.each(RESOLVERS)('%s: a foreign name in task text is a mention', (_name, } }) + // The four routes `getAgentLabel` mints identity from that a predicate built on the evidence + // parser alone cannot see. Each is the agent naming itself, so each must still take the pane. + it.each([ + ['pi native', '\u03c0 > session - ~/orca', 'pi'], + ['pi native, blocked', '\u03c0 ! blocked-session', 'pi'], + ['name plus status', 'codex working', 'codex'], + ['name plus status, spinner', '\u2838 aider running', 'aider'], + ['name plus status, grok', 'grok done', 'grok'], + ['em-dash frame', '\u2849 Codex \u2014 refactoring', 'codex'], + ['pipe-headed', 'ssh host | opencode ready', 'opencode'], + ['windows launcher', 'aider.ps1 ready', 'aider'], + ['windows launcher, action', 'copilot.exe - action required', 'copilot'] + ])('reclaims a foreign-owned pane for a %s title', (_label, title, expected) => { + expect( + resolve({ + hasObservedAgentSignal: true, + isRemote: false, + title, + hookAgent: null, + launchAgent: 'claude' + }) + ).toBe(expected) + }) + it('keeps an OpenCode pane OpenCode when its task text mentions Claude (#8940)', () => { for (const title of [ 'OC | ⠋ ask claude about this', diff --git a/src/renderer/src/lib/tab-agent-pane-claim-corpus.test.ts b/src/renderer/src/lib/tab-agent-pane-claim-corpus.test.ts new file mode 100644 index 000000000000..d5c5143fc873 --- /dev/null +++ b/src/renderer/src/lib/tab-agent-pane-claim-corpus.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest' +import { TERMINAL_TITLE_CLASSIFICATION_CORPUS } from '../../../shared/terminal-title-classification-corpus' +import { + isClaudeIdentityFrameTitle, + resolveExplicitTerminalTitleAgentType +} from '../../../shared/terminal-title-agent-type' +import { resolveTabAgentFromSignals as resolveFromSignalsModule } from './tab-agent-from-signals' +import { resolveTabAgentFromSignals as resolveFromHookModule } from './use-tab-agent' +import { resolveTitleDerivedAgentType } from '../components/sidebar/worktree-title-derived-agent-rows' +import { resolveTitleActivityLabel } from './pane-agent-evidence' +import type { TuiAgent } from '../../../shared/tui-agent' + +/** + * The corpus swept through the CONSUMERS, not just the predicate. + * + * Round 2's regression shipped with a correct predicate: the gate agreed with its own evidence + * model, and the callers' authority was a third function with a richer one. A predicate-level + * sweep would have passed. This is the sweep that would not have. + */ + +/** A different owner for every title, so the guard is always the thing being exercised. */ +function foreignOwner(agent: TuiAgent): TuiAgent { + return agent === 'claude' ? 'codex' : 'claude' +} + +function claimedBefore(title: string, agent: string): boolean { + return agent !== 'claude' || isClaudeIdentityFrameTitle(title) +} + +const MINTING_CORPUS: [string, TuiAgent][] = TERMINAL_TITLE_CLASSIFICATION_CORPUS.flatMap( + (title) => { + const agent = resolveExplicitTerminalTitleAgentType(title) + return agent && claimedBefore(title, agent) ? [[title, agent] as [string, TuiAgent]] : [] + } +) + +describe('pane-claim corpus through the consumers', () => { + it('covers a meaningful slice of the corpus', () => { + expect(MINTING_CORPUS.length).toBeGreaterThan(20) + }) + + it.each([ + ['tab-agent-from-signals', resolveFromSignalsModule], + ['use-tab-agent', resolveFromHookModule] + ])('%s reclaims a foreign-owned pane for every minting title', (_name, resolve) => { + const lost = MINTING_CORPUS.filter(([title, agent]) => { + const owner = foreignOwner(agent) + return ( + resolve({ + hasObservedAgentSignal: true, + isRemote: false, + title, + hookAgent: null, + launchAgent: owner + }) !== agent + ) + }).map(([title, agent]) => `${JSON.stringify(title)} -> ${agent}`) + expect(lost).toEqual([]) + }) + + /** + * Isolates the OWNER GUARD, which is the only thing this change touches in the sidebar. A title + * whose label the sidebar's own map does not carry (`MiMo Code` is absent, before and after) + * could never produce that row regardless of ownership, so it is not a claim the guard can lose. + * Anything the resolver answers with no owner, it must still answer against a foreign one. + */ + it('the sidebar owner guard never drops a row the resolver would otherwise build', () => { + const lost = MINTING_CORPUS.filter(([title, agent]) => { + const label = resolveTitleActivityLabel(title) + if (!label || resolveTitleDerivedAgentType(title, label, null) !== agent) { + return false + } + return resolveTitleDerivedAgentType(title, label, foreignOwner(agent)) !== agent + }).map(([title, agent]) => `${JSON.stringify(title)} -> ${agent}`) + expect(lost).toEqual([]) + }) +}) diff --git a/src/shared/agent-title-evidence.ts b/src/shared/agent-title-evidence.ts index b8d9eb8c7aec..4560b38fbb31 100644 --- a/src/shared/agent-title-evidence.ts +++ b/src/shared/agent-title-evidence.ts @@ -13,6 +13,7 @@ import { import { DISPLAY_LABELS, agentForBareName, + agentForIdentityFrame, agentForWholeTitle, namesIn, stripBareNameDecoration @@ -269,8 +270,7 @@ export function collectAgentTitleEvidence(title: string): AgentTitleEvidence { /** * Every agent a title PRESENTS, as opposed to merely mentions. Memoized as a set rather than - * per-agent: both tab-strip resolvers ask this per pane on every render, and the positional scan - * below runs the name matchers over each wrapper segment. + * per-agent: both tab-strip resolvers ask this per pane on every render. */ const titlePresentedAgents = memoizeTitleClassification((title: string): ReadonlySet => { const evidence = collectAgentTitleEvidence(title) @@ -280,23 +280,16 @@ const titlePresentedAgents = memoizeTitleClassification((title: string): Readonl // Why Claude's marker is excluded and Gemini's and Cursor's are not: a vendor marker is // unforgeable only when it is the agent's OWN sigil. Claude's status decorations are generic — // OpenCode emits '. ' and '* ' too (#8940) — so they prove activity, not identity. A title - // that really does present Claude carries an identity frame, which is already anchored above. + // that really does present Claude carries an identity frame, which the grammar below matches. if (marker !== 'claude' || !hasGenericClaudeStatusPrefix(title)) { presented.add(marker) } } for (const segment of getEvidenceTitleSegments(title)) { - // A name in the identity position: the whole undecorated remainder, or the head of a `Name:` - // frame. The colon is what separates `Codex: fix cursor offsets` from `Claude Code compare - // Opencode`, one sentence that happens to open with a name. - const undecorated = stripLeadingAgentTitleDecorationOrEmpty(segment).trim() - const frameEnd = undecorated.indexOf(':') - const positional = - agentForBareName(undecorated) ?? - (frameEnd > 0 ? agentForBareName(undecorated.slice(0, frameEnd)) : null) - if (positional) { - presented.add(positional) + const framed = agentForIdentityFrame(segment) + if (framed) { + presented.add(framed) } } @@ -308,17 +301,23 @@ const titlePresentedAgents = memoizeTitleClassification((title: string): Readonl * is the gate a title must pass before it may take a pane away from a known owner (#8940) — for * every agent, not only Claude. * - * This is NOT collectAgentTitleEvidence with a different signature; the two answer different - * questions and diverge in BOTH directions, each pinned by test: + * This is NOT collectAgentTitleEvidence with a different signature. The parser answers "who does + * this title name, given no owner"; this answers "may this title take a pane". The second needs + * to know WHERE the name sits, which the first discards — `getAgentLabel` mints identity from + * `titleHasAgentName`, which asks only whether a name occurs anywhere, so one route there covers + * both `codex working` and `⠋ Fix the codex plugin launcher`. The two models therefore differ on + * purpose, in both directions, each pinned by test: * - * more permissive — the parser asks who a title names given no owner, so it must refuse any name - * an ordinary sentence could forge. Here the agent is supplied rather than inferred, so a name in - * the identity POSITION is enough. That admits `⠋ Codex`, which the parser files as - * `free-text-only` because codex sets `synthesizeWorkingTitle: false` in synthetic-agent-title.ts. + * more permissive — a name in an identity POSITION is enough here, which admits `⠋ Codex`; the + * parser files that as `free-text-only` because codex sets `synthesizeWorkingTitle: false`. * * less permissive — the parser resolves a lone vendor marker to its agent, including Claude's - * generic status decorations. Those are not identity here, or a `. `-prefixed OpenCode task title - * would reclaim the pane it was #8940's whole point to protect. + * generic status decorations. Those are not identity here, or a `. `-prefixed OpenCode task + * title would reclaim the pane #8940 exists to protect. + * + * Because they differ, agreement cannot be enforced by sharing code. It is enforced instead by + * the corpus ratchet in terminal-title-pane-claim-corpus.test.ts, which fails the moment a route + * `getAgentLabel` mints identity from stops being claimable here. */ export function titlePresentsAgent(title: string, agent: TuiAgent): boolean { return titlePresentedAgents(title).has(agent) diff --git a/src/shared/agent-title-name-anchoring.ts b/src/shared/agent-title-name-anchoring.ts index 728a8cd62d72..fd0a64f13952 100644 --- a/src/shared/agent-title-name-anchoring.ts +++ b/src/shared/agent-title-name-anchoring.ts @@ -4,6 +4,11 @@ import { HERMES_AGENT_NAME_RE, titleHasAgentName } from './agent-title-core' +import { stripLeadingAgentTitleDecorationOrEmpty } from './agent-title-decoration' +import { + getPiCompatibleSyntheticAgentLabel, + isLegacyPiCompatibleTitle +} from './pi-compatible-synthetic-title' import type { TuiAgent } from './tui-agent' import { TUI_AGENT_DISPLAY_NAMES } from './tui-agent-display-names' @@ -117,3 +122,39 @@ export function agentForWholeTitle(text: string): TuiAgent | null { } return agentForBareName(stripped) } + +/** Status words an agent appends to its own name in a title frame. */ +const IDENTITY_FRAME_STATUS_RE = /\s+(?:ready|idle|done|working|thinking|running|waiting|blocked)$/i +const IDENTITY_FRAME_ACTION_RE = /\s*[-–—]\s*action required$/i +/** The frame head: everything before the first separator an agent puts after its own name. */ +const IDENTITY_FRAME_HEAD_RE = /^([^:>—–|]+?)(?:\s*[:>—–|]|$)/ + +/** + * The agent a single title segment PRESENTS by putting its name in an identity position, as + * opposed to mentioning it inside task text. + * + * This generalizes the grammar `isClaudeIdentityFrameSegment` has always described — a name, an + * optional status word, an optional "- action required" — which was agent-neutral in shape and + * applied only to Claude. Every route `computeAgentLabel` mints identity from is a case of it: + * a bare name, `Codex: …`, `⠉ Codex — refactoring`, `codex working`, `aider.ps1 ready`, and a + * name at the head of a "|"-joined title. What it will not match is a name in the middle of a + * sentence, which is the only forgeable route and the whole reason this gate exists. + */ +export function agentForIdentityFrame(segment: string): TuiAgent | null { + // Pi and OMP print their own native format, which is not a name-plus-decoration shape at all. + const piCompatible = getPiCompatibleSyntheticAgentLabel(segment) + if (piCompatible) { + return piCompatible === 'OMP' ? 'omp' : 'pi' + } + if (isLegacyPiCompatibleTitle(segment)) { + return 'pi' + } + const undecorated = stripLeadingAgentTitleDecorationOrEmpty(segment).trim() + const head = IDENTITY_FRAME_HEAD_RE.exec(undecorated)?.[1]?.trim() + if (!head) { + return null + } + return agentForBareName( + head.replace(IDENTITY_FRAME_ACTION_RE, '').replace(IDENTITY_FRAME_STATUS_RE, '').trim() + ) +} diff --git a/src/shared/terminal-title-pane-claim-corpus.test.ts b/src/shared/terminal-title-pane-claim-corpus.test.ts new file mode 100644 index 000000000000..0dfe8c4ad380 --- /dev/null +++ b/src/shared/terminal-title-pane-claim-corpus.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from 'vitest' +import { TERMINAL_TITLE_CLASSIFICATION_CORPUS } from './terminal-title-classification-corpus' +import { + isClaudeIdentityFrameTitle, + resolveExplicitTerminalTitleAgentType +} from './terminal-title-agent-type' +import { titlePresentsAgent } from './agent-title-evidence' + +/** + * The ratchet that enforces agreement between the gate and the resolver that feeds it. + * + * `titlePresentsAgent` and `getAgentLabel` are different models on purpose — the gate needs to + * know WHERE a name sits and the resolver discards that. Agreement therefore cannot be enforced + * by sharing code, so it is enforced here instead: for every corpus title the resolver mints an + * identity from, the gate must still let that identity claim a pane. + * + * This exists because two rounds of review found the same class of defect. A predicate that was + * correct about its own evidence model silently stopped four whole routes — Pi's native titles, + * name-plus-status forms, "|"-headed titles and Windows launcher forms — from ever claiming a + * pane, and no test failed. Add a route to `getAgentLabel` that the gate cannot read and this + * goes red, naming the title. + */ + +/** The pre-change gate: any non-Claude title claimed, Claude needed an identity frame (#8940). */ +function claimedBeforeThisChange(title: string, agent: string): boolean { + return agent !== 'claude' || isClaudeIdentityFrameTitle(title) +} + +/** + * Titles the gate now accepts that the old one refused. Symmetry, not drift: the old gate accepted + * `aider.ps1 ready` for aider and refused the identical Windows-launcher-plus-status-word form for + * Claude, purely because the guard was Claude-only. Making the grammar agent-neutral necessarily + * makes Claude symmetric with every other agent; keeping the carve-out would preserve a Claude + * exception inside the change whose whole purpose is removing Claude exceptions. + */ +const INTENDED_NEW_CLAIMS: readonly string[] = ['claude.bat working'] + +describe('terminal title pane-claim corpus', () => { + it('never loses a pane claim the resolver still mints', () => { + const lost: string[] = [] + for (const title of TERMINAL_TITLE_CLASSIFICATION_CORPUS) { + const agent = resolveExplicitTerminalTitleAgentType(title) + if (!agent) { + continue + } + if (claimedBeforeThisChange(title, agent) && !titlePresentsAgent(title, agent)) { + lost.push(`${JSON.stringify(title)} -> ${agent}`) + } + } + expect(lost).toEqual([]) + }) + + it('gains only the claims listed as intended', () => { + const gained: string[] = [] + for (const title of TERMINAL_TITLE_CLASSIFICATION_CORPUS) { + const agent = resolveExplicitTerminalTitleAgentType(title) + if (!agent) { + continue + } + if (!claimedBeforeThisChange(title, agent) && titlePresentsAgent(title, agent)) { + gained.push(title) + } + } + expect(gained).toEqual([...INTENDED_NEW_CLAIMS]) + }) + + // The forgeable route, which is the only one the gate exists to stop. A name in the middle of a + // sentence is a mention; #8940's direction and #14937's direction are the same rule. + it('still refuses a name that only appears inside task text', () => { + const mustReject: [string, Parameters[1]][] = [ + ['⠋ Fix the codex plugin launcher', 'codex'], + ['⠙ Investigate why codex hangs on Windows', 'codex'], + ['⠹ compare codex and claude output', 'codex'], + ['⠋ add grok support to the tab bar', 'grok'], + ['⠋ port the gemini status parser', 'gemini'], + ['⠋ review copilot suggestions', 'copilot'], + ['⠋ refactor the aider bridge', 'aider'], + ['⠋ Codex plugin launcher rewrite', 'codex'], + ['. port the claude prompt', 'claude'], + ['. ship it with claude', 'claude'], + ['. Claude Code compare Opencode', 'claude'], + ['⠋ use Claude Sonnet', 'claude'], + ['OC | ⠋ ask claude about this', 'claude'], + ['. Compare Opencode Vs Orca', 'claude'], + ['✳ investigating startup', 'claude'] + ] + expect(mustReject.filter(([title, agent]) => titlePresentsAgent(title, agent))).toEqual([]) + }) + + // The routes round 2 lost. Named individually so a regression says which grammar broke. + it('accepts every route the resolver mints identity from', () => { + const routes: [string, Parameters[1]][] = [ + ['π > session - ~/orca', 'pi'], + ['π ! blocked-session', 'pi'], + ['⠋ π - session - ~/orca', 'pi'], + ['codex working', 'codex'], + ['grok done', 'grok'], + ['devin thinking', 'devin'], + ['mimo idle', 'mimo-code'], + ['aider running', 'aider'], + ['copilot waiting', 'copilot'], + ['opencode ready', 'opencode'], + ['ssh host | opencode ready', 'opencode'], + ['⠉ Codex — refactoring', 'codex'], + ['aider.ps1 ready', 'aider'], + ['copilot.exe - action required', 'copilot'], + ['✦ Analyzing the repository', 'gemini'], + ['cursor agent', 'cursor'], + ['⠋ Codex', 'codex'], + ['⠋ Codex: fix cursor offsets', 'codex'], + ['⠋ Claude Code', 'claude'] + ] + expect(routes.filter(([title, agent]) => !titlePresentsAgent(title, agent))).toEqual([]) + }) +}) From 8b65244ffc0362596f74afc976f83bd6be9556ad Mon Sep 17 00:00:00 2001 From: Merge Sim Date: Mon, 7 Sep 2026 13:16:23 -0700 Subject: [PATCH 06/13] fix(agents): stop reading a wrapper prefix as an identity frame MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The head grammar treated '|' as a separator an agent puts after its own name. Wrappers PREFIX the pane's title and the innermost title comes LAST (terminal-title-wrapper-segments.ts), so a name before a '|' is a tmux window or an ssh host, never the pane. `claude | zsh` on a Codex-owned pane therefore handed it to Claude through all three consumers — this change's own bug, inverted. Wrapper-joined titles already reach the real pane title through getEvidenceTitleSegments' suffix splitting, which is what actually resolves `ssh host | opencode ready`; the separator was not carrying that case. '>' goes too. Pi's native `π > session` is matched before the head grammar runs, so the only titles it affected were `name > text` breadcrumbs, which are closer to task text than to an identity frame. That narrows `⠋ gemini > next steps` and `⠋ codex > plan` relative to the previous gate; both are pinned as intended rejections, since refusing leaves the pane with its known owner, which is the safe direction on ambiguous evidence. The corpus gain assertion is renamed to say it is corpus-scoped. Over every string literal in the repo the change gains more than the one title this 67-title corpus can see, mostly the same Claude symmetry, and the test should not read as a global guarantee. Near-misses the grammar deliberately accepts are pinned too, so the boundary is visible and moving it requires editing a list. --- src/shared/agent-title-name-anchoring.ts | 20 +++++++--- .../terminal-title-pane-claim-corpus.test.ts | 39 +++++++++++++++++-- 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/src/shared/agent-title-name-anchoring.ts b/src/shared/agent-title-name-anchoring.ts index fd0a64f13952..9d813fd220d7 100644 --- a/src/shared/agent-title-name-anchoring.ts +++ b/src/shared/agent-title-name-anchoring.ts @@ -126,8 +126,18 @@ export function agentForWholeTitle(text: string): TuiAgent | null { /** Status words an agent appends to its own name in a title frame. */ const IDENTITY_FRAME_STATUS_RE = /\s+(?:ready|idle|done|working|thinking|running|waiting|blocked)$/i const IDENTITY_FRAME_ACTION_RE = /\s*[-–—]\s*action required$/i -/** The frame head: everything before the first separator an agent puts after its own name. */ -const IDENTITY_FRAME_HEAD_RE = /^([^:>—–|]+?)(?:\s*[:>—–|]|$)/ +/** + * The frame head: everything before the first separator an agent puts after its own name. + * + * Deliberately excludes '|'. Wrappers PREFIX the pane's title and the innermost title comes LAST + * (terminal-title-wrapper-segments.ts), so a name before a '|' is a tmux window or ssh host, not + * the pane — reading it as identity hands a Codex pane in a window named `claude` to Claude, which + * is this change's own bug inverted. Wrapper-joined titles reach the real pane title through + * getEvidenceTitleSegments' suffix splitting instead, which is what resolves `ssh host | opencode + * ready`. '>' is excluded for the same reason it is unnecessary: Pi's native `π > session` form is + * matched by the branch above, before this regex runs. + */ +const IDENTITY_FRAME_HEAD_RE = /^([^:—–]+?)(?:\s*[:—–]|$)/ /** * The agent a single title segment PRESENTS by putting its name in an identity position, as @@ -136,9 +146,9 @@ const IDENTITY_FRAME_HEAD_RE = /^([^:>—–|]+?)(?:\s*[:>—–|]|$)/ * This generalizes the grammar `isClaudeIdentityFrameSegment` has always described — a name, an * optional status word, an optional "- action required" — which was agent-neutral in shape and * applied only to Claude. Every route `computeAgentLabel` mints identity from is a case of it: - * a bare name, `Codex: …`, `⠉ Codex — refactoring`, `codex working`, `aider.ps1 ready`, and a - * name at the head of a "|"-joined title. What it will not match is a name in the middle of a - * sentence, which is the only forgeable route and the whole reason this gate exists. + * a bare name, `Codex: …`, `⠉ Codex — refactoring`, `codex working` and `aider.ps1 ready`. What + * it will not match is a name in the middle of a sentence, nor a name in a wrapper prefix — + * the two forgeable routes, and the whole reason this gate exists. */ export function agentForIdentityFrame(segment: string): TuiAgent | null { // Pi and OMP print their own native format, which is not a name-plus-decoration shape at all. diff --git a/src/shared/terminal-title-pane-claim-corpus.test.ts b/src/shared/terminal-title-pane-claim-corpus.test.ts index 0dfe8c4ad380..c571f03a9055 100644 --- a/src/shared/terminal-title-pane-claim-corpus.test.ts +++ b/src/shared/terminal-title-pane-claim-corpus.test.ts @@ -27,7 +27,12 @@ function claimedBeforeThisChange(title: string, agent: string): boolean { } /** - * Titles the gate now accepts that the old one refused. Symmetry, not drift: the old gate accepted + * Titles IN THIS CORPUS that the gate now accepts and the old one refused. Corpus-scoped, and the + * test name says so: swept over every string literal in the repo the change gains more than this, + * mostly the same symmetry (`claude:`, `claude — `, `claude.exe`). This asserts what a + * 67-title corpus can assert, not a global guarantee. + * + * Symmetry, not drift: the old gate accepted * `aider.ps1 ready` for aider and refused the identical Windows-launcher-plus-status-word form for * Claude, purely because the guard was Claude-only. Making the grammar agent-neutral necessarily * makes Claude symmetric with every other agent; keeping the carve-out would preserve a Claude @@ -50,7 +55,7 @@ describe('terminal title pane-claim corpus', () => { expect(lost).toEqual([]) }) - it('gains only the claims listed as intended', () => { + it('gains only the listed claims, within this corpus', () => { const gained: string[] = [] for (const title of TERMINAL_TITLE_CLASSIFICATION_CORPUS) { const agent = resolveExplicitTerminalTitleAgentType(title) @@ -82,11 +87,39 @@ describe('terminal title pane-claim corpus', () => { ['⠋ use Claude Sonnet', 'claude'], ['OC | ⠋ ask claude about this', 'claude'], ['. Compare Opencode Vs Orca', 'claude'], - ['✳ investigating startup', 'claude'] + ['✳ investigating startup', 'claude'], + // A wrapper PREFIXES the pane title (terminal-title-wrapper-segments.ts), so a name before + // a '|' is a tmux window or ssh host, never the pane. Reading it as identity handed a Codex + // pane in a window named `claude` to Claude — this change's own bug, inverted. + ['claude | zsh', 'claude'], + ['claude | ~/orca', 'claude'], + ['codex | main | Fix the parser', 'codex'], + // '>' is not an identity separator for any agent except Pi, whose native form is matched + // before the head grammar runs. `name > text` reads as a breadcrumb, so these narrow + // relative to the pre-change gate, which claimed them. Deliberate: refusing keeps the pane + // with its known owner, which is the safe direction on ambiguous evidence. + ['⠋ gemini > next steps', 'gemini'], + ['⠋ codex > plan', 'codex'] ] expect(mustReject.filter(([title, agent]) => titlePresentsAgent(title, agent))).toEqual([]) }) + /** + * The ACCEPTED boundary, pinned so a future widening is visible rather than silent. Each of + * these hands the pane to the named agent, and did so before this change too — they are the + * cost of accepting `Codex: fix cursor offsets` and `codex working` as identity at all. Nothing + * regresses here; the point is that the line sits between these and the must-reject set above, + * and moving it should require editing this list. + */ + it('accepts these near-misses, deliberately', () => { + const accepted: [string, Parameters[1]][] = [ + ['⠋ codex: why does this hang', 'codex'], + ['⠋ codex — investigating', 'codex'], + ['⠋ aider done', 'aider'] + ] + expect(accepted.filter(([title, agent]) => !titlePresentsAgent(title, agent))).toEqual([]) + }) + // The routes round 2 lost. Named individually so a regression says which grammar broke. it('accepts every route the resolver mints identity from', () => { const routes: [string, Parameters[1]][] = [ From 5f6673188fef86d61b4d855e91987d61e3a22e9c Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:16:08 -0700 Subject: [PATCH 07/13] fix(agents): admit identity frames before trusting terminal titles --- .../session/mobile-terminal-tab-agent.test.ts | 12 ++ .../title-derived-pane-agent-identity.ts | 23 +- .../worktree-title-derived-agent-rows.test.ts | 33 ++- .../terminal-pane/terminal-ctrl-enter.test.ts | 6 + .../terminal-windows-shift-enter.test.ts | 8 + src/renderer/src/lib/use-tab-agent.test.ts | 20 +- src/shared/agent-title-evidence.ts | 197 +++++------------- src/shared/agent-title-name-anchoring.ts | 159 ++++++++++++++ src/shared/tab-agent-from-signals.ts | 9 +- src/shared/terminal-title-agent-type.test.ts | 76 +++++++ src/shared/terminal-title-agent-type.ts | 28 +-- 11 files changed, 377 insertions(+), 194 deletions(-) create mode 100644 src/shared/agent-title-name-anchoring.ts diff --git a/mobile/src/session/mobile-terminal-tab-agent.test.ts b/mobile/src/session/mobile-terminal-tab-agent.test.ts index e171b1c540d4..e316baf6d190 100644 --- a/mobile/src/session/mobile-terminal-tab-agent.test.ts +++ b/mobile/src/session/mobile-terminal-tab-agent.test.ts @@ -47,6 +47,18 @@ function terminalTab( } describe('resolveMobileTerminalTabAgentId', () => { + it('keeps completed Claude ownership when task text names another agent', () => { + expect( + resolveMobileTerminalTabAgentId( + terminalTab('⠋ fix the grok launcher', { + agentType: 'claude', + state: 'done', + launchAgent: 'claude' + }) + ) + ).toBe('claude') + }) + it('uses hook-reported agent identity before title fallback', () => { expect(resolveMobileTerminalTabAgentId(terminalTab('Terminal', { agentType: 'codex' }))).toBe( 'codex' diff --git a/src/renderer/src/components/sidebar/title-derived-pane-agent-identity.ts b/src/renderer/src/components/sidebar/title-derived-pane-agent-identity.ts index e9e42aff6364..01484d5870fe 100644 --- a/src/renderer/src/components/sidebar/title-derived-pane-agent-identity.ts +++ b/src/renderer/src/components/sidebar/title-derived-pane-agent-identity.ts @@ -1,7 +1,7 @@ import { titleShowsNoAgent } from '../../../../shared/agent-detection' import type { AgentType } from '../../../../shared/agent-status-types' import { resolveCompatibleAgentTypeForOwner } from '../../../../shared/agent-title-owner' -import { isClaudeIdentityFrameTitle } from '../../../../shared/terminal-title-agent-type' +import { resolveExplicitTerminalTitleAgentType } from '../../../../shared/terminal-title-agent-type' import type { PaneForegroundAgentEntry } from '@/store/slices/pane-foreground-agent' const TITLE_AGENT_LABEL_TO_TYPE: Record = { @@ -24,27 +24,16 @@ const TITLE_AGENT_LABEL_TO_TYPE: Record = { OMP: 'omp' } -const CLAUDE_AGENT_TOKEN_RE = /(? { expect( rowsFor('✳ Claude Code', 'opencode', processRead('claude')).map((row) => row.agentType) ).toEqual(['claude']) - // No owner to defend the pane: naming Claude stays the only available identity. - expect(rowsFor('⠋ use Claude Sonnet').map((row) => row.agentType)).toEqual(['claude']) + // Task mentions cannot establish identity even when the pane has no owner. + expect(rowsFor('⠋ use Claude Sonnet')).toHaveLength(0) expect(rowsFor('zsh', 'opencode')).toHaveLength(0) }) @@ -725,3 +728,27 @@ describe('split-pane runtime title attribution', () => { ]) }) }) + +describe('owner identity with foreign task names', () => { + it('preserves the unknown-label fallback for an admitted identity', () => { + expect(resolveTitleDerivedAgentType('MiMo Code', 'MiMo Code')).toBe('unknown') + }) + + it.each([ + '⠋ Fix the codex plugin launcher', + '⠋ fix the grok launcher', + '⠋ port the gemini status parser', + '⠋ fix the mimo launcher' + ])('keeps the existing Claude row for %j', (title) => { + const rows = buildWorktreeAgentRows({ + tabs: [makeTab('tab-1', { launchAgent: 'claude' })], + entries: [], + retained: [], + runtimePaneTitlesByTabId: { 'tab-1': { 1: title } }, + ptyIdsByTabId: { 'tab-1': ['pty-claude'] }, + terminalLayoutsByTabId: { 'tab-1': makeSingleLayout(LEAF_ID_1) }, + now: 2000 + }) + expect(rows.map((row) => [row.agentType, row.entry.prompt])).toEqual([['claude', 'Claude']]) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts b/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts index 94c277436cfa..bc35b8d166ef 100644 --- a/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts @@ -4,6 +4,12 @@ import { hasCtrlEnterCsiUAuthorityForPane } from './terminal-ctrl-enter' const PANE_KEY = 'tab:pane' describe('hasCtrlEnterCsiUAuthorityForPane', () => { + it('does not route input using an agent mentioned only in task text', () => { + const state = { paneForegroundAgentByPaneKey: {} } + expect(hasCtrlEnterCsiUAuthorityForPane(state, PANE_KEY, '⠋ fix the grok launcher')).toBe(false) + expect(hasCtrlEnterCsiUAuthorityForPane(state, PANE_KEY, '⠋ Grok')).toBe(true) + }) + it.each([ { agent: 'dsb' as const, routingTrusted: true, shellForeground: false }, { agent: 'dsb' as const, routingConfirmationPending: true, shellForeground: false } diff --git a/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts b/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts index 5dcbd338d249..a29d0da4d53f 100644 --- a/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts @@ -5,6 +5,14 @@ import { } from './terminal-windows-shift-enter' describe('resolveWindowsShiftEnterEncoding', () => { + it('does not select a keyboard mode from a task mentioning another agent', () => { + const state = { paneForegroundAgentByPaneKey: {}, agentLaunchConfigByPaneKey: {} } + expect( + resolveWindowsShiftEnterEncodingForPane(state, 'tab:pane', '⠋ fix the droid launcher') + ).toBe('alt-enter') + expect(resolveWindowsShiftEnterEncodingForPane(state, 'tab:pane', '⠋ Droid')).toBe('csi-u') + }) + it.each(['dsb', 'codex'] as const)( 'keeps pending %s input encoding when a stale title names another agent', (agent) => { diff --git a/src/renderer/src/lib/use-tab-agent.test.ts b/src/renderer/src/lib/use-tab-agent.test.ts index 56dc6df698fe..6c3d2ef32a33 100644 --- a/src/renderer/src/lib/use-tab-agent.test.ts +++ b/src/renderer/src/lib/use-tab-agent.test.ts @@ -415,7 +415,7 @@ describe('resolveTabAgentFromSignals', () => { ).toBe('codex') }) - it('treats Claude-prefixed title text as Claude only when it names Claude', () => { + it('requires a Claude identity frame even without a known owner', () => { expect( resolveTabAgentFromSignals({ hasObservedAgentSignal: false, @@ -434,7 +434,7 @@ describe('resolveTabAgentFromSignals', () => { hookAgent: null, launchAgent: undefined }) - ).toBe('claude') + ).toBeNull() }) it('clears local launch identity once observed activity vanishes at a shell title', () => { @@ -546,6 +546,22 @@ describe('useTabAgent', () => { launchAgent: 'codex' } + it('paints the completed owner while its task names another agent', async () => { + const paneKey = makePaneKey('tab-1', LEAF_ID) + useAppStore.setState({ + terminalLayoutsByTabId: { + 'tab-1': { + root: { type: 'leaf', leafId: LEAF_ID }, + activeLeafId: LEAF_ID, + expandedLeafId: null + } + }, + agentStatusByPaneKey: { [paneKey]: { ...completedAgentStatus(paneKey), agentType: 'claude' } } + }) + await renderHookProbe({ ...baseTab, launchAgent: 'claude', title: '⠋ fix the grok launcher' }) + expect(latestHookAgent).toBe('claude') + }) + beforeEach(() => { latestHookAgent = undefined getForegroundProcess.mockReset() diff --git a/src/shared/agent-title-evidence.ts b/src/shared/agent-title-evidence.ts index 500dee34dc05..cd39d33ddee7 100644 --- a/src/shared/agent-title-evidence.ts +++ b/src/shared/agent-title-evidence.ts @@ -1,28 +1,36 @@ import { - AGY_AGENT_NAME_RE, CLAUDE_IDLE, - DROID_AGENT_NAME_RE, GEMINI_IDLE, GEMINI_PERMISSION, GEMINI_SILENT_WORKING, GEMINI_WORKING, - HERMES_AGENT_NAME_RE, containsAgentSpinnerGlyph, isClaudeIdentityFrameSegment, isClaudeManagementTitle, - isCursorNativeAgentTitle, - titleHasAgentName + isCursorNativeAgentTitle } from './agent-title-core' import { isOpenCodeNativeTitle } from './opencode-terminal-title' import { isDeepSeekBuildTerminalTitle } from './dsb-terminal-title' import { stripLeadingAgentTitleDecorationOrEmpty } from './agent-title-decoration' -import { getPiCompatibleSyntheticAgentLabel } from './pi-compatible-synthetic-title' +import { + getPiCompatibleSyntheticAgentLabel, + getPiCompatibleTitleBrand, + isLegacyPiCompatibleTitle +} from './pi-compatible-synthetic-title' +import { isDshTerminalTitle } from './dsh-terminal-title' +import { isQoderTerminalTitle } from './qoder-terminal-title' import { SYNTHETIC_AGENT_TITLE_AGENTS, SYNTHETIC_AGENT_TITLE_PROFILES } from './synthetic-agent-title' import type { TerminalAgent } from './terminal-agent' -import { TUI_AGENT_DISPLAY_NAMES } from './tui-agent-display-names' +import { + agentForNativeFrame, + agentForOwnerSuffix, + agentForWholeTitle, + namesConsumedByAnchoredLabels, + namesIn +} from './agent-title-name-anchoring' /** Collect before ranking: anchored identity names outrank vendor glyphs, which outrank free-text mentions. Free text alone never identifies a pane; prefer no icon to a wrong one. Activity parsing handles generic busy signals separately. */ export type AgentTitleEvidenceReason = @@ -42,62 +50,13 @@ export type AgentTitleEvidence = { readonly reason: AgentTitleEvidenceReason } -/** Names matched as whole tokens, paired with the agent each identifies. */ -const NAME_TOKENS: readonly (readonly [string, TerminalAgent])[] = [ - ['claude', 'claude'], - ['openclaude', 'openclaude'], - ['codex', 'codex'], - ['copilot', 'copilot'], - ['cursor', 'cursor'], - ['gemini', 'gemini'], - ['antigravity', 'antigravity'], - ['opencode', 'opencode'], - ['mimo', 'mimo-code'], - ['openclaw', 'openclaw'], - ['aider', 'aider'], - ['grok', 'grok'], - ['devin', 'devin'] -] - -/** Agents whose name is matched by a dedicated pattern rather than a plain token. */ -const PATTERN_NAMES: readonly (readonly [RegExp, TerminalAgent])[] = [ - [AGY_AGENT_NAME_RE, 'antigravity'], - [DROID_AGENT_NAME_RE, 'droid'], - [HERMES_AGENT_NAME_RE, 'hermes'] -] - -/** Catalog labels known to be emitted as terminal titles, not merely presented in Orca's UI. */ -const EMITTED_DISPLAY_LABEL_AGENTS = [ - 'claude-agent-teams', - 'mimo-code', - 'prime-agent', - 'command-code', - 'copilot' -] as const satisfies readonly TerminalAgent[] - -const DISPLAY_LABELS = [ - ...EMITTED_DISPLAY_LABEL_AGENTS.map( - (agent) => [TUI_AGENT_DISPLAY_NAMES[agent].toLowerCase(), agent] as const - ), - ['claude code', 'claude'], - ['gemini cli', 'gemini'], - ['agent teams', 'claude-agent-teams'] -] satisfies readonly (readonly [string, TerminalAgent])[] - const GEMINI_GLYPHS = [GEMINI_WORKING, GEMINI_SILENT_WORKING, GEMINI_IDLE, GEMINI_PERMISSION] const ANTIGRAVITY_MODEL_TITLE_RE = /^(?:agy|antigravity)(?:\s*[\u00B7\u2014:-]\s*|\s+)gemini\s+\d/i /** Orca owns the final - suffix. Require leading whitespace to avoid treating hyphenated cwd names as ownership. */ const OWNER_SUFFIX_RE = /\s-\s+([A-Za-z][\w-]*)\s*$/ -const WINDOWS_LAUNCHER_SUFFIX_RE = /\.(?:exe|cmd|bat|ps1)$/i const WRAPPER_SEPARATOR = ' | ' const MAX_WRAPPER_EVIDENCE_SEGMENTS = 8 -const RESERVED_OWNER_IDS: ReadonlyMap = new Map([ - ['pi', 'pi'], - ['omp', 'omp'], - ['claude-agent-teams', 'claude-agent-teams'], - ['qwen-code', 'qwen-code'] -]) function getEvidenceTitleSegments(title: string): string[] { const segments = [title] @@ -116,68 +75,6 @@ function getEvidenceTitleSegments(title: string): string[] { return segments } -function namesIn(text: string): TerminalAgent[] { - const found = new Set() - for (const [token, agent] of NAME_TOKENS) { - if (titleHasAgentName(text, token)) { - found.add(agent) - } - } - for (const [pattern, agent] of PATTERN_NAMES) { - if (pattern.test(text)) { - found.add(agent) - } - } - return [...found] -} - -function stripBareNameDecoration(text: string): string { - return text - .trim() - .replace(/^[^\p{L}\p{N}]+/u, '') - .replace(/[^\p{L}\p{N}]+$/u, '') -} - -function agentForBareName(text: string): TerminalAgent | null { - const trimmed = text.trim() - if (!trimmed || /[\\/]/.test(trimmed)) { - return null - } - const stripped = stripBareNameDecoration(trimmed) - // The entire vendor display label makes the same identity claim as a bare agent token. - const normalized = stripped.toLowerCase() - const label = DISPLAY_LABELS.find(([text]) => text === normalized) - if (label) { - return label[1] - } - const bareToken = stripped.replace(WINDOWS_LAUNCHER_SUFFIX_RE, '') - const names = namesIn(bareToken) - // Require the whole remainder to be the name; task phrases and hyphenated directories cannot anchor identity. - return names.length === 1 && /^[\p{L}\p{N}]+$/u.test(bareToken) ? names[0] : null -} - -function agentForWholeTitle(text: string): TerminalAgent | null { - const trimmed = text.trim() - if (!trimmed || /[\\/]/.test(trimmed)) { - return null - } - const stripped = stripBareNameDecoration(trimmed) - const normalized = stripped.toLowerCase() - const label = DISPLAY_LABELS.find(([text]) => text === normalized) - if (label) { - return label[1] - } - if (!WINDOWS_LAUNCHER_SUFFIX_RE.test(stripped)) { - return null - } - return agentForBareName(stripped) -} - -function agentForOwnerSuffix(text: string): TerminalAgent | null { - const normalized = text.trim().toLowerCase() - return RESERVED_OWNER_IDS.get(normalized) ?? agentForBareName(text) -} - function agentForSyntheticTitle(text: string): TerminalAgent | null { const trimmed = text.trim() if (/[\\/]/.test(trimmed)) { @@ -229,30 +126,15 @@ function collectVendorMarkers(segments: readonly string[]): TerminalAgent[] { return [...markers] } -function namesConsumedByAnchoredLabels( - segments: readonly string[], - anchoredNames: ReadonlySet -): Set { - const consumed = new Set() - for (const segment of segments) { - const normalized = stripBareNameDecoration(segment).toLowerCase() - const label = DISPLAY_LABELS.find(([text]) => text === normalized) - if (label && anchoredNames.has(label[1])) { - for (const name of namesIn(label[0])) { - consumed.add(name) - } - } - } - return consumed -} - function collectAnchoredNames( segments: readonly string[], - vendorMarkers: readonly TerminalAgent[] + vendorMarkers: readonly TerminalAgent[], + nativeFrames: boolean ): TerminalAgent[] { const anchored = new Set() // Why: a native owner's task text can end with DSB's product-name suffix, including inside wrappers. - const allowDsbTitle = vendorMarkers.length === 0 && !segments.some(isOpenCodeNativeTitle) + const nativeOpenCode = segments.some(isOpenCodeNativeTitle) + const allowDsbTitle = vendorMarkers.length === 0 && !nativeOpenCode for (const segment of segments) { // Native wrapped titles own their envelope even when session text names other agents. @@ -263,6 +145,26 @@ function collectAnchoredNames( anchored.add('dsb') } + if (nativeFrames && !nativeOpenCode) { + const native = agentForNativeFrame(segment) + if (native) { + anchored.add(native) + } + if ( + isDshTerminalTitle(segment) && + stripLeadingAgentTitleDecorationOrEmpty(segment).startsWith('🐋') + ) { + anchored.add('dsh') + } + if (isQoderTerminalTitle(segment)) { + anchored.add(segment.includes('Qoder CLI CN') ? 'qoder-cn' : 'qoder') + } + const piBrand = getPiCompatibleTitleBrand(segment) + if (piBrand || isLegacyPiCompatibleTitle(segment)) { + anchored.add(piBrand === 'OMP' ? 'omp' : 'pi') + } + } + const suffix = OWNER_SUFFIX_RE.exec(segment) if (suffix) { const agent = agentForOwnerSuffix(suffix[1]) @@ -271,6 +173,11 @@ function collectAnchoredNames( } } + // OpenCode owns its session envelope; only competing owner suffixes can conflict. + if (nativeFrames && nativeOpenCode) { + continue + } + // Strip the leading sigil to expose anchored names: in ✳ agy, the name outranks the inherited Claude glyph. const withoutSigil = segment.startsWith(`${CLAUDE_IDLE} `) ? segment.slice(CLAUDE_IDLE.length) @@ -305,7 +212,7 @@ function collectAnchoredNames( } /** Collects every identity signal in `title` and ranks them by class, never by declaration order. */ -export function collectAgentTitleEvidence(title: string): AgentTitleEvidence { +function collectTitleEvidence(title: string, nativeFrames: boolean): AgentTitleEvidence { const empty = { vendorMarkers: [], anchoredNames: [], freeTextNames: [] } as const if (!title.trim() || isClaudeManagementTitle(title)) { // Why: a `claude agents` management screen is Claude's own UI, not an agent session. @@ -314,7 +221,7 @@ export function collectAgentTitleEvidence(title: string): AgentTitleEvidence { const segments = getEvidenceTitleSegments(title) const vendorMarkers = collectVendorMarkers(segments) - const anchoredNames = collectAnchoredNames(segments, vendorMarkers) + const anchoredNames = collectAnchoredNames(segments, vendorMarkers, nativeFrames) const anchoredSet = new Set(anchoredNames) const anchoredLabelNames = namesConsumedByAnchoredLabels(segments, anchoredSet) const freeTextNames = namesIn(title).filter( @@ -332,7 +239,7 @@ export function collectAgentTitleEvidence(title: string): AgentTitleEvidence { if (vendorMarkers.length > 1) { return { ...evidence, agent: null, reason: 'conflicting-vendor-markers' } } - if (vendorMarkers.length === 1) { + if (vendorMarkers.length === 1 && (!nativeFrames || vendorMarkers[0] !== 'claude')) { // Free-text names cannot veto a vendor glyph (✳ Fix Codex… is Claude); a conflicting anchored name already outranks it. return { ...evidence, agent: vendorMarkers[0], reason: 'vendor-marker' } } @@ -342,3 +249,13 @@ export function collectAgentTitleEvidence(title: string): AgentTitleEvidence { reason: freeTextNames.length > 0 ? 'free-text-only' : 'no-evidence' } } + +/** Canonical host evidence retains its existing conservative title vocabulary. */ +export function collectAgentTitleEvidence(title: string): AgentTitleEvidence { + return collectTitleEvidence(title, false) +} + +/** Hookless terminal readers also admit native named frames, but generic Claude activity cannot claim identity. */ +export function collectExplicitAgentTitleEvidence(title: string): AgentTitleEvidence { + return collectTitleEvidence(title, true) +} diff --git a/src/shared/agent-title-name-anchoring.ts b/src/shared/agent-title-name-anchoring.ts new file mode 100644 index 000000000000..3f17f2d44be1 --- /dev/null +++ b/src/shared/agent-title-name-anchoring.ts @@ -0,0 +1,159 @@ +import { + AGY_AGENT_NAME_RE, + DROID_AGENT_NAME_RE, + HERMES_AGENT_NAME_RE, + titleHasAgentName +} from './agent-title-core' +import { stripLeadingAgentTitleDecorationOrEmpty } from './agent-title-decoration' +import type { TerminalAgent } from './terminal-agent' +import { ALL_TUI_AGENTS, TUI_AGENT_DISPLAY_NAMES } from './tui-agent-display-names' + +/** Names matched as whole tokens, paired with the agent each identifies. */ +const NAME_TOKENS: readonly (readonly [string, TerminalAgent])[] = [ + ['claude', 'claude'], + ['openclaude', 'openclaude'], + ['codex', 'codex'], + ['copilot', 'copilot'], + ['cursor', 'cursor'], + ['gemini', 'gemini'], + ['antigravity', 'antigravity'], + ['opencode', 'opencode'], + ['mimo', 'mimo-code'], + ['openclaw', 'openclaw'], + ['aider', 'aider'], + ['grok', 'grok'], + ['devin', 'devin'] +] + +/** Agents whose name is matched by a dedicated pattern rather than a plain token. */ +const PATTERN_NAMES: readonly (readonly [RegExp, TerminalAgent])[] = [ + [AGY_AGENT_NAME_RE, 'antigravity'], + [DROID_AGENT_NAME_RE, 'droid'], + [HERMES_AGENT_NAME_RE, 'hermes'] +] + +/** Catalog labels known to be emitted as terminal titles, not merely presented in Orca's UI. */ +const EMITTED_DISPLAY_LABEL_AGENTS = [ + 'claude-agent-teams', + 'mimo-code', + 'prime-agent', + 'command-code', + 'copilot' +] as const satisfies readonly TerminalAgent[] + +const DISPLAY_LABELS = [ + ...EMITTED_DISPLAY_LABEL_AGENTS.map( + (agent) => [TUI_AGENT_DISPLAY_NAMES[agent].toLowerCase(), agent] as const + ), + ['claude code', 'claude'], + ['gemini cli', 'gemini'], + ['agent teams', 'claude-agent-teams'] +] satisfies readonly (readonly [string, TerminalAgent])[] + +const WINDOWS_LAUNCHER_SUFFIX_RE = /\.(?:exe|cmd|bat|ps1)$/i +const RESERVED_OWNER_IDS: ReadonlyMap = new Map([ + ['pi', 'pi'], + ['omp', 'omp'], + ['claude-agent-teams', 'claude-agent-teams'], + ['qwen-code', 'qwen-code'] +]) + +export function namesIn(text: string): TerminalAgent[] { + const found = new Set() + for (const [token, agent] of NAME_TOKENS) { + if (titleHasAgentName(text, token)) { + found.add(agent) + } + } + for (const [pattern, agent] of PATTERN_NAMES) { + if (pattern.test(text)) { + found.add(agent) + } + } + return [...found] +} + +function stripBareNameDecoration(text: string): string { + return text + .trim() + .replace(/^[^\p{L}\p{N}]+/u, '') + .replace(/[^\p{L}\p{N}]+$/u, '') +} + +function agentForBareName(text: string): TerminalAgent | null { + const trimmed = text.trim() + if (!trimmed || /[\\/]/.test(trimmed)) { + return null + } + const stripped = stripBareNameDecoration(trimmed) + // The entire vendor display label makes the same identity claim as a bare agent token. + const normalized = stripped.toLowerCase() + const label = DISPLAY_LABELS.find(([text]) => text === normalized) + if (label) { + return label[1] + } + const bareToken = stripped.replace(WINDOWS_LAUNCHER_SUFFIX_RE, '') + const names = namesIn(bareToken) + // Require the whole remainder to be the name; task phrases and hyphenated directories cannot anchor identity. + return names.length === 1 && /^[\p{L}\p{N}]+$/u.test(bareToken) ? names[0] : null +} + +export function agentForWholeTitle(text: string): TerminalAgent | null { + const trimmed = text.trim() + if (!trimmed || /[\\/]/.test(trimmed)) { + return null + } + const stripped = stripBareNameDecoration(trimmed) + const normalized = stripped.toLowerCase() + const label = DISPLAY_LABELS.find(([text]) => text === normalized) + if (label) { + return label[1] + } + if (!WINDOWS_LAUNCHER_SUFFIX_RE.test(stripped)) { + return null + } + return agentForBareName(stripped) +} + +export function agentForOwnerSuffix(text: string): TerminalAgent | null { + const normalized = text.trim().toLowerCase() + return RESERVED_OWNER_IDS.get(normalized) ?? agentForBareName(text) +} + +/** Native frames identify an agent by a complete name, a named status, or a name before task text. */ +export function agentForNativeFrame(text: string): TerminalAgent | null { + const undecorated = stripLeadingAgentTitleDecorationOrEmpty(text).trim() + const frameName = undecorated.replace( + /(?::\s+.*|\s*[\u2013\u2014]\s*.*|\s+(?:ready|idle|done|working|thinking|running|waiting|permission)|\s+-\s+action required)$/i, + '' + ) + if (!frameName || /[|>\\/]/.test(frameName)) { + return null + } + const normalized = frameName.replace(WINDOWS_LAUNCHER_SUFFIX_RE, '').toLowerCase() + const agent = + agentForBareName(frameName) ?? + ALL_TUI_AGENTS.find( + (agent) => normalized === agent || normalized === TUI_AGENT_DISPLAY_NAMES[agent].toLowerCase() + ) ?? + null + // Pi/OMP have their own separator grammar, including special spinner requirements. + return agent === 'pi' || agent === 'omp' ? null : agent +} + +export function namesConsumedByAnchoredLabels( + segments: readonly string[], + anchoredNames: ReadonlySet +): Set { + const consumed = new Set() + for (const segment of segments) { + const normalized = stripBareNameDecoration(segment).toLowerCase() + const label = DISPLAY_LABELS.find(([text]) => text === normalized) + if (label && anchoredNames.has(label[1])) { + for (const name of namesIn(label[0])) { + consumed.add(name) + } + } + } + return consumed +} diff --git a/src/shared/tab-agent-from-signals.ts b/src/shared/tab-agent-from-signals.ts index aa3f188b1890..3661d358f257 100644 --- a/src/shared/tab-agent-from-signals.ts +++ b/src/shared/tab-agent-from-signals.ts @@ -1,8 +1,5 @@ import { titleShowsNoAgent } from './agent-detection' -import { - isClaudeIdentityFrameTitle, - resolveExplicitTerminalTitleAgentType -} from './terminal-title-agent-type' +import { resolveExplicitTerminalTitleAgentType } from './terminal-title-agent-type' import { resolveCompatibleAgentTypeForOwner, shareCompatibleTitleIdentityGroup @@ -112,9 +109,6 @@ export function resolveTabAgentFromSignals(args: { const explicitTitleAgent = resolveSignalAgentForLaunchOwner(rawTitleAgent, owner, ownerIsLaunch) const priorIdentity = idleFocusedIdentity ?? launchAgent const nativeOpenCodeTitle = explicitTitleAgent === 'opencode' && isOpenCodeNativeTitle(args.title) - // A task mentioning claude cannot take another agent’s pane; only titles presenting Claude establish identity (#8940). - const titleClaimsIdentity = - explicitTitleAgent !== 'claude' || isClaudeIdentityFrameTitle(args.title) // Why: native OpenCode titles can reclaim stale launch intent before any observed hook signal. // Raw title group, not the fallback-rewritten agent: inferred Pi owners would otherwise treat an OMP wrapper title as a different identity. const titleReclaimsReusedPane = @@ -122,7 +116,6 @@ export function resolveTabAgentFromSignals(args: { explicitTitleAgent !== null && explicitTitleAgent !== priorIdentity && !shareCompatibleTitleIdentityGroup(rawTitleAgent, priorIdentity) && - titleClaimsIdentity && (args.hasObservedAgentSignal || hasCompletedHook || nativeOpenCodeTitle) // Why: native OpenCode titles lack a provider generation and cannot displace durable ownership. const titleAgent = diff --git a/src/shared/terminal-title-agent-type.test.ts b/src/shared/terminal-title-agent-type.test.ts index d021ab21814e..1b16ae05990f 100644 --- a/src/shared/terminal-title-agent-type.test.ts +++ b/src/shared/terminal-title-agent-type.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import { getAgentLabel as getSharedAgentLabel } from './agent-title-identity' +import { resolveTabAgentFromSignals } from './tab-agent-from-signals' import { isOpenCodeNativeTitle } from './opencode-terminal-title' import { isClaudeIdentityFrameTitle, @@ -119,3 +120,78 @@ describe('resolveTerminalTitleAgentType', () => { expect(resolveTerminalTitleAgentType('⠋ Codex: fix cursor offsets')).toBe('codex') }) }) + +describe('explicit identity admission shared by display and input readers', () => { + it.each([ + 'codex', + 'grok', + 'gemini', + 'copilot', + 'devin', + 'aider', + 'openclaude', + 'claude', + 'jcode', + 'antigravity', + 'droid', + 'hermes', + 'mimo' + ])('does not identify a task mentioning %s', (name) => { + expect(resolveExplicitTerminalTitleAgentType(`⠋ fix the ${name} launcher`)).toBeNull() + }) + + // Native/synthetic spellings already recognized by the title parser and its producer fixtures. + it.each([ + ['Claude Code', 'claude'], + ['claude.bat working', 'claude'], + ['⠋ OpenClaude', 'openclaude'], + ['openclaude.cmd', 'openclaude'], + ['⠋ Codex: fix cursor offsets', 'codex'], + ['codex.exe', 'codex'], + ['✦ Analyzing the repository', 'gemini'], + ['◇ Gemini CLI', 'gemini'], + ['GitHub Copilot', 'copilot'], + ['copilot.exe - action required', 'copilot'], + ['devin thinking', 'devin'], + ['aider.ps1 ready', 'aider'], + ['⠋ - Waiting for response… - grok', 'grok'], + ['grok done', 'grok'], + ['Jcode', 'jcode'], + ['Antigravity', 'antigravity'], + ['agy — Gemini 3.1 Pro', 'antigravity'], + ['OC | Compare Codex and Claude', 'opencode'], + ['ssh host | opencode ready', 'opencode'], + ['opencode2', 'opencode2'], + ['MiMo Code', 'mimo-code'], + ['Cursor Agent', 'cursor'], + ['⠋ Droid', 'droid'], + ['hermes ready', 'hermes'], + ['DeepSeek Build', 'dsb'], + ['🐋 DeepSeek Harness', 'dsh'], + ['π > session - ~/orca', 'pi'], + ['OMP ready', 'omp'], + ['Qoder CLI', 'qoder'], + ['Qoder CLI CN', 'qoder-cn'], + ['Compare Antigravity with Gemini… - grok', 'grok'] + ])('preserves the identity frame %j', (title, agent) => { + expect(resolveExplicitTerminalTitleAgentType(title)).toBe(agent) + expect( + resolveTabAgentFromSignals({ + title, + hookAgent: null, + hasObservedAgentSignal: true, + isRemote: true, + launchAgent: agent === 'claude' ? 'codex' : 'claude' + }) + ).toBe(agent) + }) + + it.each([ + 'claude | zsh', + 'codex | main | fix the parser', + '⠋ grok > next steps', + 'OC | session - grok' + ])('rejects wrapper prefixes, breadcrumbs and competing identities in %j', (title) => { + expect(resolveExplicitTerminalTitleAgentType(title)).toBeNull() + }) +}) diff --git a/src/shared/terminal-title-agent-type.ts b/src/shared/terminal-title-agent-type.ts index d11746a09d13..273e4637df7e 100644 --- a/src/shared/terminal-title-agent-type.ts +++ b/src/shared/terminal-title-agent-type.ts @@ -1,3 +1,4 @@ +import { collectExplicitAgentTitleEvidence } from './agent-title-evidence' import { isQoderTerminalTitle } from './qoder-terminal-title' import { AGY_AGENT_NAME_RE, @@ -261,26 +262,8 @@ const TITLE_LABEL_TO_AGENT: Partial> = { OMP: 'omp' } -function hasGenericClaudeStatusPrefix(title: string): boolean { - return ( - containsAgentSpinnerGlyph(title) || - title.startsWith('✳ ') || - title === '✳' || - title.startsWith('. ') || - title.startsWith('* ') - ) -} - export { isClaudeIdentityFrameTitle } from './agent-title-core' -function isGenericClaudeStatusClaim(title: string, titleAgent: TerminalAgent | null): boolean { - return ( - titleAgent === 'claude' && - hasGenericClaudeStatusPrefix(title) && - !titleHasAgentName(title, 'claude') - ) -} - export function resolveTerminalTitleAgentType(title: string): TerminalAgent | null { const label = getAgentLabel(title) const parsed = label ? (TITLE_LABEL_TO_AGENT[label] ?? null) : null @@ -291,13 +274,10 @@ export function resolveTerminalTitleAgentType(title: string): TerminalAgent | nu }).agent } -/** Treat bare Claude-style prefixes as activity only; explicit identity requires a Claude Code name, not a task/workspace spinner. */ +/** Activity and task mentions cannot establish identity for display or input routing. */ function computeExplicitTerminalTitleAgentType(title: string): TerminalAgent | null { - const titleAgent = resolveTerminalTitleAgentType(title) - if (isGenericClaudeStatusClaim(title, titleAgent)) { - return null - } - return titleAgent + const candidate = resolveTerminalTitleAgentType(title) + return collectExplicitAgentTitleEvidence(title).agent === candidate ? candidate : null } /** Pure in `title` — memoized so repeated selector reads skip the canonical/title parse. */ From 8f52bd5b602349c7819c402e282b2eb9fb7f7b8c Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:28:22 -0700 Subject: [PATCH 08/13] fix(agents): separate title identity from readiness policy --- .../session/mobile-terminal-tab-agent.test.ts | 25 ++++ ...chestration-mailbox-cold-park-idle.spec.ts | 39 ++++++ ...ation-mailbox-notification-test-harness.ts | 14 ++- .../terminal-wait-name-only-idle.test.ts | 42 +++++++ src/main/runtime/tui-idle-evidence.ts | 4 +- .../title-derived-pane-agent-identity.ts | 10 +- .../worktree-title-derived-agent-rows.test.ts | 50 ++++++++ .../worktree-title-derived-agent-rows.ts | 8 +- .../terminal-pane/terminal-ctrl-enter.test.ts | 3 + .../terminal-title-evidence.test.ts | 114 +++++++++++++++++- .../terminal-pane/terminal-title-evidence.ts | 17 ++- src/shared/agent-title-evidence.ts | 98 ++++++++++----- src/shared/agent-title-name-anchoring.ts | 42 +++++-- src/shared/agent-title-status.ts | 8 +- src/shared/terminal-pane-title-reset.test.ts | 2 + src/shared/terminal-pane-title-reset.ts | 4 +- src/shared/terminal-title-agent-type.test.ts | 73 ++++++++++- src/shared/terminal-title-agent-type.ts | 20 ++- ...rminal-title-classification-corpus.test.ts | 29 ++++- ...terminal-title-classification-memo.test.ts | 113 +++++++++++++++++ 20 files changed, 644 insertions(+), 71 deletions(-) diff --git a/mobile/src/session/mobile-terminal-tab-agent.test.ts b/mobile/src/session/mobile-terminal-tab-agent.test.ts index e316baf6d190..d669bc96b3ed 100644 --- a/mobile/src/session/mobile-terminal-tab-agent.test.ts +++ b/mobile/src/session/mobile-terminal-tab-agent.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { createTerminalTitleTracker } from '../../../src/shared/terminal-output-side-effects' import type { AgentStatusEntry } from '../../../src/shared/agent-status-types' import type { TuiAgent } from '../../../src/shared/tui-agent' import type { MobileSessionTab } from './mobile-session-route-types' @@ -47,6 +48,30 @@ function terminalTab( } describe('resolveMobileTerminalTabAgentId', () => { + it.each([ + ['⠋ fix the gemini launcher', 'claude'], + ['⠋ add ✦ icon to header', 'claude'], + ['⠋ Codex: fix Gemini terminal behavior', 'codex'], + ['Fix Codex terminal behavior… - grok', 'grok'], + ['✦ Analyze Codex', 'gemini'] + ])('uses the production OSC normalization for %s', (raw, agent) => { + let title = '' + const tracker = createTerminalTitleTracker({ + onTitle: (emitted) => { + title = emitted + } + }) + try { + tracker.handleChunk(`\x1b]0;${raw}\x07`) + expect( + resolveMobileTerminalTabAgentId( + terminalTab(title, { agentType: 'claude', state: 'done', launchAgent: 'claude' }) + ) + ).toBe(agent) + } finally { + tracker.dispose() + } + }) it('keeps completed Claude ownership when task text names another agent', () => { expect( resolveMobileTerminalTabAgentId( diff --git a/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts b/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts index 7d5bba882330..1fab249a0285 100644 --- a/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts +++ b/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts @@ -2,6 +2,7 @@ import { rmSync } from 'node:fs' import { stubWriteSettlement } from '../providers/settled-pty-write-stub' import type { WriteSettlement } from '../../shared/pty-write-settlement' import { afterEach, describe, expect, it, vi } from 'vitest' +import type { TuiIdleEvidenceSource } from './tui-idle-evidence-source' import { checkBoundMailbox, createBoundRun, @@ -24,6 +25,44 @@ describe('orchestration mailbox cold-park idle continuation', () => { } }) + it('parks null-agent task-title mail through fresh output, then dispatches and settles once on quiet alone', async () => { + vi.useFakeTimers() + const db = createDatabase('orca-mailbox-null-title-policy-') + const { runtime, write } = createRuntime(db, { launchAgent: null }) + await runtime.listTerminals() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: inspect the actual evaluator source; no method is replaced. + const source = Reflect.get(runtime, 'tuiIdleEvidenceSource') as TuiIdleEvidenceSource + expect(source.getPaneAgent(PTY_ID)).toBeNull() + const run = createBoundRun(db, 'Null-agent title policy Run') + const message = insertDirectRunMessage(db, run.id, 'Deliver after legitimate quiet') + runtime.onPtyData(PTY_ID, '\x1b]0;⠋ Fix the codex launcher\x07working\n', Date.now()) + runtime.onPtyData(PTY_ID, '\x1b]0;Fix the codex launcher\x07output\n', Date.now()) + await runtime.serializeMainTerminalBuffer(PTY_ID) + expect(source.getPaneAgent(PTY_ID)).toBeNull() + for (let tick = 0; tick < 5; tick += 1) { + runtime.onPtyData(PTY_ID, 'still outputting\n', Date.now()) + await vi.advanceTimersByTimeAsync(500) + expect(write).not.toHaveBeenCalled() + expect(db.getMessageById(message.id)).toMatchObject({ + delivered_at: null, + pointer_enter_pending: 0 + }) + } + // No new OSC/graph/mail edge: the production quiet recheck must wake and finish transport settlement. + await vi.advanceTimersByTimeAsync(5_000) + expect(pointerCount(write)).toBe(1) + expect(write.mock.calls.filter(([, payload]) => payload === '\r')).toHaveLength(1) + expect(db.getMessageById(message.id)).toMatchObject({ + delivered_at: expect.any(String), + pointer_enter_pending: 0 + }) + await vi.advanceTimersByTimeAsync(5_000) + expect(pointerCount(write)).toBe(1) + expect(write.mock.calls.filter(([, payload]) => payload === '\r')).toHaveLength(1) + runtime.onPtyExit(PTY_ID, 0) + db.close() + }) + it('submits the deferred Enter on same-incarnation idle while the PTY stays parked', async () => { vi.useFakeTimers() const db = createDatabase('orca-mailbox-cold-park-idle-') diff --git a/src/main/runtime/orchestration-mailbox-notification-test-harness.ts b/src/main/runtime/orchestration-mailbox-notification-test-harness.ts index 9846bf884d77..216c83d96251 100644 --- a/src/main/runtime/orchestration-mailbox-notification-test-harness.ts +++ b/src/main/runtime/orchestration-mailbox-notification-test-harness.ts @@ -119,7 +119,7 @@ export function createRuntime( headless?: boolean getAgentStatusSnapshot?: () => AgentStatusIpcPayload[] checkHookAgentPresence?: (paneKey: string) => Promise<'live' | 'unverifiable' | 'exited' | null> - launchAgent?: TuiAgent + launchAgent?: TuiAgent | null } = {} ): MailboxNotificationHarness { const runtime = new OrcaRuntimeService( @@ -151,10 +151,14 @@ export function createRuntime( tabId: TAB_ID, leafId: LEAF_ID, incarnationId: 'mailbox-incarnation', - agentLaunchAuthority: { - launchToken: LAUNCH_TOKEN, - launchAgent: options.launchAgent ?? 'codex' - } + ...(options.launchAgent === null + ? {} + : { + agentLaunchAuthority: { + launchToken: LAUNCH_TOKEN, + launchAgent: options.launchAgent ?? 'codex' + } + }) }, options.isWsl ) diff --git a/src/main/runtime/terminal-wait-name-only-idle.test.ts b/src/main/runtime/terminal-wait-name-only-idle.test.ts index 2e19b772894c..bd764e22df41 100644 --- a/src/main/runtime/terminal-wait-name-only-idle.test.ts +++ b/src/main/runtime/terminal-wait-name-only-idle.test.ts @@ -103,6 +103,48 @@ describe('tui-idle evidence ranking', () => { vi.useRealTimers() }) + it.each([ + ['pty', 'claude ~/p/repo', false], + ['leaf', 'Fix the codex launcher', false], + ['leaf', 'Fix the codex launcher', true] + ] as const)( + 'keeps null-agent %s %s pending through streaming (clockless=%s)', + async (kind, title, clockless) => { + const record = { + lastAgentStatus: 'idle' as const, + lastOscTitle: title, + lastOutputAt: clockless ? null : Date.now() + } + const pty = kind === 'pty' ? makeTuiIdlePty(record) : undefined + const leaf = kind === 'leaf' ? makeTuiIdleLeaf(record) : undefined + const { wait, waiters, polls } = createWait({ + pty, + leaf, + agent: null, + liveLeaf: leaf ? () => leaf : undefined + }) + const settled = watch(wait.wait(HANDLE, { condition: 'tui-idle', timeoutMs: 60_000 })) + await vi.advanceTimersByTimeAsync(0) + expect(settled).not.toHaveBeenCalled() + expect(waiters.get(HANDLE)?.size).toBe(1) + expect(polls.activeTimerCount).toBe(1) + if (clockless) { + await vi.advanceTimersByTimeAsync(QUIESCENCE_MS + POLL_INTERVAL_MS) + expect(settled).not.toHaveBeenCalled() + } + const live = pty ?? leaf! + await advanceWhileStreaming(live, 3) + expect(settled).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(QUIESCENCE_MS + POLL_INTERVAL_MS) + expect(settled).toHaveBeenCalledExactlyOnceWith({ + ok: expect.objectContaining({ satisfied: true }) + }) + expect(waiters.get(HANDLE)).toBeUndefined() + expect(polls.activeTimerCount).toBe(0) + expect(vi.getTimerCount()).toBe(0) + } + ) + it('refuses a stored name-only idle while the pane is still streaming', async () => { const pty = makeTuiIdlePty({ lastAgentStatus: 'idle', lastOscTitle: NAME_ONLY_TITLE }) const { wait } = createWait({ pty, agent: 'codex' }) diff --git a/src/main/runtime/tui-idle-evidence.ts b/src/main/runtime/tui-idle-evidence.ts index 98b57276e3fc..9a7b059debd7 100644 --- a/src/main/runtime/tui-idle-evidence.ts +++ b/src/main/runtime/tui-idle-evidence.ts @@ -6,7 +6,7 @@ import { import type { AgentStatusState } from '../../shared/agent-status-types' import type { RuntimeTerminalWaitBlockedReason } from '../../shared/runtime-types' import { getSyntheticAgentTerminalTitle } from '../../shared/synthetic-agent-title' -import { resolveExplicitTerminalTitleAgentType } from '../../shared/terminal-title-agent-type' +import { resolveTerminalTitlePolicyAgentType } from '../../shared/terminal-title-agent-type' import type { TuiAgent } from '../../shared/tui-agent' import type { TerminalAgent } from '../../shared/terminal-agent' import { isTuiAgent } from '../../shared/tui-agent-config' @@ -73,7 +73,7 @@ export function nameOnlyIdleNeedsCorroboration( ): boolean { // Why the title fallback: an adopted pane carries no launch metadata, but its // name-only title is exactly the thing that names the agent. - const resolved = agent ?? (title ? resolveExplicitTerminalTitleAgentType(title) : null) + const resolved = agent ?? (title ? resolveTerminalTitlePolicyAgentType(title) : null) if (!isTuiAgent(resolved)) { return false } diff --git a/src/renderer/src/components/sidebar/title-derived-pane-agent-identity.ts b/src/renderer/src/components/sidebar/title-derived-pane-agent-identity.ts index 01484d5870fe..3c60fe1a290b 100644 --- a/src/renderer/src/components/sidebar/title-derived-pane-agent-identity.ts +++ b/src/renderer/src/components/sidebar/title-derived-pane-agent-identity.ts @@ -4,7 +4,7 @@ import { resolveCompatibleAgentTypeForOwner } from '../../../../shared/agent-tit import { resolveExplicitTerminalTitleAgentType } from '../../../../shared/terminal-title-agent-type' import type { PaneForegroundAgentEntry } from '@/store/slices/pane-foreground-agent' -const TITLE_AGENT_LABEL_TO_TYPE: Record = { +export const TITLE_AGENT_LABEL_TO_TYPE: Record = { 'Claude Code': 'claude', OpenClaude: 'openclaude', Codex: 'codex', @@ -26,13 +26,13 @@ const TITLE_AGENT_LABEL_TO_TYPE: Record = { export function resolveTitleDerivedAgentType( title: string, - label: string, + _label: string, _ownerAgentType?: AgentType | null ): AgentType | null { - const agentType = TITLE_AGENT_LABEL_TO_TYPE[label] ?? 'unknown' const admittedAgent = resolveExplicitTerminalTitleAgentType(title) - return admittedAgent && (agentType === 'unknown' || admittedAgent === agentType) - ? agentType + return admittedAgent + ? (Object.values(TITLE_AGENT_LABEL_TO_TYPE).find((agent) => agent === admittedAgent) ?? + 'unknown') : null } diff --git a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts index ac707cca6156..b6431ff56833 100644 --- a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts +++ b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts @@ -4,6 +4,8 @@ import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/ter import type { TuiAgent } from '../../../../shared/tui-agent' import { makePaneKey } from '../../../../shared/stable-pane-id' import { buildWorktreeAgentRows } from './worktree-agent-rows' +import { createTerminalTitleTracker } from '../../../../shared/terminal-output-side-effects' +import { resolveTabAgentFromSignalSnapshot } from '../../../../shared/tab-agent-from-signals' import { resolveTitleDerivedAgentType, type TitleDerivedPaneForeground @@ -52,6 +54,54 @@ function processRead(agent: TuiAgent): TitleDerivedPaneForeground { } describe('buildTitleDerivedAgentRows', () => { + it.each([ + ['⠋ fix the gemini launcher', '⠋ fix the gemini launcher', 'claude', 'Claude'], + ['⠋ add ✦ icon to header', '⠋ add ✦ icon to header', 'claude', 'Claude'], + [ + '⠋ Codex: fix Gemini terminal behavior', + '⠋ Codex: fix Gemini terminal behavior', + 'codex', + 'Codex' + ], + ['Fix Codex terminal behavior… - grok', 'Fix Codex terminal behavior… - grok', 'grok', 'Grok'], + ['✦ Analyze Codex', '✦ Gemini CLI', 'gemini', 'Gemini CLI'], + ['✦ Claude Code', '✦ Gemini CLI', 'gemini', 'Gemini CLI'] + ])( + 'projects actual OSC %s into the shared desktop/mobile icon and visible row', + (raw, normalized, agent, label) => { + let title = '' + const tracker = createTerminalTitleTracker({ + onTitle: (emitted) => { + title = emitted + } + }) + try { + tracker.handleChunk(`\x1b]0;${raw}\x07`) + expect(title).toBe(normalized) + expect( + resolveTabAgentFromSignalSnapshot({ + title, + hookAgent: null, + focusedCompletedHookAgent: 'claude', + launchAgent: 'claude' + }) + ).toBe(agent) + const rows = buildWorktreeAgentRows({ + tabs: [makeTab('tab-1', { title, launchAgent: 'claude' })], + entries: [], + retained: [], + runtimePaneTitlesByTabId: { 'tab-1': { 1: title } }, + ptyIdsByTabId: { 'tab-1': ['pty'] }, + terminalLayoutsByTabId: { 'tab-1': makeSingleLayout(LEAF_ID_1) }, + now: 2000 + }) + expect(rows).toHaveLength(1) + expect(rows[0]).toMatchObject({ agentType: agent, entry: { prompt: label } }) + } finally { + tracker.dispose() + } + } + ) it('labels a working DeepSeek Build title as dsb and does not claim a Claude mention', () => { const rows = buildWorktreeAgentRows({ tabs: [makeTab('tab-1')], diff --git a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts index b240d71bf8c6..b93fe7e1de1c 100644 --- a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts @@ -26,6 +26,7 @@ import { resolvePaneAgentOwner } from '../../../../shared/pane-agent-owner' import { resolveTitleDerivedAgentType, resolveTitleDerivedPaneAgent, + TITLE_AGENT_LABEL_TO_TYPE, type TitleDerivedPaneForeground } from './title-derived-pane-agent-identity' @@ -178,7 +179,12 @@ function buildTitleDerivedAgentRow(args: { } // Why: the title sets activity only; a plain title on a process-identified pane is idle. const status = titleStatus ?? 'idle' - const rowLabel = agentType === titleAgentType && label ? label : formatAgentTypeLabel(agentType) + const rowLabel = + agentType === titleAgentType && + label && + (agentType === 'unknown' || TITLE_AGENT_LABEL_TO_TYPE[label] === agentType) + ? label + : formatAgentTypeLabel(agentType) const rowState = titleStatusToRowState(status) const secondary = status === 'permission' ? 'Needs input' : status === 'working' ? 'Running' : 'Idle' diff --git a/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts b/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts index bc35b8d166ef..a1ab8ceffb7e 100644 --- a/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts @@ -8,6 +8,9 @@ describe('hasCtrlEnterCsiUAuthorityForPane', () => { const state = { paneForegroundAgentByPaneKey: {} } expect(hasCtrlEnterCsiUAuthorityForPane(state, PANE_KEY, '⠋ fix the grok launcher')).toBe(false) expect(hasCtrlEnterCsiUAuthorityForPane(state, PANE_KEY, '⠋ Grok')).toBe(true) + expect( + hasCtrlEnterCsiUAuthorityForPane(state, PANE_KEY, 'Fix Codex terminal behavior… - grok') + ).toBe(true) }) it.each([ diff --git a/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts b/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts index dc359ccef724..ababc1740d69 100644 --- a/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts @@ -1,7 +1,119 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' +import { + createTerminalTitleTracker, + STALE_WORKING_TITLE_TIMEOUT_MS, + type TerminalTitleFactMeta +} from '../../../../shared/terminal-output-side-effects' import { resolvePaneTitleDecision } from './terminal-title-evidence' +import { installTitleSpawnBell } from './pty-connection/title-spawn-bell' +import { clearStaleAgentTabTitleOnConfirmedShell } from './pty-connection/confirmed-shell-agent-title' + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => ({ + settings: { terminalGpuAcceleration: 'auto' }, + agentStatusByPaneKey: {}, + runtimePaneTitlesByTabId: { tab: { 1: 'fix the gemini launcher' } }, + tabsByWorktree: {} + }) + } +})) +vi.mock('./pty-connection/pane-pty-visibility-bind', () => ({ + installPanePtyVisibilityBind: vi.fn() +})) describe('resolvePaneTitleDecision', () => { + it.each([ + ['✦ Gemini CLI', '⠋ fix the gemini launcher', '⠋ fix the gemini launcher'], + ['◇ Gemini CLI', '⠋ add ✦ icon to header', '⠋ add ✦ icon to header'], + [ + '✋ Gemini CLI', + '⠋ Codex: fix Gemini terminal behavior', + '⠋ Codex: fix Gemini terminal behavior' + ], + ['✦ Gemini CLI', '✦ Analyze Codex', '✦ Gemini CLI'], + // Normalized-only history cannot recover the original task; title-only reuse remains supported. + ['✦ Gemini CLI', '✦ Gemini CLI', '✦ Gemini CLI'] + ])( + 'corrects only disproved old Gemini stamps (%s, %s)', + (normalizedTitle, rawTitle, displayTitle) => { + const decision = resolvePaneTitleDecision({ + normalizedTitle, + rawTitle, + displayOwnerAgentType: 'claude', + rendererOwnerAgentType: null, + userGpuMode: 'auto' + }) + expect(decision.displayTitle).toBe(displayTitle) + expect(decision.rawTitle).toBe(rawTitle) + } + ) + + it('keeps current timer facts cleared with equal raw/display input and existing provenance', async () => { + vi.useFakeTimers() + const facts: [string, string, unknown][] = [] + const startup = vi.fn() + const completion = vi.fn() + const session = { + cacheKey: 'tab:leaf', + pane: { id: 1 }, + deps: { + tabId: 'tab', + worktreeId: 'wt', + setRuntimePaneTitle: vi.fn(), + updateTabTitle: vi.fn() + }, + manager: { getActivePane: () => ({ id: 1 }), setPaneGpuRendering: vi.fn() }, + getAuthoritativePaneAgent: () => 'claude', + getPaneScopedRendererOwner: () => 'claude', + syncAgentTaskCompleteTrackingEnabled: () => true, + shouldSuppressTitleCompletionForFreshHook: () => false, + paneForegroundAgentTracker: { onAgentStartupObserved: startup }, + agentCompletionCoordinator: { observeTitle: completion }, + hasConsideredInitialCacheTimerSeed: true, + neutralTerminalTitle: () => 'Terminal 1', + releaseCommandCodeDoneSettleExecutor: () => {}, + onTitleChange: (_title: string, _raw: string, _meta?: TerminalTitleFactMeta) => {} + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the installed title callback runs; its session dependencies are supplied above. + installTitleSpawnBell(session as never) + const tracker = createTerminalTitleTracker({ + onTitle: (title, raw, meta) => { + facts.push([title, raw, meta]) + session.onTitleChange(title, raw, meta) + } + }) + try { + tracker.handleChunk('\x1b]0;⠋ fix the gemini launcher\x07') + tracker.handleChunk('more output\n') + await vi.advanceTimersByTimeAsync(STALE_WORKING_TITLE_TIMEOUT_MS) + expect(facts).toEqual([ + ['⠋ fix the gemini launcher', '⠋ fix the gemini launcher', undefined], + ['fix the gemini launcher', 'fix the gemini launcher', { staleWorkingTitleClear: true }] + ]) + expect(startup).not.toHaveBeenCalled() + expect(completion).toHaveBeenCalledExactlyOnceWith('⠋ fix the gemini launcher') + expect(session.deps.updateTabTitle).toHaveBeenLastCalledWith('tab', 'fix the gemini launcher') + const [normalizedTitle, rawTitle] = facts[1] + expect( + resolvePaneTitleDecision({ + normalizedTitle, + rawTitle, + displayOwnerAgentType: 'claude', + rendererOwnerAgentType: null, + userGpuMode: 'auto' + }).displayTitle + ).toBe('fix the gemini launcher') + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the reset reads only pane/deps/manager/default-title fields supplied above. + clearStaleAgentTabTitleOnConfirmedShell(session as never) + expect(session.deps.setRuntimePaneTitle).toHaveBeenLastCalledWith('tab', 1, 'Terminal 1') + expect(session.deps.updateTabTitle).toHaveBeenLastCalledWith('tab', 'Terminal 1') + } finally { + tracker.dispose() + session.releaseCommandCodeDoneSettleExecutor() + vi.useRealTimers() + } + }) it('derives the display label and the renderer veto from a pane-scoped OMP owner', () => { const decision = resolvePaneTitleDecision({ normalizedTitle: 'Pi ready', diff --git a/src/renderer/src/components/terminal-pane/terminal-title-evidence.ts b/src/renderer/src/components/terminal-pane/terminal-title-evidence.ts index c2755f83a366..01fbc9968bd6 100644 --- a/src/renderer/src/components/terminal-pane/terminal-title-evidence.ts +++ b/src/renderer/src/components/terminal-pane/terminal-title-evidence.ts @@ -1,4 +1,11 @@ import { normalizeCompatibleAgentTitleForOwner } from '../../../../shared/agent-title-owner' +import { normalizeTerminalTitle } from '../../../../shared/agent-title-status' +import { resolveExplicitTerminalTitleAgentType } from '../../../../shared/terminal-title-agent-type' +import { + GEMINI_IDLE, + GEMINI_PERMISSION, + GEMINI_WORKING +} from '../../../../shared/agent-title-glyphs' import type { AgentType } from '../../../../shared/agent-status-types' import { resolvePaneRendererPolicy, @@ -39,8 +46,16 @@ export type ResolvePaneTitleDecisionInput = { } export function resolvePaneTitleDecision(input: ResolvePaneTitleDecisionInput): PaneTitleDecision { + // Old producers can stamp task prose as Gemini while still supplying the disproving raw title. + const oldGeminiStamp = [GEMINI_WORKING, GEMINI_IDLE, GEMINI_PERMISSION].some( + (glyph) => input.normalizedTitle === `${glyph} Gemini CLI` + ) + const displayInput = + oldGeminiStamp && resolveExplicitTerminalTitleAgentType(input.rawTitle) !== 'gemini' + ? normalizeTerminalTitle(input.rawTitle) + : input.normalizedTitle const displayTitle = resolvePaneDisplayTitle( - input.normalizedTitle, + displayInput, input.displayOwnerAgentType, input.displayOwnerIsLaunch === true ) diff --git a/src/shared/agent-title-evidence.ts b/src/shared/agent-title-evidence.ts index cd39d33ddee7..a072162cdb87 100644 --- a/src/shared/agent-title-evidence.ts +++ b/src/shared/agent-title-evidence.ts @@ -27,6 +27,7 @@ import type { TerminalAgent } from './terminal-agent' import { agentForNativeFrame, agentForOwnerSuffix, + agentForShellCommand, agentForWholeTitle, namesConsumedByAnchoredLabels, namesIn @@ -128,8 +129,7 @@ function collectVendorMarkers(segments: readonly string[]): TerminalAgent[] { function collectAnchoredNames( segments: readonly string[], - vendorMarkers: readonly TerminalAgent[], - nativeFrames: boolean + vendorMarkers: readonly TerminalAgent[] ): TerminalAgent[] { const anchored = new Set() // Why: a native owner's task text can end with DSB's product-name suffix, including inside wrappers. @@ -145,26 +145,6 @@ function collectAnchoredNames( anchored.add('dsb') } - if (nativeFrames && !nativeOpenCode) { - const native = agentForNativeFrame(segment) - if (native) { - anchored.add(native) - } - if ( - isDshTerminalTitle(segment) && - stripLeadingAgentTitleDecorationOrEmpty(segment).startsWith('🐋') - ) { - anchored.add('dsh') - } - if (isQoderTerminalTitle(segment)) { - anchored.add(segment.includes('Qoder CLI CN') ? 'qoder-cn' : 'qoder') - } - const piBrand = getPiCompatibleTitleBrand(segment) - if (piBrand || isLegacyPiCompatibleTitle(segment)) { - anchored.add(piBrand === 'OMP' ? 'omp' : 'pi') - } - } - const suffix = OWNER_SUFFIX_RE.exec(segment) if (suffix) { const agent = agentForOwnerSuffix(suffix[1]) @@ -173,11 +153,6 @@ function collectAnchoredNames( } } - // OpenCode owns its session envelope; only competing owner suffixes can conflict. - if (nativeFrames && nativeOpenCode) { - continue - } - // Strip the leading sigil to expose anchored names: in ✳ agy, the name outranks the inherited Claude glyph. const withoutSigil = segment.startsWith(`${CLAUDE_IDLE} `) ? segment.slice(CLAUDE_IDLE.length) @@ -211,6 +186,67 @@ function collectAnchoredNames( return [...anchored] } +/** An envelope consumes its payload before any inner wrapper or name can be interpreted. */ +function collectObserverAnchors(segments: readonly string[]): TerminalAgent[] { + const anchored = new Set() + const suffix = OWNER_SUFFIX_RE.exec(segments[0]) + const suffixAgent = suffix ? agentForOwnerSuffix(suffix[1]) : null + if (suffixAgent) { + anchored.add(suffixAgent) + } + // Inspect the outermost available frame first, retaining the existing bounded innermost window. + const ordered = [segments[0], ...segments.slice(1).toReversed()] + for (const segment of ordered) { + const undecorated = stripLeadingAgentTitleDecorationOrEmpty(segment).trim() + const piBrand = getPiCompatibleTitleBrand(segment) + const genericClaude = + segment === CLAUDE_IDLE || + segment.startsWith(`${CLAUDE_IDLE} `) || + segment.startsWith('. ') || + segment.startsWith('* ') + let agent: TerminalAgent | null + if ( + !genericClaude && + isOpenCodeNativeTitle(segment) && + (undecorated.startsWith('OC | ') || segment.startsWith('▣ OC | ')) + ) { + agent = 'opencode' + } else if (isDshTerminalTitle(segment) && undecorated.startsWith('🐋')) { + agent = 'dsh' + } else if (isQoderTerminalTitle(segment)) { + agent = segment.includes('Qoder CLI CN') ? 'qoder-cn' : 'qoder' + } else if (piBrand || isLegacyPiCompatibleTitle(segment)) { + agent = piBrand === 'OMP' ? 'omp' : 'pi' + } else if (GEMINI_GLYPHS.some((glyph) => segment.startsWith(glyph))) { + agent = 'gemini' + } else if (genericClaude) { + agent = agentForNativeFrame(segment) === 'claude' ? 'claude' : null + } else { + agent = + (isDeepSeekBuildTerminalTitle(segment) ? 'dsb' : null) ?? + agentForNativeFrame(segment) ?? + agentForWholeTitle(segment) ?? + agentForSyntheticTitle(segment) ?? + (ANTIGRAVITY_MODEL_TITLE_RE.test(undecorated) ? 'antigravity' : null) ?? + (getPiCompatibleSyntheticAgentLabel(segment) === 'OMP' + ? 'omp' + : getPiCompatibleSyntheticAgentLabel(segment) === 'Pi' + ? 'pi' + : null) ?? + (!suffixAgent ? agentForShellCommand(segment) : null) + } + if (agent) { + anchored.add(agent) + break + } + // A decorated task or colon payload is not an outer multiplexer wrapper. + if (genericClaude || undecorated !== segment.trim() || /^[^|]*:/.test(segment)) { + break + } + } + return [...anchored] +} + /** Collects every identity signal in `title` and ranks them by class, never by declaration order. */ function collectTitleEvidence(title: string, nativeFrames: boolean): AgentTitleEvidence { const empty = { vendorMarkers: [], anchoredNames: [], freeTextNames: [] } as const @@ -221,7 +257,9 @@ function collectTitleEvidence(title: string, nativeFrames: boolean): AgentTitleE const segments = getEvidenceTitleSegments(title) const vendorMarkers = collectVendorMarkers(segments) - const anchoredNames = collectAnchoredNames(segments, vendorMarkers, nativeFrames) + const anchoredNames = nativeFrames + ? collectObserverAnchors(segments) + : collectAnchoredNames(segments, vendorMarkers) const anchoredSet = new Set(anchoredNames) const anchoredLabelNames = namesConsumedByAnchoredLabels(segments, anchoredSet) const freeTextNames = namesIn(title).filter( @@ -236,10 +274,10 @@ function collectTitleEvidence(title: string, nativeFrames: boolean): AgentTitleE if (anchoredNames.length > 1) { return { ...evidence, agent: null, reason: 'conflicting-anchored-names' } } - if (vendorMarkers.length > 1) { + if (!nativeFrames && vendorMarkers.length > 1) { return { ...evidence, agent: null, reason: 'conflicting-vendor-markers' } } - if (vendorMarkers.length === 1 && (!nativeFrames || vendorMarkers[0] !== 'claude')) { + if (!nativeFrames && vendorMarkers.length === 1) { // Free-text names cannot veto a vendor glyph (✳ Fix Codex… is Claude); a conflicting anchored name already outranks it. return { ...evidence, agent: vendorMarkers[0], reason: 'vendor-marker' } } diff --git a/src/shared/agent-title-name-anchoring.ts b/src/shared/agent-title-name-anchoring.ts index 3f17f2d44be1..6937186b9b2e 100644 --- a/src/shared/agent-title-name-anchoring.ts +++ b/src/shared/agent-title-name-anchoring.ts @@ -2,11 +2,12 @@ import { AGY_AGENT_NAME_RE, DROID_AGENT_NAME_RE, HERMES_AGENT_NAME_RE, + isCursorAgentTitle, titleHasAgentName } from './agent-title-core' import { stripLeadingAgentTitleDecorationOrEmpty } from './agent-title-decoration' import type { TerminalAgent } from './terminal-agent' -import { ALL_TUI_AGENTS, TUI_AGENT_DISPLAY_NAMES } from './tui-agent-display-names' +import { TUI_AGENT_DISPLAY_NAMES } from './tui-agent-display-names' /** Names matched as whole tokens, paired with the agent each identifies. */ const NAME_TOKENS: readonly (readonly [string, TerminalAgent])[] = [ @@ -122,23 +123,42 @@ export function agentForOwnerSuffix(text: string): TerminalAgent | null { /** Native frames identify an agent by a complete name, a named status, or a name before task text. */ export function agentForNativeFrame(text: string): TerminalAgent | null { + if (isCursorAgentTitle(text)) { + return 'cursor' + } const undecorated = stripLeadingAgentTitleDecorationOrEmpty(text).trim() const frameName = undecorated.replace( - /(?::\s+.*|\s*[\u2013\u2014]\s*.*|\s+(?:ready|idle|done|working|thinking|running|waiting|permission)|\s+-\s+action required)$/i, + /(?::\s+[\s\S]*|\s*[\u2013\u2014]\s*[\s\S]*|\s+(?:(?:ready|idle|done|working|thinking|running|waiting|permission)|\[(?:ready|idle|done|working|thinking|running|waiting|permission)\])|\s+-\s+action required)$/i, '' ) if (!frameName || /[|>\\/]/.test(frameName)) { return null } - const normalized = frameName.replace(WINDOWS_LAUNCHER_SUFFIX_RE, '').toLowerCase() - const agent = - agentForBareName(frameName) ?? - ALL_TUI_AGENTS.find( - (agent) => normalized === agent || normalized === TUI_AGENT_DISPLAY_NAMES[agent].toLowerCase() - ) ?? - null - // Pi/OMP have their own separator grammar, including special spinner requirements. - return agent === 'pi' || agent === 'omp' ? null : agent + return agentForNativeName(frameName) +} + +function agentForNativeName(text: string): TerminalAgent | null { + const normalized = text.replace(WINDOWS_LAUNCHER_SUFFIX_RE, '').toLowerCase() + if (normalized === 'jcode' || normalized === 'opencode2') { + return normalized + } + const agent = agentForBareName(text) + // Emitted aliases and Cursor/Pi/OMP use their own closed grammars, not arbitrary named tasks. + return agent && + agent !== 'cursor' && + (NAME_TOKENS.some(([, native]) => native === agent) || + PATTERN_NAMES.some(([, native]) => native === agent)) + ? agent + : null +} + +/** Shell auto-titles keep arguments as content owned by the command-position name. */ +export function agentForShellCommand(text: string): TerminalAgent | null { + if (text.trim() !== stripLeadingAgentTitleDecorationOrEmpty(text) || /[|>]/.test(text)) { + return null + } + const command = /^(\S+)\s+(?!\[)\S[\s\S]*$/.exec(text.trim()) + return command ? agentForNativeName(command[1]) : null } export function namesConsumedByAnchoredLabels( diff --git a/src/shared/agent-title-status.ts b/src/shared/agent-title-status.ts index 5a3fe7b4941d..2e7d147c1eea 100644 --- a/src/shared/agent-title-status.ts +++ b/src/shared/agent-title-status.ts @@ -22,7 +22,6 @@ import { containsLegacyAgentName, isClaudeManagementTitle, isDshTerminalTitle, - isGeminiTerminalTitle, isPiAgentTitle, isPiTerminalTitle, titleHasAgentName @@ -35,7 +34,10 @@ import { } from './pi-compatible-synthetic-title' import { clearPiStateWorkingMarker, getPiStateTitleStatus } from './pi-state-title-marker' import { getWrapperTitleSegments } from './terminal-title-wrapper-segments' -import { isGrokRotatingWorkingTitle } from './terminal-title-agent-type' +import { + isGrokRotatingWorkingTitle, + resolveExplicitTerminalTitleAgentType +} from './terminal-title-agent-type' import { memoizeTitleClassification } from './terminal-title-classification-memo' /** @@ -170,7 +172,7 @@ export function normalizeTerminalTitle(title: string): string { } // Pi/OMP explicit markers outrank Gemini glyphs embedded in free-form session/cwd labels. - if (!getPiStateTitleStatus(title) && isGeminiTerminalTitle(title)) { + if (!getPiStateTitleStatus(title) && resolveExplicitTerminalTitleAgentType(title) === 'gemini') { const status = detectAgentStatusFromTitle(title) if (status === 'permission') { return `${GEMINI_PERMISSION} Gemini CLI` diff --git a/src/shared/terminal-pane-title-reset.test.ts b/src/shared/terminal-pane-title-reset.test.ts index 496ec0f1dbef..e3c2d80f5409 100644 --- a/src/shared/terminal-pane-title-reset.test.ts +++ b/src/shared/terminal-pane-title-reset.test.ts @@ -14,6 +14,8 @@ describe('pane title resets', () => { it('resets only an agent-named title on a confirmed return to a shell', () => { expect(titleAfterConfirmedShell('✳ Claude Code', 'Terminal 1')).toBe('Terminal 1') + expect(titleAfterConfirmedShell('⠋ fix the grok launcher', 'Terminal 1')).toBe('Terminal 1') + expect(titleAfterConfirmedShell('⠋ fix the parser', 'Terminal 1')).toBeNull() expect(titleAfterConfirmedShell('vim notes.md', 'Terminal 1')).toBeNull() expect(titleAfterConfirmedShell(null, 'Terminal 1')).toBeNull() }) diff --git a/src/shared/terminal-pane-title-reset.ts b/src/shared/terminal-pane-title-reset.ts index c1739d1f2702..8a2841cc806e 100644 --- a/src/shared/terminal-pane-title-reset.ts +++ b/src/shared/terminal-pane-title-reset.ts @@ -1,6 +1,6 @@ // CLIs can leave agent names/spinners after exit; replace them only when the agent is known gone. -import { resolveExplicitTerminalTitleAgentType } from './terminal-title-agent-type' +import { resolveTerminalTitlePolicyAgentType } from './terminal-title-agent-type' export function neutralTerminalTitle(defaultTitle: string | null | undefined): string { return defaultTitle?.trim() || 'Terminal' @@ -11,7 +11,7 @@ export function titleAfterConfirmedShell( title: string | null | undefined, defaultTitle: string | null | undefined ): string | null { - if (!title || resolveExplicitTerminalTitleAgentType(title) === null) { + if (!title || resolveTerminalTitlePolicyAgentType(title) === null) { return null } return neutralTerminalTitle(defaultTitle) diff --git a/src/shared/terminal-title-agent-type.test.ts b/src/shared/terminal-title-agent-type.test.ts index 1b16ae05990f..50dfcf2d3e68 100644 --- a/src/shared/terminal-title-agent-type.test.ts +++ b/src/shared/terminal-title-agent-type.test.ts @@ -6,7 +6,8 @@ import { isClaudeIdentityFrameTitle, isGrokRotatingWorkingTitle, resolveExplicitTerminalTitleAgentType, - resolveTerminalTitleAgentType + resolveTerminalTitleAgentType, + resolveTerminalTitlePolicyAgentType } from './terminal-title-agent-type' describe('isGrokRotatingWorkingTitle', () => { @@ -144,12 +145,24 @@ describe('explicit identity admission shared by display and input readers', () = it.each([ ['Claude Code', 'claude'], ['claude.bat working', 'claude'], + ['claude [working]', 'claude'], + ['claude ~/p/repo', 'claude'], + ['codex ~/p/repo', 'codex'], + ['codex.exe C:\\p\\repo', 'codex'], ['⠋ OpenClaude', 'openclaude'], ['openclaude.cmd', 'openclaude'], ['⠋ Codex: fix cursor offsets', 'codex'], ['codex.exe', 'codex'], ['✦ Analyzing the repository', 'gemini'], ['◇ Gemini CLI', 'gemini'], + ['✦ Claude Code', 'gemini'], + ['✦ Codex', 'gemini'], + ['✦ Codex: fix parser', 'gemini'], + ['✦ Codex: fix parser | Thinking', 'qoder'], + ['Codex: fix parser | OC | Claude Code', 'codex'], + ['⠂ 🐋 Codex: fix parser', 'dsh'], + ['⠂ 🐋 Codex | Claude Code', 'dsh'], + ['🐋 Claude Code', 'dsh'], ['GitHub Copilot', 'copilot'], ['copilot.exe - action required', 'copilot'], ['devin thinking', 'devin'], @@ -165,6 +178,8 @@ describe('explicit identity admission shared by display and input readers', () = ['MiMo Code', 'mimo-code'], ['Cursor Agent', 'cursor'], ['⠋ Droid', 'droid'], + ['droid.exe', 'droid'], + ['tmux | claude - action required', 'claude'], ['hermes ready', 'hermes'], ['DeepSeek Build', 'dsb'], ['🐋 DeepSeek Harness', 'dsh'], @@ -172,7 +187,14 @@ describe('explicit identity admission shared by display and input readers', () = ['OMP ready', 'omp'], ['Qoder CLI', 'qoder'], ['Qoder CLI CN', 'qoder-cn'], - ['Compare Antigravity with Gemini… - grok', 'grok'] + ['Qoder CLI CN (Codex | Claude Code)', 'qoder-cn'], + ['Prime Agent', 'prime-agent'], + ['Command Code', 'command-code'], + ['⠋ ZCode', 'zcode'], + ['ZCode ready', 'zcode'], + ['Compare Antigravity with Gemini… - grok', 'grok'], + ['Fix Codex terminal behavior… - grok', 'grok'], + ['Codex parity fixes - grok', 'grok'] ])('preserves the identity frame %j', (title, agent) => { expect(resolveExplicitTerminalTitleAgentType(title)).toBe(agent) expect( @@ -190,8 +212,55 @@ describe('explicit identity admission shared by display and input readers', () = 'claude | zsh', 'codex | main | fix the parser', '⠋ grok > next steps', + 'claude [banana]', + 'codex [working', + '⠋ Fix foo | OC | bar', + '✳ Fix foo | OC | bar', 'OC | session - grok' ])('rejects wrapper prefixes, breadcrumbs and competing identities in %j', (title) => { expect(resolveExplicitTerminalTitleAgentType(title)).toBeNull() }) + + it.each(['Continue', 'Goose', 'Charm', 'Amp', 'CodeBuddy'])( + 'keeps UI-only %s labels outside the producer grammar regardless of task nouns', + (label) => { + for (const title of [ + label, + `⠋ ${label}`, + `${label} ready`, + `${label}: fix Codex`, + `⠋ ${label}: fix Gemini` + ]) { + expect(resolveExplicitTerminalTitleAgentType(title), title).toBeNull() + } + } + ) + + it.each([ + '✳ Codex', + '. Codex', + '* Codex', + '✳ agy', + '. Codex: fix parser', + '✳ Codex | Claude Code' + ])('does not turn generic Claude activity into foreign identity: %s', (title) => + expect(resolveExplicitTerminalTitleAgentType(title)).toBeNull() + ) + + it('separates identity from exact legacy policy, including the generic Claude exclusion', () => { + for (const [title, policy] of [ + ['Fix the codex launcher', 'codex'], + ['⠋ fix the grok launcher', 'grok'], + ['⠋ fix the parser', null], + ['task ⠋', null], + ['✳', null], + ['. Review the parser', null], + ['* Review the parser', null] + ] as const) { + expect(resolveExplicitTerminalTitleAgentType(title), title).toBeNull() + expect(resolveTerminalTitlePolicyAgentType(title), title).toBe(policy) + } + expect(resolveTerminalTitlePolicyAgentType('claude ~/p/repo')).toBe('claude') + expect(resolveTerminalTitlePolicyAgentType('✳ Claude Code')).toBe('claude') + }) }) diff --git a/src/shared/terminal-title-agent-type.ts b/src/shared/terminal-title-agent-type.ts index 273e4637df7e..3337d66f9876 100644 --- a/src/shared/terminal-title-agent-type.ts +++ b/src/shared/terminal-title-agent-type.ts @@ -276,10 +276,26 @@ export function resolveTerminalTitleAgentType(title: string): TerminalAgent | nu /** Activity and task mentions cannot establish identity for display or input routing. */ function computeExplicitTerminalTitleAgentType(title: string): TerminalAgent | null { - const candidate = resolveTerminalTitleAgentType(title) - return collectExplicitAgentTitleEvidence(title).agent === candidate ? candidate : null + return collectExplicitAgentTitleEvidence(title).agent } /** Pure in `title` — memoized so repeated selector reads skip the canonical/title parse. */ export const resolveExplicitTerminalTitleAgentType: (title: string) => TerminalAgent | null = memoizeTitleClassification(computeExplicitTerminalTitleAgentType) + +/** Readiness and confirmed-shell cleanup retain their pre-existing title policy. */ +function computeTerminalTitlePolicyAgentType(title: string): TerminalAgent | null { + const agent = resolveTerminalTitleAgentType(title) + const genericClaudeStatus = + containsAgentSpinnerGlyph(title) || + title.startsWith(`${CLAUDE_IDLE} `) || + title === CLAUDE_IDLE || + title.startsWith('. ') || + title.startsWith('* ') + return agent === 'claude' && genericClaudeStatus && !titleHasAgentName(title, 'claude') + ? null + : agent +} + +export const resolveTerminalTitlePolicyAgentType: (title: string) => TerminalAgent | null = + memoizeTitleClassification(computeTerminalTitlePolicyAgentType) diff --git a/src/shared/terminal-title-classification-corpus.test.ts b/src/shared/terminal-title-classification-corpus.test.ts index 5a5c11fa2333..4a2da8a6355d 100644 --- a/src/shared/terminal-title-classification-corpus.test.ts +++ b/src/shared/terminal-title-classification-corpus.test.ts @@ -6,7 +6,8 @@ import { getAgentLabel as getExplicitAgentLabel, isClaudeAgent as isExplicitClaudeAgent, resolveExplicitTerminalTitleAgentType, - resolveTerminalTitleAgentType + resolveTerminalTitleAgentType, + resolveTerminalTitlePolicyAgentType } from './terminal-title-agent-type' /** Pin pre-memoization verdicts so caching cannot silently repaint panes with another agent’s identity. */ @@ -19,7 +20,8 @@ type PinnedRow = [ explicitLabel: string | null, explicitClaude: boolean, titleAgent: string | null, - explicitTitleAgent: string | null + policyTitleAgent: string | null, + identityTitleAgent?: string | null ] const PINNED_CLASSIFICATIONS: readonly PinnedRow[] = [ @@ -85,7 +87,7 @@ const PINNED_CLASSIFICATIONS: readonly PinnedRow[] = [ 'copilot', 'copilot' ], - ['droid.exe', null, null, false, false, null, false, null, null], + ['droid.exe', null, null, false, false, null, false, null, null, 'droid'], ['\u2733', 'idle', 'Claude Code', true, false, 'Claude Code', true, 'claude', null], [ '\u2733 Claude Code', @@ -228,7 +230,18 @@ const PINNED_CLASSIFICATIONS: readonly PinnedRow[] = [ ['\u03c0 ! blocked-session', 'permission', 'Pi', false, false, 'Pi', false, 'pi', 'pi'], ['\u280b \u03c0 - session - ~/orca', 'working', 'Pi', true, false, 'Pi', true, 'pi', 'pi'], ['zsh | \u280b Codex', 'working', 'Codex', true, false, 'Codex', true, 'codex', 'codex'], - ['tmux | claude - action required', 'permission', null, false, false, null, false, null, null], + [ + 'tmux | claude - action required', + 'permission', + null, + false, + false, + null, + false, + null, + null, + 'claude' + ], [ 'ssh host | opencode ready', 'idle', @@ -254,7 +267,8 @@ describe('terminal title classification', () => { explicitLabel, explicitClaude, titleAgent, - explicitTitleAgent + policyTitleAgent, + identityTitleAgent ) => { expect(detectAgentStatusFromTitle(title)).toBe(status) expect(getAgentLabel(title)).toBe(label) @@ -263,7 +277,10 @@ describe('terminal title classification', () => { expect(getExplicitAgentLabel(title)).toBe(explicitLabel) expect(isExplicitClaudeAgent(title)).toBe(explicitClaude) expect(resolveTerminalTitleAgentType(title)).toBe(titleAgent) - expect(resolveExplicitTerminalTitleAgentType(title)).toBe(explicitTitleAgent) + expect(resolveTerminalTitlePolicyAgentType(title)).toBe(policyTitleAgent) + expect(resolveExplicitTerminalTitleAgentType(title)).toBe( + identityTitleAgent === undefined ? policyTitleAgent : identityTitleAgent + ) } ) }) diff --git a/src/shared/terminal-title-classification-memo.test.ts b/src/shared/terminal-title-classification-memo.test.ts index 5f523ac61941..614f866bb922 100644 --- a/src/shared/terminal-title-classification-memo.test.ts +++ b/src/shared/terminal-title-classification-memo.test.ts @@ -4,6 +4,24 @@ import { getAgentLabel } from './agent-title-identity' import { detectAgentStatusFromTitle } from './agent-title-status' import { memoizeTitleClassification } from './terminal-title-classification-memo' import { resolveExplicitTerminalTitleAgentType } from './terminal-title-agent-type' +import * as Evidence from './agent-title-evidence' +import * as Frames from './agent-title-name-anchoring' +import { createTerminalTitleTracker } from './terminal-output-side-effects' +import { resolveTabAgentFromSignalSnapshot } from './tab-agent-from-signals' +import { buildTitleDerivedAgentRows } from '../renderer/src/components/sidebar/worktree-title-derived-agent-rows' +import type { TerminalTab } from './terminal-tab-types' + +vi.mock('./agent-title-evidence', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + collectExplicitAgentTitleEvidence: vi.fn(actual.collectExplicitAgentTitleEvidence) + } +}) +vi.mock('./agent-title-name-anchoring', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, agentForNativeFrame: vi.fn(actual.agentForNativeFrame) } +}) // Count the leaf titleHasAgentName regex to measure unchanged-title work across store writes. vi.mock('./agent-name-token-match', async (importOriginal) => { @@ -58,6 +76,101 @@ describe('terminal title classification memo', () => { expect(detectAgentStatusFromTitle('codex working')).toBe('working') }) + it('bounds cold OSC work at N/10N and does zero new classification on unchanged production projections', () => { + const strict = vi.mocked(Evidence.collectExplicitAgentTitleEvidence) + const frames = vi.mocked(Frames.agentForNativeFrame) + const clear = () => { + strict.mockClear() + frames.mockClear() + classifierCalls.mockClear() + } + const counts = () => [ + strict.mock.calls.length, + frames.mock.calls.length + classifierCalls.mock.calls.length + ] + const measure = (population: number) => { + const leafId = '77777777-7777-4777-8777-777777777777' + const tabs: TerminalTab[] = Array.from({ length: population }, (_, index) => ({ + id: `tab-${index}`, + worktreeId: 'memo', + ptyId: `pty-${index}`, + title: '', + customTitle: null, + color: null, + sortOrder: index, + createdAt: 0, + launchAgent: 'claude' + })) + const trackers = tabs.map((tab) => + createTerminalTitleTracker({ + onTitle: (title) => { + tab.title = title + } + }) + ) + const project = () => { + const icons = tabs.map((tab) => + resolveTabAgentFromSignalSnapshot({ + title: tab.title, + hookAgent: null, + focusedCompletedHookAgent: 'claude', + launchAgent: 'claude' + }) + ) + const rows = buildTitleDerivedAgentRows({ + tabs, + ptyIdsByTabId: Object.fromEntries(tabs.map((tab) => [tab.id, [tab.ptyId!]])), + terminalLayoutsByTabId: Object.fromEntries( + tabs.map((tab) => [ + tab.id, + { root: { type: 'leaf', leafId }, activeLeafId: leafId, expandedLeafId: null } + ]) + ), + seenPaneKeys: new Set(), + now: 1 + }) + return { icons, rows } + } + try { + clear() + trackers.forEach((tracker, index) => + tracker.handleChunk( + `\x1b]0;⠋ Codex: memo-${String(population).padStart(3, '0')}-${String(index).padStart(3, '0')}\x07` + ) + ) + const first = project() + expect(first.icons).toEqual(Array(population).fill('codex')) + expect(first.rows.map((row) => [row.agentType, row.entry.prompt])).toEqual( + Array.from({ length: population }, () => ['codex', 'Codex']) + ) + const cold = counts() + clear() + for (let write = 0; write < STORE_WRITES; write += 1) { + project() + } + expect(counts()).toEqual([0, 0]) + trackers[0].handleChunk( + `\x1b]0;Fix Codex memo-${String(population).padStart(3, '0')} - grok\x07` + ) + const changed = project() + expect(changed.icons[0]).toBe('grok') + expect(changed.rows[0]).toMatchObject({ agentType: 'grok', entry: { prompt: 'Grok' } }) + expect(changed.icons.slice(1)).toEqual(Array(population - 1).fill('codex')) + return { cold, changed: counts() } + } finally { + trackers.forEach((tracker) => tracker.dispose()) + } + } + const n = measure(10) + const tenN = measure(100) + expect(n.cold[0]).toBe(10) + expect(tenN.cold[0]).toBe(100) + expect(tenN.cold[1]).toBeLessThanOrEqual(n.cold[1] * 10) + expect(n.cold[1]).toBeGreaterThan(0) + expect(tenN.changed).toEqual(n.changed) + expect(n.changed[0]).toBe(1) + }) + it('caches null and false verdicts, not just truthy ones', () => { const classify = vi.fn((): string | null => null) const memoized = memoizeTitleClassification(classify) From ea3059038044a6904f9047515f37e0689bb32290 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 05:56:44 -0700 Subject: [PATCH 09/13] Preserve title frame boundaries and normalization identity --- .../session/mobile-terminal-tab-agent.test.ts | 12 + .../worktree-title-derived-agent-rows.test.ts | 98 ++++++- .../native-chat-leaf-title-agent.test.ts | 20 ++ .../terminal-pane/terminal-ctrl-enter.test.ts | 14 + .../terminal-title-evidence.test.ts | 77 ++++- .../terminal-pane/terminal-title-evidence.ts | 19 +- .../terminal-windows-shift-enter.test.ts | 10 + src/shared/agent-detection.test.ts | 36 +++ src/shared/agent-title-core.ts | 12 + src/shared/agent-title-evidence.test.ts | 11 +- src/shared/agent-title-evidence.ts | 146 ++++++---- src/shared/agent-title-name-anchoring.ts | 33 ++- src/shared/agent-title-status.ts | 50 +++- src/shared/dsb-terminal-title.ts | 20 +- src/shared/opencode-terminal-title.ts | 18 +- src/shared/qoder-terminal-title.ts | 8 +- src/shared/terminal-title-agent-type.test.ts | 34 +++ src/shared/terminal-title-agent-type.ts | 12 +- ...terminal-title-classification-memo.test.ts | 263 +++++++++++++++--- 19 files changed, 731 insertions(+), 162 deletions(-) diff --git a/mobile/src/session/mobile-terminal-tab-agent.test.ts b/mobile/src/session/mobile-terminal-tab-agent.test.ts index d669bc96b3ed..5603b0ebae2a 100644 --- a/mobile/src/session/mobile-terminal-tab-agent.test.ts +++ b/mobile/src/session/mobile-terminal-tab-agent.test.ts @@ -53,6 +53,11 @@ describe('resolveMobileTerminalTabAgentId', () => { ['⠋ add ✦ icon to header', 'claude'], ['⠋ Codex: fix Gemini terminal behavior', 'codex'], ['Fix Codex terminal behavior… - grok', 'grok'], + [`${'x | '.repeat(200)}OC | a | b | c | d | e | f | g | h | Codex`, 'opencode'], + ['tmux | 🐋 a | b | c | d | e | f | g | h | Codex', 'dsh'], + ['✦ session | Thinking - grok', 'claude'], + ['✦ session | Thinking', 'qoder'], + ['⠋ - Codex: fix parser - grok', 'grok'], ['✦ Analyze Codex', 'gemini'] ])('uses the production OSC normalization for %s', (raw, agent) => { let title = '' @@ -63,11 +68,18 @@ describe('resolveMobileTerminalTabAgentId', () => { }) try { tracker.handleChunk(`\x1b]0;${raw}\x07`) + expect(raw.length).toBeLessThanOrEqual(1024) expect( resolveMobileTerminalTabAgentId( terminalTab(title, { agentType: 'claude', state: 'done', launchAgent: 'claude' }) ) ).toBe(agent) + if (raw.includes('OC | ')) { + expect(resolveMobileTerminalTabAgentId(terminalTab(title))).toBe('opencode') + expect(resolveMobileTerminalTabAgentId(terminalTab(title, { launchAgent: 'claude' }))).toBe( + raw.startsWith('x | ') ? 'claude' : 'opencode' + ) + } } finally { tracker.dispose() } diff --git a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts index b6431ff56833..5fd483cec8fe 100644 --- a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts +++ b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts @@ -11,6 +11,8 @@ import { type TitleDerivedPaneForeground } from './title-derived-pane-agent-identity' +import { resolveExplicitTerminalTitleAgentType } from '../../../../shared/terminal-title-agent-type' + const LEAF_ID_1 = '77777777-7777-4777-8777-777777777777' const LEAF_ID_2 = '88888888-8888-4888-8888-888888888888' @@ -55,29 +57,96 @@ function processRead(agent: TuiAgent): TitleDerivedPaneForeground { describe('buildTitleDerivedAgentRows', () => { it.each([ - ['⠋ fix the gemini launcher', '⠋ fix the gemini launcher', 'claude', 'Claude'], - ['⠋ add ✦ icon to header', '⠋ add ✦ icon to header', 'claude', 'Claude'], + ['⠋ fix the gemini launcher', '⠋ fix the gemini launcher', null, 'claude', 'claude', 'Claude'], + ['⠋ add ✦ icon to header', '⠋ add ✦ icon to header', null, 'claude', 'claude', 'Claude'], [ '⠋ Codex: fix Gemini terminal behavior', '⠋ Codex: fix Gemini terminal behavior', 'codex', + 'codex', + 'codex', + 'Codex' + ], + [ + 'Fix Codex terminal behavior… - grok', + 'Fix Codex terminal behavior… - grok', + 'grok', + 'grok', + 'grok', + 'Grok' + ], + ['✦ Analyze Codex', '✦ Gemini CLI', 'gemini', 'gemini', 'gemini', 'Gemini CLI'], + ['✦ Claude Code', '✦ Gemini CLI', 'gemini', 'gemini', 'gemini', 'Gemini CLI'], + [ + `${'x | '.repeat(200)}OC | a | b | c | d | e | f | g | h | Codex`, + null, + 'opencode', + 'opencode', + 'opencode', + 'OpenCode' + ], + [ + `${'x | '.repeat(200)}🐋 a | b | c | d | e | f | g | h | Codex`, + null, + 'dsh', + 'dsh', + 'unknown', + 'Codex' + ], + [ + 'Wrapper | OC | Review Codex - DeepSeek Build', + null, + 'opencode', + 'claude', + 'opencode', + 'OpenCode' + ], + ['user@host: ~/code | ⠋ OC | ses_123', null, 'opencode', 'claude', 'opencode', 'OpenCode'], + [ + `${'x | '.repeat(9)}Codex: fix | a | b | c | d | e | f | g | Claude Code`, + null, + 'codex', + 'codex', + 'codex', 'Codex' ], - ['Fix Codex terminal behavior… - grok', 'Fix Codex terminal behavior… - grok', 'grok', 'Grok'], - ['✦ Analyze Codex', '✦ Gemini CLI', 'gemini', 'Gemini CLI'], - ['✦ Claude Code', '✦ Gemini CLI', 'gemini', 'Gemini CLI'] + [ + `${'x | '.repeat(8)}⠋ fix | a | b | c | d | e | f | g | Codex`, + null, + null, + 'claude', + 'claude', + 'Claude' + ], + ['✦ session | Thinking - grok', null, null, 'claude', 'claude', 'Claude'], + ['▲ session | Action Required - grok', null, null, 'claude', 'claude', 'Claude'], + ['✦ session | Thinking', '✦ Qoder CLI', 'qoder', 'qoder', 'unknown', 'Qoder CLI'], + [ + '◇ Qoder CLI CN (Codex | Claude Code)', + '◇ Qoder CLI CN', + 'qoder-cn', + 'qoder-cn', + 'unknown', + 'Qoder CLI CN' + ], + ['⠋ - Codex: fix parser - grok', '⠋ Grok', 'grok', 'grok', 'grok', 'Grok'] ])( - 'projects actual OSC %s into the shared desktop/mobile icon and visible row', - (raw, normalized, agent, label) => { + 'projects actual untruncated OSC %s into the shared icon and visible row', + (raw, normalized, strict, agent, rowAgent, label) => { let title = '' + let observed = '' const tracker = createTerminalTitleTracker({ - onTitle: (emitted) => { + onTitle: (emitted, actualRaw) => { title = emitted + observed = actualRaw } }) try { + expect(raw.length).toBeLessThanOrEqual(1024) tracker.handleChunk(`\x1b]0;${raw}\x07`) - expect(title).toBe(normalized) + expect(observed).toBe(raw) + expect(title).toBe(normalized ?? raw) + expect(resolveExplicitTerminalTitleAgentType(title)).toBe(strict) expect( resolveTabAgentFromSignalSnapshot({ title, @@ -86,6 +155,15 @@ describe('buildTitleDerivedAgentRows', () => { launchAgent: 'claude' }) ).toBe(agent) + if (strict === 'opencode') { + expect(resolveTabAgentFromSignalSnapshot({ title, hookAgent: null })).toBe('opencode') + expect( + resolveTabAgentFromSignalSnapshot({ title, hookAgent: null, launchAgent: 'claude' }) + ).toBe(raw.startsWith('x | ') ? 'claude' : 'opencode') + } + expect( + resolveTabAgentFromSignalSnapshot({ title, hookAgent: 'claude', launchAgent: 'claude' }) + ).toBe('claude') const rows = buildWorktreeAgentRows({ tabs: [makeTab('tab-1', { title, launchAgent: 'claude' })], entries: [], @@ -96,7 +174,7 @@ describe('buildTitleDerivedAgentRows', () => { now: 2000 }) expect(rows).toHaveLength(1) - expect(rows[0]).toMatchObject({ agentType: agent, entry: { prompt: label } }) + expect(rows[0]).toMatchObject({ agentType: rowAgent, entry: { prompt: label } }) } finally { tracker.dispose() } diff --git a/src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.test.ts b/src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.test.ts index ab10530b8165..e8fd2c816459 100644 --- a/src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.test.ts +++ b/src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { normalizeTerminalTitle } from '../../../../shared/agent-title-status' import { resolveNativeChatLeafTitleAgent } from './native-chat-leaf-title-agent' const panes = [ @@ -7,6 +8,25 @@ const panes = [ ] describe('resolveNativeChatLeafTitleAgent', () => { + it.each([ + ['⠋ - Codex: fix parser - grok', 'grok'], + ['⠋ Codex: fix parser - grok', null], + ['tmux | ⠋ fix | a | b | c | d | e | f | g | Codex', null], + ['tmux | 🐋 a | b | c | d | e | f | g | h | Codex', 'dsh'], + ['✦ session | Thinking - grok', null], + ['✦ session | Thinking', 'qoder'] + ])('preserves raw/stored committed leaf identity for %j', (raw, agent) => { + for (const title of [raw, normalizeTerminalTitle(raw)]) { + expect( + resolveNativeChatLeafTitleAgent({ + leafId: 'leaf-1', + panes: [panes[0]], + runtimePaneTitlesByPaneId: { 1: title } + }) + ).toBe(agent) + } + }) + it('does not offer recognition-only DeepSeek Build as a native chat agent', () => { expect( resolveNativeChatLeafTitleAgent({ diff --git a/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts b/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts index a1ab8ceffb7e..756fa44cf884 100644 --- a/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { normalizeTerminalTitle } from '../../../../shared/agent-title-status' import { hasCtrlEnterCsiUAuthorityForPane } from './terminal-ctrl-enter' const PANE_KEY = 'tab:pane' @@ -13,6 +14,19 @@ describe('hasCtrlEnterCsiUAuthorityForPane', () => { ).toBe(true) }) + it.each([ + ['⠋ - Codex: fix parser - grok', true], + ['⠋ Codex: fix parser - grok', false], + ['tmux | ⠋ fix | a | b | c | d | e | f | g | Grok', false], + ['✦ session | Thinking - grok', false] + ])('uses raw and stored structural input authority for %j', (raw, expected) => { + for (const title of [raw, normalizeTerminalTitle(raw)]) { + expect( + hasCtrlEnterCsiUAuthorityForPane({ paneForegroundAgentByPaneKey: {} }, PANE_KEY, title) + ).toBe(expected) + } + }) + it.each([ { agent: 'dsb' as const, routingTrusted: true, shellForeground: false }, { agent: 'dsb' as const, routingConfirmationPending: true, shellForeground: false } diff --git a/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts b/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts index ababc1740d69..05174798ccdb 100644 --- a/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts @@ -8,6 +8,8 @@ import { resolvePaneTitleDecision } from './terminal-title-evidence' import { installTitleSpawnBell } from './pty-connection/title-spawn-bell' import { clearStaleAgentTabTitleOnConfirmedShell } from './pty-connection/confirmed-shell-agent-title' +import { isNormalizedAgentTitleStamp } from '../../../../shared/agent-title-status' + vi.mock('@/store', () => ({ useAppStore: { getState: () => ({ @@ -32,23 +34,76 @@ describe('resolvePaneTitleDecision', () => { '⠋ Codex: fix Gemini terminal behavior' ], ['✦ Gemini CLI', '✦ Analyze Codex', '✦ Gemini CLI'], + ['✦ Qoder CLI', '✦ session | Thinking - grok', '✦ session | Thinking - grok'], + ['▲ Qoder CLI', '▲ session | Action Required - grok', '▲ session | Action Required - grok'], + ['◇ Qoder CLI CN', '◇ Qoder CLI CN | Idle - grok', '◇ Qoder CLI CN | Idle - grok'], + ['✦ Qoder CLI CN', '✦ Qoder CLI CN (Codex | Claude Code)', '✦ Qoder CLI CN'], + ['⠋ Grok', '⠋ Codex: fix parser - grok', '⠋ Codex: fix parser - grok'], + ['⠋ Grok', '⠋ - Codex: fix parser - grok', '⠋ Grok'], // Normalized-only history cannot recover the original task; title-only reuse remains supported. ['✦ Gemini CLI', '✦ Gemini CLI', '✦ Gemini CLI'] + ])('corrects only disproved old stamps (%s, %s)', (normalizedTitle, rawTitle, displayTitle) => { + const decision = resolvePaneTitleDecision({ + normalizedTitle, + rawTitle, + displayOwnerAgentType: 'claude', + rendererOwnerAgentType: null, + userGpuMode: 'auto' + }) + expect(decision.displayTitle).toBe(displayTitle) + expect(decision.rawTitle).toBe(rawTitle) + }) + + it.each([ + '✦ Gemini CLI', + '✋ Gemini CLI', + '◇ Gemini CLI', + '✦ Qoder CLI', + '▲ Qoder CLI', + '◇ Qoder CLI', + '✦ Qoder CLI CN', + '▲ Qoder CLI CN', + '◇ Qoder CLI CN', + '⠋ Grok' ])( - 'corrects only disproved old Gemini stamps (%s, %s)', - (normalizedTitle, rawTitle, displayTitle) => { - const decision = resolvePaneTitleDecision({ - normalizedTitle, - rawTitle, - displayOwnerAgentType: 'claude', - rendererOwnerAgentType: null, - userGpuMode: 'auto' - }) - expect(decision.displayTitle).toBe(displayTitle) - expect(decision.rawTitle).toBe(rawTitle) + 'corrects actual raw disproof and preserves normalized-only history for exact output %j', + (stamp) => { + expect(isNormalizedAgentTitleStamp(stamp)).toBe(true) + const decide = (rawTitle: string) => + resolvePaneTitleDecision({ + normalizedTitle: stamp, + rawTitle, + displayOwnerAgentType: null, + rendererOwnerAgentType: null, + userGpuMode: 'auto' + }) + const raw = '⠋ Codex: repair parser' + expect(decide(raw)).toEqual( + resolvePaneTitleDecision({ + normalizedTitle: raw, + rawTitle: raw, + displayOwnerAgentType: null, + rendererOwnerAgentType: null, + userGpuMode: 'auto' + }) + ) + expect(decide(stamp).displayTitle).toBe(stamp) } ) + it.each([ + 'Gemini', + 'gemini cli', + 'Qoder CLI', + 'Grok', + '⠴ Grok', + 'Pi ready', + 'OMP ready', + '✦ Qoder CLI extra' + ])('does not treat loose or owner-shaped text %j as an exact output', (title) => { + expect(isNormalizedAgentTitleStamp(title)).toBe(false) + }) + it('keeps current timer facts cleared with equal raw/display input and existing provenance', async () => { vi.useFakeTimers() const facts: [string, string, unknown][] = [] diff --git a/src/renderer/src/components/terminal-pane/terminal-title-evidence.ts b/src/renderer/src/components/terminal-pane/terminal-title-evidence.ts index 01fbc9968bd6..207838f44cdf 100644 --- a/src/renderer/src/components/terminal-pane/terminal-title-evidence.ts +++ b/src/renderer/src/components/terminal-pane/terminal-title-evidence.ts @@ -1,11 +1,9 @@ import { normalizeCompatibleAgentTitleForOwner } from '../../../../shared/agent-title-owner' -import { normalizeTerminalTitle } from '../../../../shared/agent-title-status' -import { resolveExplicitTerminalTitleAgentType } from '../../../../shared/terminal-title-agent-type' import { - GEMINI_IDLE, - GEMINI_PERMISSION, - GEMINI_WORKING -} from '../../../../shared/agent-title-glyphs' + isNormalizedAgentTitleStamp, + normalizeTerminalTitle +} from '../../../../shared/agent-title-status' +import { resolveExplicitTerminalTitleAgentType } from '../../../../shared/terminal-title-agent-type' import type { AgentType } from '../../../../shared/agent-status-types' import { resolvePaneRendererPolicy, @@ -46,12 +44,11 @@ export type ResolvePaneTitleDecisionInput = { } export function resolvePaneTitleDecision(input: ResolvePaneTitleDecisionInput): PaneTitleDecision { - // Old producers can stamp task prose as Gemini while still supplying the disproving raw title. - const oldGeminiStamp = [GEMINI_WORKING, GEMINI_IDLE, GEMINI_PERMISSION].some( - (glyph) => input.normalizedTitle === `${glyph} Gemini CLI` - ) + // Actual raw evidence can disprove an old producer's destructive display stamp. const displayInput = - oldGeminiStamp && resolveExplicitTerminalTitleAgentType(input.rawTitle) !== 'gemini' + isNormalizedAgentTitleStamp(input.normalizedTitle) && + resolveExplicitTerminalTitleAgentType(input.rawTitle) !== + resolveExplicitTerminalTitleAgentType(input.normalizedTitle) ? normalizeTerminalTitle(input.rawTitle) : input.normalizedTitle const displayTitle = resolvePaneDisplayTitle( diff --git a/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts b/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts index a29d0da4d53f..039cb9ec9180 100644 --- a/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts @@ -13,6 +13,16 @@ describe('resolveWindowsShiftEnterEncoding', () => { expect(resolveWindowsShiftEnterEncodingForPane(state, 'tab:pane', '⠋ Droid')).toBe('csi-u') }) + it('does not expose a keyboard mode inside a wrapped task barrier', () => { + expect( + resolveWindowsShiftEnterEncodingForPane( + { paneForegroundAgentByPaneKey: {}, agentLaunchConfigByPaneKey: {} }, + 'tab:pane', + 'tmux | ⠋ fix | a | b | c | d | e | f | g | Droid' + ) + ).toBe('alt-enter') + }) + it.each(['dsb', 'codex'] as const)( 'keeps pending %s input encoding when a stale title names another agent', (agent) => { diff --git a/src/shared/agent-detection.test.ts b/src/shared/agent-detection.test.ts index 953d1e1ffd4c..863f08b36578 100644 --- a/src/shared/agent-detection.test.ts +++ b/src/shared/agent-detection.test.ts @@ -18,6 +18,42 @@ import { } from './agent-title-owner' import { SYNTHETIC_AGENT_TITLE_PROFILES } from './synthetic-agent-title' +import { resolveExplicitTerminalTitleAgentType } from './terminal-title-agent-type' + +describe('normalization structural identity invariant', () => { + it.each([ + ['✦ session | Thinking - grok', '✦ session | Thinking - grok'], + ['▲ session | Action Required - grok', '▲ session | Action Required - grok'], + ['◇ Qoder CLI CN | Idle - grok', '◇ Qoder CLI CN | Idle - grok'], + ['✦ session | Thinking', '✦ Qoder CLI'], + ['▲ session | Action Required', '▲ Qoder CLI'], + ['◇ session | Idle', '◇ Qoder CLI'], + ['✦ Qoder CLI CN (Codex | Claude Code)', '✦ Qoder CLI CN'], + ['▲ Qoder CLI CN', '▲ Qoder CLI CN'], + ['◇ Qoder CLI CN', '◇ Qoder CLI CN'], + ['⠋ fix the gemini launcher', '⠋ fix the gemini launcher'], + ['⠋ add ✦ icon to header', '⠋ add ✦ icon to header'], + ['✦ Analyze Codex', '✦ Gemini CLI'], + ['✋ waiting for permission', '✋ Gemini CLI'], + ['◇ ready', '◇ Gemini CLI'], + ['⠴ π - session - cwd', '⠋ π - session - cwd'], + ['⠴ OMP - session - cwd', '⠴ OMP - session - cwd'], + ['Plan: migrate | π - ⠴ cwd', 'Plan: migrate | π - ⠋ cwd'], + ['⠋ - Codex: fix parser - grok', '⠋ Grok'], + ['⠋ Codex: fix parser - grok', '⠋ Codex: fix parser - grok'], + ['⠋ Grok', '⠋ Grok'], + ['Fix Codex - grok', 'Fix Codex - grok'], + ['⠴ - Review Codex - DeepSeek Build', '⠴ - Review Codex - DeepSeek Build'] + ])('preserves identity and idempotence for %j', (raw, expected) => { + const display = normalizeTerminalTitle(raw) + expect(display).toBe(expected) + expect(resolveExplicitTerminalTitleAgentType(display)).toBe( + resolveExplicitTerminalTitleAgentType(raw) + ) + expect(normalizeTerminalTitle(display)).toBe(display) + }) +}) + describe('OSC title extraction', () => { it('extracts the last OSC title from BEL-terminated PTY data', () => { expect(extractLastOscTitle('\x1b]0;First\x07noise\x1b]2;Second\x07')).toBe('Second') diff --git a/src/shared/agent-title-core.ts b/src/shared/agent-title-core.ts index f9a92316d0e7..2dfb5da6dd25 100644 --- a/src/shared/agent-title-core.ts +++ b/src/shared/agent-title-core.ts @@ -167,3 +167,15 @@ export function isCursorAgentTitle(title: string | null | undefined): boolean { export function shouldSuppressCursorNativeTitle(lastEmittedTitle: string | null): boolean { return lastEmittedTitle !== null && isCursorAgentTitle(lastEmittedTitle) } + +// Collapse only Grok’s spinner - phrase - grok frame; both delimiters exclude Claude/Codex task mentions. +// Keep unspun session titles unchanged and accept spinner + grok so our collapsed label stays idempotent. +const GROK_ROTATING_FRAME_RE = /^[\u2800-\u28FF]+\s+-\s+[\s\S]+?\s-\s+grok\s*$/i +const GROK_COLLAPSED_WORKING_TITLE_RE = /^[\u2800-\u28FF]+\s+grok\s*$/i + +export function isGrokRotatingWorkingTitle(title: string): boolean { + if (!containsBrailleSpinner(title)) { + return false + } + return GROK_ROTATING_FRAME_RE.test(title) || GROK_COLLAPSED_WORKING_TITLE_RE.test(title) +} diff --git a/src/shared/agent-title-evidence.test.ts b/src/shared/agent-title-evidence.test.ts index 31eb5ab70a6c..829a53b80473 100644 --- a/src/shared/agent-title-evidence.test.ts +++ b/src/shared/agent-title-evidence.test.ts @@ -5,7 +5,10 @@ import { GEMINI_SILENT_WORKING, GEMINI_WORKING } from './agent-title-core' -import { collectAgentTitleEvidence } from './agent-title-evidence' +import { + collectAgentTitleEvidence, + collectExplicitAgentTitleEvidence +} from './agent-title-evidence' import { resolveCanonicalPaneAgentIdentity } from './pane-agent-identity-adapter' import { resolvePublishedPaneAgentIdentity } from './published-pane-agent-identity' @@ -272,6 +275,12 @@ describe('collectAgentTitleEvidence', () => { expect(agentFor('zsh | Fix the Codex parser')).toBeNull() }) + it('keeps canonical diagnostics separate from consuming observer frames', () => { + const title = `outer-a | outer-b | OC | ${'x | '.repeat(200)}Cursor Agent` + expect(collectAgentTitleEvidence(title).agent).toBe('cursor') + expect(collectExplicitAgentTitleEvidence(title).agent).toBe('opencode') + }) + it('bounds wrapper inspection while preserving innermost identity', () => { const wrappers = Array.from({ length: 200 }, (_, index) => `wrapper-${index}`).join(' | ') expect(agentFor(`${wrappers} | ⠋ Cursor Agent`)).toBe('cursor') diff --git a/src/shared/agent-title-evidence.ts b/src/shared/agent-title-evidence.ts index a072162cdb87..c5f74685d662 100644 --- a/src/shared/agent-title-evidence.ts +++ b/src/shared/agent-title-evidence.ts @@ -7,10 +7,19 @@ import { containsAgentSpinnerGlyph, isClaudeIdentityFrameSegment, isClaudeManagementTitle, - isCursorNativeAgentTitle + isCursorNativeAgentTitle, + isGrokRotatingWorkingTitle } from './agent-title-core' -import { isOpenCodeNativeTitle } from './opencode-terminal-title' -import { isDeepSeekBuildTerminalTitle } from './dsb-terminal-title' +import { + isOpenCodeNativeTitle, + isOpenCodeNativeTitleHeader, + isDirectOpenCodeNativeTitle +} from './opencode-terminal-title' +import { + hasDeepSeekBuildWorkingTitlePrefix, + isDeepSeekBuildWorkingTitle, + isDeepSeekBuildTerminalTitle +} from './dsb-terminal-title' import { stripLeadingAgentTitleDecorationOrEmpty } from './agent-title-decoration' import { getPiCompatibleSyntheticAgentLabel, @@ -18,7 +27,7 @@ import { isLegacyPiCompatibleTitle } from './pi-compatible-synthetic-title' import { isDshTerminalTitle } from './dsh-terminal-title' -import { isQoderTerminalTitle } from './qoder-terminal-title' +import { hasQoderTitleLabelPayload, isQoderTerminalTitle } from './qoder-terminal-title' import { SYNTHETIC_AGENT_TITLE_AGENTS, SYNTHETIC_AGENT_TITLE_PROFILES @@ -26,6 +35,8 @@ import { import type { TerminalAgent } from './terminal-agent' import { agentForNativeFrame, + agentForNamedTitlePrefix, + isNeutralAgentTitleWrapper, agentForOwnerSuffix, agentForShellCommand, agentForWholeTitle, @@ -186,63 +197,84 @@ function collectAnchoredNames( return [...anchored] } -/** An envelope consumes its payload before any inner wrapper or name can be interpreted. */ -function collectObserverAnchors(segments: readonly string[]): TerminalAgent[] { +/** Only neutral headers advance; payload pipes never become candidates. */ +function observerFrameStart(title: string): number { + let start = 0 + let boundary = title.indexOf(WRAPPER_SEPARATOR) + while (boundary >= 0) { + // Retain the separator's first space for whitespace-delimited native brands. + const header = title.slice(start, boundary + 1) + const undecorated = stripLeadingAgentTitleDecorationOrEmpty(header).trim() + const neutralWrapper = isNeutralAgentTitleWrapper(header) + if ( + isOpenCodeNativeTitleHeader(header) || + hasQoderTitleLabelPayload(header) || + undecorated.startsWith('🐋') || + getPiCompatibleTitleBrand(header) || + isLegacyPiCompatibleTitle(header) || + hasDeepSeekBuildWorkingTitlePrefix(header) || + agentForNamedTitlePrefix(header) || + ANTIGRAVITY_MODEL_TITLE_RE.test(undecorated) || + !neutralWrapper + ) { + break + } + start = boundary + WRAPPER_SEPARATOR.length + boundary = title.indexOf(WRAPPER_SEPARATOR, start) + } + return start +} + +/** Evaluate the sole unconsumed remainder, keeping the independent final owner suffix. */ +function collectObserverAnchors(title: string): TerminalAgent[] { const anchored = new Set() - const suffix = OWNER_SUFFIX_RE.exec(segments[0]) + const suffix = OWNER_SUFFIX_RE.exec(title) const suffixAgent = suffix ? agentForOwnerSuffix(suffix[1]) : null if (suffixAgent) { anchored.add(suffixAgent) } - // Inspect the outermost available frame first, retaining the existing bounded innermost window. - const ordered = [segments[0], ...segments.slice(1).toReversed()] - for (const segment of ordered) { - const undecorated = stripLeadingAgentTitleDecorationOrEmpty(segment).trim() - const piBrand = getPiCompatibleTitleBrand(segment) - const genericClaude = - segment === CLAUDE_IDLE || - segment.startsWith(`${CLAUDE_IDLE} `) || - segment.startsWith('. ') || - segment.startsWith('* ') - let agent: TerminalAgent | null - if ( - !genericClaude && - isOpenCodeNativeTitle(segment) && - (undecorated.startsWith('OC | ') || segment.startsWith('▣ OC | ')) - ) { - agent = 'opencode' - } else if (isDshTerminalTitle(segment) && undecorated.startsWith('🐋')) { - agent = 'dsh' - } else if (isQoderTerminalTitle(segment)) { - agent = segment.includes('Qoder CLI CN') ? 'qoder-cn' : 'qoder' - } else if (piBrand || isLegacyPiCompatibleTitle(segment)) { - agent = piBrand === 'OMP' ? 'omp' : 'pi' - } else if (GEMINI_GLYPHS.some((glyph) => segment.startsWith(glyph))) { - agent = 'gemini' - } else if (genericClaude) { - agent = agentForNativeFrame(segment) === 'claude' ? 'claude' : null - } else { - agent = - (isDeepSeekBuildTerminalTitle(segment) ? 'dsb' : null) ?? - agentForNativeFrame(segment) ?? - agentForWholeTitle(segment) ?? - agentForSyntheticTitle(segment) ?? - (ANTIGRAVITY_MODEL_TITLE_RE.test(undecorated) ? 'antigravity' : null) ?? - (getPiCompatibleSyntheticAgentLabel(segment) === 'OMP' - ? 'omp' - : getPiCompatibleSyntheticAgentLabel(segment) === 'Pi' - ? 'pi' - : null) ?? - (!suffixAgent ? agentForShellCommand(segment) : null) - } - if (agent) { - anchored.add(agent) - break - } - // A decorated task or colon payload is not an outer multiplexer wrapper. - if (genericClaude || undecorated !== segment.trim() || /^[^|]*:/.test(segment)) { - break - } + const segment = title.slice(observerFrameStart(title)).trim() + const undecorated = stripLeadingAgentTitleDecorationOrEmpty(segment).trim() + const nativeOpenCode = isOpenCodeNativeTitle(segment) + const piBrand = getPiCompatibleTitleBrand(segment) + const genericClaude = + segment === CLAUDE_IDLE || + segment.startsWith(`${CLAUDE_IDLE} `) || + segment.startsWith('. ') || + segment.startsWith('* ') + let agent: TerminalAgent | null + if (!genericClaude && nativeOpenCode && isDirectOpenCodeNativeTitle(segment)) { + agent = 'opencode' + } else if (isDshTerminalTitle(segment) && undecorated.startsWith('🐋')) { + agent = 'dsh' + } else if (isQoderTerminalTitle(segment)) { + agent = segment.includes('Qoder CLI CN') ? 'qoder-cn' : 'qoder' + } else if (piBrand || isLegacyPiCompatibleTitle(segment)) { + agent = piBrand === 'OMP' ? 'omp' : 'pi' + } else if (GEMINI_GLYPHS.some((glyph) => segment.startsWith(glyph))) { + agent = 'gemini' + } else if (genericClaude) { + agent = agentForNativeFrame(segment) === 'claude' ? 'claude' : null + } else { + agent = + (isGrokRotatingWorkingTitle(segment) ? 'grok' : null) ?? + (isDeepSeekBuildWorkingTitle(segment) || + (!segment.includes('|') && isDeepSeekBuildTerminalTitle(segment)) + ? 'dsb' + : null) ?? + agentForNativeFrame(segment) ?? + agentForWholeTitle(segment) ?? + agentForSyntheticTitle(segment) ?? + (ANTIGRAVITY_MODEL_TITLE_RE.test(undecorated) ? 'antigravity' : null) ?? + (getPiCompatibleSyntheticAgentLabel(segment) === 'OMP' + ? 'omp' + : getPiCompatibleSyntheticAgentLabel(segment) === 'Pi' + ? 'pi' + : null) ?? + (!suffixAgent ? agentForShellCommand(segment) : null) + } + if (agent) { + anchored.add(agent) } return [...anchored] } @@ -258,7 +290,7 @@ function collectTitleEvidence(title: string, nativeFrames: boolean): AgentTitleE const segments = getEvidenceTitleSegments(title) const vendorMarkers = collectVendorMarkers(segments) const anchoredNames = nativeFrames - ? collectObserverAnchors(segments) + ? collectObserverAnchors(title) : collectAnchoredNames(segments, vendorMarkers) const anchoredSet = new Set(anchoredNames) const anchoredLabelNames = namesConsumedByAnchoredLabels(segments, anchoredSet) diff --git a/src/shared/agent-title-name-anchoring.ts b/src/shared/agent-title-name-anchoring.ts index 6937186b9b2e..61b6d51193f5 100644 --- a/src/shared/agent-title-name-anchoring.ts +++ b/src/shared/agent-title-name-anchoring.ts @@ -121,16 +121,41 @@ export function agentForOwnerSuffix(text: string): TerminalAgent | null { return RESERVED_OWNER_IDS.get(normalized) ?? agentForBareName(text) } +const NATIVE_PAYLOAD_RE = /(?::\s+[\s\S]*|\s*[\u2013\u2014]\s*[\s\S]*)$/ +const NATIVE_STATUS_RE = + /(?:\s+(?:(?:ready|idle|done|working|thinking|running|waiting|permission)|\[(?:ready|idle|done|working|thinking|running|waiting|permission)\])|\s+-\s+action required)$/i + +/** Only payload delimiters consume later pipes; bare names/statuses still require the full frame. */ +export function agentForNamedTitlePrefix(text: string): TerminalAgent | null { + const undecorated = stripLeadingAgentTitleDecorationOrEmpty(text).trim() + const match = NATIVE_PAYLOAD_RE.exec(undecorated) + return match ? agentForNativeName(undecorated.slice(0, match.index)) : null +} + +/** Inspect one disjoint header, preserving shell host/cwd syntax without admitting colon task prose. */ +export function isNeutralAgentTitleWrapper(header: string): boolean { + const trimmed = header.trim() + if (stripLeadingAgentTitleDecorationOrEmpty(trimmed) !== trimmed) { + return false + } + return ( + !trimmed.includes(':') || + /^(?:[^\s@:[\]]+@(?:\[[^\]]+\]|[^\s:]+)|\[[^\]\s]+@[^\]\s]+\]):\s*(?:[~/]|[A-Za-z]:[\\/])/.test( + trimmed + ) || + /^[A-Za-z]:[\\/]/.test(trimmed) + ) +} + /** Native frames identify an agent by a complete name, a named status, or a name before task text. */ export function agentForNativeFrame(text: string): TerminalAgent | null { if (isCursorAgentTitle(text)) { return 'cursor' } const undecorated = stripLeadingAgentTitleDecorationOrEmpty(text).trim() - const frameName = undecorated.replace( - /(?::\s+[\s\S]*|\s*[\u2013\u2014]\s*[\s\S]*|\s+(?:(?:ready|idle|done|working|thinking|running|waiting|permission)|\[(?:ready|idle|done|working|thinking|running|waiting|permission)\])|\s+-\s+action required)$/i, - '' - ) + const frameName = NATIVE_PAYLOAD_RE.test(undecorated) + ? undecorated.replace(NATIVE_PAYLOAD_RE, '') + : undecorated.replace(NATIVE_STATUS_RE, '') if (!frameName || /[|>\\/]/.test(frameName)) { return null } diff --git a/src/shared/agent-title-status.ts b/src/shared/agent-title-status.ts index 2e7d147c1eea..c9a4ae5b3497 100644 --- a/src/shared/agent-title-status.ts +++ b/src/shared/agent-title-status.ts @@ -24,6 +24,8 @@ import { isDshTerminalTitle, isPiAgentTitle, isPiTerminalTitle, + isGeminiTerminalTitle, + isGrokRotatingWorkingTitle, titleHasAgentName } from './agent-title-core' import type { AgentStatus } from './agent-title-core' @@ -34,10 +36,7 @@ import { } from './pi-compatible-synthetic-title' import { clearPiStateWorkingMarker, getPiStateTitleStatus } from './pi-state-title-marker' import { getWrapperTitleSegments } from './terminal-title-wrapper-segments' -import { - isGrokRotatingWorkingTitle, - resolveExplicitTerminalTitleAgentType -} from './terminal-title-agent-type' +import { resolveExplicitTerminalTitleAgentType } from './terminal-title-agent-type' import { memoizeTitleClassification } from './terminal-title-classification-memo' /** @@ -159,30 +158,59 @@ export function createAgentStatusTracker( * Normalize high-churn agent titles into stable display labels before storage. */ export function normalizeTerminalTitle(title: string): string { + const proposal = proposeTerminalTitle(title) + return proposal === title || + resolveExplicitTerminalTitleAgentType(title) === resolveExplicitTerminalTitleAgentType(proposal) + ? proposal + : title +} + +const GEMINI_DISPLAY_LABEL = 'Gemini CLI' +const QODER_DISPLAY_LABEL = 'Qoder CLI' +const QODER_CN_DISPLAY_LABEL = 'Qoder CLI CN' +const GROK_WORKING_TITLE = '\u280b Grok' +const QODER_TITLE_GLYPHS = { working: GEMINI_WORKING, permission: '▲', idle: GEMINI_IDLE } as const +const DESTRUCTIVE_TITLE_STAMPS: ReadonlySet = new Set([ + ...[GEMINI_WORKING, GEMINI_PERMISSION, GEMINI_IDLE].map( + (glyph) => `${glyph} ${GEMINI_DISPLAY_LABEL}` + ), + ...Object.values(QODER_TITLE_GLYPHS).flatMap((glyph) => + [QODER_DISPLAY_LABEL, QODER_CN_DISPLAY_LABEL].map((label) => `${glyph} ${label}`) + ), + GROK_WORKING_TITLE +]) + +export function isNormalizedAgentTitleStamp(title: string): boolean { + return DESTRUCTIVE_TITLE_STAMPS.has(title) +} + +function proposeTerminalTitle(title: string): string { if (getDeepSeekBuildTitleStatus(title)) { return title } const qoderStatus = qoderTitleStatus(title) if (qoderStatus) { - const label = title.includes('Qoder CLI CN') ? 'Qoder CLI CN' : 'Qoder CLI' - return `${qoderStatus === 'working' ? '✦' : qoderStatus === 'permission' ? '▲' : '◇'} ${label}` + const label = title.includes(QODER_CN_DISPLAY_LABEL) + ? QODER_CN_DISPLAY_LABEL + : QODER_DISPLAY_LABEL + return `${QODER_TITLE_GLYPHS[qoderStatus]} ${label}` } if (!title) { return title } // Pi/OMP explicit markers outrank Gemini glyphs embedded in free-form session/cwd labels. - if (!getPiStateTitleStatus(title) && resolveExplicitTerminalTitleAgentType(title) === 'gemini') { + if (!getPiStateTitleStatus(title) && isGeminiTerminalTitle(title)) { const status = detectAgentStatusFromTitle(title) if (status === 'permission') { - return `${GEMINI_PERMISSION} Gemini CLI` + return `${GEMINI_PERMISSION} ${GEMINI_DISPLAY_LABEL}` } if (status === 'working') { - return `${GEMINI_WORKING} Gemini CLI` + return `${GEMINI_WORKING} ${GEMINI_DISPLAY_LABEL}` } // Require a glyph before stamping Gemini rest state; a bare shell auto-title is not readiness evidence. if (status === 'idle' && title.includes(GEMINI_IDLE)) { - return `${GEMINI_IDLE} Gemini CLI` + return `${GEMINI_IDLE} ${GEMINI_DISPLAY_LABEL}` } } @@ -193,7 +221,7 @@ export function normalizeTerminalTitle(title: string): string { // Collapse Grok spinner/status churn to one label; idle titles pass through so the final semantic title remains (#7863). if (isGrokRotatingWorkingTitle(title)) { - return '\u280b Grok' + return GROK_WORKING_TITLE } return title diff --git a/src/shared/dsb-terminal-title.ts b/src/shared/dsb-terminal-title.ts index 4f75bc1cc7b3..a60773cf660e 100644 --- a/src/shared/dsb-terminal-title.ts +++ b/src/shared/dsb-terminal-title.ts @@ -12,8 +12,20 @@ import { getWrapperTitleSegments } from './terminal-title-wrapper-segments' const DSB_TITLE_RE = /(?:^| - )deepseek build$/i // Why: DSB separates its spinner with " - "; a Claude task can end on the same suffix. -const DSB_WORKING_TITLE_RE = - /^(?:\u26A0 Action Required - )?[\u2800-\u28ff]+\s+-\s+[\s\S]+?\s-\s+deepseek build$/i +const DSB_WORKING_PREFIX = String.raw`^(?:\u26A0 Action Required - )?[\u2800-\u28ff]+\s+-\s+` +const DSB_WORKING_PREFIX_RE = new RegExp(DSB_WORKING_PREFIX, 'i') +const DSB_WORKING_TITLE_RE = new RegExp( + DSB_WORKING_PREFIX + String.raw`[\s\S]+?\s-\s+deepseek build$`, + 'i' +) + +export function hasDeepSeekBuildWorkingTitlePrefix(header: string): boolean { + return DSB_WORKING_PREFIX_RE.test(header) +} + +export function isDeepSeekBuildWorkingTitle(title: string): boolean { + return DSB_WORKING_TITLE_RE.test(title) +} const NATIVE_VENDOR_PREFIXES = [ `${CLAUDE_IDLE} `, '. ', @@ -39,7 +51,7 @@ export function isDeepSeekBuildTerminalTitle(title: string): boolean { return segments.some( (segment) => DSB_TITLE_RE.test(segment) && - (!containsAgentSpinnerGlyph(segment) || DSB_WORKING_TITLE_RE.test(segment)) + (!containsAgentSpinnerGlyph(segment) || isDeepSeekBuildWorkingTitle(segment)) ) } @@ -51,5 +63,5 @@ export function getDeepSeekBuildTitleStatus(title: string): AgentStatus | null { if (segments.some((segment) => segment.startsWith('⚠ Action Required - '))) { return 'permission' } - return segments.some((segment) => DSB_WORKING_TITLE_RE.test(segment)) ? 'working' : 'idle' + return segments.some((segment) => isDeepSeekBuildWorkingTitle(segment)) ? 'working' : 'idle' } diff --git a/src/shared/opencode-terminal-title.ts b/src/shared/opencode-terminal-title.ts index eb2bbae9d185..4e156259fca6 100644 --- a/src/shared/opencode-terminal-title.ts +++ b/src/shared/opencode-terminal-title.ts @@ -1,7 +1,21 @@ // Why: wrappers may prepend an SSH/tmux label, and OpenCode may prepend one // status glyph. A spinner-led task from another agent must not become a wrapper. -const OPENCODE_NATIVE_TITLE_RE = - /^\s*(?:(?![\u25A3\u2800-\u28ff])[^|]+? \| )?(?:[\u25A3\u2800-\u28ff] )?OC \|[ \t]+\S/u +const OPENCODE_HEADER = String.raw`(?:[\u25A3\u2800-\u28ff] )?OC` +const OPENCODE_HEADER_RE = new RegExp(String.raw`^\s*${OPENCODE_HEADER} $`, 'u') +const OPENCODE_NATIVE_TITLE_RE = new RegExp( + String.raw`^\s*(?:(?![\u25A3\u2800-\u28ff])[^|]+? \| )?${OPENCODE_HEADER} \|[ \t]+\S`, + 'u' +) + +const OPENCODE_DIRECT_TITLE_RE = new RegExp(String.raw`^\s*${OPENCODE_HEADER} \|[ \t]+\S`, 'u') + +export function isDirectOpenCodeNativeTitle(title: string): boolean { + return OPENCODE_DIRECT_TITLE_RE.test(title) +} + +export function isOpenCodeNativeTitleHeader(header: string): boolean { + return OPENCODE_HEADER_RE.test(header) +} export function isOpenCodeNativeTitle(title: string | null | undefined): boolean { return title ? OPENCODE_NATIVE_TITLE_RE.test(title) : false diff --git a/src/shared/qoder-terminal-title.ts b/src/shared/qoder-terminal-title.ts index e5f4bb3d5b56..4d3b6b4dc732 100644 --- a/src/shared/qoder-terminal-title.ts +++ b/src/shared/qoder-terminal-title.ts @@ -2,7 +2,13 @@ import { isDshTerminalTitle } from './dsh-terminal-title' // Qoder 1.1.64: one space after the glyph, then a session title and a pipe-delimited status. const QODER_DYNAMIC_TITLE_RE = /^[\u2726\u25C7\u25B2] (?! ).*\s\|\s[^|]+$/ -const QODER_LABEL_RE = /^(?:[\u2726\u25C7\u25B2] )?Qoder CLI(?: CN)?(?: \(.*\))?$/ +const QODER_LABEL_PREFIX = String.raw`^(?:[\u2726\u25C7\u25B2] )?Qoder CLI(?: CN)?` +const QODER_LABEL_RE = new RegExp(QODER_LABEL_PREFIX + String.raw`(?: \(.*\))?$`) +const QODER_LABEL_PAYLOAD_RE = new RegExp(QODER_LABEL_PREFIX + String.raw` \(`) + +export function hasQoderTitleLabelPayload(header: string): boolean { + return QODER_LABEL_PAYLOAD_RE.test(header.trimStart()) +} export function isQoderTerminalTitle(title: string): boolean { if (isDshTerminalTitle(title)) { diff --git a/src/shared/terminal-title-agent-type.test.ts b/src/shared/terminal-title-agent-type.test.ts index 50dfcf2d3e68..aaccb375956c 100644 --- a/src/shared/terminal-title-agent-type.test.ts +++ b/src/shared/terminal-title-agent-type.test.ts @@ -59,6 +59,40 @@ describe('resolveExplicitTerminalTitleAgentType', () => { expect(resolveExplicitTerminalTitleAgentType('oc | Understand about the plugin')).toBeNull() }) + it.each([ + ['tmux | OC | a | b | c | d | e | f | g | h | Codex', 'opencode'], + ['tmux | 🐋 a | b | c | d | e | f | g | h | Codex', 'dsh'], + ['Wrapper | OC | Review Codex - DeepSeek Build', 'opencode'], + ['user@host: ~/code | OC | ses_123', 'opencode'], + ['user@[::1]: ~/code | ⠋ OC | ses_123', 'opencode'], + ['[user@host]: ~/code | Codex: fix parser', 'codex'], + ['C:\\repo | ⠋ Cursor Agent', 'cursor'], + ['tmux | Codex: fix parser | a | b | c | d | e | f | g | Claude Code', 'codex'], + ['tmux | ⠋ fix parser | a | b | c | d | e | f | g | Codex', null], + ['Plan: migrate | Codex', null], + ['codex | main | fix parser', null], + ['OC |\tCodex', 'opencode'], + ['⠋ - Codex: fix parser - grok', 'grok'], + ['⠋ Codex: fix parser - grok', null], + ['tmux | OC | ⠋ - Codex: fix parser - grok', null], + ['⠋ - OC | Claude Code - DeepSeek Build', 'dsb'] + ] as const)('consumes the actual frame/barrier in %j', (title, agent) => { + expect(resolveExplicitTerminalTitleAgentType(title)).toBe(agent) + }) + + it.each([7, 8, 9, 200])('retains frames and barriers after %i actual wrappers', (depth) => { + const wrappers = 'x | '.repeat(depth) + const payload = 'a | b | c | d | e | f | g | h | Codex' + for (const [frame, agent] of [ + [`OC | ${payload}`, 'opencode'], + [`🐋 ${payload}`, 'dsh'], + [`Codex: fix parser | ${payload}`, 'codex'], + [`⠋ fix parser | ${payload}`, null] + ] as const) { + expect(resolveExplicitTerminalTitleAgentType(wrappers + frame)).toBe(agent) + } + }) + it('does not find an OpenCode marker inside another agent task title', () => { expect(isOpenCodeNativeTitle('⠋ Fix foo | OC | bar')).toBe(false) expect(resolveExplicitTerminalTitleAgentType('⠋ Fix foo | OC | bar')).toBeNull() diff --git a/src/shared/terminal-title-agent-type.ts b/src/shared/terminal-title-agent-type.ts index 3337d66f9876..4b348eb576a2 100644 --- a/src/shared/terminal-title-agent-type.ts +++ b/src/shared/terminal-title-agent-type.ts @@ -71,17 +71,7 @@ export function isGeminiTerminalTitle(title: string): boolean { return titleHasAgentName(title, 'gemini') } -// Collapse only Grok’s spinner - phrase - grok frame; both delimiters exclude Claude/Codex task mentions. -// Keep unspun session titles unchanged and accept spinner + grok so our collapsed label stays idempotent. -const GROK_ROTATING_FRAME_RE = /^[\u2800-\u28FF]+\s+-\s+[\s\S]+?\s-\s+grok\s*$/i -const GROK_COLLAPSED_WORKING_TITLE_RE = /^[\u2800-\u28FF]+\s+grok\s*$/i - -export function isGrokRotatingWorkingTitle(title: string): boolean { - if (!containsBrailleSpinner(title)) { - return false - } - return GROK_ROTATING_FRAME_RE.test(title) || GROK_COLLAPSED_WORKING_TITLE_RE.test(title) -} +export { isGrokRotatingWorkingTitle } from './agent-title-core' export function isPiAgentTitle(title: string): boolean { return isLegacyPiCompatibleTitle(title) diff --git a/src/shared/terminal-title-classification-memo.test.ts b/src/shared/terminal-title-classification-memo.test.ts index 614f866bb922..92813e606f6f 100644 --- a/src/shared/terminal-title-classification-memo.test.ts +++ b/src/shared/terminal-title-classification-memo.test.ts @@ -11,16 +11,64 @@ import { resolveTabAgentFromSignalSnapshot } from './tab-agent-from-signals' import { buildTitleDerivedAgentRows } from '../renderer/src/components/sidebar/worktree-title-derived-agent-rows' import type { TerminalTab } from './terminal-tab-types' +import type * as OpenCode from './opencode-terminal-title' +import * as Status from './agent-title-status' +import * as Wrappers from './terminal-title-wrapper-segments' +import * as Ingress from '../renderer/src/components/terminal-pane/terminal-title-evidence' + +const work = vi.hoisted((): { strict: boolean; frames: number[] } => ({ + strict: false, + frames: [] +})) +vi.mock('./opencode-terminal-title', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + isOpenCodeNativeTitle: vi.fn((title: string) => { + if (work.strict) { + work.frames.push(title.length) + } + return actual.isOpenCodeNativeTitle(title) + }) + } +}) +vi.mock('./agent-title-status', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, normalizeTerminalTitle: vi.fn(actual.normalizeTerminalTitle) } +}) +vi.mock('./terminal-title-wrapper-segments', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, getWrapperTitleSegments: vi.fn(actual.getWrapperTitleSegments) } +}) +vi.mock( + '../renderer/src/components/terminal-pane/terminal-title-evidence', + async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, resolvePaneTitleDecision: vi.fn(actual.resolvePaneTitleDecision) } + } +) + vi.mock('./agent-title-evidence', async (importOriginal) => { const actual = await importOriginal() return { ...actual, - collectExplicitAgentTitleEvidence: vi.fn(actual.collectExplicitAgentTitleEvidence) + collectExplicitAgentTitleEvidence: vi.fn((title: string) => { + work.strict = true + try { + return actual.collectExplicitAgentTitleEvidence(title) + } finally { + work.strict = false + } + }) } }) vi.mock('./agent-title-name-anchoring', async (importOriginal) => { const actual = await importOriginal() - return { ...actual, agentForNativeFrame: vi.fn(actual.agentForNativeFrame) } + return { + ...actual, + agentForNativeFrame: vi.fn(actual.agentForNativeFrame), + isNeutralAgentTitleWrapper: vi.fn(actual.isNeutralAgentTitleWrapper) + } }) // Count the leaf titleHasAgentName regex to measure unchanged-title work across store writes. @@ -76,20 +124,117 @@ describe('terminal title classification memo', () => { expect(detectAgentStatusFromTitle('codex working')).toBe('working') }) - it('bounds cold OSC work at N/10N and does zero new classification on unchanged production projections', () => { + it.each([ + 'native', + 'wrap8', + 'wrap9', + 'wrap200', + 'named', + 'barrier', + 'dense', + 'sparse', + 'qoder', + 'gemini', + 'grok', + 'pi', + 'old-stamp' + ])('bounds production OSC/projection work at N/10N: %s', (scenario) => { const strict = vi.mocked(Evidence.collectExplicitAgentTitleEvidence) const frames = vi.mocked(Frames.agentForNativeFrame) + const headers = vi.mocked(Frames.isNeutralAgentTitleWrapper) + const normalize = vi.mocked(Status.normalizeTerminalTitle) + const ingress = vi.mocked(Ingress.resolvePaneTitleDecision) + const inherited = vi.mocked(Wrappers.getWrapperTitleSegments) const clear = () => { - strict.mockClear() - frames.mockClear() - classifierCalls.mockClear() + for (const spy of [strict, frames, headers, normalize, ingress, inherited, classifierCalls]) { + spy.mockClear() + } + work.frames = [] } - const counts = () => [ - strict.mock.calls.length, - frames.mock.calls.length + classifierCalls.mock.calls.length - ] + const counts = () => ({ + strict: strict.mock.calls.length, + leaf: frames.mock.calls.length + classifierCalls.mock.calls.length, + boundaries: headers.mock.calls.length, + headerSpan: headers.mock.calls.reduce((sum, [header]) => sum + header.length, 0), + full: work.frames.length, + fullSpan: work.frames.reduce((sum, length) => sum + length, 0), + normalize: normalize.mock.calls.length, + ingress: ingress.mock.calls.length + }) + const inheritedBudget = () => + inherited.mock.calls.reduce( + (total, [title]) => { + const boundaries = [...title.matchAll(/ \| /g)] + const materialized = boundaries.reduce( + (sum, match) => sum + title.length - match.index - 3, + title.length + ) + expect(materialized).toBeLessThanOrEqual((boundaries.length + 1) * title.length) + return { + calls: total.calls + 1, + spans: total.spans + materialized, + comparisonBound: + total.comparisonBound + + ((boundaries.length * (boundaries.length + 1)) / 2) * title.length + } + }, + { calls: 0, spans: 0, comparisonBound: 0 } + ) const measure = (population: number) => { const leafId = '77777777-7777-4777-8777-777777777777' + const owner = scenario === 'pi' ? 'omp' : 'claude' + const rawTitle = (index: number) => { + const id = `memo-${String(population).padStart(3, '0')}-${String(index).padStart(3, '0')}` + const payload = `${id} | a | b | c | d | e | f | g | h | Codex` + if (scenario.startsWith('wrap')) { + return `${'x | '.repeat(Number(scenario.slice(4)))}OC | ${payload}` + } + if (scenario === 'native') { + return `tmux | 🐋 ${payload}` + } + if (scenario === 'named') { + return `tmux | Codex: ${payload}` + } + if (scenario === 'barrier') { + return `tmux | ⠋ fix ${payload}` + } + if (scenario === 'dense') { + return `${'x | '.repeat(200)}⠋ ${id}` + } + if (scenario === 'sparse') { + return `${'x'.repeat(800)}⠋ ${id}` + } + if (scenario === 'qoder') { + return `✦ Qoder CLI CN (${id}) | Thinking` + } + if (scenario === 'gemini') { + return `✦ Analyze ${id}` + } + if (scenario === 'grok') { + return `⠴ - Codex: ${id} - grok` + } + if (scenario === 'pi') { + return `⠴ π - ${id} - cwd` + } + return `✦ ${id} | Thinking - grok` + } + const expectedIcon = + scenario === 'native' + ? 'dsh' + : scenario.startsWith('wrap') + ? 'opencode' + : scenario === 'named' + ? 'codex' + : scenario === 'qoder' + ? 'qoder-cn' + : scenario === 'gemini' + ? 'gemini' + : scenario === 'grok' + ? 'grok' + : scenario === 'pi' + ? 'omp' + : 'claude' + const expectedRow = scenario === 'native' || scenario === 'qoder' ? 'unknown' : expectedIcon const tabs: TerminalTab[] = Array.from({ length: population }, (_, index) => ({ id: `tab-${index}`, worktreeId: 'memo', @@ -99,25 +244,41 @@ describe('terminal title classification memo', () => { color: null, sortOrder: index, createdAt: 0, - launchAgent: 'claude' + launchAgent: owner })) + const observedRaw: string[] = [] const trackers = tabs.map((tab) => createTerminalTitleTracker({ - onTitle: (title) => { - tab.title = title + onTitle: (normalizedTitle, raw) => { + expect(raw.length).toBeLessThanOrEqual(1024) + observedRaw.push(raw) + if ( + observedRaw.length <= population && + (scenario === 'dense' || scenario === 'sparse') + ) { + expect(raw.length).toBe(800 + '⠋ memo-010-000'.length) + } + tab.title = Ingress.resolvePaneTitleDecision({ + normalizedTitle: scenario === 'old-stamp' ? '✦ Qoder CLI' : normalizedTitle, + rawTitle: raw, + displayOwnerAgentType: owner, + displayOwnerIsLaunch: true, + rendererOwnerAgentType: owner, + userGpuMode: 'auto' + }).displayTitle } }) ) - const project = () => { - const icons = tabs.map((tab) => + const project = () => ({ + icons: tabs.map((tab) => resolveTabAgentFromSignalSnapshot({ title: tab.title, hookAgent: null, - focusedCompletedHookAgent: 'claude', - launchAgent: 'claude' + focusedCompletedHookAgent: owner, + launchAgent: owner }) - ) - const rows = buildTitleDerivedAgentRows({ + ), + rows: buildTitleDerivedAgentRows({ tabs, ptyIdsByTabId: Object.fromEntries(tabs.map((tab) => [tab.id, [tab.ptyId!]])), terminalLayoutsByTabId: Object.fromEntries( @@ -129,46 +290,70 @@ describe('terminal title classification memo', () => { seenPaneKeys: new Set(), now: 1 }) - return { icons, rows } - } + }) try { clear() - trackers.forEach((tracker, index) => - tracker.handleChunk( - `\x1b]0;⠋ Codex: memo-${String(population).padStart(3, '0')}-${String(index).padStart(3, '0')}\x07` - ) - ) + trackers.forEach((tracker, index) => tracker.handleChunk(`\x1b]0;${rawTitle(index)}\x07`)) + // Exact equality proves deep inputs reach the tracker without OSC truncation. + expect(observedRaw).toEqual(tabs.map((_, index) => rawTitle(index))) const first = project() - expect(first.icons).toEqual(Array(population).fill('codex')) - expect(first.rows.map((row) => [row.agentType, row.entry.prompt])).toEqual( - Array.from({ length: population }, () => ['codex', 'Codex']) - ) + expect(first.icons).toEqual(Array(population).fill(expectedIcon)) + expect(first.rows.map((row) => row.agentType)).toEqual(Array(population).fill(expectedRow)) const cold = counts() + expect(cold.strict).toBeLessThanOrEqual(3 * population + 10) + expect(cold.normalize).toBeLessThanOrEqual(2 * population) + expect(cold.ingress).toBe(population) + const coldSpan = strict.mock.calls.reduce((sum, [title]) => sum + title.length, 0) + expect(cold.headerSpan).toBeLessThanOrEqual(coldSpan) + expect(cold.full).toBe(cold.strict) + expect(cold.full).toBeLessThanOrEqual(8 * cold.strict) + expect(cold.fullSpan).toBeLessThanOrEqual(8 * coldSpan) + const inheritedCold = inheritedBudget() clear() for (let write = 0; write < STORE_WRITES; write += 1) { project() } - expect(counts()).toEqual([0, 0]) + expect(Object.values(counts())).toEqual(Array(8).fill(0)) + const inheritedWarm = inheritedBudget() + if (scenario === 'pi') { + expect(inheritedWarm.calls).toBeGreaterThan(0) + } + clear() trackers[0].handleChunk( - `\x1b]0;Fix Codex memo-${String(population).padStart(3, '0')} - grok\x07` + `\x1b]0;Fix Codex ${scenario}-${String(population).padStart(3, '0')} - grok\x07` ) const changed = project() expect(changed.icons[0]).toBe('grok') expect(changed.rows[0]).toMatchObject({ agentType: 'grok', entry: { prompt: 'Grok' } }) - expect(changed.icons.slice(1)).toEqual(Array(population - 1).fill('codex')) - return { cold, changed: counts() } + expect(changed.icons.slice(1)).toEqual(Array(population - 1).fill(expectedIcon)) + return { cold, inheritedCold, inheritedWarm, changed: counts() } } finally { trackers.forEach((tracker) => tracker.dispose()) } } const n = measure(10) const tenN = measure(100) - expect(n.cold[0]).toBe(10) - expect(tenN.cold[0]).toBe(100) - expect(tenN.cold[1]).toBeLessThanOrEqual(n.cold[1] * 10) - expect(n.cold[1]).toBeGreaterThan(0) + for (const category of [ + 'strict', + 'leaf', + 'boundaries', + 'headerSpan', + 'full', + 'fullSpan', + 'normalize', + 'ingress' + ] as const) { + expect(tenN.cold[category]).toBeLessThanOrEqual(10 * n.cold[category] + 10) + } + expect(tenN.inheritedCold.calls).toBeLessThanOrEqual(10 * n.inheritedCold.calls + 10) + expect(tenN.inheritedCold.spans).toBeLessThanOrEqual(10 * n.inheritedCold.spans + 10240) + expect(tenN.inheritedCold.comparisonBound).toBeLessThanOrEqual( + 10 * n.inheritedCold.comparisonBound + 10240 + ) + expect(tenN.inheritedWarm.spans).toBeLessThanOrEqual(10 * n.inheritedWarm.spans) + expect(tenN.inheritedWarm.calls).toBeLessThanOrEqual(10 * n.inheritedWarm.calls) expect(tenN.changed).toEqual(n.changed) - expect(n.changed[0]).toBe(1) + console.info('production title work', scenario, JSON.stringify({ n, tenN })) }) it('caches null and false verdicts, not just truthy ones', () => { From 89597b94666fd955ca81a23cdf3d8f65b0a46a80 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 07:32:58 -0700 Subject: [PATCH 10/13] Preserve activity token whitespace at title wrapper boundaries --- .../session/mobile-terminal-tab-agent.test.ts | 8 ++- .../worktree-title-derived-agent-rows.test.ts | 13 ++++- .../native-chat-leaf-title-agent.test.ts | 2 + .../terminal-pane/terminal-ctrl-enter.test.ts | 2 + .../terminal-title-evidence.test.ts | 13 +++++ .../terminal-windows-shift-enter.test.ts | 13 +++++ src/shared/agent-detection.test.ts | 6 +++ src/shared/agent-title-name-anchoring.ts | 6 ++- src/shared/terminal-title-agent-type.test.ts | 51 ++++++++++++++++++- ...terminal-title-classification-memo.test.ts | 13 ++++- 10 files changed, 119 insertions(+), 8 deletions(-) diff --git a/mobile/src/session/mobile-terminal-tab-agent.test.ts b/mobile/src/session/mobile-terminal-tab-agent.test.ts index 5603b0ebae2a..0310e7d8a4ec 100644 --- a/mobile/src/session/mobile-terminal-tab-agent.test.ts +++ b/mobile/src/session/mobile-terminal-tab-agent.test.ts @@ -49,6 +49,9 @@ function terminalTab( describe('resolveMobileTerminalTabAgentId', () => { it.each([ + ['. | Droid', 'claude'], + ['tmux | Droid', 'droid'], + ['OC | . | Droid', 'claude'], ['⠋ fix the gemini launcher', 'claude'], ['⠋ add ✦ icon to header', 'claude'], ['⠋ Codex: fix Gemini terminal behavior', 'codex'], @@ -61,14 +64,17 @@ describe('resolveMobileTerminalTabAgentId', () => { ['✦ Analyze Codex', 'gemini'] ])('uses the production OSC normalization for %s', (raw, agent) => { let title = '' + let observedRaw = '' const tracker = createTerminalTitleTracker({ - onTitle: (emitted) => { + onTitle: (emitted, rawTitle) => { + observedRaw = rawTitle title = emitted } }) try { tracker.handleChunk(`\x1b]0;${raw}\x07`) expect(raw.length).toBeLessThanOrEqual(1024) + expect(observedRaw).toBe(raw) expect( resolveMobileTerminalTabAgentId( terminalTab(title, { agentType: 'claude', state: 'done', launchAgent: 'claude' }) diff --git a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts index 5fd483cec8fe..2e9590f443d9 100644 --- a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts +++ b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts @@ -57,6 +57,10 @@ function processRead(agent: TuiAgent): TitleDerivedPaneForeground { describe('buildTitleDerivedAgentRows', () => { it.each([ + ['. | Droid', null, null, 'claude', 'claude', 'Claude'], + [`${'x | '.repeat(200)}* | Grok`, null, null, 'claude', 'claude', 'Claude'], + ['tmux | Grok', null, 'grok', 'grok', 'grok', 'Grok'], + ['OC | . | Droid', null, 'opencode', 'claude', 'opencode', 'OpenCode'], ['⠋ fix the gemini launcher', '⠋ fix the gemini launcher', null, 'claude', 'claude', 'Claude'], ['⠋ add ✦ icon to header', '⠋ add ✦ icon to header', null, 'claude', 'claude', 'Claude'], [ @@ -155,6 +159,12 @@ describe('buildTitleDerivedAgentRows', () => { launchAgent: 'claude' }) ).toBe(agent) + if (raw === '. | Droid' || raw.endsWith('* | Grok')) { + expect(resolveTabAgentFromSignalSnapshot({ title, hookAgent: null })).toBeNull() + expect( + resolveTabAgentFromSignalSnapshot({ title, hookAgent: null, launchAgent: 'claude' }) + ).toBe('claude') + } if (strict === 'opencode') { expect(resolveTabAgentFromSignalSnapshot({ title, hookAgent: null })).toBe('opencode') expect( @@ -173,8 +183,7 @@ describe('buildTitleDerivedAgentRows', () => { terminalLayoutsByTabId: { 'tab-1': makeSingleLayout(LEAF_ID_1) }, now: 2000 }) - expect(rows).toHaveLength(1) - expect(rows[0]).toMatchObject({ agentType: rowAgent, entry: { prompt: label } }) + expect(rows.map((row) => [row.agentType, row.entry.prompt])).toEqual([[rowAgent, label]]) } finally { tracker.dispose() } diff --git a/src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.test.ts b/src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.test.ts index e8fd2c816459..8bd4a1f14d3f 100644 --- a/src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.test.ts +++ b/src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.test.ts @@ -9,6 +9,8 @@ const panes = [ describe('resolveNativeChatLeafTitleAgent', () => { it.each([ + ['. | Droid', null], + ['tmux | Droid', 'droid'], ['⠋ - Codex: fix parser - grok', 'grok'], ['⠋ Codex: fix parser - grok', null], ['tmux | ⠋ fix | a | b | c | d | e | f | g | Codex', null], diff --git a/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts b/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts index 756fa44cf884..1c794b844340 100644 --- a/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts @@ -15,6 +15,8 @@ describe('hasCtrlEnterCsiUAuthorityForPane', () => { }) it.each([ + ['. | Droid', false], + ['tmux | Droid', true], ['⠋ - Codex: fix parser - grok', true], ['⠋ Codex: fix parser - grok', false], ['tmux | ⠋ fix | a | b | c | d | e | f | g | Grok', false], diff --git a/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts b/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts index 05174798ccdb..c80607a864d9 100644 --- a/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts @@ -8,6 +8,7 @@ import { resolvePaneTitleDecision } from './terminal-title-evidence' import { installTitleSpawnBell } from './pty-connection/title-spawn-bell' import { clearStaleAgentTabTitleOnConfirmedShell } from './pty-connection/confirmed-shell-agent-title' +import { resolveExplicitTerminalTitleAgentType } from '../../../../shared/terminal-title-agent-type' import { isNormalizedAgentTitleStamp } from '../../../../shared/agent-title-status' vi.mock('@/store', () => ({ @@ -38,6 +39,7 @@ describe('resolvePaneTitleDecision', () => { ['▲ Qoder CLI', '▲ session | Action Required - grok', '▲ session | Action Required - grok'], ['◇ Qoder CLI CN', '◇ Qoder CLI CN | Idle - grok', '◇ Qoder CLI CN | Idle - grok'], ['✦ Qoder CLI CN', '✦ Qoder CLI CN (Codex | Claude Code)', '✦ Qoder CLI CN'], + ['⠋ Grok', '* | Grok', '* | Grok'], ['⠋ Grok', '⠋ Codex: fix parser - grok', '⠋ Codex: fix parser - grok'], ['⠋ Grok', '⠋ - Codex: fix parser - grok', '⠋ Grok'], // Normalized-only history cannot recover the original task; title-only reuse remains supported. @@ -52,6 +54,17 @@ describe('resolvePaneTitleDecision', () => { }) expect(decision.displayTitle).toBe(displayTitle) expect(decision.rawTitle).toBe(rawTitle) + if (rawTitle === '* | Grok') { + const replay = resolvePaneTitleDecision({ + normalizedTitle: displayTitle, + rawTitle: displayTitle, + displayOwnerAgentType: 'claude', + rendererOwnerAgentType: null, + userGpuMode: 'auto' + }) + expect(resolveExplicitTerminalTitleAgentType(replay.displayTitle)).toBeNull() + expect(replay).toEqual(decision) + } }) it.each([ diff --git a/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts b/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts index 039cb9ec9180..5276e9e78953 100644 --- a/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts @@ -13,6 +13,19 @@ describe('resolveWindowsShiftEnterEncoding', () => { expect(resolveWindowsShiftEnterEncodingForPane(state, 'tab:pane', '⠋ Droid')).toBe('csi-u') }) + it.each([ + ['. | Droid', 'alt-enter'], + ['tmux | Droid', 'csi-u'] + ] as const)('uses the actual marker boundary for Windows input in %j', (title, encoding) => { + expect( + resolveWindowsShiftEnterEncodingForPane( + { paneForegroundAgentByPaneKey: {}, agentLaunchConfigByPaneKey: {} }, + 'tab:pane', + title + ) + ).toBe(encoding) + }) + it('does not expose a keyboard mode inside a wrapped task barrier', () => { expect( resolveWindowsShiftEnterEncodingForPane( diff --git a/src/shared/agent-detection.test.ts b/src/shared/agent-detection.test.ts index 863f08b36578..298b8e1a2f6b 100644 --- a/src/shared/agent-detection.test.ts +++ b/src/shared/agent-detection.test.ts @@ -22,6 +22,9 @@ import { resolveExplicitTerminalTitleAgentType } from './terminal-title-agent-ty describe('normalization structural identity invariant', () => { it.each([ + ['* | Grok', '* | Grok'], + ['. | ✦ session | Thinking', '. | ✦ session | Thinking'], + ['. | ✦ Analyze', '. | ✦ Analyze'], ['✦ session | Thinking - grok', '✦ session | Thinking - grok'], ['▲ session | Action Required - grok', '▲ session | Action Required - grok'], ['◇ Qoder CLI CN | Idle - grok', '◇ Qoder CLI CN | Idle - grok'], @@ -45,6 +48,9 @@ describe('normalization structural identity invariant', () => { ['Fix Codex - grok', 'Fix Codex - grok'], ['⠴ - Review Codex - DeepSeek Build', '⠴ - Review Codex - DeepSeek Build'] ])('preserves identity and idempotence for %j', (raw, expected) => { + if (raw.startsWith('. | ') || raw.startsWith('* | ')) { + expect(resolveExplicitTerminalTitleAgentType(raw)).toBeNull() + } const display = normalizeTerminalTitle(raw) expect(display).toBe(expected) expect(resolveExplicitTerminalTitleAgentType(display)).toBe( diff --git a/src/shared/agent-title-name-anchoring.ts b/src/shared/agent-title-name-anchoring.ts index 61b6d51193f5..2711c42cd04d 100644 --- a/src/shared/agent-title-name-anchoring.ts +++ b/src/shared/agent-title-name-anchoring.ts @@ -134,10 +134,12 @@ export function agentForNamedTitlePrefix(text: string): TerminalAgent | null { /** Inspect one disjoint header, preserving shell host/cwd syntax without admitting colon task prose. */ export function isNeutralAgentTitleWrapper(header: string): boolean { - const trimmed = header.trim() - if (stripLeadingAgentTitleDecorationOrEmpty(trimmed) !== trimmed) { + // ASCII activity tokens include trailing whitespace, so classify before right trimming. + const lexical = header.trimStart() + if (stripLeadingAgentTitleDecorationOrEmpty(lexical) !== lexical) { return false } + const trimmed = lexical.trim() return ( !trimmed.includes(':') || /^(?:[^\s@:[\]]+@(?:\[[^\]]+\]|[^\s:]+)|\[[^\]\s]+@[^\]\s]+\]):\s*(?:[~/]|[A-Za-z]:[\\/])/.test( diff --git a/src/shared/terminal-title-agent-type.test.ts b/src/shared/terminal-title-agent-type.test.ts index aaccb375956c..516c32007d13 100644 --- a/src/shared/terminal-title-agent-type.test.ts +++ b/src/shared/terminal-title-agent-type.test.ts @@ -49,7 +49,6 @@ describe('resolveExplicitTerminalTitleAgentType', () => { expect(resolveExplicitTerminalTitleAgentType('OC | Understand about the plugin')).toBe( 'opencode' ) - expect(resolveExplicitTerminalTitleAgentType('OC | Compare Codex and Claude')).toBe('opencode') // Why: Gemini glyphs inside OpenCode session text must not rebrand the tab. expect(resolveExplicitTerminalTitleAgentType('OC | ✦ Gemini CLI')).toBe('opencode') expect(getSharedAgentLabel('OC | Compare Codex and Claude')).toBe('OpenCode') @@ -80,6 +79,55 @@ describe('resolveExplicitTerminalTitleAgentType', () => { expect(resolveExplicitTerminalTitleAgentType(title)).toBe(agent) }) + it.each([0, 1, 8, 9, 200])('keeps ASCII marker barriers after %i wrappers', (depth) => { + for (const marker of ['.', '*']) { + for (const payload of ['Droid', 'Grok']) { + expect( + resolveExplicitTerminalTitleAgentType(`${'x | '.repeat(depth)}${marker} | ${payload}`) + ).toBeNull() + } + } + }) + + it.each([ + [' . | Grok', null], + ['x | * | Droid', null], + ['. | Droid', null], + ['.\t | Grok', null], + ['*\u00a0 | Droid', null], + ['x | Grok', 'grok'], + [' x | Grok', 'grok'], + [' | Grok', 'grok'], + [' | Grok', 'grok'], + [' | | Grok', 'grok'], + ['', null], + ...['...', './repo', '.venv', '*.ts'].map((header) => [`${header} | Grok`, 'grok'] as const), + ['.|Grok', null], + ['*|Droid', null], + ['.', null], + ['*', null], + ['. Grok', null], + ['* Grok', null], + ['. Claude Code', 'claude'], + ['. | Claude Code', null], + ['. | OC | ses_1', null], + ['OC | . | Droid', 'opencode'], + ['Codex: . | Droid', 'codex'], + ['⠋ | Grok', null], + ['⠋ | Droid', 'droid'], + ['. | Droid - grok', 'grok'], + ['. | Droid - droid', 'droid'], + ['. | fix parser - grok', 'grok'], + ['. | ✦ session | Thinking - grok', 'grok'], + ['Codex: task - grok', null], + ['OC | task - grok', null] + ] as const)( + 'preserves lexical barrier and independent anchor semantics in %j', + (title, agent) => { + expect(resolveExplicitTerminalTitleAgentType(title)).toBe(agent) + } + ) + it.each([7, 8, 9, 200])('retains frames and barriers after %i actual wrappers', (depth) => { const wrappers = 'x | '.repeat(depth) const payload = 'a | b | c | d | e | f | g | h | Codex' @@ -95,7 +143,6 @@ describe('resolveExplicitTerminalTitleAgentType', () => { it('does not find an OpenCode marker inside another agent task title', () => { expect(isOpenCodeNativeTitle('⠋ Fix foo | OC | bar')).toBe(false) - expect(resolveExplicitTerminalTitleAgentType('⠋ Fix foo | OC | bar')).toBeNull() }) // Only explicit Claude identity may replace the owner; task-text mentions do not prove identity (#8940). diff --git a/src/shared/terminal-title-classification-memo.test.ts b/src/shared/terminal-title-classification-memo.test.ts index 92813e606f6f..c8b63213b2e5 100644 --- a/src/shared/terminal-title-classification-memo.test.ts +++ b/src/shared/terminal-title-classification-memo.test.ts @@ -131,6 +131,7 @@ describe('terminal title classification memo', () => { 'wrap200', 'named', 'barrier', + 'ascii-barrier', 'dense', 'sparse', 'qoder', @@ -198,6 +199,9 @@ describe('terminal title classification memo', () => { if (scenario === 'barrier') { return `tmux | ⠋ fix ${payload}` } + if (scenario === 'ascii-barrier') { + return `${'x | '.repeat(200)}${id} | ${index % 2 ? '*' : '.'} | ${index % 2 ? ' Grok' : 'Droid'}` + } if (scenario === 'dense') { return `${'x | '.repeat(200)}⠋ ${id}` } @@ -298,7 +302,14 @@ describe('terminal title classification memo', () => { expect(observedRaw).toEqual(tabs.map((_, index) => rawTitle(index))) const first = project() expect(first.icons).toEqual(Array(population).fill(expectedIcon)) - expect(first.rows.map((row) => row.agentType)).toEqual(Array(population).fill(expectedRow)) + expect(first.rows.map((row) => row.agentType)).toEqual( + Array(scenario === 'ascii-barrier' ? population / 2 : population).fill(expectedRow) + ) + if (scenario === 'ascii-barrier') { + expect(tabs.map((tab) => resolveExplicitTerminalTitleAgentType(tab.title))).toEqual( + Array(population).fill(null) + ) + } const cold = counts() expect(cold.strict).toBeLessThanOrEqual(3 * population + 10) expect(cold.normalize).toBeLessThanOrEqual(2 * population) From c99ccd6d620fc484a616f6f7951b7d611639b231 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:54:31 -0700 Subject: [PATCH 11/13] test: expose typed mailbox idle evidence source --- .../orchestration-mailbox-cold-park-idle.spec.ts | 4 +--- .../orchestration-mailbox-notification-test-harness.ts | 10 ++++++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts b/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts index 1fab249a0285..ef2af3a2b02a 100644 --- a/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts +++ b/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts @@ -2,7 +2,6 @@ import { rmSync } from 'node:fs' import { stubWriteSettlement } from '../providers/settled-pty-write-stub' import type { WriteSettlement } from '../../shared/pty-write-settlement' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { TuiIdleEvidenceSource } from './tui-idle-evidence-source' import { checkBoundMailbox, createBoundRun, @@ -30,8 +29,7 @@ describe('orchestration mailbox cold-park idle continuation', () => { const db = createDatabase('orca-mailbox-null-title-policy-') const { runtime, write } = createRuntime(db, { launchAgent: null }) await runtime.listTerminals() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: inspect the actual evaluator source; no method is replaced. - const source = Reflect.get(runtime, 'tuiIdleEvidenceSource') as TuiIdleEvidenceSource + const source = runtime.idleEvidenceSource expect(source.getPaneAgent(PTY_ID)).toBeNull() const run = createBoundRun(db, 'Null-agent title policy Run') const message = insertDirectRunMessage(db, run.id, 'Deliver after legitimate quiet') diff --git a/src/main/runtime/orchestration-mailbox-notification-test-harness.ts b/src/main/runtime/orchestration-mailbox-notification-test-harness.ts index 216c83d96251..446bfc687804 100644 --- a/src/main/runtime/orchestration-mailbox-notification-test-harness.ts +++ b/src/main/runtime/orchestration-mailbox-notification-test-harness.ts @@ -64,8 +64,14 @@ export function insertDirectRunMessage(db: OrchestrationDb, runId: string, subje return db.getMessageById(message.id)! } +class MailboxRuntime extends OrcaRuntimeService { + get idleEvidenceSource() { + return this.tuiIdleEvidenceSource + } +} + export type MailboxNotificationHarness = { - runtime: OrcaRuntimeService + runtime: MailboxRuntime write: ReturnType } @@ -122,7 +128,7 @@ export function createRuntime( launchAgent?: TuiAgent | null } = {} ): MailboxNotificationHarness { - const runtime = new OrcaRuntimeService( + const runtime = new MailboxRuntime( ORCA_LAYOUT_OWNER_IS_MAIN ? mailboxLayoutStore() : null, undefined, { From 5f080dc23ef7f8cac1a6d71be7deec6cbe9f46ed Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:08:26 -0700 Subject: [PATCH 12/13] test: scope title projection work contract to renderer --- ...worktree-title-classification-work.test.ts | 321 ++++++++++++++++++ ...terminal-title-classification-memo.test.ts | 310 ----------------- 2 files changed, 321 insertions(+), 310 deletions(-) create mode 100644 src/renderer/src/components/sidebar/worktree-title-classification-work.test.ts diff --git a/src/renderer/src/components/sidebar/worktree-title-classification-work.test.ts b/src/renderer/src/components/sidebar/worktree-title-classification-work.test.ts new file mode 100644 index 000000000000..1cb3f93e2509 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-title-classification-work.test.ts @@ -0,0 +1,321 @@ +import { describe, expect, it, vi } from 'vitest' +import * as AgentNameTokenMatchModule from '../../../../shared/agent-name-token-match' +import { resolveExplicitTerminalTitleAgentType } from '../../../../shared/terminal-title-agent-type' +import * as Evidence from '../../../../shared/agent-title-evidence' +import * as Frames from '../../../../shared/agent-title-name-anchoring' +import { createTerminalTitleTracker } from '../../../../shared/terminal-output-side-effects' +import { resolveTabAgentFromSignalSnapshot } from '../../../../shared/tab-agent-from-signals' +import { buildTitleDerivedAgentRows } from './worktree-title-derived-agent-rows' +import type { TerminalTab } from '../../../../shared/terminal-tab-types' + +import type * as OpenCode from '../../../../shared/opencode-terminal-title' +import * as Status from '../../../../shared/agent-title-status' +import * as Wrappers from '../../../../shared/terminal-title-wrapper-segments' +import * as Ingress from '../terminal-pane/terminal-title-evidence' + +const work = vi.hoisted((): { strict: boolean; frames: number[] } => ({ + strict: false, + frames: [] +})) +vi.mock('../../../../shared/opencode-terminal-title', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + isOpenCodeNativeTitle: vi.fn((title: string) => { + if (work.strict) { + work.frames.push(title.length) + } + return actual.isOpenCodeNativeTitle(title) + }) + } +}) +vi.mock('../../../../shared/agent-title-status', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, normalizeTerminalTitle: vi.fn(actual.normalizeTerminalTitle) } +}) +vi.mock('../../../../shared/terminal-title-wrapper-segments', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, getWrapperTitleSegments: vi.fn(actual.getWrapperTitleSegments) } +}) +vi.mock('../terminal-pane/terminal-title-evidence', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, resolvePaneTitleDecision: vi.fn(actual.resolvePaneTitleDecision) } +}) + +vi.mock('../../../../shared/agent-title-evidence', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + collectExplicitAgentTitleEvidence: vi.fn((title: string) => { + work.strict = true + try { + return actual.collectExplicitAgentTitleEvidence(title) + } finally { + work.strict = false + } + }) + } +}) +vi.mock('../../../../shared/agent-title-name-anchoring', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + agentForNativeFrame: vi.fn(actual.agentForNativeFrame), + isNeutralAgentTitleWrapper: vi.fn(actual.isNeutralAgentTitleWrapper) + } +}) + +// Count the leaf titleHasAgentName regex to measure unchanged-title work across store writes. +vi.mock('../../../../shared/agent-name-token-match', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, titleHasAgentName: vi.fn(actual.titleHasAgentName) } +}) + +const classifierCalls = vi.mocked(AgentNameTokenMatchModule.titleHasAgentName) + +const STORE_WRITES = 50 + +describe('terminal title production classification work', () => { + it.each([ + 'native', + 'wrap8', + 'wrap9', + 'wrap200', + 'named', + 'barrier', + 'ascii-barrier', + 'dense', + 'sparse', + 'qoder', + 'gemini', + 'grok', + 'pi', + 'old-stamp' + ])('bounds production OSC/projection work at N/10N: %s', (scenario) => { + const strict = vi.mocked(Evidence.collectExplicitAgentTitleEvidence) + const frames = vi.mocked(Frames.agentForNativeFrame) + const headers = vi.mocked(Frames.isNeutralAgentTitleWrapper) + const normalize = vi.mocked(Status.normalizeTerminalTitle) + const ingress = vi.mocked(Ingress.resolvePaneTitleDecision) + const inherited = vi.mocked(Wrappers.getWrapperTitleSegments) + const clear = () => { + for (const spy of [strict, frames, headers, normalize, ingress, inherited, classifierCalls]) { + spy.mockClear() + } + work.frames = [] + } + const counts = () => ({ + strict: strict.mock.calls.length, + leaf: frames.mock.calls.length + classifierCalls.mock.calls.length, + boundaries: headers.mock.calls.length, + headerSpan: headers.mock.calls.reduce((sum, [header]) => sum + header.length, 0), + full: work.frames.length, + fullSpan: work.frames.reduce((sum, length) => sum + length, 0), + normalize: normalize.mock.calls.length, + ingress: ingress.mock.calls.length + }) + const inheritedBudget = () => + inherited.mock.calls.reduce( + (total, [title]) => { + const boundaries = [...title.matchAll(/ \| /g)] + const materialized = boundaries.reduce( + (sum, match) => sum + title.length - match.index - 3, + title.length + ) + expect(materialized).toBeLessThanOrEqual((boundaries.length + 1) * title.length) + return { + calls: total.calls + 1, + spans: total.spans + materialized, + comparisonBound: + total.comparisonBound + + ((boundaries.length * (boundaries.length + 1)) / 2) * title.length + } + }, + { calls: 0, spans: 0, comparisonBound: 0 } + ) + const measure = (population: number) => { + const leafId = '77777777-7777-4777-8777-777777777777' + const owner = scenario === 'pi' ? 'omp' : 'claude' + const rawTitle = (index: number) => { + const id = `memo-${String(population).padStart(3, '0')}-${String(index).padStart(3, '0')}` + const payload = `${id} | a | b | c | d | e | f | g | h | Codex` + if (scenario.startsWith('wrap')) { + return `${'x | '.repeat(Number(scenario.slice(4)))}OC | ${payload}` + } + if (scenario === 'native') { + return `tmux | 🐋 ${payload}` + } + if (scenario === 'named') { + return `tmux | Codex: ${payload}` + } + if (scenario === 'barrier') { + return `tmux | ⠋ fix ${payload}` + } + if (scenario === 'ascii-barrier') { + return `${'x | '.repeat(200)}${id} | ${index % 2 ? '*' : '.'} | ${index % 2 ? ' Grok' : 'Droid'}` + } + if (scenario === 'dense') { + return `${'x | '.repeat(200)}⠋ ${id}` + } + if (scenario === 'sparse') { + return `${'x'.repeat(800)}⠋ ${id}` + } + if (scenario === 'qoder') { + return `✦ Qoder CLI CN (${id}) | Thinking` + } + if (scenario === 'gemini') { + return `✦ Analyze ${id}` + } + if (scenario === 'grok') { + return `⠴ - Codex: ${id} - grok` + } + if (scenario === 'pi') { + return `⠴ π - ${id} - cwd` + } + return `✦ ${id} | Thinking - grok` + } + const expectedIcon = + scenario === 'native' + ? 'dsh' + : scenario.startsWith('wrap') + ? 'opencode' + : scenario === 'named' + ? 'codex' + : scenario === 'qoder' + ? 'qoder-cn' + : scenario === 'gemini' + ? 'gemini' + : scenario === 'grok' + ? 'grok' + : scenario === 'pi' + ? 'omp' + : 'claude' + const expectedRow = scenario === 'native' || scenario === 'qoder' ? 'unknown' : expectedIcon + const tabs: TerminalTab[] = Array.from({ length: population }, (_, index) => ({ + id: `tab-${index}`, + worktreeId: 'memo', + ptyId: `pty-${index}`, + title: '', + customTitle: null, + color: null, + sortOrder: index, + createdAt: 0, + launchAgent: owner + })) + const observedRaw: string[] = [] + const trackers = tabs.map((tab) => + createTerminalTitleTracker({ + onTitle: (normalizedTitle, raw) => { + expect(raw.length).toBeLessThanOrEqual(1024) + observedRaw.push(raw) + if ( + observedRaw.length <= population && + (scenario === 'dense' || scenario === 'sparse') + ) { + expect(raw.length).toBe(800 + '⠋ memo-010-000'.length) + } + tab.title = Ingress.resolvePaneTitleDecision({ + normalizedTitle: scenario === 'old-stamp' ? '✦ Qoder CLI' : normalizedTitle, + rawTitle: raw, + displayOwnerAgentType: owner, + displayOwnerIsLaunch: true, + rendererOwnerAgentType: owner, + userGpuMode: 'auto' + }).displayTitle + } + }) + ) + const project = () => ({ + icons: tabs.map((tab) => + resolveTabAgentFromSignalSnapshot({ + title: tab.title, + hookAgent: null, + focusedCompletedHookAgent: owner, + launchAgent: owner + }) + ), + rows: buildTitleDerivedAgentRows({ + tabs, + ptyIdsByTabId: Object.fromEntries(tabs.map((tab) => [tab.id, [tab.ptyId!]])), + terminalLayoutsByTabId: Object.fromEntries( + tabs.map((tab) => [ + tab.id, + { root: { type: 'leaf', leafId }, activeLeafId: leafId, expandedLeafId: null } + ]) + ), + seenPaneKeys: new Set(), + now: 1 + }) + }) + try { + clear() + trackers.forEach((tracker, index) => tracker.handleChunk(`\x1b]0;${rawTitle(index)}\x07`)) + // Exact equality proves deep inputs reach the tracker without OSC truncation. + expect(observedRaw).toEqual(tabs.map((_, index) => rawTitle(index))) + const first = project() + expect(first.icons).toEqual(Array(population).fill(expectedIcon)) + expect(first.rows.map((row) => row.agentType)).toEqual( + Array(scenario === 'ascii-barrier' ? population / 2 : population).fill(expectedRow) + ) + if (scenario === 'ascii-barrier') { + expect(tabs.map((tab) => resolveExplicitTerminalTitleAgentType(tab.title))).toEqual( + Array(population).fill(null) + ) + } + const cold = counts() + expect(cold.strict).toBeLessThanOrEqual(3 * population + 10) + expect(cold.normalize).toBeLessThanOrEqual(2 * population) + expect(cold.ingress).toBe(population) + const coldSpan = strict.mock.calls.reduce((sum, [title]) => sum + title.length, 0) + expect(cold.headerSpan).toBeLessThanOrEqual(coldSpan) + expect(cold.full).toBe(cold.strict) + expect(cold.full).toBeLessThanOrEqual(8 * cold.strict) + expect(cold.fullSpan).toBeLessThanOrEqual(8 * coldSpan) + const inheritedCold = inheritedBudget() + clear() + for (let write = 0; write < STORE_WRITES; write += 1) { + project() + } + expect(Object.values(counts())).toEqual(Array(8).fill(0)) + const inheritedWarm = inheritedBudget() + if (scenario === 'pi') { + expect(inheritedWarm.calls).toBeGreaterThan(0) + } + clear() + trackers[0].handleChunk( + `\x1b]0;Fix Codex ${scenario}-${String(population).padStart(3, '0')} - grok\x07` + ) + const changed = project() + expect(changed.icons[0]).toBe('grok') + expect(changed.rows[0]).toMatchObject({ agentType: 'grok', entry: { prompt: 'Grok' } }) + expect(changed.icons.slice(1)).toEqual(Array(population - 1).fill(expectedIcon)) + return { cold, inheritedCold, inheritedWarm, changed: counts() } + } finally { + trackers.forEach((tracker) => tracker.dispose()) + } + } + const n = measure(10) + const tenN = measure(100) + for (const category of [ + 'strict', + 'leaf', + 'boundaries', + 'headerSpan', + 'full', + 'fullSpan', + 'normalize', + 'ingress' + ] as const) { + expect(tenN.cold[category]).toBeLessThanOrEqual(10 * n.cold[category] + 10) + } + expect(tenN.inheritedCold.calls).toBeLessThanOrEqual(10 * n.inheritedCold.calls + 10) + expect(tenN.inheritedCold.spans).toBeLessThanOrEqual(10 * n.inheritedCold.spans + 10240) + expect(tenN.inheritedCold.comparisonBound).toBeLessThanOrEqual( + 10 * n.inheritedCold.comparisonBound + 10240 + ) + expect(tenN.inheritedWarm.spans).toBeLessThanOrEqual(10 * n.inheritedWarm.spans) + expect(tenN.inheritedWarm.calls).toBeLessThanOrEqual(10 * n.inheritedWarm.calls) + expect(tenN.changed).toEqual(n.changed) + console.info('production title work', scenario, JSON.stringify({ n, tenN })) + }) +}) diff --git a/src/shared/terminal-title-classification-memo.test.ts b/src/shared/terminal-title-classification-memo.test.ts index c8b63213b2e5..a82506509577 100644 --- a/src/shared/terminal-title-classification-memo.test.ts +++ b/src/shared/terminal-title-classification-memo.test.ts @@ -4,73 +4,6 @@ import { getAgentLabel } from './agent-title-identity' import { detectAgentStatusFromTitle } from './agent-title-status' import { memoizeTitleClassification } from './terminal-title-classification-memo' import { resolveExplicitTerminalTitleAgentType } from './terminal-title-agent-type' -import * as Evidence from './agent-title-evidence' -import * as Frames from './agent-title-name-anchoring' -import { createTerminalTitleTracker } from './terminal-output-side-effects' -import { resolveTabAgentFromSignalSnapshot } from './tab-agent-from-signals' -import { buildTitleDerivedAgentRows } from '../renderer/src/components/sidebar/worktree-title-derived-agent-rows' -import type { TerminalTab } from './terminal-tab-types' - -import type * as OpenCode from './opencode-terminal-title' -import * as Status from './agent-title-status' -import * as Wrappers from './terminal-title-wrapper-segments' -import * as Ingress from '../renderer/src/components/terminal-pane/terminal-title-evidence' - -const work = vi.hoisted((): { strict: boolean; frames: number[] } => ({ - strict: false, - frames: [] -})) -vi.mock('./opencode-terminal-title', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - isOpenCodeNativeTitle: vi.fn((title: string) => { - if (work.strict) { - work.frames.push(title.length) - } - return actual.isOpenCodeNativeTitle(title) - }) - } -}) -vi.mock('./agent-title-status', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, normalizeTerminalTitle: vi.fn(actual.normalizeTerminalTitle) } -}) -vi.mock('./terminal-title-wrapper-segments', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, getWrapperTitleSegments: vi.fn(actual.getWrapperTitleSegments) } -}) -vi.mock( - '../renderer/src/components/terminal-pane/terminal-title-evidence', - async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, resolvePaneTitleDecision: vi.fn(actual.resolvePaneTitleDecision) } - } -) - -vi.mock('./agent-title-evidence', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - collectExplicitAgentTitleEvidence: vi.fn((title: string) => { - work.strict = true - try { - return actual.collectExplicitAgentTitleEvidence(title) - } finally { - work.strict = false - } - }) - } -}) -vi.mock('./agent-title-name-anchoring', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - agentForNativeFrame: vi.fn(actual.agentForNativeFrame), - isNeutralAgentTitleWrapper: vi.fn(actual.isNeutralAgentTitleWrapper) - } -}) - // Count the leaf titleHasAgentName regex to measure unchanged-title work across store writes. vi.mock('./agent-name-token-match', async (importOriginal) => { const actual = await importOriginal() @@ -124,249 +57,6 @@ describe('terminal title classification memo', () => { expect(detectAgentStatusFromTitle('codex working')).toBe('working') }) - it.each([ - 'native', - 'wrap8', - 'wrap9', - 'wrap200', - 'named', - 'barrier', - 'ascii-barrier', - 'dense', - 'sparse', - 'qoder', - 'gemini', - 'grok', - 'pi', - 'old-stamp' - ])('bounds production OSC/projection work at N/10N: %s', (scenario) => { - const strict = vi.mocked(Evidence.collectExplicitAgentTitleEvidence) - const frames = vi.mocked(Frames.agentForNativeFrame) - const headers = vi.mocked(Frames.isNeutralAgentTitleWrapper) - const normalize = vi.mocked(Status.normalizeTerminalTitle) - const ingress = vi.mocked(Ingress.resolvePaneTitleDecision) - const inherited = vi.mocked(Wrappers.getWrapperTitleSegments) - const clear = () => { - for (const spy of [strict, frames, headers, normalize, ingress, inherited, classifierCalls]) { - spy.mockClear() - } - work.frames = [] - } - const counts = () => ({ - strict: strict.mock.calls.length, - leaf: frames.mock.calls.length + classifierCalls.mock.calls.length, - boundaries: headers.mock.calls.length, - headerSpan: headers.mock.calls.reduce((sum, [header]) => sum + header.length, 0), - full: work.frames.length, - fullSpan: work.frames.reduce((sum, length) => sum + length, 0), - normalize: normalize.mock.calls.length, - ingress: ingress.mock.calls.length - }) - const inheritedBudget = () => - inherited.mock.calls.reduce( - (total, [title]) => { - const boundaries = [...title.matchAll(/ \| /g)] - const materialized = boundaries.reduce( - (sum, match) => sum + title.length - match.index - 3, - title.length - ) - expect(materialized).toBeLessThanOrEqual((boundaries.length + 1) * title.length) - return { - calls: total.calls + 1, - spans: total.spans + materialized, - comparisonBound: - total.comparisonBound + - ((boundaries.length * (boundaries.length + 1)) / 2) * title.length - } - }, - { calls: 0, spans: 0, comparisonBound: 0 } - ) - const measure = (population: number) => { - const leafId = '77777777-7777-4777-8777-777777777777' - const owner = scenario === 'pi' ? 'omp' : 'claude' - const rawTitle = (index: number) => { - const id = `memo-${String(population).padStart(3, '0')}-${String(index).padStart(3, '0')}` - const payload = `${id} | a | b | c | d | e | f | g | h | Codex` - if (scenario.startsWith('wrap')) { - return `${'x | '.repeat(Number(scenario.slice(4)))}OC | ${payload}` - } - if (scenario === 'native') { - return `tmux | 🐋 ${payload}` - } - if (scenario === 'named') { - return `tmux | Codex: ${payload}` - } - if (scenario === 'barrier') { - return `tmux | ⠋ fix ${payload}` - } - if (scenario === 'ascii-barrier') { - return `${'x | '.repeat(200)}${id} | ${index % 2 ? '*' : '.'} | ${index % 2 ? ' Grok' : 'Droid'}` - } - if (scenario === 'dense') { - return `${'x | '.repeat(200)}⠋ ${id}` - } - if (scenario === 'sparse') { - return `${'x'.repeat(800)}⠋ ${id}` - } - if (scenario === 'qoder') { - return `✦ Qoder CLI CN (${id}) | Thinking` - } - if (scenario === 'gemini') { - return `✦ Analyze ${id}` - } - if (scenario === 'grok') { - return `⠴ - Codex: ${id} - grok` - } - if (scenario === 'pi') { - return `⠴ π - ${id} - cwd` - } - return `✦ ${id} | Thinking - grok` - } - const expectedIcon = - scenario === 'native' - ? 'dsh' - : scenario.startsWith('wrap') - ? 'opencode' - : scenario === 'named' - ? 'codex' - : scenario === 'qoder' - ? 'qoder-cn' - : scenario === 'gemini' - ? 'gemini' - : scenario === 'grok' - ? 'grok' - : scenario === 'pi' - ? 'omp' - : 'claude' - const expectedRow = scenario === 'native' || scenario === 'qoder' ? 'unknown' : expectedIcon - const tabs: TerminalTab[] = Array.from({ length: population }, (_, index) => ({ - id: `tab-${index}`, - worktreeId: 'memo', - ptyId: `pty-${index}`, - title: '', - customTitle: null, - color: null, - sortOrder: index, - createdAt: 0, - launchAgent: owner - })) - const observedRaw: string[] = [] - const trackers = tabs.map((tab) => - createTerminalTitleTracker({ - onTitle: (normalizedTitle, raw) => { - expect(raw.length).toBeLessThanOrEqual(1024) - observedRaw.push(raw) - if ( - observedRaw.length <= population && - (scenario === 'dense' || scenario === 'sparse') - ) { - expect(raw.length).toBe(800 + '⠋ memo-010-000'.length) - } - tab.title = Ingress.resolvePaneTitleDecision({ - normalizedTitle: scenario === 'old-stamp' ? '✦ Qoder CLI' : normalizedTitle, - rawTitle: raw, - displayOwnerAgentType: owner, - displayOwnerIsLaunch: true, - rendererOwnerAgentType: owner, - userGpuMode: 'auto' - }).displayTitle - } - }) - ) - const project = () => ({ - icons: tabs.map((tab) => - resolveTabAgentFromSignalSnapshot({ - title: tab.title, - hookAgent: null, - focusedCompletedHookAgent: owner, - launchAgent: owner - }) - ), - rows: buildTitleDerivedAgentRows({ - tabs, - ptyIdsByTabId: Object.fromEntries(tabs.map((tab) => [tab.id, [tab.ptyId!]])), - terminalLayoutsByTabId: Object.fromEntries( - tabs.map((tab) => [ - tab.id, - { root: { type: 'leaf', leafId }, activeLeafId: leafId, expandedLeafId: null } - ]) - ), - seenPaneKeys: new Set(), - now: 1 - }) - }) - try { - clear() - trackers.forEach((tracker, index) => tracker.handleChunk(`\x1b]0;${rawTitle(index)}\x07`)) - // Exact equality proves deep inputs reach the tracker without OSC truncation. - expect(observedRaw).toEqual(tabs.map((_, index) => rawTitle(index))) - const first = project() - expect(first.icons).toEqual(Array(population).fill(expectedIcon)) - expect(first.rows.map((row) => row.agentType)).toEqual( - Array(scenario === 'ascii-barrier' ? population / 2 : population).fill(expectedRow) - ) - if (scenario === 'ascii-barrier') { - expect(tabs.map((tab) => resolveExplicitTerminalTitleAgentType(tab.title))).toEqual( - Array(population).fill(null) - ) - } - const cold = counts() - expect(cold.strict).toBeLessThanOrEqual(3 * population + 10) - expect(cold.normalize).toBeLessThanOrEqual(2 * population) - expect(cold.ingress).toBe(population) - const coldSpan = strict.mock.calls.reduce((sum, [title]) => sum + title.length, 0) - expect(cold.headerSpan).toBeLessThanOrEqual(coldSpan) - expect(cold.full).toBe(cold.strict) - expect(cold.full).toBeLessThanOrEqual(8 * cold.strict) - expect(cold.fullSpan).toBeLessThanOrEqual(8 * coldSpan) - const inheritedCold = inheritedBudget() - clear() - for (let write = 0; write < STORE_WRITES; write += 1) { - project() - } - expect(Object.values(counts())).toEqual(Array(8).fill(0)) - const inheritedWarm = inheritedBudget() - if (scenario === 'pi') { - expect(inheritedWarm.calls).toBeGreaterThan(0) - } - clear() - trackers[0].handleChunk( - `\x1b]0;Fix Codex ${scenario}-${String(population).padStart(3, '0')} - grok\x07` - ) - const changed = project() - expect(changed.icons[0]).toBe('grok') - expect(changed.rows[0]).toMatchObject({ agentType: 'grok', entry: { prompt: 'Grok' } }) - expect(changed.icons.slice(1)).toEqual(Array(population - 1).fill(expectedIcon)) - return { cold, inheritedCold, inheritedWarm, changed: counts() } - } finally { - trackers.forEach((tracker) => tracker.dispose()) - } - } - const n = measure(10) - const tenN = measure(100) - for (const category of [ - 'strict', - 'leaf', - 'boundaries', - 'headerSpan', - 'full', - 'fullSpan', - 'normalize', - 'ingress' - ] as const) { - expect(tenN.cold[category]).toBeLessThanOrEqual(10 * n.cold[category] + 10) - } - expect(tenN.inheritedCold.calls).toBeLessThanOrEqual(10 * n.inheritedCold.calls + 10) - expect(tenN.inheritedCold.spans).toBeLessThanOrEqual(10 * n.inheritedCold.spans + 10240) - expect(tenN.inheritedCold.comparisonBound).toBeLessThanOrEqual( - 10 * n.inheritedCold.comparisonBound + 10240 - ) - expect(tenN.inheritedWarm.spans).toBeLessThanOrEqual(10 * n.inheritedWarm.spans) - expect(tenN.inheritedWarm.calls).toBeLessThanOrEqual(10 * n.inheritedWarm.calls) - expect(tenN.changed).toEqual(n.changed) - console.info('production title work', scenario, JSON.stringify({ n, tenN })) - }) - it('caches null and false verdicts, not just truthy ones', () => { const classify = vi.fn((): string | null => null) const memoized = memoizeTitleClassification(classify) From 7193757ff863f6bbbb7cc5813ff585fd166055b4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:48:21 -0700 Subject: [PATCH 13/13] test: distinguish task activity from agent identity --- ...y-connection-hook-idle-arbitration.test.ts | 19 ++++++++++++++++--- src/renderer/src/lib/worktree-status.test.ts | 12 +++++++++++- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/renderer/src/components/terminal-pane/pty-connection-hook-idle-arbitration.test.ts b/src/renderer/src/components/terminal-pane/pty-connection-hook-idle-arbitration.test.ts index cd0f15622626..1e128bbe1ada 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection-hook-idle-arbitration.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection-hook-idle-arbitration.test.ts @@ -271,7 +271,10 @@ describe('connectPanePty', () => { ) }) - it('allows an explicit idle title from a different agent than fresh hook status', async () => { + it.each([ + { title: '* Claude cross-agent done', completion: false }, + { title: '✳ Claude Code', completion: true } + ])('requires replacement identity over a fresh hook: $title', async ({ title, completion }) => { const { connectPanePty } = await import('./pty-connection') const transport = createMockTransport() transportFactoryQueue.push(transport) @@ -300,12 +303,22 @@ describe('connectPanePty', () => { throw new Error('Expected onAgentBecameIdle to be registered') } - idleHandler('* Claude cross-agent done') + idleHandler(title) vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS) + if (!completion) { + expect(deps.dispatchNotification).not.toHaveBeenCalled() + expect(deps.setCacheTimerStartedAt).not.toHaveBeenCalledWith(paneKey, expect.any(Number)) + expect(pane.terminal.write).not.toHaveBeenCalledWith( + RESET_TERMINAL_CURSOR_STYLE, + expect.any(Function) + ) + return + } + expect(deps.dispatchNotification).toHaveBeenCalledWith({ source: 'agent-task-complete', - terminalTitle: '* Claude cross-agent done', + terminalTitle: title, ptyId: 'tab-pty', paneKey }) diff --git a/src/renderer/src/lib/worktree-status.test.ts b/src/renderer/src/lib/worktree-status.test.ts index 907ea5e57b0b..2b4c8cb00692 100644 --- a/src/renderer/src/lib/worktree-status.test.ts +++ b/src/renderer/src/lib/worktree-status.test.ts @@ -117,13 +117,23 @@ describe('getWorktreeStatus', () => { expect(status).toBe('active') }) - it('still spins on an agent-attributable braille-spinner title', () => { + it('keeps an unowned task title active despite an incidental agent name', () => { const status = getWorktreeStatus( [{ id: 'tab-1', title: '⠹ codex fix flaky test' }], [], livePtyMap('tab-1') ) + expect(status).toBe('active') + }) + + it('spins on the same task title with independent launch identity', () => { + const status = getWorktreeStatus( + [{ id: 'tab-1', title: '⠹ codex fix flaky test', launchAgent: 'codex' }], + [], + livePtyMap('tab-1') + ) + expect(status).toBe('working') }) })