fix(grok): clipboard, native chat, hooks, sessions, ConPTY KKP (#7944)
* fix(grok): restore clipboard and native-chat parity Grok CLI already supports argv prompts, OSC 52 copy, and image paste chips. Orca was blocking those paths: stdin-after-start keystroke injection, OSC 52 writes default-off, image-attachment denylist, and native-chat allowlist. - Launch Grok with positional argv prompts - Default OSC 52 TUI clipboard writes on (still user-toggleable) - Treat Grok as image-attachment capable - Parse ~/.grok/.../chat_history.jsonl for native chat OSC 52 clipboard *query* remains ignored by design (host clipboard exfil risk); xAI docs only require OSC 52 write for remote copy. * fix(grok): sync OSC 52 docs and locale catalog with default-on Update terminalAllowOsc52Clipboard type docs for the true default, and refresh locale strings so settings UI mentions Grok alongside other TUIs. * fix(grok): tool hook matcher, StopFailure, previews, AskUser waiting Grok tool-event matchers are real regexes; bare `*` failed as match-all. Install `.*` for Pre/Post tool hooks, add StopFailure for API-error ends, recognize Grok-native tool input keys, and map ask_user_question PreToolUse to waiting with interactivePrompt (Kimi-style live card path). * fix(grok): resolve chat_history under GROK_HOME and long-cwd layouts Centralize Grok session path helpers so hooks and native-chat honor GROK_HOME and find chat_history.jsonl by session id when the cwd group is slug-encoded (encoded name > 255 bytes) instead of only encodeURIComponent(cwd). * fix(terminal): keep Kitty keyboard for Grok on Windows ConPTY Local Windows ConPTY withholds KKP so CSI-u-blind CLIs (e.g. Antigravity) keep Enter/nav working (#2434). Grok needs KKP for Ctrl+Enter interject and modified-Enter newline chords; blanking the advertisement for Orca-launched Grok left those actions broken. - Prefer KKP when tuiAgent is grok despite ConPTY withhold - Wire launchAgent from tab/startup into keyboard protocol options * fix(grok): restore OSC52 default-off, split decoders, honor GROK_HOME hooks - Keep terminalAllowOsc52Clipboard default false (clipboard exfil risk) - Split transcript-line-decoders under max-lines without suppressions - Install local Grok hooks under resolveGrokHomeDir() / GROK_HOME * refactor(grok): share CLI home resolution * fix(grok): harden terminal and native chat integration * test(grok): align CI coverage with native chat support --------- Co-authored-by: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com>
This commit is contained in:
@@ -411,6 +411,7 @@ describe('remote hook service installers', () => {
|
||||
'SessionStart',
|
||||
'UserPromptSubmit',
|
||||
'Stop',
|
||||
'StopFailure',
|
||||
'SessionEnd',
|
||||
'PreToolUse',
|
||||
'PostToolUse',
|
||||
@@ -422,7 +423,10 @@ describe('remote hook service installers', () => {
|
||||
expect(command).toContain('/home/dev/.orca/agent-hooks/grok-hook.sh')
|
||||
expect(command).toMatch(/^if \[ -x /)
|
||||
}
|
||||
expect(grokConfig.hooks.PreToolUse?.[0]?.matcher).toBe('*')
|
||||
// Why: Grok tool matchers are real regexes; bare `*` is invalid match-all.
|
||||
expect(grokConfig.hooks.PreToolUse?.[0]?.matcher).toBe('.*')
|
||||
expect(grokConfig.hooks.PostToolUse?.[0]?.matcher).toBe('.*')
|
||||
expect(grokConfig.hooks.StopFailure?.[0]?.matcher).toBeUndefined()
|
||||
|
||||
const devinConfig = JSON.parse(devin.fs.files.get('/home/dev/.config/devin/config.json')!) as {
|
||||
permissions: { mode: string }
|
||||
@@ -451,6 +455,35 @@ describe('remote hook service installers', () => {
|
||||
expect(devin.fs.files.get('/home/dev/.orca/agent-hooks/devin-hook.sh')).toContain('/hook/devin')
|
||||
})
|
||||
|
||||
it('installs remote Grok config in the explicit guest GROK_HOME', async () => {
|
||||
const { sftp, fs } = createFakeSftp()
|
||||
|
||||
const status = await new GrokHookService().installRemote(
|
||||
sftp,
|
||||
'/home/dev',
|
||||
'/srv/grok profile/'
|
||||
)
|
||||
|
||||
expect(status.configPath).toBe('/srv/grok profile/hooks/orca-status.json')
|
||||
expect(fs.files.has('/srv/grok profile/hooks/orca-status.json')).toBe(true)
|
||||
expect(fs.files.has('/home/dev/.grok/hooks/orca-status.json')).toBe(false)
|
||||
const script = fs.files.get('/home/dev/.orca/agent-hooks/grok-hook.sh')!
|
||||
expect(script).toContain('${#GROK_HOME}" -le 4096')
|
||||
expect(script).toContain('--data-urlencode "grokHome=${grok_home}"')
|
||||
})
|
||||
|
||||
it.each(['relative/grok', '/bad\\grok', `/${'x'.repeat(4096)}`])(
|
||||
'falls back to login-home Grok config for invalid remote home %s',
|
||||
async (remoteGrokHome) => {
|
||||
const { sftp, fs } = createFakeSftp()
|
||||
|
||||
const status = await new GrokHookService().installRemote(sftp, '/home/dev', remoteGrokHome)
|
||||
|
||||
expect(status.configPath).toBe('/home/dev/.grok/hooks/orca-status.json')
|
||||
expect(fs.files.has('/home/dev/.grok/hooks/orca-status.json')).toBe(true)
|
||||
}
|
||||
)
|
||||
|
||||
it('installs remote Kimi hooks as a managed config.toml block preserving user config', async () => {
|
||||
const userConfig = 'default_model = "kimi-k2.6"\n\n[providers."mine"]\napi_key = "sk-secret"\n'
|
||||
const { sftp, fs } = createFakeSftp({ '/home/dev/.kimi-code/config.toml': userConfig })
|
||||
|
||||
@@ -21,6 +21,8 @@ export type RemoteManagedHookInstallOptions = {
|
||||
* defers the config.toml trust write until that file exists, so the
|
||||
* launch path's only-if-absent seed is never pre-empted. */
|
||||
codexHomeDir?: string
|
||||
/** Explicit GROK_HOME for remote runtimes that redirect Grok's config. */
|
||||
grokHomeDir?: string
|
||||
}
|
||||
|
||||
type RemoteManagedHookInstaller = readonly [
|
||||
@@ -52,7 +54,11 @@ const REMOTE_MANAGED_HOOK_INSTALLERS: readonly RemoteManagedHookInstaller[] = [
|
||||
['cursor', (sftp, remoteHome) => cursorHookService.installRemote(sftp, remoteHome)],
|
||||
['command-code', (sftp, remoteHome) => commandCodeHookService.installRemote(sftp, remoteHome)],
|
||||
['copilot', (sftp, remoteHome) => copilotHookService.installRemote(sftp, remoteHome)],
|
||||
['grok', (sftp, remoteHome) => grokHookService.installRemote(sftp, remoteHome)],
|
||||
[
|
||||
'grok',
|
||||
(sftp, remoteHome, options) =>
|
||||
grokHookService.installRemote(sftp, remoteHome, options?.grokHomeDir)
|
||||
],
|
||||
['droid', (sftp, remoteHome) => droidHookService.installRemote(sftp, remoteHome)],
|
||||
['hermes', (sftp, remoteHome) => hermesHookService.installRemote(sftp, remoteHome)],
|
||||
['devin', (sftp, remoteHome) => devinHookService.installRemote(sftp, remoteHome)],
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import * as agentHookListener from '../../shared/agent-hook-listener'
|
||||
import { makePaneKey } from '../../shared/stable-pane-id'
|
||||
import { AgentHookServer } from './server'
|
||||
|
||||
const PANE_KEY = makePaneKey('tab-1', '11111111-1111-4111-8111-111111111111')
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
function hookBody(payload: Record<string, unknown>): Record<string, unknown> {
|
||||
return {
|
||||
paneKey: PANE_KEY,
|
||||
tabId: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
env: 'production',
|
||||
payload
|
||||
}
|
||||
}
|
||||
|
||||
async function postGrokHook(
|
||||
endpoint: { port: string; token: string },
|
||||
payload: Record<string, unknown>
|
||||
): Promise<Response> {
|
||||
return fetch(`http://127.0.0.1:${endpoint.port}/hook/grok`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Orca-Agent-Hook-Token': endpoint.token
|
||||
},
|
||||
body: JSON.stringify(hookBody(payload))
|
||||
})
|
||||
}
|
||||
|
||||
describe('AgentHookServer Grok discovery retries', () => {
|
||||
it('waits for delayed discovery beyond the transcript retry window', async () => {
|
||||
let releaseDiscovery!: () => void
|
||||
const discovery = new Promise<void>((resolve) => {
|
||||
releaseDiscovery = resolve
|
||||
})
|
||||
vi.spyOn(agentHookListener, 'preparePendingGrokResultDiscovery').mockReturnValue(discovery)
|
||||
const server = new AgentHookServer()
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-grok-delayed-discovery-'))
|
||||
const sessionId = '019e37f4-5135-7b63-a4ab-6d13aa6bf532'
|
||||
const cwd = join(root, 'workspace')
|
||||
const sessionDir = join(root, '.grok', 'sessions', encodeURIComponent(cwd), sessionId)
|
||||
mkdirSync(sessionDir, { recursive: true })
|
||||
const history = join(sessionDir, 'chat_history.jsonl')
|
||||
writeFileSync(history, '')
|
||||
vi.stubEnv('HOME', root)
|
||||
vi.stubEnv('USERPROFILE', root)
|
||||
await server.start({ env: 'production' })
|
||||
try {
|
||||
const env = server.buildPtyEnv()
|
||||
const endpoint = { port: env.ORCA_AGENT_HOOK_PORT, token: env.ORCA_AGENT_HOOK_TOKEN }
|
||||
const listener = vi.fn()
|
||||
server.setListener(listener)
|
||||
|
||||
await postGrokHook(endpoint, { hookEventName: 'UserPromptSubmit', prompt: 'delayed result' })
|
||||
await postGrokHook(endpoint, { hookEventName: 'Stop', sessionId, cwd })
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
expect(listener.mock.calls.at(-1)?.[0].payload.lastAssistantMessage).toBeUndefined()
|
||||
|
||||
writeFileSync(
|
||||
history,
|
||||
`${JSON.stringify({ type: 'assistant', content: 'Found after discovery.' })}\n`
|
||||
)
|
||||
releaseDiscovery()
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(listener.mock.calls.at(-1)?.[0].payload.lastAssistantMessage).toBe(
|
||||
'Found after discovery.'
|
||||
)
|
||||
})
|
||||
} finally {
|
||||
server.stop()
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('does not overwrite a newer same-text prompt when delayed discovery completes', async () => {
|
||||
let releaseDiscovery!: () => void
|
||||
const discovery = new Promise<void>((resolve) => {
|
||||
releaseDiscovery = resolve
|
||||
})
|
||||
vi.spyOn(agentHookListener, 'preparePendingGrokResultDiscovery').mockReturnValue(discovery)
|
||||
const server = new AgentHookServer()
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-grok-stale-discovery-'))
|
||||
vi.stubEnv('HOME', root)
|
||||
vi.stubEnv('USERPROFILE', root)
|
||||
await server.start({ env: 'production' })
|
||||
try {
|
||||
const env = server.buildPtyEnv()
|
||||
const endpoint = { port: env.ORCA_AGENT_HOOK_PORT, token: env.ORCA_AGENT_HOOK_TOKEN }
|
||||
await postGrokHook(endpoint, { hookEventName: 'UserPromptSubmit', prompt: 'old prompt' })
|
||||
await postGrokHook(endpoint, {
|
||||
hookEventName: 'Stop',
|
||||
sessionId: '019e37f4-5135-7b63-a4ab-6d13aa6bf533',
|
||||
cwd: join(root, 'workspace')
|
||||
})
|
||||
await postGrokHook(endpoint, { hookEventName: 'UserPromptSubmit', prompt: 'old prompt' })
|
||||
|
||||
releaseDiscovery()
|
||||
await new Promise((resolve) => setTimeout(resolve, 80))
|
||||
|
||||
expect(server.getStatusSnapshot()).toEqual([
|
||||
expect.objectContaining({ state: 'working', prompt: 'old prompt', agentType: 'grok' })
|
||||
])
|
||||
} finally {
|
||||
server.stop()
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -5305,6 +5305,8 @@ describe('Copilot hook normalization', () => {
|
||||
})
|
||||
)
|
||||
|
||||
// Let the first 50ms retry miss so continuation across SessionEnd is proven.
|
||||
await new Promise((resolve) => setTimeout(resolve, 70))
|
||||
writeFileSync(
|
||||
transcriptPath,
|
||||
`${JSON.stringify({
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
parseFormEncodedBody,
|
||||
readRequestBody,
|
||||
resolveHookSource,
|
||||
preparePendingGrokResultDiscovery,
|
||||
warnOnHookEnvOrVersionMismatch,
|
||||
writeEndpointFile,
|
||||
type AgentHookEventPayload,
|
||||
@@ -804,7 +805,8 @@ export class AgentHookServer {
|
||||
source: AgentHookSource,
|
||||
body: unknown,
|
||||
original: EnrichedAgentHookEventPayload,
|
||||
attempt = 1
|
||||
attempt = 1,
|
||||
discoveryReady = false
|
||||
): void {
|
||||
if (
|
||||
original.payload.lastAssistantMessage ||
|
||||
@@ -814,28 +816,27 @@ export class AgentHookServer {
|
||||
return
|
||||
}
|
||||
this.clearAssistantMessageRetry(original.paneKey)
|
||||
if (!discoveryReady) {
|
||||
const discovery = preparePendingGrokResultDiscovery(source, body)
|
||||
if (discovery) {
|
||||
// Why: slug-group discovery can outlive the bounded transcript-flush
|
||||
// timers. Its completion must drive the first retry deterministically.
|
||||
void discovery
|
||||
.then(() => {
|
||||
if (this.server) {
|
||||
this.applyAssistantMessageRetry(source, body, original, 1, true)
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('[agent-hooks] Grok result discovery failed:', err)
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
this.assistantMessageRetryTimers.delete(original.paneKey)
|
||||
const current = this.state.lastStatusByPaneKey.get(original.paneKey) as
|
||||
| EnrichedAgentHookEventPayload
|
||||
| undefined
|
||||
if (
|
||||
!current ||
|
||||
current.payload.agentType !== original.payload.agentType ||
|
||||
current.payload.prompt !== original.payload.prompt ||
|
||||
current.payload.lastAssistantMessage
|
||||
) {
|
||||
return
|
||||
}
|
||||
const normalized = normalizeHookPayload(this.state, source, body, this.env)
|
||||
if (!normalized?.payload.lastAssistantMessage) {
|
||||
this.scheduleAssistantMessageRetry(source, body, original, attempt + 1)
|
||||
return
|
||||
}
|
||||
// Why: some agents POST Stop before their transcript/chat-history line
|
||||
// is flushed. Retry from a timer so the hook request returns immediately.
|
||||
this.applyNormalizedStatus(normalized)
|
||||
this.applyAssistantMessageRetry(source, body, original, attempt + 1, discoveryReady)
|
||||
} catch (err) {
|
||||
console.error('[agent-hooks] assistant message retry failed:', err)
|
||||
}
|
||||
@@ -846,6 +847,35 @@ export class AgentHookServer {
|
||||
}
|
||||
}
|
||||
|
||||
private applyAssistantMessageRetry(
|
||||
source: AgentHookSource,
|
||||
body: unknown,
|
||||
original: EnrichedAgentHookEventPayload,
|
||||
nextAttempt: number,
|
||||
requireExactOriginal: boolean
|
||||
): void {
|
||||
const current = this.state.lastStatusByPaneKey.get(original.paneKey) as
|
||||
| EnrichedAgentHookEventPayload
|
||||
| undefined
|
||||
if (
|
||||
!current ||
|
||||
(requireExactOriginal && current !== original) ||
|
||||
current.payload.agentType !== original.payload.agentType ||
|
||||
current.payload.prompt !== original.payload.prompt ||
|
||||
current.payload.lastAssistantMessage
|
||||
) {
|
||||
return
|
||||
}
|
||||
const normalized = normalizeHookPayload(this.state, source, body, this.env)
|
||||
if (!normalized?.payload.lastAssistantMessage) {
|
||||
this.scheduleAssistantMessageRetry(source, body, original, nextAttempt, requireExactOriginal)
|
||||
return
|
||||
}
|
||||
// Why: some agents POST Stop before their transcript/chat-history line is
|
||||
// flushed. Discovery is event-driven; subsequent content retries stay timed.
|
||||
this.applyNormalizedStatus(normalized)
|
||||
}
|
||||
|
||||
setPaneKeyAliasPersistenceListener(listener: PaneKeyAliasPersistenceListener | null): void {
|
||||
this.paneKeyAliasPersistenceListener = listener
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { droidDiscoveries, kimiDiscoveries } from './session-scanner-droid-kimi-
|
||||
import { opencodeDiscoveries } from './session-scanner-opencode-sources'
|
||||
import type { AiVaultScanOptions, SessionFileDiscovery } from './session-scanner-types'
|
||||
import { normalizeAgentSessionsDir } from './session-scanner-values'
|
||||
import { resolveGrokSessionsDir } from '../../shared/grok-session-paths'
|
||||
|
||||
const CLAUDE_PROJECTS_DIR = join(homedir(), '.claude', 'projects')
|
||||
export const DEFAULT_CODEX_HOME_DIR = join(homedir(), '.codex')
|
||||
@@ -19,10 +20,7 @@ const COPILOT_SESSIONS_DIR = join(
|
||||
'session-state'
|
||||
)
|
||||
const CURSOR_PROJECTS_DIR = join(homedir(), '.cursor', 'projects')
|
||||
const GROK_SESSIONS_DIR = join(
|
||||
process.env.GROK_HOME?.trim() || join(homedir(), '.grok'),
|
||||
'sessions'
|
||||
)
|
||||
const GROK_SESSIONS_DIR = resolveGrokSessionsDir()
|
||||
const HERMES_SESSIONS_DIR = join(homedir(), '.hermes', 'sessions')
|
||||
const ROVO_SESSIONS_DIR = join(homedir(), '.rovodev', 'sessions')
|
||||
const OPENCLAW_STATE_DIR = process.env.OPENCLAW_STATE_DIR?.trim() || join(homedir(), '.openclaw')
|
||||
|
||||
@@ -79,7 +79,7 @@ function createSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings
|
||||
terminalRightClickToPaste: false,
|
||||
terminalFocusFollowsMouse: false,
|
||||
terminalClipboardOnSelect: false,
|
||||
terminalAllowOsc52Clipboard: false,
|
||||
terminalAllowOsc52Clipboard: true,
|
||||
setupScriptLaunchMode: 'split-vertical',
|
||||
terminalScrollbackRows: 5_000,
|
||||
localAccountRuntime: 'host',
|
||||
|
||||
@@ -84,7 +84,7 @@ function createSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings
|
||||
terminalRightClickToPaste: false,
|
||||
terminalFocusFollowsMouse: false,
|
||||
terminalClipboardOnSelect: false,
|
||||
terminalAllowOsc52Clipboard: false,
|
||||
terminalAllowOsc52Clipboard: true,
|
||||
setupScriptLaunchMode: 'split-vertical',
|
||||
terminalScrollbackRows: 5_000,
|
||||
localAccountRuntime: 'host',
|
||||
|
||||
@@ -15,7 +15,7 @@ vi.mock('os', async () => {
|
||||
}
|
||||
})
|
||||
|
||||
import { GrokHookService } from './hook-service'
|
||||
import { getGrokToolEventMatcherForTests, GrokHookService } from './hook-service'
|
||||
|
||||
const GROK_SCRIPT_FILE_NAME = process.platform === 'win32' ? 'grok-hook.cmd' : 'grok-hook.sh'
|
||||
const WINDOWS_POWERSHELL_LAUNCHER =
|
||||
@@ -55,12 +55,25 @@ describe('GrokHookService', () => {
|
||||
'SessionEnd',
|
||||
'SessionStart',
|
||||
'Stop',
|
||||
'StopFailure',
|
||||
'UserPromptSubmit'
|
||||
].sort()
|
||||
)
|
||||
expect(config.hooks.PreToolUse[0].matcher).toBe('*')
|
||||
expect(config.hooks.PostToolUseFailure[0].matcher).toBe('*')
|
||||
// Why: Grok matchers are real regexes; bare `*` does not match-all.
|
||||
expect(config.hooks.PreToolUse[0].matcher).toBe('.*')
|
||||
expect(config.hooks.PostToolUseFailure[0].matcher).toBe('.*')
|
||||
expect(config.hooks.PostToolUse[0].matcher).toBe('.*')
|
||||
// Why: StopFailure must not carry a tool matcher — lifecycle-only event.
|
||||
expect(config.hooks.StopFailure[0].matcher).toBeUndefined()
|
||||
expect(config.hooks.Notification[0].matcher).toBeUndefined()
|
||||
// Why: assert the shipped helper still matches what install wrote (regression
|
||||
// guard if GROK_TOOL_EVENT_MATCHER drifts from install).
|
||||
expect(getGrokToolEventMatcherForTests()).toBe('.*')
|
||||
expect(getGrokToolEventMatcherForTests()).not.toBe('*')
|
||||
expect(new RegExp(getGrokToolEventMatcherForTests()).test('run_terminal_command')).toBe(true)
|
||||
// Why: build the invalid pattern at runtime so static lint does not flag it.
|
||||
const bareStar = ['*', ''].join('')
|
||||
expect(() => new RegExp(bareStar)).toThrow()
|
||||
expect(config.hooks.PreToolUse[0].hooks[0].command).toMatch(
|
||||
process.platform === 'win32' ? WINDOWS_POWERSHELL_LAUNCHER : /grok-hook/
|
||||
)
|
||||
@@ -75,12 +88,20 @@ describe('GrokHookService', () => {
|
||||
expect(script).toContain('/hook/grok')
|
||||
if (process.platform === 'win32') {
|
||||
expect(script).toContain('%SystemRoot%\\System32\\curl.exe')
|
||||
expect(script).toContain('set "ORCA_GROK_HOME=%GROK_HOME%"')
|
||||
expect(script).toContain('%GROK_HOME:~4096,1%')
|
||||
expect(script).toContain(
|
||||
'if "%ORCA_GROK_HOME:~-1%"=="\\" set "ORCA_GROK_HOME=%ORCA_GROK_HOME%."'
|
||||
)
|
||||
expect(script).toContain('--data-urlencode "grokHome=%ORCA_GROK_HOME%"')
|
||||
} else {
|
||||
// Why: payload is piped to curl via stdin (`payload@-`) so it never lands
|
||||
// on the curl command line (EDR oversized-command-line false positive).
|
||||
expect(script).toContain('payload=$(cat)')
|
||||
expect(script).toContain('printf \'%s\' "$payload" | curl')
|
||||
expect(script).toContain('--data-urlencode "payload@-"')
|
||||
expect(script).toContain('${#GROK_HOME}" -le 4096')
|
||||
expect(script).toContain('--data-urlencode "grokHome=${grok_home}"')
|
||||
expect(script).not.toContain('--data-urlencode "payload=${payload}"')
|
||||
}
|
||||
})
|
||||
@@ -112,6 +133,31 @@ describe('GrokHookService', () => {
|
||||
}
|
||||
)
|
||||
|
||||
it('installs hooks under GROK_HOME when set', () => {
|
||||
const grokHome = mkdtempSync(join(tmpdir(), 'orca-grok-home-env-'))
|
||||
const previous = process.env.GROK_HOME
|
||||
process.env.GROK_HOME = grokHome
|
||||
try {
|
||||
const status = new GrokHookService().install()
|
||||
expect(status.state).toBe('installed')
|
||||
expect(status.configPath).toBe(join(grokHome, 'hooks', 'orca-status.json'))
|
||||
expect(readFileSync(join(grokHome, 'hooks', 'orca-status.json'), 'utf8')).toContain(
|
||||
'SessionStart'
|
||||
)
|
||||
// Why: must not also write into the mocked ~/.grok when GROK_HOME wins.
|
||||
expect(() =>
|
||||
readFileSync(join(homeDir, '.grok', 'hooks', 'orca-status.json'), 'utf8')
|
||||
).toThrow()
|
||||
} finally {
|
||||
if (previous === undefined) {
|
||||
delete process.env.GROK_HOME
|
||||
} else {
|
||||
process.env.GROK_HOME = previous
|
||||
}
|
||||
rmSync(grokHome, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves user-authored hook entries in the Orca Grok config file', () => {
|
||||
const configPath = join(homeDir, '.grok', 'hooks', 'orca-status.json')
|
||||
mkdirSync(dirname(configPath), { recursive: true })
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import type { SFTPWrapper } from 'ssh2'
|
||||
import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-types'
|
||||
import { resolveGrokHomeDir } from '../../shared/grok-session-paths'
|
||||
import {
|
||||
buildManagedCommandHook,
|
||||
createManagedCommandMatcher,
|
||||
@@ -21,33 +21,80 @@ import {
|
||||
writeManagedScriptRemote
|
||||
} from '../agent-hooks/installer-utils-remote'
|
||||
|
||||
// Why: Grok's tool-event matcher is a real regex (see Grok hooks docs). Bare
|
||||
// `*` is not a valid "match all" pattern and can fail to load/match, so tool
|
||||
// lifecycle hooks never fire. `.*` matches every tool name (same as Command
|
||||
// Code's managed hooks).
|
||||
const GROK_TOOL_EVENT_MATCHER = '.*'
|
||||
const GROK_HOME_ENVELOPE_MAX_LENGTH = 4096
|
||||
const WINDOWS_HOOK_PAYLOAD_FORM_LINE = ' --data-urlencode "payload@-" >nul 2>nul'
|
||||
|
||||
const GROK_EVENTS = [
|
||||
{ eventName: 'SessionStart', definition: { hooks: [{ type: 'command', command: '' }] } },
|
||||
{ eventName: 'UserPromptSubmit', definition: { hooks: [{ type: 'command', command: '' }] } },
|
||||
{ eventName: 'Stop', definition: { hooks: [{ type: 'command', command: '' }] } },
|
||||
// Why: Grok can end a turn on API error without a normal Stop; without this
|
||||
// the sidebar can stick on working (same rationale as Claude StopFailure).
|
||||
{ eventName: 'StopFailure', definition: { hooks: [{ type: 'command', command: '' }] } },
|
||||
{ eventName: 'SessionEnd', definition: { hooks: [{ type: 'command', command: '' }] } },
|
||||
{
|
||||
eventName: 'PreToolUse',
|
||||
definition: { matcher: '*', hooks: [{ type: 'command', command: '' }] }
|
||||
definition: { matcher: GROK_TOOL_EVENT_MATCHER, hooks: [{ type: 'command', command: '' }] }
|
||||
},
|
||||
{
|
||||
eventName: 'PostToolUse',
|
||||
definition: { matcher: '*', hooks: [{ type: 'command', command: '' }] }
|
||||
definition: { matcher: GROK_TOOL_EVENT_MATCHER, hooks: [{ type: 'command', command: '' }] }
|
||||
},
|
||||
{
|
||||
eventName: 'PostToolUseFailure',
|
||||
definition: { matcher: '*', hooks: [{ type: 'command', command: '' }] }
|
||||
definition: { matcher: GROK_TOOL_EVENT_MATCHER, hooks: [{ type: 'command', command: '' }] }
|
||||
},
|
||||
{ eventName: 'Notification', definition: { hooks: [{ type: 'command', command: '' }] } }
|
||||
] as const
|
||||
|
||||
function getConfigPath(): string {
|
||||
// Why: Grok loads trusted global hook files from ~/.grok/hooks/*.json. Keep
|
||||
// Orca's managed entries in a dedicated file so user-authored hook files stay
|
||||
// untouched and project-level trust is not required for status reporting.
|
||||
return join(homedir(), '.grok', 'hooks', 'orca-status.json')
|
||||
/** Test seam: the matcher string written for Pre/Post tool lifecycle hooks. */
|
||||
export function getGrokToolEventMatcherForTests(): string {
|
||||
return GROK_TOOL_EVENT_MATCHER
|
||||
}
|
||||
|
||||
function getConfigPath(): string {
|
||||
// Why: Grok loads trusted global hook files from $GROK_HOME/hooks/*.json
|
||||
// (or ~/.grok when unset). Honor GROK_HOME so install/status match the same
|
||||
// home Grok and transcript lookup use; keep Orca entries in a dedicated file
|
||||
// so user-authored hook files stay untouched.
|
||||
return join(resolveGrokHomeDir(), 'hooks', 'orca-status.json')
|
||||
}
|
||||
|
||||
/** Validated guest Grok home with a login-home fallback. */
|
||||
function getRemoteGrokHome(remoteHome: string, remoteGrokHome?: string): string {
|
||||
// Why: SFTP paths are always POSIX — never use host path.join here.
|
||||
const home = remoteHome.replace(/\/+$/, '') || remoteHome
|
||||
const candidate = remoteGrokHome?.trim()
|
||||
if (
|
||||
candidate &&
|
||||
candidate === remoteGrokHome &&
|
||||
candidate.startsWith('/') &&
|
||||
!candidate.includes('\\') &&
|
||||
candidate.length <= GROK_HOME_ENVELOPE_MAX_LENGTH &&
|
||||
!hasControlCharacter(candidate)
|
||||
) {
|
||||
return candidate.replace(/\/+$/, '') || '/'
|
||||
}
|
||||
return `${home}/.grok`
|
||||
}
|
||||
|
||||
function hasControlCharacter(value: string): boolean {
|
||||
return Array.from(value).some((character) => {
|
||||
const code = character.charCodeAt(0)
|
||||
return code <= 0x1f || code === 0x7f
|
||||
})
|
||||
}
|
||||
|
||||
const WINDOWS_GROK_HOOK_POST_COMMAND = buildWindowsAgentHookPostCommand('grok').replace(
|
||||
WINDOWS_HOOK_PAYLOAD_FORM_LINE,
|
||||
` --data-urlencode "grokHome=%ORCA_GROK_HOME%" ^\r\n${WINDOWS_HOOK_PAYLOAD_FORM_LINE}`
|
||||
)
|
||||
|
||||
function getManagedScriptFileName(): string {
|
||||
return process.platform === 'win32' ? 'grok-hook.cmd' : 'grok-hook.sh'
|
||||
}
|
||||
@@ -71,7 +118,12 @@ function getManagedScript(target: 'local' | 'posix' = 'local'): string {
|
||||
'if "%ORCA_AGENT_HOOK_PORT%"=="" exit /b 0',
|
||||
'if "%ORCA_AGENT_HOOK_TOKEN%"=="" exit /b 0',
|
||||
'if "%ORCA_PANE_KEY%"=="" exit /b 0',
|
||||
buildWindowsAgentHookPostCommand('grok'),
|
||||
'set "ORCA_GROK_HOME=%GROK_HOME%"',
|
||||
`if not "%GROK_HOME:~${GROK_HOME_ENVELOPE_MAX_LENGTH},1%"=="" set "ORCA_GROK_HOME="`,
|
||||
// Why: a trailing backslash escapes curl's closing argv quote on Windows,
|
||||
// merging the payload option into grokHome and dropping the hook body.
|
||||
'if "%ORCA_GROK_HOME:~-1%"=="\\" set "ORCA_GROK_HOME=%ORCA_GROK_HOME%."',
|
||||
WINDOWS_GROK_HOOK_POST_COMMAND,
|
||||
'exit /b 0',
|
||||
''
|
||||
].join('\r\n')
|
||||
@@ -89,6 +141,10 @@ function getManagedScript(target: 'local' | 'posix' = 'local'): string {
|
||||
'if [ -z "$payload" ]; then',
|
||||
' exit 0',
|
||||
'fi',
|
||||
'grok_home=',
|
||||
`if [ -n "\${GROK_HOME:-}" ] && [ "\${#GROK_HOME}" -le ${GROK_HOME_ENVELOPE_MAX_LENGTH} ]; then`,
|
||||
' grok_home=$GROK_HOME',
|
||||
'fi',
|
||||
// Timeout caps best-effort hook posts if the local listener stalls.
|
||||
// Why: pipe payload to curl's stdin (`payload@-`) instead of an inline
|
||||
// `payload=$VALUE` arg, so tens-of-KB tool output stays off the curl
|
||||
@@ -103,6 +159,7 @@ function getManagedScript(target: 'local' | 'posix' = 'local'): string {
|
||||
' --data-urlencode "worktreeId=${ORCA_WORKTREE_ID}" \\',
|
||||
' --data-urlencode "env=${ORCA_AGENT_HOOK_ENV}" \\',
|
||||
' --data-urlencode "version=${ORCA_AGENT_HOOK_VERSION}" \\',
|
||||
' --data-urlencode "grokHome=${grok_home}" \\',
|
||||
' --data-urlencode "payload@-" >/dev/null 2>&1 || true',
|
||||
'exit 0',
|
||||
''
|
||||
@@ -213,9 +270,15 @@ export class GrokHookService {
|
||||
return this.getStatus()
|
||||
}
|
||||
|
||||
async installRemote(sftp: SFTPWrapper, remoteHome: string): Promise<AgentHookInstallStatus> {
|
||||
async installRemote(
|
||||
sftp: SFTPWrapper,
|
||||
remoteHome: string,
|
||||
remoteGrokHome?: string
|
||||
): Promise<AgentHookInstallStatus> {
|
||||
const home = remoteHome.replace(/\/$/, '')
|
||||
const remoteConfigPath = `${home}/.grok/hooks/orca-status.json`
|
||||
// Why: only a guest-resolved path can describe remote Grok; never apply the
|
||||
// host process's GROK_HOME to SFTP paths.
|
||||
const remoteConfigPath = `${getRemoteGrokHome(home, remoteGrokHome)}/hooks/orca-status.json`
|
||||
const remoteScriptPath = `${home}/.orca/agent-hooks/grok-hook.sh`
|
||||
try {
|
||||
const config = await readHooksJsonRemote(sftp, remoteConfigPath)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import { resolveSessionFilePath } from './session-file-resolver'
|
||||
|
||||
let tempRoots: string[] = []
|
||||
@@ -38,6 +39,77 @@ describe('resolveSessionFilePath', () => {
|
||||
expect(resolved).toBe(target)
|
||||
})
|
||||
|
||||
it('resolves Grok chat_history.jsonl under encodeURIComponent(cwd)/sessionId', async () => {
|
||||
const root = await makeRoot('orca-native-chat-resolve-grok-')
|
||||
const grokSessionsDir = join(root, 'grok-sessions')
|
||||
const sessionDir = join(grokSessionsDir, encodeURIComponent('/tmp/work'), 'sess-grok-1')
|
||||
await mkdir(sessionDir, { recursive: true })
|
||||
const target = join(sessionDir, 'chat_history.jsonl')
|
||||
await writeFile(target, '{"type":"user","content":"hi"}\n')
|
||||
|
||||
const resolved = await resolveSessionFilePath('grok', 'sess-grok-1', { grokSessionsDir })
|
||||
expect(resolved).toBe(target)
|
||||
})
|
||||
|
||||
it('resolves Grok chat_history by session id under a long-cwd slug group', async () => {
|
||||
const root = await makeRoot('orca-native-chat-resolve-grok-long-')
|
||||
const grokSessionsDir = join(root, 'grok-sessions')
|
||||
const sessionDir = join(grokSessionsDir, 'slug-hash-ab12', 'sess-long-1')
|
||||
await mkdir(sessionDir, { recursive: true })
|
||||
const target = join(sessionDir, 'chat_history.jsonl')
|
||||
await writeFile(join(grokSessionsDir, 'slug-hash-ab12', '.cwd'), `/${'x'.repeat(400)}\n`)
|
||||
await writeFile(target, '{"type":"assistant","content":"ok"}\n')
|
||||
|
||||
await expect(resolveSessionFilePath('grok', 'sess-long-1', { grokSessionsDir })).resolves.toBe(
|
||||
target
|
||||
)
|
||||
})
|
||||
|
||||
it('ignores nested Grok decoys outside the direct group/session layout', async () => {
|
||||
const root = await makeRoot('orca-native-chat-resolve-grok-decoy-')
|
||||
const grokSessionsDir = join(root, 'grok-sessions')
|
||||
const decoy = join(
|
||||
grokSessionsDir,
|
||||
'group',
|
||||
'other-session',
|
||||
'nested',
|
||||
'sess-decoy',
|
||||
'chat_history.jsonl'
|
||||
)
|
||||
await mkdir(dirname(decoy), { recursive: true })
|
||||
await writeFile(decoy, '{}\n')
|
||||
|
||||
await expect(
|
||||
resolveSessionFilePath('grok', 'sess-decoy', { grokSessionsDir })
|
||||
).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('rejects unsafe Grok session ids before filesystem discovery', async () => {
|
||||
const root = await makeRoot('orca-native-chat-resolve-grok-invalid-')
|
||||
const grokSessionsDir = join(root, 'grok-sessions')
|
||||
await mkdir(grokSessionsDir, { recursive: true })
|
||||
|
||||
await expect(
|
||||
resolveSessionFilePath('grok', '../escape', { grokSessionsDir })
|
||||
).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('resolves Grok sessions under GROK_HOME when no override is passed', async () => {
|
||||
const root = await makeRoot('orca-native-chat-resolve-grok-home-')
|
||||
const sessionsDir = join(root, 'sessions')
|
||||
const sessionDir = join(sessionsDir, encodeURIComponent('/repo'), 'sess-env-1')
|
||||
await mkdir(sessionDir, { recursive: true })
|
||||
const target = join(sessionDir, 'chat_history.jsonl')
|
||||
await writeFile(target, '{}\n')
|
||||
const previous = process.env.GROK_HOME
|
||||
process.env.GROK_HOME = root
|
||||
try {
|
||||
await expect(resolveSessionFilePath('grok', 'sess-env-1')).resolves.toBe(target)
|
||||
} finally {
|
||||
restoreEnv('GROK_HOME', previous)
|
||||
}
|
||||
})
|
||||
|
||||
it('matches Codex rollout files by session id suffix', async () => {
|
||||
const root = await makeRoot('orca-native-chat-resolve-codex-')
|
||||
const codexSessionsDir = join(root, 'codex-sessions')
|
||||
|
||||
@@ -4,6 +4,10 @@ import { basename, extname, join } from 'node:path'
|
||||
import type { AgentType } from '../../shared/native-chat-types'
|
||||
import { walkSessionFiles } from '../ai-vault/session-scanner-discovery'
|
||||
import { getOrcaManagedCodexHomePath } from '../codex/codex-home-paths'
|
||||
import {
|
||||
findGrokChatHistoryBySessionId,
|
||||
resolveGrokSessionsDir
|
||||
} from '../../shared/grok-session-paths'
|
||||
|
||||
// Why: these mirror the path constants in ai-vault/session-scanner.ts. Reads
|
||||
// run in the main process against the runtime's own home directory; over SSH
|
||||
@@ -28,12 +32,18 @@ function codexSessionsDirs(): string[] {
|
||||
return candidates.filter((dir, index) => candidates.indexOf(dir) === index)
|
||||
}
|
||||
|
||||
function grokSessionsDir(): string {
|
||||
return resolveGrokSessionsDir(process.env, homedir())
|
||||
}
|
||||
|
||||
export type ResolveSessionFileOptions = {
|
||||
/** Override the Claude projects root (used by tests / isolated scans). */
|
||||
claudeProjectsDir?: string
|
||||
/** Override the Codex sessions roots, searched in order (tests / isolated
|
||||
* scans). Defaults to the orca-managed home then CODEX_HOME/~/.codex. */
|
||||
codexSessionsDirs?: string[]
|
||||
/** Override the Grok sessions root (`~/.grok/sessions`). */
|
||||
grokSessionsDir?: string
|
||||
/** Authoritative transcript path reported by the agent hook
|
||||
* (`providerSession.transcriptPath`). When set and the file exists, it is used
|
||||
* directly — recent Claude Code names the transcript with a UUID that differs
|
||||
@@ -76,6 +86,9 @@ export async function resolveSessionFilePath(
|
||||
if (agent === 'codex') {
|
||||
return resolveCodexSessionFile(trimmedId, options.codexSessionsDirs ?? codexSessionsDirs())
|
||||
}
|
||||
if (agent === 'grok') {
|
||||
return resolveGrokSessionFile(trimmedId, options.grokSessionsDir ?? grokSessionsDir())
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -115,3 +128,13 @@ async function resolveCodexSessionFile(
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function resolveGrokSessionFile(
|
||||
sessionId: string,
|
||||
sessionsDir: string
|
||||
): Promise<string | null> {
|
||||
// Why: Native Chat runs on the main thread; use the bounded async direct-layout
|
||||
// lookup instead of blocking, then repeating, a recursive full-tree scan.
|
||||
const history = await findGrokChatHistoryBySessionId(sessionsDir, sessionId)
|
||||
return history
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { transcriptFallbackId } from './transcript-fallback-id'
|
||||
|
||||
describe('transcriptFallbackId', () => {
|
||||
it('sorts line positions numerically when timestamps are unavailable', () => {
|
||||
const ids = [10, 2, 100, 9].map((offset) => transcriptFallbackId('/chat.jsonl', offset))
|
||||
|
||||
expect(ids.sort()).toEqual([
|
||||
transcriptFallbackId('/chat.jsonl', 2),
|
||||
transcriptFallbackId('/chat.jsonl', 9),
|
||||
transcriptFallbackId('/chat.jsonl', 10),
|
||||
transcriptFallbackId('/chat.jsonl', 100)
|
||||
])
|
||||
})
|
||||
|
||||
it('sorts later incremental byte ranges after earlier ranges', () => {
|
||||
const earlier = transcriptFallbackId('/chat.jsonl', 99)
|
||||
const later = transcriptFallbackId('/chat.jsonl', 100)
|
||||
|
||||
expect(earlier < later).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
const TRANSCRIPT_POSITION_WIDTH = 16
|
||||
|
||||
/** Stable JSONL position id shared by full reads and incremental tailing. */
|
||||
export function transcriptFallbackId(filePath: string, byteOffset: number): string {
|
||||
return `${filePath}:${positionPart(byteOffset)}`
|
||||
}
|
||||
|
||||
function positionPart(value: number): string {
|
||||
return value.toString().padStart(TRANSCRIPT_POSITION_WIDTH, '0')
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Claude JSONL line → NativeChatMessage decoder.
|
||||
|
||||
import type { NativeChatBlock, NativeChatMessage } from '../../shared/native-chat-types'
|
||||
import {
|
||||
asRecord,
|
||||
extractString,
|
||||
parseJsonObject,
|
||||
timestampMs
|
||||
} from '../ai-vault/session-scanner-values'
|
||||
import { claudeContentBlocks } from './transcript-record-blocks'
|
||||
|
||||
export function decodeClaudeTranscriptLine(
|
||||
line: string,
|
||||
fallbackId: string
|
||||
): NativeChatMessage | null {
|
||||
const record = parseJsonObject(line)
|
||||
if (!record) {
|
||||
return null
|
||||
}
|
||||
const role = record.type
|
||||
if (role !== 'user' && role !== 'assistant') {
|
||||
return null
|
||||
}
|
||||
const message = asRecord(record.message)
|
||||
const blocks = claudeContentBlocks(message?.content)
|
||||
if (blocks.length === 0) {
|
||||
return null
|
||||
}
|
||||
const messageId = extractString(record.uuid) ?? extractString(message?.id)
|
||||
return {
|
||||
id: messageId ?? fallbackId,
|
||||
role: claudeMessageRole(role, blocks),
|
||||
blocks,
|
||||
timestamp: parseTimestamp(record.timestamp),
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
|
||||
// Claude marks reasoning via `thinking` content blocks; when a message is made
|
||||
// up solely of reasoning, surface it as a reasoning-role message.
|
||||
function claudeMessageRole(
|
||||
role: 'user' | 'assistant',
|
||||
blocks: NativeChatBlock[]
|
||||
): NativeChatMessage['role'] {
|
||||
if (role === 'user') {
|
||||
const onlyToolResults = blocks.every((block) => block.type === 'tool-result')
|
||||
return onlyToolResults && blocks.length > 0 ? 'tool' : 'user'
|
||||
}
|
||||
return role
|
||||
}
|
||||
|
||||
function parseTimestamp(value: unknown): number | null {
|
||||
const parsed = timestampMs(value)
|
||||
return Number.isFinite(parsed) ? parsed : null
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// Codex JSONL line → NativeChatMessage decoder.
|
||||
|
||||
import type { NativeChatBlock, NativeChatMessage } from '../../shared/native-chat-types'
|
||||
import {
|
||||
asRecord,
|
||||
extractString,
|
||||
parseJsonObject,
|
||||
timestampMs
|
||||
} from '../ai-vault/session-scanner-values'
|
||||
import { claudeContentBlocks, toolResultOutput } from './transcript-record-blocks'
|
||||
|
||||
export function decodeCodexTranscriptLine(
|
||||
line: string,
|
||||
fallbackId: string
|
||||
): NativeChatMessage | null {
|
||||
const record = parseJsonObject(line)
|
||||
if (!record) {
|
||||
return null
|
||||
}
|
||||
const payload = asRecord(record.payload)
|
||||
if (!payload) {
|
||||
return null
|
||||
}
|
||||
const timestamp = parseTimestamp(record.timestamp)
|
||||
const baseId = extractString(payload.id) ?? fallbackId
|
||||
|
||||
if (record.type === 'response_item') {
|
||||
return codexResponseItem(payload, baseId, timestamp)
|
||||
}
|
||||
if (record.type === 'event_msg') {
|
||||
return codexEventMessage(payload, baseId, timestamp)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function codexResponseItem(
|
||||
payload: Record<string, unknown>,
|
||||
id: string,
|
||||
timestamp: number | null
|
||||
): NativeChatMessage | null {
|
||||
if (payload.type === 'message') {
|
||||
const blocks = claudeContentBlocks(payload.content)
|
||||
if (blocks.length === 0) {
|
||||
return null
|
||||
}
|
||||
const role =
|
||||
payload.role === 'assistant' ? 'assistant' : payload.role === 'user' ? 'user' : 'system'
|
||||
return { id, role, blocks, timestamp, source: 'transcript' }
|
||||
}
|
||||
if (payload.type === 'reasoning') {
|
||||
const text = extractString(payload.text) ?? codexSummaryText(payload.summary)
|
||||
if (!text) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
id,
|
||||
role: 'reasoning',
|
||||
blocks: [{ type: 'text', text }],
|
||||
timestamp,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
if (payload.type === 'function_call' || payload.type === 'local_shell_call') {
|
||||
const name = extractString(payload.name) ?? 'tool'
|
||||
return {
|
||||
id,
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'tool-call', name, input: codexCallInput(payload) }],
|
||||
timestamp,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
if (payload.type === 'function_call_output') {
|
||||
return {
|
||||
id,
|
||||
role: 'tool',
|
||||
blocks: [codexToolResult(payload.output)],
|
||||
timestamp,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function codexEventMessage(
|
||||
payload: Record<string, unknown>,
|
||||
id: string,
|
||||
timestamp: number | null
|
||||
): NativeChatMessage | null {
|
||||
if (payload.type === 'user_message') {
|
||||
const text = extractString(payload.message)
|
||||
return text
|
||||
? { id, role: 'user', blocks: [{ type: 'text', text }], timestamp, source: 'transcript' }
|
||||
: null
|
||||
}
|
||||
if (payload.type === 'agent_message') {
|
||||
const text = extractString(payload.message)
|
||||
return text
|
||||
? { id, role: 'assistant', blocks: [{ type: 'text', text }], timestamp, source: 'transcript' }
|
||||
: null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function codexCallInput(payload: Record<string, unknown>): unknown {
|
||||
if (payload.arguments !== undefined) {
|
||||
return payload.arguments
|
||||
}
|
||||
return payload.input ?? payload.action ?? null
|
||||
}
|
||||
|
||||
function codexToolResult(output: unknown): NativeChatBlock {
|
||||
const record = asRecord(output)
|
||||
const isError = record?.success === false || record?.is_error === true
|
||||
return {
|
||||
type: 'tool-result',
|
||||
output: toolResultOutput(record?.content ?? record?.output ?? output),
|
||||
...(isError ? { isError: true } : {})
|
||||
}
|
||||
}
|
||||
|
||||
function codexSummaryText(summary: unknown): string | null {
|
||||
if (!Array.isArray(summary)) {
|
||||
return null
|
||||
}
|
||||
const parts: string[] = []
|
||||
for (const item of summary) {
|
||||
const text = extractString(asRecord(item)?.text) ?? extractString(item)
|
||||
if (text) {
|
||||
parts.push(text)
|
||||
}
|
||||
}
|
||||
return parts.length ? parts.join('\n') : null
|
||||
}
|
||||
|
||||
function parseTimestamp(value: unknown): number | null {
|
||||
const parsed = timestampMs(value)
|
||||
return Number.isFinite(parsed) ? parsed : null
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
// Grok chat_history.jsonl line → NativeChatMessage decoder.
|
||||
|
||||
import type { NativeChatBlock, NativeChatMessage } from '../../shared/native-chat-types'
|
||||
import {
|
||||
asRecord,
|
||||
extractString,
|
||||
parseJsonObject,
|
||||
timestampMs
|
||||
} from '../ai-vault/session-scanner-values'
|
||||
import { claudeContentBlocks, toolResultOutput } from './transcript-record-blocks'
|
||||
|
||||
/**
|
||||
* Grok `chat_history.jsonl` rows: user/assistant/reasoning/tool records with
|
||||
* Claude-like content blocks plus Grok-specific `backend_tool_call` /
|
||||
* `tool_result` shapes. System prompts are skipped.
|
||||
*/
|
||||
export function decodeGrokTranscriptLine(
|
||||
line: string,
|
||||
fallbackId: string
|
||||
): NativeChatMessage | null {
|
||||
const record = parseJsonObject(line)
|
||||
if (!record) {
|
||||
return null
|
||||
}
|
||||
const type = extractString(record.type)
|
||||
if (!type) {
|
||||
return null
|
||||
}
|
||||
const timestamp = parseTimestamp(record.timestamp)
|
||||
const recordId = extractString(record.id)
|
||||
// Why: Grok rows frequently omit timestamps and only some carry ids; prefix
|
||||
// every row with its JSONL position so Native Chat preserves transcript order.
|
||||
const id = recordId ? `${fallbackId}:${recordId}` : fallbackId
|
||||
|
||||
if (type === 'user' || type === 'assistant') {
|
||||
// Why: Grok records bootstrap context as user rows; only submitted prompts
|
||||
// belong in the conversation shown to the user.
|
||||
if (
|
||||
type === 'user' &&
|
||||
(hasNonEmptySyntheticReason(record) || isGrokBootstrapContext(record.content))
|
||||
) {
|
||||
return null
|
||||
}
|
||||
const rawBlocks = claudeContentBlocks(record.content)
|
||||
const blocks = type === 'user' ? rawBlocks.flatMap(normalizeGrokUserQueryBlock) : rawBlocks
|
||||
if (blocks.length === 0) {
|
||||
// Empty assistant rows often only hold tool_calls — surface those.
|
||||
const toolBlocks = grokToolCallBlocks(record.tool_calls)
|
||||
if (toolBlocks.length === 0) {
|
||||
return null
|
||||
}
|
||||
return { id, role: 'assistant', blocks: toolBlocks, timestamp, source: 'transcript' }
|
||||
}
|
||||
if (type === 'assistant') {
|
||||
const toolBlocks = grokToolCallBlocks(record.tool_calls)
|
||||
return {
|
||||
id,
|
||||
role: 'assistant',
|
||||
blocks: [...blocks, ...toolBlocks],
|
||||
timestamp,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
return { id, role: 'user', blocks, timestamp, source: 'transcript' }
|
||||
}
|
||||
|
||||
if (type === 'reasoning') {
|
||||
const text =
|
||||
extractString(record.text) ??
|
||||
grokSummaryText(record.summary) ??
|
||||
extractString(asRecord(record.content)?.text)
|
||||
if (!text?.trim()) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
id,
|
||||
role: 'reasoning',
|
||||
blocks: [{ type: 'text', text }],
|
||||
timestamp,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 'backend_tool_call' || type === 'tool_call') {
|
||||
const name =
|
||||
extractString(asRecord(record.kind)?.tool_type) ??
|
||||
extractString(record.name) ??
|
||||
extractString(record.tool) ??
|
||||
'tool'
|
||||
return {
|
||||
id,
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'tool-call', name, input: record.kind ?? record.arguments ?? record.input }],
|
||||
timestamp,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 'tool_result') {
|
||||
const output = toolResultOutput(record.content ?? record.output ?? record.result)
|
||||
return {
|
||||
id,
|
||||
role: 'tool',
|
||||
blocks: [
|
||||
{
|
||||
type: 'tool-result',
|
||||
output,
|
||||
...(record.is_error === true || record.isError === true ? { isError: true } : {})
|
||||
}
|
||||
],
|
||||
timestamp,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function grokToolCallBlocks(value: unknown): NativeChatBlock[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return []
|
||||
}
|
||||
const blocks: NativeChatBlock[] = []
|
||||
for (const item of value) {
|
||||
const record = asRecord(item)
|
||||
if (!record) {
|
||||
continue
|
||||
}
|
||||
const name = extractString(record.name) ?? extractString(record.tool) ?? 'tool'
|
||||
let input: unknown = record.arguments ?? record.input ?? record.args
|
||||
if (typeof input === 'string') {
|
||||
try {
|
||||
input = JSON.parse(input)
|
||||
} catch {
|
||||
// keep string
|
||||
}
|
||||
}
|
||||
blocks.push({ type: 'tool-call', name, input })
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
function grokSummaryText(value: unknown): string | null {
|
||||
if (typeof value === 'string') {
|
||||
return value
|
||||
}
|
||||
if (!Array.isArray(value)) {
|
||||
return null
|
||||
}
|
||||
const parts: string[] = []
|
||||
for (const item of value) {
|
||||
const record = asRecord(item)
|
||||
const text = extractString(record?.text) ?? extractString(record?.summary_text)
|
||||
if (text) {
|
||||
parts.push(text)
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? parts.join('\n') : null
|
||||
}
|
||||
|
||||
function hasNonEmptySyntheticReason(record: Record<string, unknown>): boolean {
|
||||
return typeof record.synthetic_reason === 'string' && record.synthetic_reason.trim().length > 0
|
||||
}
|
||||
|
||||
function isGrokBootstrapContext(content: unknown): boolean {
|
||||
const text = standaloneTextContent(content)
|
||||
if (!text) {
|
||||
return false
|
||||
}
|
||||
const normalized = text.trim().toLowerCase()
|
||||
if (!normalized.startsWith('<user_info>')) {
|
||||
return false
|
||||
}
|
||||
const userInfoEnd = normalized.indexOf('</user_info>')
|
||||
if (userInfoEnd === -1) {
|
||||
return false
|
||||
}
|
||||
const remainder = normalized.slice(userInfoEnd + '</user_info>'.length).trim()
|
||||
// Why: Grok 0.2.93 appends its git snapshot to the user-info bootstrap row;
|
||||
// reject only that known envelope so real prompts mentioning either tag survive.
|
||||
return (
|
||||
remainder.length === 0 ||
|
||||
(remainder.startsWith('<git_status>') && remainder.endsWith('</git_status>'))
|
||||
)
|
||||
}
|
||||
|
||||
function standaloneTextContent(content: unknown): string | null {
|
||||
if (typeof content === 'string') {
|
||||
return content
|
||||
}
|
||||
if (!Array.isArray(content) || content.length !== 1) {
|
||||
return null
|
||||
}
|
||||
const block = asRecord(content[0])
|
||||
return block?.type === 'text' ? (extractString(block.text) ?? null) : null
|
||||
}
|
||||
|
||||
function normalizeGrokUserQueryBlock(block: NativeChatBlock): NativeChatBlock[] {
|
||||
if (block.type !== 'text') {
|
||||
return [block]
|
||||
}
|
||||
const stripped = stripGrokUserQueryEnvelope(block.text)
|
||||
if (!stripped.trim()) {
|
||||
return []
|
||||
}
|
||||
const pastedImage = splitGrokPastedImageQuery(stripped)
|
||||
if (!pastedImage) {
|
||||
return [stripped === block.text ? block : { type: 'text', text: stripped }]
|
||||
}
|
||||
return [
|
||||
{ type: 'image-ref', path: pastedImage.path },
|
||||
...(pastedImage.query ? [{ type: 'text' as const, text: pastedImage.query }] : [])
|
||||
]
|
||||
}
|
||||
|
||||
function splitGrokPastedImageQuery(text: string): { path: string; query: string } | null {
|
||||
// Why: Grok 0.2.93 persists clipboard images as an absolute temp path directly
|
||||
// concatenated with the prompt; recover Orca's attachment without exposing it.
|
||||
const match = text.match(
|
||||
/^((?:[a-z]:[\\/]|\/|[\\/]{2}[^\\/\r\n]+[\\/][^\\/\r\n]+[\\/])(?:.*?[\\/])?orca-paste-[^\\/\r\n]+?\.png)([\s\S]*)$/i
|
||||
)
|
||||
if (!match?.[1]) {
|
||||
return null
|
||||
}
|
||||
return { path: match[1], query: (match[2] ?? '').trim() }
|
||||
}
|
||||
|
||||
function stripGrokUserQueryEnvelope(text: string): string {
|
||||
const opener = '<user_query>'
|
||||
const closer = '</user_query>'
|
||||
const lower = text.toLowerCase()
|
||||
const start = lower.indexOf(opener)
|
||||
if (start === -1) {
|
||||
return text
|
||||
}
|
||||
const bodyStart = start + opener.length
|
||||
const end = lower.indexOf(closer, bodyStart)
|
||||
if (end === -1) {
|
||||
return text.slice(bodyStart).trim()
|
||||
}
|
||||
return text.slice(bodyStart, end).trim()
|
||||
}
|
||||
|
||||
function parseTimestamp(value: unknown): number | null {
|
||||
const parsed = timestampMs(value)
|
||||
return Number.isFinite(parsed) ? parsed : null
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decodeGrokTranscriptLine } from './transcript-line-decoders'
|
||||
|
||||
describe('decodeGrokTranscriptLine', () => {
|
||||
it('decodes user text and strips <user_query> wrappers', () => {
|
||||
const line = JSON.stringify({
|
||||
type: 'user',
|
||||
content: [{ type: 'text', text: '<user_query>\nFix the bug\n</user_query>' }],
|
||||
timestamp: '2026-06-18T00:00:00.000Z'
|
||||
})
|
||||
expect(decodeGrokTranscriptLine(line, 'fb-1')).toEqual({
|
||||
id: 'fb-1',
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: 'Fix the bug' }],
|
||||
timestamp: Date.parse('2026-06-18T00:00:00.000Z'),
|
||||
source: 'transcript'
|
||||
})
|
||||
})
|
||||
|
||||
it('decodes assistant tool calls on empty content rows', () => {
|
||||
const line = JSON.stringify({
|
||||
type: 'assistant',
|
||||
content: '',
|
||||
tool_calls: [{ id: 'c1', name: 'grep', arguments: '{"pattern":"foo"}' }],
|
||||
id: 'asst-1'
|
||||
})
|
||||
expect(decodeGrokTranscriptLine(line, 'fb-2')).toEqual({
|
||||
id: 'fb-2:asst-1',
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'tool-call', name: 'grep', input: { pattern: 'foo' } }],
|
||||
timestamp: null,
|
||||
source: 'transcript'
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
'C:\\Users\\me\\AppData\\Local\\Temp\\orca-paste-1783675302563-2207c073-535f-4b83-a181-61127c8bbd68.png',
|
||||
'/tmp/orca-paste-1783675302563-2207c073-535f-4b83-a181-61127c8bbd68.png',
|
||||
'C:\\orca-paste-1783675302563-2207c073-535f-4b83-a181-61127c8bbd68.png',
|
||||
'/orca-paste-1783675302563-2207c073-535f-4b83-a181-61127c8bbd68.png',
|
||||
'\\\\server\\temp\\orca-paste-1783675302563-2207c073-535f-4b83-a181-61127c8bbd68.png'
|
||||
])('restores a pasted image and prompt from Grok transcript text for %s', (imagePath) => {
|
||||
const line = JSON.stringify({
|
||||
type: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `<user_query>\n${imagePath}Describe this image\n</user_query>`
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
expect(decodeGrokTranscriptLine(line, 'fb-image')).toMatchObject({
|
||||
role: 'user',
|
||||
blocks: [
|
||||
{ type: 'image-ref', path: imagePath },
|
||||
{ type: 'text', text: 'Describe this image' }
|
||||
]
|
||||
})
|
||||
})
|
||||
|
||||
it('restores an attachment-only pasted image from Grok transcript text', () => {
|
||||
const imagePath = '/tmp/orca-paste-1783675302563-2207c073-535f-4b83-a181-61127c8bbd68.png'
|
||||
const line = JSON.stringify({
|
||||
type: 'user',
|
||||
content: [{ type: 'text', text: `<user_query>${imagePath}</user_query>` }]
|
||||
})
|
||||
|
||||
expect(decodeGrokTranscriptLine(line, 'fb-image-only')).toMatchObject({
|
||||
role: 'user',
|
||||
blocks: [{ type: 'image-ref', path: imagePath }]
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves ordinary prompts that mention pasted-image filenames', () => {
|
||||
const text = 'Explain what an orca-paste-123-example.png file is'
|
||||
const line = JSON.stringify({
|
||||
type: 'user',
|
||||
content: [{ type: 'text', text: `<user_query>${text}</user_query>` }]
|
||||
})
|
||||
|
||||
expect(decodeGrokTranscriptLine(line, 'fb-image-mention')).toMatchObject({
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text }]
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves assistant text containing a literal user_query tag', () => {
|
||||
const text = 'Before <user_query>quoted example</user_query> after'
|
||||
const line = JSON.stringify({ type: 'assistant', content: text })
|
||||
|
||||
expect(decodeGrokTranscriptLine(line, 'fb-assistant-tag')).toMatchObject({
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'text', text }]
|
||||
})
|
||||
})
|
||||
|
||||
it.each(['project_instructions', 'system_reminder'])(
|
||||
'skips Grok synthetic user rows with reason %s',
|
||||
(syntheticReason) => {
|
||||
const line = JSON.stringify({
|
||||
type: 'user',
|
||||
content: [{ type: 'text', text: 'Internal context' }],
|
||||
synthetic_reason: syntheticReason
|
||||
})
|
||||
|
||||
expect(decodeGrokTranscriptLine(line, `fb-${syntheticReason}`)).toBeNull()
|
||||
}
|
||||
)
|
||||
|
||||
it.each([
|
||||
'<user_info>bootstrap context</user_info>',
|
||||
[{ type: 'text', text: '<USER_INFO>bootstrap context</USER_INFO>' }],
|
||||
[
|
||||
{
|
||||
type: 'text',
|
||||
text: [
|
||||
'<user_info>Runtime context</user_info>',
|
||||
'<git_status>Working tree snapshot</git_status>'
|
||||
].join('\n\n')
|
||||
}
|
||||
]
|
||||
])('skips a standalone Grok user_info bootstrap row', (content) => {
|
||||
expect(
|
||||
decodeGrokTranscriptLine(JSON.stringify({ type: 'user', content }), 'fb-user-info')
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps a real query that discusses the user_info tag', () => {
|
||||
const line = JSON.stringify({
|
||||
type: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: '<user_query>Explain the <user_info> tag</user_query>'
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
expect(decodeGrokTranscriptLine(line, 'fb-user-info-query')).toMatchObject({
|
||||
role: 'user',
|
||||
blocks: [{ type: 'text', text: 'Explain the <user_info> tag' }]
|
||||
})
|
||||
})
|
||||
|
||||
it('filters Grok bootstrap rows from a real-schema transcript prefix', () => {
|
||||
const rows = [
|
||||
{ type: 'system', content: 'System context' },
|
||||
{
|
||||
type: 'user',
|
||||
content: [{ type: 'text', text: '<user_info>Runtime context</user_info>' }]
|
||||
},
|
||||
{
|
||||
type: 'user',
|
||||
content: [{ type: 'text', text: 'Project context' }],
|
||||
synthetic_reason: 'project_instructions'
|
||||
},
|
||||
{
|
||||
type: 'user',
|
||||
content: [{ type: 'text', text: 'Reminder context' }],
|
||||
synthetic_reason: 'system_reminder'
|
||||
},
|
||||
{
|
||||
type: 'user',
|
||||
content: [{ type: 'text', text: '<user_query>Visible prompt</user_query>' }]
|
||||
},
|
||||
{ type: 'assistant', content: 'Visible answer' }
|
||||
]
|
||||
|
||||
const messages = rows
|
||||
.map((row, index) => decodeGrokTranscriptLine(JSON.stringify(row), `fb-real-schema-${index}`))
|
||||
.filter((message) => message !== null)
|
||||
|
||||
expect(messages).toMatchObject([
|
||||
{ role: 'user', blocks: [{ type: 'text', text: 'Visible prompt' }] },
|
||||
{ role: 'assistant', blocks: [{ type: 'text', text: 'Visible answer' }] }
|
||||
])
|
||||
})
|
||||
|
||||
it('decodes reasoning summaries', () => {
|
||||
const line = JSON.stringify({
|
||||
type: 'reasoning',
|
||||
id: 'rs-1',
|
||||
summary: [{ type: 'summary_text', text: 'Planning the change' }]
|
||||
})
|
||||
expect(decodeGrokTranscriptLine(line, 'fb-3')).toMatchObject({
|
||||
id: 'fb-3:rs-1',
|
||||
role: 'reasoning',
|
||||
blocks: [{ type: 'text', text: 'Planning the change' }],
|
||||
source: 'transcript'
|
||||
})
|
||||
})
|
||||
|
||||
it('skips system prompts', () => {
|
||||
const line = JSON.stringify({ type: 'system', content: 'You are Grok' })
|
||||
expect(decodeGrokTranscriptLine(line, 'fb-4')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -5,181 +5,10 @@
|
||||
// or null (unknown/empty records are skipped, never thrown — plan KTD risk:
|
||||
// schema drift). `fallbackId` is used only when the record carries no intrinsic
|
||||
// id; the caller supplies a value unique per line.
|
||||
//
|
||||
// Why: agent-specific decoders live in dedicated modules so this barrel stays
|
||||
// under the max-lines limit while callers keep a single import path.
|
||||
|
||||
import type { NativeChatBlock, NativeChatMessage } from '../../shared/native-chat-types'
|
||||
import {
|
||||
asRecord,
|
||||
extractString,
|
||||
parseJsonObject,
|
||||
timestampMs
|
||||
} from '../ai-vault/session-scanner-values'
|
||||
import { claudeContentBlocks, toolResultOutput } from './transcript-record-blocks'
|
||||
|
||||
export function decodeClaudeTranscriptLine(
|
||||
line: string,
|
||||
fallbackId: string
|
||||
): NativeChatMessage | null {
|
||||
const record = parseJsonObject(line)
|
||||
if (!record) {
|
||||
return null
|
||||
}
|
||||
const role = record.type
|
||||
if (role !== 'user' && role !== 'assistant') {
|
||||
return null
|
||||
}
|
||||
const message = asRecord(record.message)
|
||||
const blocks = claudeContentBlocks(message?.content)
|
||||
if (blocks.length === 0) {
|
||||
return null
|
||||
}
|
||||
const messageId = extractString(record.uuid) ?? extractString(message?.id)
|
||||
return {
|
||||
id: messageId ?? fallbackId,
|
||||
role: claudeMessageRole(role, blocks),
|
||||
blocks,
|
||||
timestamp: parseTimestamp(record.timestamp),
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
|
||||
// Claude marks reasoning via `thinking` content blocks; when a message is made
|
||||
// up solely of reasoning, surface it as a reasoning-role message.
|
||||
function claudeMessageRole(
|
||||
role: 'user' | 'assistant',
|
||||
blocks: NativeChatBlock[]
|
||||
): NativeChatMessage['role'] {
|
||||
if (role === 'user') {
|
||||
const onlyToolResults = blocks.every((block) => block.type === 'tool-result')
|
||||
return onlyToolResults && blocks.length > 0 ? 'tool' : 'user'
|
||||
}
|
||||
return role
|
||||
}
|
||||
|
||||
export function decodeCodexTranscriptLine(
|
||||
line: string,
|
||||
fallbackId: string
|
||||
): NativeChatMessage | null {
|
||||
const record = parseJsonObject(line)
|
||||
if (!record) {
|
||||
return null
|
||||
}
|
||||
const payload = asRecord(record.payload)
|
||||
if (!payload) {
|
||||
return null
|
||||
}
|
||||
const timestamp = parseTimestamp(record.timestamp)
|
||||
const baseId = extractString(payload.id) ?? fallbackId
|
||||
|
||||
if (record.type === 'response_item') {
|
||||
return codexResponseItem(payload, baseId, timestamp)
|
||||
}
|
||||
if (record.type === 'event_msg') {
|
||||
return codexEventMessage(payload, baseId, timestamp)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function codexResponseItem(
|
||||
payload: Record<string, unknown>,
|
||||
id: string,
|
||||
timestamp: number | null
|
||||
): NativeChatMessage | null {
|
||||
if (payload.type === 'message') {
|
||||
const blocks = claudeContentBlocks(payload.content)
|
||||
if (blocks.length === 0) {
|
||||
return null
|
||||
}
|
||||
const role =
|
||||
payload.role === 'assistant' ? 'assistant' : payload.role === 'user' ? 'user' : 'system'
|
||||
return { id, role, blocks, timestamp, source: 'transcript' }
|
||||
}
|
||||
if (payload.type === 'reasoning') {
|
||||
const text = extractString(payload.text) ?? codexSummaryText(payload.summary)
|
||||
if (!text) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
id,
|
||||
role: 'reasoning',
|
||||
blocks: [{ type: 'text', text }],
|
||||
timestamp,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
if (payload.type === 'function_call' || payload.type === 'local_shell_call') {
|
||||
const name = extractString(payload.name) ?? 'tool'
|
||||
return {
|
||||
id,
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'tool-call', name, input: codexCallInput(payload) }],
|
||||
timestamp,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
if (payload.type === 'function_call_output') {
|
||||
return {
|
||||
id,
|
||||
role: 'tool',
|
||||
blocks: [codexToolResult(payload.output)],
|
||||
timestamp,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function codexEventMessage(
|
||||
payload: Record<string, unknown>,
|
||||
id: string,
|
||||
timestamp: number | null
|
||||
): NativeChatMessage | null {
|
||||
if (payload.type === 'user_message') {
|
||||
const text = extractString(payload.message)
|
||||
return text
|
||||
? { id, role: 'user', blocks: [{ type: 'text', text }], timestamp, source: 'transcript' }
|
||||
: null
|
||||
}
|
||||
if (payload.type === 'agent_message') {
|
||||
const text = extractString(payload.message)
|
||||
return text
|
||||
? { id, role: 'assistant', blocks: [{ type: 'text', text }], timestamp, source: 'transcript' }
|
||||
: null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function codexCallInput(payload: Record<string, unknown>): unknown {
|
||||
if (payload.arguments !== undefined) {
|
||||
return payload.arguments
|
||||
}
|
||||
return payload.input ?? payload.action ?? null
|
||||
}
|
||||
|
||||
function codexToolResult(output: unknown): NativeChatBlock {
|
||||
const record = asRecord(output)
|
||||
const isError = record?.success === false || record?.is_error === true
|
||||
return {
|
||||
type: 'tool-result',
|
||||
output: toolResultOutput(record?.content ?? record?.output ?? output),
|
||||
...(isError ? { isError: true } : {})
|
||||
}
|
||||
}
|
||||
|
||||
function codexSummaryText(summary: unknown): string | null {
|
||||
if (!Array.isArray(summary)) {
|
||||
return null
|
||||
}
|
||||
const parts: string[] = []
|
||||
for (const item of summary) {
|
||||
const text = extractString(asRecord(item)?.text) ?? extractString(item)
|
||||
if (text) {
|
||||
parts.push(text)
|
||||
}
|
||||
}
|
||||
return parts.length ? parts.join('\n') : null
|
||||
}
|
||||
|
||||
function parseTimestamp(value: unknown): number | null {
|
||||
const parsed = timestampMs(value)
|
||||
return Number.isFinite(parsed) ? parsed : null
|
||||
}
|
||||
export { decodeClaudeTranscriptLine } from './transcript-line-decoders-claude'
|
||||
export { decodeCodexTranscriptLine } from './transcript-line-decoders-codex'
|
||||
export { decodeGrokTranscriptLine } from './transcript-line-decoders-grok'
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { createReadStream } from 'node:fs'
|
||||
import { createInterface } from 'node:readline'
|
||||
import type { AgentType, NativeChatMessage } from '../../shared/native-chat-types'
|
||||
import { errorMessage } from '../ai-vault/session-scanner-values'
|
||||
import { resolveSessionFilePath, type ResolveSessionFileOptions } from './session-file-resolver'
|
||||
import { decodeClaudeTranscriptLine, decodeCodexTranscriptLine } from './transcript-line-decoders'
|
||||
import {
|
||||
decodeClaudeTranscriptLine,
|
||||
decodeCodexTranscriptLine,
|
||||
decodeGrokTranscriptLine
|
||||
} from './transcript-line-decoders'
|
||||
import { decodeTranscriptStream } from './transcript-stream-lines'
|
||||
|
||||
export type ReadTranscriptResult = { messages: NativeChatMessage[] } | { error: string }
|
||||
|
||||
@@ -17,8 +21,7 @@ export type ReadTranscriptOptions = ResolveSessionFileOptions & {
|
||||
* the NativeChatMessage model. Unlike the AI-Vault preview scan, this applies
|
||||
* NO message cap. Unknown record types are skipped rather than throwing, so a
|
||||
* single malformed/unrecognized line cannot fail the whole read. The per-line
|
||||
* record→message mapping is shared with the live tailer (transcript-watch.ts)
|
||||
* via transcript-line-decoders.ts.
|
||||
* record-to-message mapping is shared with the live tailer.
|
||||
*/
|
||||
export async function readNativeChatTranscript(
|
||||
agent: AgentType,
|
||||
@@ -36,6 +39,9 @@ export async function readNativeChatTranscript(
|
||||
if (agent === 'codex') {
|
||||
return { messages: await readTranscript(filePath, decodeCodexTranscriptLine) }
|
||||
}
|
||||
if (agent === 'grok') {
|
||||
return { messages: await readTranscript(filePath, decodeGrokTranscriptLine) }
|
||||
}
|
||||
return { error: `Unsupported agent for native chat transcript: ${agent}` }
|
||||
} catch (err) {
|
||||
return { error: errorMessage(err) }
|
||||
@@ -46,21 +52,7 @@ async function readTranscript(
|
||||
filePath: string,
|
||||
decode: (line: string, fallbackId: string) => NativeChatMessage | null
|
||||
): Promise<NativeChatMessage[]> {
|
||||
const reader = createInterface({
|
||||
input: createReadStream(filePath, { encoding: 'utf-8' }),
|
||||
crlfDelay: Infinity
|
||||
})
|
||||
const messages: NativeChatMessage[] = []
|
||||
let index = 0
|
||||
for await (const line of reader) {
|
||||
// Why: fallback id embeds start offset 0 so it matches the live tailer's id
|
||||
// for the same record (the tailer's first drain reads from offset 0 too).
|
||||
// Records that re-emit then collapse by id in the assembler — no dup, no drop.
|
||||
const message = decode(line, `${filePath}:0:${index}`)
|
||||
if (message) {
|
||||
messages.push(message)
|
||||
}
|
||||
index++
|
||||
}
|
||||
const stream = createReadStream(filePath, { encoding: 'utf-8' })
|
||||
const { messages } = await decodeTranscriptStream(stream, filePath, 0, decode, true)
|
||||
return messages
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Readable } from 'node:stream'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decodeTranscriptStream } from './transcript-stream-lines'
|
||||
|
||||
const decode = (line: string, id: string) => ({
|
||||
id,
|
||||
role: 'user' as const,
|
||||
blocks: [{ type: 'text' as const, text: line }],
|
||||
timestamp: null,
|
||||
source: 'transcript' as const
|
||||
})
|
||||
|
||||
describe('decodeTranscriptStream', () => {
|
||||
it('uses identical absolute byte ids for full and incremental reads', async () => {
|
||||
const prefix = '{"first":"é"}\r\n'
|
||||
const appended = '{"second":true}\n'
|
||||
const full = await decodeTranscriptStream(
|
||||
Readable.from([prefix + appended]),
|
||||
'/chat.jsonl',
|
||||
0,
|
||||
decode,
|
||||
true
|
||||
)
|
||||
const incremental = await decodeTranscriptStream(
|
||||
Readable.from([appended]),
|
||||
'/chat.jsonl',
|
||||
Buffer.byteLength(prefix, 'utf8'),
|
||||
decode,
|
||||
false
|
||||
)
|
||||
|
||||
expect(incremental.messages[0]?.id).toBe(full.messages[1]?.id)
|
||||
})
|
||||
|
||||
it('does not consume a partial trailing JSONL record', async () => {
|
||||
const complete = '{"first":true}\n'
|
||||
const partial = '{"second"'
|
||||
const result = await decodeTranscriptStream(
|
||||
Readable.from([complete + partial]),
|
||||
'/chat.jsonl',
|
||||
0,
|
||||
decode,
|
||||
false
|
||||
)
|
||||
|
||||
expect(result.messages).toHaveLength(1)
|
||||
expect(result.consumedBytes).toBe(Buffer.byteLength(complete, 'utf8'))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { Readable } from 'node:stream'
|
||||
import type { NativeChatMessage } from '../../shared/native-chat-types'
|
||||
import { transcriptFallbackId } from './transcript-fallback-id'
|
||||
|
||||
type TranscriptDecoder = (line: string, fallbackId: string) => NativeChatMessage | null
|
||||
|
||||
export async function decodeTranscriptStream(
|
||||
stream: Readable,
|
||||
filePath: string,
|
||||
start: number,
|
||||
decode: TranscriptDecoder,
|
||||
includeTrailingLine: boolean
|
||||
): Promise<{ messages: NativeChatMessage[]; consumedBytes: number }> {
|
||||
const messages: NativeChatMessage[] = []
|
||||
let pending = ''
|
||||
let consumedBytes = 0
|
||||
|
||||
for await (const chunk of stream) {
|
||||
pending += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8')
|
||||
let newlineIndex = pending.indexOf('\n')
|
||||
while (newlineIndex !== -1) {
|
||||
const segment = pending.slice(0, newlineIndex + 1)
|
||||
decodeLine(segment.slice(0, -1), consumedBytes)
|
||||
consumedBytes += Buffer.byteLength(segment, 'utf8')
|
||||
pending = pending.slice(newlineIndex + 1)
|
||||
newlineIndex = pending.indexOf('\n')
|
||||
}
|
||||
}
|
||||
|
||||
if (includeTrailingLine && pending.length > 0) {
|
||||
decodeLine(pending, consumedBytes)
|
||||
consumedBytes += Buffer.byteLength(pending, 'utf8')
|
||||
}
|
||||
|
||||
return { messages, consumedBytes }
|
||||
|
||||
function decodeLine(rawLine: string, relativeOffset: number): void {
|
||||
const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine
|
||||
if (!line) {
|
||||
return
|
||||
}
|
||||
const message = decode(line, transcriptFallbackId(filePath, start + relativeOffset))
|
||||
if (message) {
|
||||
messages.push(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,14 @@
|
||||
|
||||
import { watch, type FSWatcher } from 'node:fs'
|
||||
import { open, stat } from 'node:fs/promises'
|
||||
import type { Readable } from 'node:stream'
|
||||
import type { AgentType, NativeChatMessage } from '../../shared/native-chat-types'
|
||||
import { resolveSessionFilePath, type ResolveSessionFileOptions } from './session-file-resolver'
|
||||
import { decodeClaudeTranscriptLine, decodeCodexTranscriptLine } from './transcript-line-decoders'
|
||||
import {
|
||||
decodeClaudeTranscriptLine,
|
||||
decodeCodexTranscriptLine,
|
||||
decodeGrokTranscriptLine
|
||||
} from './transcript-line-decoders'
|
||||
import { decodeTranscriptStream } from './transcript-stream-lines'
|
||||
|
||||
export type SubscribeNativeChatTranscriptArgs = ResolveSessionFileOptions & {
|
||||
agent: AgentType
|
||||
@@ -57,6 +61,9 @@ function lineDecoderForAgent(
|
||||
if (agent === 'codex') {
|
||||
return decodeCodexTranscriptLine
|
||||
}
|
||||
if (agent === 'grok') {
|
||||
return decodeGrokTranscriptLine
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -94,53 +101,19 @@ async function readAppendedMessages(
|
||||
end: end - 1,
|
||||
autoClose: false
|
||||
})
|
||||
const { messages, consumedBytes } = await decodeStreamLines(stream, filePath, start, decode)
|
||||
const { messages, consumedBytes } = await decodeTranscriptStream(
|
||||
stream,
|
||||
filePath,
|
||||
start,
|
||||
decode,
|
||||
false
|
||||
)
|
||||
return { messages, consumedTo: start + consumedBytes }
|
||||
} finally {
|
||||
await handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function decodeStreamLines(
|
||||
stream: Readable,
|
||||
filePath: string,
|
||||
start: number,
|
||||
decode: (line: string, fallbackId: string) => NativeChatMessage | null
|
||||
): Promise<{ messages: NativeChatMessage[]; consumedBytes: number }> {
|
||||
const text = await readStreamText(stream)
|
||||
const completeEnd = text.lastIndexOf('\n')
|
||||
if (completeEnd === -1) {
|
||||
return { messages: [], consumedBytes: 0 }
|
||||
}
|
||||
|
||||
// Why: transcript writers can flush mid-record. Only advance through
|
||||
// newline-terminated JSONL so invalid partial JSON is retried on the next
|
||||
// append instead of being lost forever.
|
||||
const completeText = text.slice(0, completeEnd + 1)
|
||||
const lines = completeText.split('\n')
|
||||
const messages: NativeChatMessage[] = []
|
||||
for (const [index, line] of lines.entries()) {
|
||||
if (!line) {
|
||||
continue
|
||||
}
|
||||
// Fallback id embeds the byte offset so ids stay stable+unique across
|
||||
// appends even when a record carries no intrinsic id.
|
||||
const message = decode(line, `${filePath}:${start}:${index}`)
|
||||
if (message) {
|
||||
messages.push(message)
|
||||
}
|
||||
}
|
||||
return { messages, consumedBytes: Buffer.byteLength(completeText, 'utf8') }
|
||||
}
|
||||
|
||||
async function readStreamText(stream: Readable): Promise<string> {
|
||||
const chunks: string[] = []
|
||||
for await (const chunk of stream) {
|
||||
chunks.push(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8'))
|
||||
}
|
||||
return chunks.join('')
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to live appends on an agent's transcript file. Returns an
|
||||
* unsubscribe fn that tears the watcher down completely.
|
||||
|
||||
@@ -138,10 +138,41 @@ describe('SshPtyProvider', () => {
|
||||
cols: 120,
|
||||
rows: 40,
|
||||
cwd: undefined,
|
||||
env: {}
|
||||
env: {},
|
||||
envToDelete: [POWERLEVEL10K_WIZARD_DISABLE_ENV]
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves explicit TERM and forwards final env deletions to the relay', async () => {
|
||||
mux.request.mockResolvedValue({ id: 'pty-env-precedence' })
|
||||
const envToDelete = ['TERM_PROGRAM', 'ORCA_ATTRIBUTION_SHIM_DIR']
|
||||
|
||||
await provider.spawn({
|
||||
cols: 120,
|
||||
rows: 40,
|
||||
env: {
|
||||
TERM: 'screen-256color',
|
||||
TERM_PROGRAM: 'stale-terminal',
|
||||
ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/stale-attribution'
|
||||
},
|
||||
envToDelete
|
||||
})
|
||||
|
||||
expect(mux.request).toHaveBeenCalledWith('pty.spawn', {
|
||||
cols: 120,
|
||||
rows: 40,
|
||||
cwd: undefined,
|
||||
env: {
|
||||
TERM: 'screen-256color',
|
||||
[POWERLEVEL10K_WIZARD_DISABLE_ENV]: 'true'
|
||||
},
|
||||
envToDelete
|
||||
})
|
||||
const spawnCall = mux.request.mock.calls.find((call) => call[0] === 'pty.spawn')
|
||||
expect(spawnCall?.[1]?.env).not.toHaveProperty('TERM_PROGRAM')
|
||||
expect(spawnCall?.[1]?.env).not.toHaveProperty('ORCA_ATTRIBUTION_SHIM_DIR')
|
||||
})
|
||||
|
||||
it('forwards provider command delivery to the relay', async () => {
|
||||
mux.request.mockResolvedValue({ id: 'pty-provider-command' })
|
||||
|
||||
|
||||
@@ -149,6 +149,7 @@ export class SshPtyProvider implements IPtyProvider {
|
||||
rows: opts.rows,
|
||||
cwd: opts.cwd,
|
||||
env: this.withRemoteCliBridgeEnv(opts.env, opts.envToDelete),
|
||||
...(opts.envToDelete?.length ? { envToDelete: opts.envToDelete } : {}),
|
||||
// Why: the relay's plugin-overlay env augmenter needs to know which
|
||||
// Pi-compatible agent is being launched, while commandDelivery tells it
|
||||
// whether to submit the command itself for runtime-owned background PTYs.
|
||||
@@ -179,27 +180,28 @@ export class SshPtyProvider implements IPtyProvider {
|
||||
envToDelete?: readonly string[]
|
||||
): Record<string, string> {
|
||||
const merged = { ...env }
|
||||
if (this.remoteCliBridgeEnv) {
|
||||
const pathDelimiter = this.remoteCliBridgeEnv.pathDelimiter ?? ':'
|
||||
const pathKey = merged.PATH !== undefined ? 'PATH' : merged.Path !== undefined ? 'Path' : null
|
||||
if (pathKey) {
|
||||
const pathValue = merged[pathKey] ?? ''
|
||||
merged[pathKey] = pathValue.split(pathDelimiter).includes(this.remoteCliBridgeEnv.binDir)
|
||||
? pathValue
|
||||
: pathValue
|
||||
? `${this.remoteCliBridgeEnv.binDir}${pathDelimiter}${pathValue}`
|
||||
: this.remoteCliBridgeEnv.binDir
|
||||
}
|
||||
merged.ORCA_REMOTE_CLI_BIN_DIR = this.remoteCliBridgeEnv.binDir
|
||||
merged.ORCA_RELAY_DIR = this.remoteCliBridgeEnv.relayDir
|
||||
merged.ORCA_RELAY_NODE_PATH = this.remoteCliBridgeEnv.nodePath
|
||||
merged.ORCA_RELAY_SOCKET_PATH = this.remoteCliBridgeEnv.sockPath
|
||||
}
|
||||
// Why: match local/daemon precedence—managed defaults and augmentations
|
||||
// cannot resurrect values the caller explicitly removed.
|
||||
for (const key of envToDelete ?? []) {
|
||||
delete merged[key]
|
||||
}
|
||||
seedPowerlevel10kWizardEnv(merged, { envToDelete })
|
||||
if (!this.remoteCliBridgeEnv) {
|
||||
return merged
|
||||
}
|
||||
const pathDelimiter = this.remoteCliBridgeEnv.pathDelimiter ?? ':'
|
||||
const pathKey = merged.PATH !== undefined ? 'PATH' : merged.Path !== undefined ? 'Path' : null
|
||||
if (pathKey) {
|
||||
const pathValue = merged[pathKey] ?? ''
|
||||
merged[pathKey] = pathValue.split(pathDelimiter).includes(this.remoteCliBridgeEnv.binDir)
|
||||
? pathValue
|
||||
: pathValue
|
||||
? `${this.remoteCliBridgeEnv.binDir}${pathDelimiter}${pathValue}`
|
||||
: this.remoteCliBridgeEnv.binDir
|
||||
}
|
||||
merged.ORCA_REMOTE_CLI_BIN_DIR = this.remoteCliBridgeEnv.binDir
|
||||
merged.ORCA_RELAY_DIR = this.remoteCliBridgeEnv.relayDir
|
||||
merged.ORCA_RELAY_NODE_PATH = this.remoteCliBridgeEnv.nodePath
|
||||
merged.ORCA_RELAY_SOCKET_PATH = this.remoteCliBridgeEnv.sockPath
|
||||
return merged
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { resolveGrokHomeDir } from '../../shared/grok-session-paths'
|
||||
|
||||
// Why: when GROK_HOME is set, auth.json must be the same path Grok CLI uses.
|
||||
export function getGrokHome(): string {
|
||||
return process.env.GROK_HOME?.trim() || join(homedir(), '.grok')
|
||||
return resolveGrokHomeDir()
|
||||
}
|
||||
|
||||
export function getGrokAuthPath(): string {
|
||||
|
||||
@@ -172,6 +172,39 @@ describe('SshRelaySession', () => {
|
||||
expect(registerSshGitProvider).toHaveBeenCalledWith('target-1', expect.anything())
|
||||
})
|
||||
|
||||
it.each([
|
||||
['/bin/bash', "'/bin/bash' -lc 'printenv GROK_HOME | head -c 4097'"],
|
||||
['/usr/bin/fish', "'/usr/bin/fish' -lc 'printenv GROK_HOME | head -c 4097'"],
|
||||
['/bin/tcsh', "'/bin/tcsh' -lc 'printenv GROK_HOME | head -c 4097'"],
|
||||
['/bin/sh', "'/bin/sh' -c 'printenv GROK_HOME | head -c 4097'"]
|
||||
])('uses a shell-independent GROK_HOME probe with login shell %s', async (shell, command) => {
|
||||
process.env.ORCA_FEATURE_REMOTE_AGENT_HOOKS = '1'
|
||||
muxRequestMock.mockImplementation(async (method: string) =>
|
||||
method === 'session.resolveHome' ? { resolvedPath: '/home/orca' } : { ok: true }
|
||||
)
|
||||
vi.mocked(execCommand).mockResolvedValueOnce(`${shell}\n`).mockResolvedValueOnce('/srv/grok\n')
|
||||
const sftp = { end: vi.fn() }
|
||||
const { mockStore, mockPortForward, getMainWindow } = createMockDeps()
|
||||
const mockConn = { sftp: vi.fn().mockResolvedValue(sftp) } as unknown as SshConnection
|
||||
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
|
||||
|
||||
await session.establish(mockConn)
|
||||
|
||||
expect(execCommand).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
mockConn,
|
||||
"printenv SHELL || printf '/bin/sh\\n'",
|
||||
{ timeoutMs: 8_000 }
|
||||
)
|
||||
expect(execCommand).toHaveBeenNthCalledWith(2, mockConn, command, {
|
||||
wrapCommand: false,
|
||||
timeoutMs: 8_000
|
||||
})
|
||||
expect(installRemoteManagedAgentHooksMock).toHaveBeenCalledWith(sftp, '/home/orca', {
|
||||
grokHomeDir: '/srv/grok'
|
||||
})
|
||||
})
|
||||
|
||||
it('installs remote managed hooks and relay-owned plugin assets before registering the SSH PTY provider', async () => {
|
||||
process.env.ORCA_FEATURE_REMOTE_AGENT_HOOKS = '1'
|
||||
muxRequestMock.mockImplementation(async (method: string) => {
|
||||
@@ -181,6 +214,9 @@ describe('SshRelaySession', () => {
|
||||
return { ok: true }
|
||||
})
|
||||
const sftp = { end: vi.fn() }
|
||||
vi.mocked(execCommand)
|
||||
.mockResolvedValueOnce('/bin/bash\n')
|
||||
.mockResolvedValueOnce('/srv/grok profile\n')
|
||||
const { mockStore, mockPortForward, getMainWindow } = createMockDeps()
|
||||
const mockConn = {
|
||||
sftp: vi.fn().mockResolvedValue(sftp)
|
||||
@@ -199,7 +235,9 @@ describe('SshRelaySession', () => {
|
||||
ompExtensionSource: expect.stringContaining('/hook/omp')
|
||||
})
|
||||
expect(mockConn.sftp).toHaveBeenCalledTimes(1)
|
||||
expect(installRemoteManagedAgentHooksMock).toHaveBeenCalledWith(sftp, '/home/orca')
|
||||
expect(installRemoteManagedAgentHooksMock).toHaveBeenCalledWith(sftp, '/home/orca', {
|
||||
grokHomeDir: '/srv/grok profile'
|
||||
})
|
||||
expect(sftp.end).toHaveBeenCalledTimes(1)
|
||||
expect(installRemoteManagedAgentHooksMock.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
muxRequestMock.mock.invocationCallOrder[installPluginsCallIndex]
|
||||
@@ -209,6 +247,26 @@ describe('SshRelaySession', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to login-home Grok config when the remote env probe is invalid', async () => {
|
||||
process.env.ORCA_FEATURE_REMOTE_AGENT_HOOKS = '1'
|
||||
muxRequestMock.mockImplementation(async (method: string) =>
|
||||
method === 'session.resolveHome' ? { resolvedPath: '/home/orca' } : { ok: true }
|
||||
)
|
||||
vi.mocked(execCommand)
|
||||
.mockResolvedValueOnce('/bin/bash\n')
|
||||
.mockResolvedValueOnce('relative/grok-home\n')
|
||||
const sftp = { end: vi.fn() }
|
||||
const { mockStore, mockPortForward, getMainWindow } = createMockDeps()
|
||||
const mockConn = { sftp: vi.fn().mockResolvedValue(sftp) } as unknown as SshConnection
|
||||
const session = new SshRelaySession('target-1', getMainWindow, mockStore, mockPortForward)
|
||||
|
||||
await session.establish(mockConn)
|
||||
|
||||
expect(installRemoteManagedAgentHooksMock).toHaveBeenCalledWith(sftp, '/home/orca', {
|
||||
grokHomeDir: '/home/orca/.grok'
|
||||
})
|
||||
})
|
||||
|
||||
it('does not run POSIX managed hook installers on Windows remotes', async () => {
|
||||
process.env.ORCA_FEATURE_REMOTE_AGENT_HOOKS = '1'
|
||||
const { mockStore, mockPortForward, getMainWindow } = createMockDeps()
|
||||
|
||||
@@ -70,6 +70,7 @@ import { runRemoteOrcaCli } from './ssh-remote-orca-cli'
|
||||
import { toSshExecutionHostId, type ExecutionHostId } from '../../shared/execution-host'
|
||||
import { isTerminalLeafId, makePaneKey } from '../../shared/stable-pane-id'
|
||||
import { isValidTerminalTabId } from '../../shared/terminal-tab-id'
|
||||
import { shellEscape } from './ssh-connection-utils'
|
||||
|
||||
export type RelaySessionState = 'idle' | 'deploying' | 'ready' | 'reconnecting' | 'disposed'
|
||||
|
||||
@@ -85,6 +86,69 @@ type RemoteCliBridgeEnv = {
|
||||
|
||||
type ExpectedPtyIdentity = { paneKey?: string; tabId?: string }
|
||||
|
||||
const REMOTE_GROK_HOME_MAX_LENGTH = 4096
|
||||
const REMOTE_GROK_HOME_PROBE_TIMEOUT_MS = 8_000
|
||||
|
||||
function defaultRemoteGrokHome(remoteHome: string): string {
|
||||
const home = remoteHome.replace(/\/+$/, '') || remoteHome
|
||||
return `${home}/.grok`
|
||||
}
|
||||
|
||||
function normalizeRemoteGrokHome(candidate: string): string | null {
|
||||
if (
|
||||
candidate.length === 0 ||
|
||||
candidate.length > REMOTE_GROK_HOME_MAX_LENGTH ||
|
||||
candidate !== candidate.trim() ||
|
||||
!candidate.startsWith('/') ||
|
||||
candidate.includes('\\') ||
|
||||
hasControlCharacter(candidate)
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return candidate.replace(/\/+$/, '') || '/'
|
||||
}
|
||||
|
||||
function hasControlCharacter(value: string): boolean {
|
||||
return Array.from(value).some((character) => {
|
||||
const code = character.charCodeAt(0)
|
||||
return code <= 0x1f || code === 0x7f
|
||||
})
|
||||
}
|
||||
|
||||
function loginShellCommand(shell: string, command: string): string {
|
||||
const shellName = shell.split('/').at(-1)
|
||||
const mode = shellName === 'sh' || shellName === 'dash' ? '-c' : '-lc'
|
||||
return `${shellEscape(shell)} ${mode} ${shellEscape(command)}`
|
||||
}
|
||||
|
||||
async function resolveRemoteGrokHome(
|
||||
connection: SshConnection,
|
||||
remoteHome: string
|
||||
): Promise<string> {
|
||||
const fallback = defaultRemoteGrokHome(remoteHome)
|
||||
try {
|
||||
// Why: remote PTYs start login shells, so probe the same profile-derived
|
||||
// environment instead of the relay service or local Electron environment.
|
||||
const shellOutput = await execCommand(connection, "printenv SHELL || printf '/bin/sh\\n'", {
|
||||
timeoutMs: REMOTE_GROK_HOME_PROBE_TIMEOUT_MS
|
||||
})
|
||||
const shell = shellOutput.trim().split(/\r?\n/, 1)[0]
|
||||
if (!shell?.startsWith('/') || hasControlCharacter(shell)) {
|
||||
return fallback
|
||||
}
|
||||
// Why: this runs inside the user's actual login shell, which may be fish or
|
||||
// tcsh. External commands avoid shell-specific variable/conditional syntax.
|
||||
const probe = `printenv GROK_HOME | head -c ${REMOTE_GROK_HOME_MAX_LENGTH + 1}`
|
||||
const output = await execCommand(connection, loginShellCommand(shell, probe), {
|
||||
wrapCommand: false,
|
||||
timeoutMs: REMOTE_GROK_HOME_PROBE_TIMEOUT_MS
|
||||
})
|
||||
return normalizeRemoteGrokHome(output.split(/\r?\n/, 1)[0] ?? '') ?? fallback
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
function expectedIdentityForLease(lease: {
|
||||
tabId?: string
|
||||
leafId?: string
|
||||
@@ -673,8 +737,10 @@ export class SshRelaySession {
|
||||
|
||||
let sftp: Awaited<ReturnType<SshConnection['sftp']>> | null = null
|
||||
try {
|
||||
sftp = await this.requireReadyConnection().sftp()
|
||||
await installRemoteManagedAgentHooks(sftp, remoteHome)
|
||||
const connection = this.requireReadyConnection()
|
||||
const remoteGrokHome = await resolveRemoteGrokHome(connection, remoteHome)
|
||||
sftp = await connection.sftp()
|
||||
await installRemoteManagedAgentHooks(sftp, remoteHome, { grokHomeDir: remoteGrokHome })
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`[ssh-relay-session] remote managed hook install failed for ${this.targetId}: ${
|
||||
|
||||
@@ -5,6 +5,7 @@ import { join } from 'node:path'
|
||||
import { endpointDirForRelaySocket, RelayAgentHookServer } from './agent-hook-server'
|
||||
import type { AgentHookRelayEnvelope } from '../shared/agent-hook-relay'
|
||||
import { makePaneKey } from '../shared/stable-pane-id'
|
||||
import * as agentHookListener from '../shared/agent-hook-listener'
|
||||
|
||||
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const PANE_KEY = makePaneKey('tab-1', LEAF_ID)
|
||||
@@ -257,6 +258,8 @@ describe('RelayAgentHookServer', () => {
|
||||
})
|
||||
expect(forward.mock.calls.at(-1)?.[0].payload.lastAssistantMessage).toBeUndefined()
|
||||
|
||||
// Let the first 50ms retry miss so continuation across SessionEnd is proven.
|
||||
await new Promise((resolve) => setTimeout(resolve, 70))
|
||||
writeFileSync(
|
||||
transcriptPath,
|
||||
`${JSON.stringify({
|
||||
@@ -378,4 +381,111 @@ describe('RelayAgentHookServer', () => {
|
||||
server.stop()
|
||||
}
|
||||
}, 30_000)
|
||||
|
||||
it('forwards a Grok result when discovery finishes after the old retry window', async () => {
|
||||
let releaseDiscovery!: () => void
|
||||
const discovery = new Promise<void>((resolve) => {
|
||||
releaseDiscovery = resolve
|
||||
})
|
||||
vi.spyOn(agentHookListener, 'preparePendingGrokResultDiscovery').mockReturnValue(discovery)
|
||||
const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>()
|
||||
const server = new RelayAgentHookServer({ endpointDir: dir, forward })
|
||||
const sessionId = '019e37f4-5135-7b63-a4ab-6d13aa6bf534'
|
||||
const cwd = join(dir, 'workspace')
|
||||
const sessionDir = join(dir, '.grok', 'sessions', encodeURIComponent(cwd), sessionId)
|
||||
mkdirSync(sessionDir, { recursive: true })
|
||||
const history = join(sessionDir, 'chat_history.jsonl')
|
||||
writeFileSync(history, '')
|
||||
vi.stubEnv('HOME', dir)
|
||||
vi.stubEnv('USERPROFILE', dir)
|
||||
await server.start()
|
||||
try {
|
||||
const { port, token } = server.getCoordinates()
|
||||
const post = (payload: Record<string, unknown>): Promise<Response> =>
|
||||
fetch(`http://127.0.0.1:${port}/hook/grok`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Orca-Agent-Hook-Token': token
|
||||
},
|
||||
body: JSON.stringify({
|
||||
paneKey: PANE_KEY,
|
||||
tabId: 'tab-1',
|
||||
env: 'remote',
|
||||
version: '1',
|
||||
payload
|
||||
})
|
||||
})
|
||||
|
||||
await post({ hookEventName: 'UserPromptSubmit', prompt: 'delayed relay result' })
|
||||
await post({ hookEventName: 'Stop', sessionId, cwd })
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
expect(forward.mock.calls.at(-1)?.[0].payload.lastAssistantMessage).toBeUndefined()
|
||||
|
||||
writeFileSync(
|
||||
history,
|
||||
`${JSON.stringify({ type: 'assistant', content: 'Relay found after discovery.' })}\n`
|
||||
)
|
||||
releaseDiscovery()
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(forward.mock.calls.at(-1)?.[0].payload.lastAssistantMessage).toBe(
|
||||
'Relay found after discovery.'
|
||||
)
|
||||
})
|
||||
} finally {
|
||||
server.stop()
|
||||
vi.unstubAllEnvs()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not forward an old result over a newer same-text Grok turn', async () => {
|
||||
let releaseDiscovery!: () => void
|
||||
const discovery = new Promise<void>((resolve) => {
|
||||
releaseDiscovery = resolve
|
||||
})
|
||||
vi.spyOn(agentHookListener, 'preparePendingGrokResultDiscovery').mockReturnValue(discovery)
|
||||
const forward = vi.fn<(envelope: AgentHookRelayEnvelope) => void>()
|
||||
const server = new RelayAgentHookServer({ endpointDir: dir, forward })
|
||||
await server.start()
|
||||
try {
|
||||
const { port, token } = server.getCoordinates()
|
||||
const post = (payload: Record<string, unknown>): Promise<Response> =>
|
||||
fetch(`http://127.0.0.1:${port}/hook/grok`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Orca-Agent-Hook-Token': token
|
||||
},
|
||||
body: JSON.stringify({
|
||||
paneKey: PANE_KEY,
|
||||
tabId: 'tab-1',
|
||||
env: 'remote',
|
||||
version: '1',
|
||||
payload
|
||||
})
|
||||
})
|
||||
|
||||
await post({ hookEventName: 'UserPromptSubmit', prompt: 'repeat me' })
|
||||
await post({
|
||||
hookEventName: 'Stop',
|
||||
sessionId: '019e37f4-5135-7b63-a4ab-6d13aa6bf535',
|
||||
cwd: join(dir, 'workspace')
|
||||
})
|
||||
await post({ hookEventName: 'UserPromptSubmit', prompt: 'repeat me' })
|
||||
const forwardsBeforeDiscovery = forward.mock.calls.length
|
||||
|
||||
releaseDiscovery()
|
||||
await new Promise((resolve) => setTimeout(resolve, 80))
|
||||
|
||||
expect(forward).toHaveBeenCalledTimes(forwardsBeforeDiscovery)
|
||||
expect(forward.mock.calls.at(-1)?.[0].payload).toMatchObject({
|
||||
state: 'working',
|
||||
prompt: 'repeat me',
|
||||
agentType: 'grok'
|
||||
})
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
hasPendingAgentResultText,
|
||||
HOOK_REQUEST_SLOWLORIS_MS,
|
||||
normalizeHookPayload,
|
||||
preparePendingGrokResultDiscovery,
|
||||
readRequestBody,
|
||||
resolveHookSource,
|
||||
writeEndpointFile,
|
||||
@@ -406,7 +407,8 @@ export class RelayAgentHookServer {
|
||||
original: AgentHookEventPayload,
|
||||
env?: string,
|
||||
version?: string,
|
||||
attempt = 1
|
||||
attempt = 1,
|
||||
discoveryReady = false
|
||||
): void {
|
||||
if (
|
||||
original.payload.lastAssistantMessage ||
|
||||
@@ -416,26 +418,37 @@ export class RelayAgentHookServer {
|
||||
return
|
||||
}
|
||||
this.clearAssistantMessageRetry(original.paneKey)
|
||||
if (!discoveryReady) {
|
||||
const discovery = preparePendingGrokResultDiscovery(source, body)
|
||||
if (discovery) {
|
||||
// Why: remote slug-group discovery can outlive the bounded transcript-
|
||||
// flush timers, so completion itself drives the first retry.
|
||||
void discovery
|
||||
.then(() => {
|
||||
if (this.server) {
|
||||
this.applyAssistantMessageRetry(source, body, original, env, version, 1, true)
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
process.stderr.write(
|
||||
`[relay-hook-server] Grok result discovery failed: ${err instanceof Error ? err.message : String(err)}\n`
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
this.assistantMessageRetryTimers.delete(original.paneKey)
|
||||
const current = this.state.lastStatusByPaneKey.get(original.paneKey)
|
||||
if (
|
||||
!current ||
|
||||
current.payload.agentType !== original.payload.agentType ||
|
||||
current.payload.prompt !== original.payload.prompt ||
|
||||
current.payload.lastAssistantMessage
|
||||
) {
|
||||
return
|
||||
}
|
||||
const event = normalizeHookPayload(this.state, source, body, this.env)
|
||||
if (!event?.payload.lastAssistantMessage) {
|
||||
this.scheduleAssistantMessageRetry(source, body, original, env, version, attempt + 1)
|
||||
return
|
||||
}
|
||||
// Why: the relay runs on SSH targets too; retry from a timer so a delayed
|
||||
// transcript/chat-history write does not block the remote hook server.
|
||||
this.applyEvent(event, source, env, version)
|
||||
this.applyAssistantMessageRetry(
|
||||
source,
|
||||
body,
|
||||
original,
|
||||
env,
|
||||
version,
|
||||
attempt + 1,
|
||||
discoveryReady
|
||||
)
|
||||
} catch (err) {
|
||||
process.stderr.write(
|
||||
`[relay-hook-server] assistant message retry failed: ${err instanceof Error ? err.message : String(err)}\n`
|
||||
@@ -448,6 +461,41 @@ export class RelayAgentHookServer {
|
||||
}
|
||||
}
|
||||
|
||||
private applyAssistantMessageRetry(
|
||||
source: AgentHookSource,
|
||||
body: unknown,
|
||||
original: AgentHookEventPayload,
|
||||
env: string | undefined,
|
||||
version: string | undefined,
|
||||
nextAttempt: number,
|
||||
requireExactOriginal: boolean
|
||||
): void {
|
||||
const current = this.state.lastStatusByPaneKey.get(original.paneKey)
|
||||
if (
|
||||
!current ||
|
||||
(requireExactOriginal && current !== original) ||
|
||||
current.payload.agentType !== original.payload.agentType ||
|
||||
current.payload.prompt !== original.payload.prompt ||
|
||||
current.payload.lastAssistantMessage
|
||||
) {
|
||||
return
|
||||
}
|
||||
const event = normalizeHookPayload(this.state, source, body, this.env)
|
||||
if (!event?.payload.lastAssistantMessage) {
|
||||
this.scheduleAssistantMessageRetry(
|
||||
source,
|
||||
body,
|
||||
original,
|
||||
env,
|
||||
version,
|
||||
nextAttempt,
|
||||
requireExactOriginal
|
||||
)
|
||||
return
|
||||
}
|
||||
this.applyEvent(event, source, env, version)
|
||||
}
|
||||
|
||||
private bodyEnv(body: unknown): string | undefined {
|
||||
if (typeof body !== 'object' || body === null) {
|
||||
return undefined
|
||||
|
||||
@@ -1290,11 +1290,78 @@ describe('PtyHandler', () => {
|
||||
}
|
||||
}
|
||||
|
||||
const spawnEnv = mockPtySpawn.mock.calls[0][2] as { env: Record<string, string> }
|
||||
const spawnEnv = mockPtySpawn.mock.calls[0][2] as {
|
||||
name: string
|
||||
env: Record<string, string>
|
||||
}
|
||||
expect(spawnEnv.name).toBe('xterm-256color')
|
||||
expect(spawnEnv.env.SEEN_OPENCODE_CONFIG_DIR).toBe('/remote/renderer-opencode')
|
||||
expect(spawnEnv.env.SEEN_PI_CODING_AGENT_DIR).toBe('/remote/pi')
|
||||
})
|
||||
|
||||
it('applies identity defaults, then deletions, while preserving explicit TERM', async () => {
|
||||
handler.addEnvAugmenter(() => ({
|
||||
TERM: 'augmenter-term',
|
||||
TERM_PROGRAM: 'augmenter-terminal',
|
||||
ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/augmenter-attribution'
|
||||
}))
|
||||
|
||||
await dispatcher.callRequest('pty.spawn', {
|
||||
env: {
|
||||
TERM: 'screen-256color',
|
||||
TERM_PROGRAM: 'renderer-terminal',
|
||||
ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/renderer-attribution'
|
||||
},
|
||||
envToDelete: ['TERM_PROGRAM', 'ORCA_ATTRIBUTION_SHIM_DIR']
|
||||
})
|
||||
|
||||
const spawnEnv = mockPtySpawn.mock.calls[0][2] as {
|
||||
name: string
|
||||
env: Record<string, string>
|
||||
}
|
||||
expect(spawnEnv.name).toBe('screen-256color')
|
||||
expect(spawnEnv.env.TERM).toBe('screen-256color')
|
||||
expect(spawnEnv.env.COLORTERM).toBe('truecolor')
|
||||
expect(spawnEnv.env.FORCE_HYPERLINK).toBe('1')
|
||||
expect(spawnEnv.env.TERM_PROGRAM).toBeUndefined()
|
||||
expect(spawnEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined()
|
||||
})
|
||||
|
||||
it('replaces an ambient TERM=dumb when no explicit TERM is supplied', async () => {
|
||||
const previousTerm = process.env.TERM
|
||||
process.env.TERM = 'dumb'
|
||||
try {
|
||||
await dispatcher.callRequest('pty.spawn', {})
|
||||
} finally {
|
||||
if (previousTerm === undefined) {
|
||||
delete process.env.TERM
|
||||
} else {
|
||||
process.env.TERM = previousTerm
|
||||
}
|
||||
}
|
||||
|
||||
const spawnEnv = mockPtySpawn.mock.calls[0][2] as {
|
||||
name: string
|
||||
env: Record<string, string>
|
||||
}
|
||||
expect(spawnEnv.name).toBe('xterm-256color')
|
||||
expect(spawnEnv.env.TERM).toBe('xterm-256color')
|
||||
expect(spawnEnv.env.TERM_PROGRAM).toBe('Orca')
|
||||
})
|
||||
|
||||
it('uses the safe terminal default when TERM is deleted without a custom value', async () => {
|
||||
await dispatcher.callRequest('pty.spawn', {
|
||||
envToDelete: ['TERM']
|
||||
})
|
||||
|
||||
const spawnEnv = mockPtySpawn.mock.calls[0][2] as {
|
||||
name: string
|
||||
env: Record<string, string>
|
||||
}
|
||||
expect(spawnEnv.name).toBe('xterm-256color')
|
||||
expect(spawnEnv.env.TERM).toBe('xterm-256color')
|
||||
})
|
||||
|
||||
it('lets relay env augmenters resolve the original sequenced startup command hint', async () => {
|
||||
handler.addEnvAugmenter((ctx) => ({
|
||||
SEEN_LAUNCH_COMMAND_HINT: resolveSetupAgentSequenceLaunchCommand(ctx.env, ctx.command) ?? ''
|
||||
@@ -1402,6 +1469,172 @@ describe('PtyHandler', () => {
|
||||
expect(callArgs.env.ORCA_WORKTREE_ID).toBe('wt-5')
|
||||
expect(callArgs.env.ORCA_AGENT_HOOK_PORT).toBe('12345')
|
||||
expect(callArgs.env.ORCA_AGENT_HOOK_TOKEN).toBe('abc-uuid')
|
||||
expect(callArgs.env.TERM).toBe('xterm-256color')
|
||||
expect(callArgs.env.TERM_PROGRAM).toBe('Orca')
|
||||
})
|
||||
|
||||
it('normalizes an explicit empty TERM and preserves sanitized env deletions on revive', async () => {
|
||||
await dispatcher.callRequest('pty.spawn', {
|
||||
env: { TERM: '' },
|
||||
envToDelete: ['ORCA_ATTRIBUTION_SHIM_DIR', '', 42]
|
||||
})
|
||||
|
||||
const initialEnv = mockPtySpawn.mock.calls[0][2] as {
|
||||
name: string
|
||||
env: Record<string, string>
|
||||
}
|
||||
expect(initialEnv.name).toBe('xterm-256color')
|
||||
expect(initialEnv.env.TERM).toBe('xterm-256color')
|
||||
|
||||
const state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string
|
||||
const [serialized] = JSON.parse(state) as {
|
||||
explicitTerm?: string
|
||||
envToDelete?: string[]
|
||||
}[]
|
||||
expect(serialized.explicitTerm).toBeUndefined()
|
||||
expect(serialized.envToDelete).toEqual(['ORCA_ATTRIBUTION_SHIM_DIR'])
|
||||
|
||||
handler.dispose()
|
||||
mockPtySpawn.mockClear()
|
||||
dispatcher = createMockDispatcher()
|
||||
handler = new PtyHandler(dispatcher as unknown as RelayDispatcher)
|
||||
handler.addEnvAugmenter(() => ({
|
||||
ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/revived-attribution'
|
||||
}))
|
||||
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true)
|
||||
try {
|
||||
await dispatcher.callRequest('pty.revive', { state })
|
||||
} finally {
|
||||
killSpy.mockRestore()
|
||||
}
|
||||
|
||||
const revivedEnv = mockPtySpawn.mock.calls[0][2] as {
|
||||
name: string
|
||||
env: Record<string, string>
|
||||
}
|
||||
expect(revivedEnv.name).toBe('xterm-256color')
|
||||
expect(revivedEnv.env.TERM).toBe('xterm-256color')
|
||||
expect(revivedEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined()
|
||||
})
|
||||
|
||||
it('drops legacy empty explicit TERM metadata after revive', async () => {
|
||||
const state = JSON.stringify([
|
||||
{
|
||||
id: 'pty-8',
|
||||
pid: process.pid,
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
cwd: process.cwd(),
|
||||
explicitTerm: '',
|
||||
envToDelete: ['ORCA_ATTRIBUTION_SHIM_DIR']
|
||||
}
|
||||
])
|
||||
handler.addEnvAugmenter(() => ({
|
||||
ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/legacy-empty-attribution'
|
||||
}))
|
||||
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true)
|
||||
try {
|
||||
await dispatcher.callRequest('pty.revive', { state })
|
||||
} finally {
|
||||
killSpy.mockRestore()
|
||||
}
|
||||
|
||||
const revivedEnv = mockPtySpawn.mock.calls[0][2] as {
|
||||
name: string
|
||||
env: Record<string, string>
|
||||
}
|
||||
expect(revivedEnv.name).toBe('xterm-256color')
|
||||
expect(revivedEnv.env.TERM).toBe('xterm-256color')
|
||||
expect(revivedEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined()
|
||||
|
||||
const serializedState = (await dispatcher.callRequest('pty.serialize', {
|
||||
ids: ['pty-8']
|
||||
})) as string
|
||||
const [serialized] = JSON.parse(serializedState) as {
|
||||
explicitTerm?: string
|
||||
envToDelete?: string[]
|
||||
}[]
|
||||
expect(serialized.explicitTerm).toBeUndefined()
|
||||
expect(serialized.envToDelete).toEqual(['ORCA_ATTRIBUTION_SHIM_DIR'])
|
||||
})
|
||||
|
||||
it('preserves explicit TERM and env deletions through repeated revive cycles', async () => {
|
||||
await dispatcher.callRequest('pty.spawn', {
|
||||
env: { TERM: 'screen-256color' },
|
||||
envToDelete: ['ORCA_ATTRIBUTION_SHIM_DIR']
|
||||
})
|
||||
let state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string
|
||||
|
||||
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true)
|
||||
try {
|
||||
handler.dispose()
|
||||
mockPtySpawn.mockClear()
|
||||
dispatcher = createMockDispatcher()
|
||||
handler = new PtyHandler(dispatcher as unknown as RelayDispatcher)
|
||||
handler.addEnvAugmenter(() => ({
|
||||
ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/first-revive'
|
||||
}))
|
||||
await dispatcher.callRequest('pty.revive', { state })
|
||||
|
||||
const firstRevivedEnv = mockPtySpawn.mock.calls[0][2] as {
|
||||
name: string
|
||||
env: Record<string, string>
|
||||
}
|
||||
expect(firstRevivedEnv.name).toBe('screen-256color')
|
||||
expect(firstRevivedEnv.env.TERM).toBe('screen-256color')
|
||||
expect(firstRevivedEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined()
|
||||
state = (await dispatcher.callRequest('pty.serialize', { ids: ['pty-1'] })) as string
|
||||
expect(JSON.parse(state)).toMatchObject([
|
||||
{
|
||||
explicitTerm: 'screen-256color',
|
||||
envToDelete: ['ORCA_ATTRIBUTION_SHIM_DIR']
|
||||
}
|
||||
])
|
||||
|
||||
handler.dispose()
|
||||
mockPtySpawn.mockClear()
|
||||
dispatcher = createMockDispatcher()
|
||||
handler = new PtyHandler(dispatcher as unknown as RelayDispatcher)
|
||||
handler.addEnvAugmenter(() => ({
|
||||
ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/second-revive'
|
||||
}))
|
||||
await dispatcher.callRequest('pty.revive', { state })
|
||||
} finally {
|
||||
killSpy.mockRestore()
|
||||
}
|
||||
|
||||
const secondRevivedEnv = mockPtySpawn.mock.calls[0][2] as {
|
||||
name: string
|
||||
env: Record<string, string>
|
||||
}
|
||||
expect(secondRevivedEnv.name).toBe('screen-256color')
|
||||
expect(secondRevivedEnv.env.TERM).toBe('screen-256color')
|
||||
expect(secondRevivedEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBeUndefined()
|
||||
})
|
||||
|
||||
it('revives legacy serialized entries with default TERM and no env deletions', async () => {
|
||||
handler.addEnvAugmenter(() => ({
|
||||
ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/legacy-attribution'
|
||||
}))
|
||||
const state = JSON.stringify([
|
||||
{
|
||||
id: 'pty-7',
|
||||
pid: process.pid,
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
cwd: process.cwd()
|
||||
}
|
||||
])
|
||||
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true)
|
||||
try {
|
||||
await dispatcher.callRequest('pty.revive', { state })
|
||||
} finally {
|
||||
killSpy.mockRestore()
|
||||
}
|
||||
|
||||
const revivedEnv = mockPtySpawn.mock.calls[0][2] as { env: Record<string, string> }
|
||||
expect(revivedEnv.env.TERM).toBe('xterm-256color')
|
||||
expect(revivedEnv.env.ORCA_ATTRIBUTION_SHIM_DIR).toBe('/tmp/legacy-attribution')
|
||||
})
|
||||
|
||||
it('revive preserves attach identity metadata without exporting hook identity env', async () => {
|
||||
|
||||
+83
-11
@@ -68,6 +68,8 @@ type ManagedPty = {
|
||||
attachIdentity?: PtyIdentity
|
||||
worktreeId?: string
|
||||
terminalHandle?: string
|
||||
explicitTerm?: string
|
||||
envToDelete: string[]
|
||||
startupCommand?: ManagedStartupCommand
|
||||
}
|
||||
|
||||
@@ -180,6 +182,16 @@ type SerializedPtyEntry = {
|
||||
attachIdentity?: PtyIdentity
|
||||
worktreeId?: string
|
||||
terminalHandle?: string
|
||||
explicitTerm?: string
|
||||
envToDelete?: string[]
|
||||
}
|
||||
|
||||
function sanitizeEnvToDelete(value: unknown): string[] {
|
||||
return Array.isArray(value)
|
||||
? value
|
||||
.filter((key): key is string => typeof key === 'string' && key.length > 0)
|
||||
.slice(0, 1_024)
|
||||
: []
|
||||
}
|
||||
|
||||
export type PtyExitListener = (event: { id: string; paneKey?: string }) => void
|
||||
@@ -283,9 +295,19 @@ export class PtyHandler {
|
||||
* otherwise agent-status over SSH silently breaks on every revive. */
|
||||
private buildSpawnEnv(
|
||||
rendererEnv: Record<string, string> | undefined,
|
||||
ctx: { id: string; paneKey?: string; shell: string; command?: string }
|
||||
ctx: { id: string; paneKey?: string; shell: string; command?: string },
|
||||
envToDelete: readonly string[] = []
|
||||
): Record<string, string> {
|
||||
const baseEnv = { ...process.env, ...rendererEnv } as Record<string, string>
|
||||
const baseEnv = {
|
||||
...process.env,
|
||||
TERM: 'xterm-256color',
|
||||
COLORTERM: 'truecolor',
|
||||
TERM_PROGRAM: 'Orca',
|
||||
TERM_PROGRAM_VERSION:
|
||||
rendererEnv?.ORCA_APP_VERSION || process.env.ORCA_APP_VERSION || '0.0.0-dev',
|
||||
FORCE_HYPERLINK: '1',
|
||||
...rendererEnv
|
||||
} as Record<string, string>
|
||||
const augmented: Record<string, string> = {}
|
||||
for (const augmenter of this.envAugmenters) {
|
||||
try {
|
||||
@@ -296,7 +318,25 @@ export class PtyHandler {
|
||||
)
|
||||
}
|
||||
}
|
||||
return { ...baseEnv, ...augmented }
|
||||
const result = { ...baseEnv, ...augmented }
|
||||
// Why: match local/daemon precedence so relay defaults and augmenters
|
||||
// cannot resurrect attribution or identity values explicitly removed.
|
||||
for (const key of envToDelete) {
|
||||
delete result[key]
|
||||
}
|
||||
if (
|
||||
!envToDelete.includes('TERM') &&
|
||||
rendererEnv &&
|
||||
Object.prototype.hasOwnProperty.call(rendererEnv, 'TERM')
|
||||
) {
|
||||
result.TERM = rendererEnv.TERM
|
||||
}
|
||||
// Why: node-pty treats missing/empty TERM as its own platform-specific
|
||||
// default. Normalize here so POSIX and Windows relay children agree.
|
||||
if (!result.TERM) {
|
||||
result.TERM = 'xterm-256color'
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private clearStartupCommandTimer(managed: ManagedPty): void {
|
||||
@@ -562,6 +602,15 @@ export class PtyHandler {
|
||||
const rows = (params.rows as number) || 24
|
||||
const cwd = (params.cwd as string) || resolveDefaultCwd()
|
||||
const env = params.env as Record<string, string> | undefined
|
||||
const envToDelete = sanitizeEnvToDelete(params.envToDelete)
|
||||
const explicitTerm =
|
||||
!envToDelete.includes('TERM') &&
|
||||
env &&
|
||||
Object.prototype.hasOwnProperty.call(env, 'TERM') &&
|
||||
typeof env.TERM === 'string' &&
|
||||
env.TERM.length > 0
|
||||
? env.TERM
|
||||
: undefined
|
||||
const shellOverride =
|
||||
typeof params.shellOverride === 'string' ? params.shellOverride.trim() : ''
|
||||
const resolvedShellOverride = resolvePtyShellOverride(shellOverride)
|
||||
@@ -585,7 +634,7 @@ export class PtyHandler {
|
||||
typeof params.terminalWindowsWslDistro === 'string' ? params.terminalWindowsWslDistro : null
|
||||
const commandDelivery = params.commandDelivery === 'provider' ? 'provider' : 'renderer'
|
||||
const shouldProviderDeliverCommand = commandDelivery === 'provider' && command !== undefined
|
||||
const spawnEnv = this.buildSpawnEnv(env, { id, paneKey, shell, command })
|
||||
const spawnEnv = this.buildSpawnEnv(env, { id, paneKey, shell, command }, envToDelete)
|
||||
const launchCommandHint = resolveSetupAgentSequenceLaunchCommand(spawnEnv, command)
|
||||
const shouldEmitShellReadyMarker =
|
||||
launchCommandHint !== undefined &&
|
||||
@@ -607,7 +656,9 @@ export class PtyHandler {
|
||||
// When overlays are injected, the launch wrapper keeps those paths after
|
||||
// user startup files re-export their defaults.
|
||||
const term = pty.spawn(shell, shellLaunch.args, {
|
||||
name: 'xterm-256color',
|
||||
// Why: node-pty overwrites env.TERM with `name`; keep caller-selected
|
||||
// terminal identities instead of losing them at the final spawn boundary.
|
||||
name: spawnEnv.TERM ?? 'xterm-256color',
|
||||
cols,
|
||||
rows,
|
||||
cwd,
|
||||
@@ -635,6 +686,8 @@ export class PtyHandler {
|
||||
tabId,
|
||||
...(attachIdentity.paneKey || attachIdentity.tabId ? { attachIdentity } : {}),
|
||||
worktreeId,
|
||||
...(explicitTerm !== undefined ? { explicitTerm } : {}),
|
||||
envToDelete,
|
||||
...(terminalHandle ? { terminalHandle } : {}),
|
||||
...(shouldProviderDeliverCommand
|
||||
? {
|
||||
@@ -935,6 +988,8 @@ export class PtyHandler {
|
||||
tabId: managed.tabId,
|
||||
attachIdentity: managed.attachIdentity,
|
||||
worktreeId: managed.worktreeId,
|
||||
...(managed.explicitTerm !== undefined ? { explicitTerm: managed.explicitTerm } : {}),
|
||||
envToDelete: managed.envToDelete,
|
||||
...(managed.terminalHandle ? { terminalHandle: managed.terminalHandle } : {})
|
||||
})
|
||||
}
|
||||
@@ -976,6 +1031,16 @@ export class PtyHandler {
|
||||
if (entry.terminalHandle) {
|
||||
revivedEnv.ORCA_TERMINAL_HANDLE = entry.terminalHandle
|
||||
}
|
||||
const explicitTerm =
|
||||
typeof entry.explicitTerm === 'string' && entry.explicitTerm.length > 0
|
||||
? entry.explicitTerm
|
||||
: undefined
|
||||
if (explicitTerm !== undefined) {
|
||||
revivedEnv.TERM = explicitTerm
|
||||
}
|
||||
// Why: serialized state can come from an older or untrusted client, so
|
||||
// revive reapplies the same bounds as a fresh spawn before retaining it.
|
||||
const envToDelete = sanitizeEnvToDelete(entry.envToDelete)
|
||||
const shell = resolveDefaultShell()
|
||||
// Why: `command` is intentionally absent from this revive path because
|
||||
// SerializedPtyEntry (see line 99) does not persist it — ManagedPty
|
||||
@@ -984,14 +1049,19 @@ export class PtyHandler {
|
||||
// undefined` for revived PTYs and prepares the Pi default plus OMP's
|
||||
// typed-command wrapper. Plumbing `command` through serialization is a
|
||||
// separate, larger change.
|
||||
const spawnEnv = this.buildSpawnEnv(revivedEnv, {
|
||||
id: entry.id,
|
||||
paneKey: entry.paneKey,
|
||||
shell
|
||||
})
|
||||
const spawnEnv = this.buildSpawnEnv(
|
||||
revivedEnv,
|
||||
{
|
||||
id: entry.id,
|
||||
paneKey: entry.paneKey,
|
||||
shell
|
||||
},
|
||||
envToDelete
|
||||
)
|
||||
const shellLaunch = getRelayShellLaunchConfig(shell, spawnEnv)
|
||||
const term = ptyMod.spawn(shell, shellLaunch.args, {
|
||||
name: 'xterm-256color',
|
||||
// Why: revive must preserve the same terminal identity as fresh spawn.
|
||||
name: spawnEnv.TERM ?? 'xterm-256color',
|
||||
cols: entry.cols,
|
||||
rows: entry.rows,
|
||||
cwd: entry.cwd,
|
||||
@@ -1008,6 +1078,8 @@ export class PtyHandler {
|
||||
tabId: entry.tabId,
|
||||
attachIdentity: entry.attachIdentity,
|
||||
worktreeId: entry.worktreeId,
|
||||
...(explicitTerm !== undefined ? { explicitTerm } : {}),
|
||||
envToDelete,
|
||||
...(entry.terminalHandle ? { terminalHandle: entry.terminalHandle } : {})
|
||||
})
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ describe('NativeChatSessionGate', () => {
|
||||
renderResolution({
|
||||
paneKey: 'tab-1:leaf-1',
|
||||
launchAgent: null,
|
||||
resolvedAgent: 'grok',
|
||||
resolvedAgent: 'gemini',
|
||||
ptyId: 'pty-1'
|
||||
})
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { canToggleNativeChat } from './native-chat-availability'
|
||||
import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability'
|
||||
|
||||
describe('canToggleNativeChat', () => {
|
||||
it('allows a terminal launched with a supported coding agent', () => {
|
||||
@@ -55,16 +56,53 @@ describe('canToggleNativeChat', () => {
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects an unsupported launch agent (Grok)', () => {
|
||||
it('accepts local Grok once native chat can parse its transcript', () => {
|
||||
expect(
|
||||
canToggleNativeChat({
|
||||
experimentalNativeChatEnabled: true,
|
||||
contentType: 'terminal',
|
||||
launchAgent: 'grok'
|
||||
launchAgent: 'grok',
|
||||
nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable(null)
|
||||
})
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('accepts runtime-owned Grok because Model B reads the transcript locally', () => {
|
||||
expect(
|
||||
canToggleNativeChat({
|
||||
experimentalNativeChatEnabled: true,
|
||||
contentType: 'terminal',
|
||||
launchAgent: 'grok',
|
||||
nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable(
|
||||
'runtime-ssh-env-1'
|
||||
)
|
||||
})
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects Model-A SSH Grok when its transcript is remote-only', () => {
|
||||
expect(
|
||||
canToggleNativeChat({
|
||||
experimentalNativeChatEnabled: true,
|
||||
contentType: 'terminal',
|
||||
launchAgent: 'grok',
|
||||
nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable('ssh-target-1')
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('lets an existing Model-A SSH Grok chat toggle back to terminal', () => {
|
||||
expect(
|
||||
canToggleNativeChat({
|
||||
experimentalNativeChatEnabled: true,
|
||||
contentType: 'terminal',
|
||||
launchAgent: 'grok',
|
||||
nativeChatTranscriptIsLocalReadable: false,
|
||||
isChatViewMode: true
|
||||
})
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects an unsupported agent detected live (Gemini)', () => {
|
||||
expect(
|
||||
canToggleNativeChat({
|
||||
@@ -76,15 +114,16 @@ describe('canToggleNativeChat', () => {
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects an unsupported agent resolved from the title', () => {
|
||||
it('accepts Grok when resolved from the title', () => {
|
||||
expect(
|
||||
canToggleNativeChat({
|
||||
experimentalNativeChatEnabled: true,
|
||||
contentType: 'terminal',
|
||||
launchAgent: null,
|
||||
resolvedAgent: 'grok'
|
||||
resolvedAgent: 'grok',
|
||||
nativeChatTranscriptIsLocalReadable: true
|
||||
})
|
||||
).toBe(false)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a stale supported title when live detection found an unsupported agent', () => {
|
||||
@@ -115,7 +154,7 @@ describe('canToggleNativeChat', () => {
|
||||
canToggleNativeChat({
|
||||
experimentalNativeChatEnabled: true,
|
||||
contentType: 'terminal',
|
||||
launchAgent: 'grok',
|
||||
launchAgent: 'gemini',
|
||||
resolvedAgent: 'claude'
|
||||
})
|
||||
).toBe(false)
|
||||
|
||||
@@ -22,6 +22,8 @@ export type NativeChatAvailabilityInput = {
|
||||
* terminal title resolver) when it identifies the foreground as an agent
|
||||
* before hooks arrive. */
|
||||
resolvedAgent?: TuiAgent | null
|
||||
/** Whether this renderer's native-chat reader can access the agent transcript. */
|
||||
nativeChatTranscriptIsLocalReadable?: boolean
|
||||
/** Already-chat tabs must always be allowed to toggle back to terminal, even
|
||||
* if live hook state was lost during a dev/app restart. */
|
||||
isChatViewMode?: boolean
|
||||
@@ -30,9 +32,9 @@ export type NativeChatAvailabilityInput = {
|
||||
/** Native chat is a rendering of a coding-agent conversation, so the toggle is
|
||||
* only meaningful on terminals that actually run an agent we can parse. Plain
|
||||
* shells, non-terminal surfaces (editor, browser, …), and unsupported agents
|
||||
* (Grok, Gemini, …) never qualify. Live identity is authoritative when present;
|
||||
* (Gemini, …) never qualify. Live identity is authoritative when present;
|
||||
* launch metadata is next, and title resolution only fills the pre-hook gap for
|
||||
* manually-started Claude/Codex sessions. */
|
||||
* manually-started Claude/Codex/Grok sessions. */
|
||||
export function canToggleNativeChat(input: NativeChatAvailabilityInput): boolean {
|
||||
if (input.experimentalNativeChatEnabled !== true) {
|
||||
return false
|
||||
@@ -44,5 +46,8 @@ export function canToggleNativeChat(input: NativeChatAvailabilityInput): boolean
|
||||
return true
|
||||
}
|
||||
const agent = input.detectedAgent ?? input.launchAgent ?? input.resolvedAgent
|
||||
if (agent === 'grok' && input.nativeChatTranscriptIsLocalReadable !== true) {
|
||||
return false
|
||||
}
|
||||
return isNativeChatSupportedAgent(agent)
|
||||
}
|
||||
|
||||
@@ -19,6 +19,14 @@ describe('image paste agent map', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('grok attaches image paths like other vision-capable TUIs', () => {
|
||||
expect(getAgentImageHandling('grok')).toBe('attachment')
|
||||
expect(resolveImagePaste('grok', '/tmp/orca-paste-1.png')).toEqual({
|
||||
kind: 'attach',
|
||||
path: '/tmp/orca-paste-1.png'
|
||||
})
|
||||
})
|
||||
|
||||
it('unknown/custom agent is unsupported', () => {
|
||||
expect(getAgentImageHandling('some-custom-agent')).toBe('unsupported')
|
||||
expect(resolveImagePaste('some-custom-agent', '/tmp/x.png')).toEqual({
|
||||
|
||||
@@ -19,7 +19,11 @@ const IMAGE_ATTACHMENT_AGENTS: ReadonlySet<AgentType> = new Set<AgentType>([
|
||||
'gemini',
|
||||
'cursor',
|
||||
'copilot',
|
||||
'droid'
|
||||
'droid',
|
||||
// Why: Grok CLI pastes images via bracketed path / image chips (see xAI
|
||||
// terminal docs + pager paste.rs). Keep it on the same attachment path as
|
||||
// Claude/Codex rather than treating path paste as unsupported text.
|
||||
'grok'
|
||||
])
|
||||
|
||||
export function getAgentImageHandling(agent: AgentType): AgentImageHandling {
|
||||
|
||||
@@ -160,19 +160,31 @@ describe('resolveNativeChatSession', () => {
|
||||
}
|
||||
)
|
||||
|
||||
it.each(['gemini', 'grok'] as TuiAgent[])(
|
||||
'does not resolve unsupported title fallback %s',
|
||||
(resolvedAgent) => {
|
||||
expect(
|
||||
resolveNativeChatSession({
|
||||
paneKey: 'tab-1:11111111-1111-4111-8111-111111111111',
|
||||
launchAgent: null,
|
||||
resolvedAgent,
|
||||
ptyId: 'pty-1'
|
||||
})
|
||||
).toBeNull()
|
||||
}
|
||||
)
|
||||
it('does not resolve unsupported title fallback gemini', () => {
|
||||
expect(
|
||||
resolveNativeChatSession({
|
||||
paneKey: 'tab-1:11111111-1111-4111-8111-111111111111',
|
||||
launchAgent: null,
|
||||
resolvedAgent: 'gemini',
|
||||
ptyId: 'pty-1'
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('resolves Grok from title fallback once native chat supports its transcript', () => {
|
||||
expect(
|
||||
resolveNativeChatSession({
|
||||
paneKey: 'tab-1:11111111-1111-4111-8111-111111111111',
|
||||
launchAgent: null,
|
||||
resolvedAgent: 'grok',
|
||||
ptyId: 'pty-1'
|
||||
})
|
||||
).toMatchObject({
|
||||
agent: 'grok',
|
||||
sessionId: null,
|
||||
ptyId: 'pty-1'
|
||||
})
|
||||
})
|
||||
|
||||
it('does not resolve an unsupported live status entry', () => {
|
||||
const paneKey = 'tab-1:11111111-1111-4111-8111-111111111111'
|
||||
@@ -224,17 +236,21 @@ describe('resolveNativeChatSession', () => {
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('does not resolve an unsupported launch agent', () => {
|
||||
it('resolves a Grok launch agent', () => {
|
||||
expect(
|
||||
resolveNativeChatSession({
|
||||
paneKey: 'tab-1:11111111-1111-4111-8111-111111111111',
|
||||
launchAgent: 'grok',
|
||||
ptyId: 'pty-1'
|
||||
})
|
||||
).toBeNull()
|
||||
).toMatchObject({
|
||||
agent: 'grok',
|
||||
sessionId: null,
|
||||
ptyId: 'pty-1'
|
||||
})
|
||||
})
|
||||
|
||||
it('does not fall back to a supported title agent when launchAgent is unsupported', () => {
|
||||
it('keeps Grok launch identity ahead of a different title agent', () => {
|
||||
expect(
|
||||
resolveNativeChatSession({
|
||||
paneKey: 'tab-1:11111111-1111-4111-8111-111111111111',
|
||||
@@ -242,7 +258,11 @@ describe('resolveNativeChatSession', () => {
|
||||
resolvedAgent: 'codex',
|
||||
ptyId: 'pty-1'
|
||||
})
|
||||
).toBeNull()
|
||||
).toMatchObject({
|
||||
agent: 'grok',
|
||||
sessionId: null,
|
||||
ptyId: 'pty-1'
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps launch identity ahead of the title fallback', () => {
|
||||
|
||||
@@ -4,7 +4,9 @@ import type { AgentType } from '../../../../shared/agent-status-types'
|
||||
import type { TerminalPaneLayoutNode } from '../../../../shared/types'
|
||||
import { resolveCommittedTitleAgentType } from '@/lib/pane-agent-evidence'
|
||||
import { canToggleNativeChat } from './native-chat-availability'
|
||||
import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability'
|
||||
import { isMacPlatform, matchesNativeChatToggleShortcut } from './native-chat-shortcut'
|
||||
import { getConnectionIdFromState } from '@/lib/connection-context'
|
||||
|
||||
export function isNativeChatShortcutTitleFallbackSafe(
|
||||
root: TerminalPaneLayoutNode | null | undefined
|
||||
@@ -61,7 +63,7 @@ export function useNativeChatToggleShortcut(worktreeId: string, isWorktreeActive
|
||||
(candidate) => candidate.id === tab.entityId
|
||||
)
|
||||
// Carry the agent identity (not just "an agent exists") so the chord stays
|
||||
// inert on unsupported agents like Grok, matching the menu/header gate.
|
||||
// inert on unsupported agents (e.g. Gemini), matching the menu/header gate.
|
||||
// Pane keys are `${entityId}:${leafId}` — the backing terminal tab id, not
|
||||
// the unified tab id.
|
||||
const terminalLayout = state.terminalLayoutsByTabId[tab.entityId]
|
||||
@@ -82,6 +84,9 @@ export function useNativeChatToggleShortcut(worktreeId: string, isWorktreeActive
|
||||
launchAgent: detectedAgent ? null : terminalTab?.launchAgent,
|
||||
detectedAgent,
|
||||
resolvedAgent: detectedAgent ? null : titleFallbackAgent,
|
||||
nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable(
|
||||
getConnectionIdFromState(state, worktreeId)
|
||||
),
|
||||
isChatViewMode: tab.viewMode === 'chat'
|
||||
})
|
||||
) {
|
||||
|
||||
@@ -26,7 +26,7 @@ export function NativeChatExperimentalSetting({
|
||||
title={translate('auto.components.settings.ExperimentalPane.nativeChat.title', 'Native chat')}
|
||||
description={translate(
|
||||
'auto.components.settings.ExperimentalPane.nativeChat.description',
|
||||
'Preview the desktop chat surface for Claude and Codex terminal sessions.'
|
||||
'Preview the desktop chat surface for supported agent terminal sessions.'
|
||||
)}
|
||||
keywords={getExperimentalSearchEntry().nativeChat.keywords}
|
||||
className="space-y-3 py-2"
|
||||
@@ -40,7 +40,7 @@ export function NativeChatExperimentalSetting({
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{translate(
|
||||
'auto.components.settings.ExperimentalPane.nativeChat.copy',
|
||||
'Adds a native chat view you can switch to from supported Claude and Codex terminal panes. Experimental while we tune transcript fidelity, streaming, and terminal parity.'
|
||||
'Adds a native chat view you can switch to from supported agent terminal panes. Experimental while we tune transcript fidelity, streaming, and terminal parity.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
@@ -70,7 +70,7 @@ export function NativeChatExperimentalSetting({
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{translate(
|
||||
'auto.components.settings.ExperimentalPane.nativeChat.defaultCopy',
|
||||
'Choose how new Claude and Codex terminal tabs open.'
|
||||
'Choose how new supported agent terminal tabs open.'
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -329,7 +329,7 @@ export function TerminalInteractionSection({
|
||||
)}
|
||||
description={translate(
|
||||
'auto.components.settings.TerminalPane.69c64a479c',
|
||||
'Let tmux, Neovim, and fzf copy to the system clipboard over the PTY (including over SSH).'
|
||||
'Let Grok, tmux, Neovim, and fzf copy to the system clipboard over the PTY (including over SSH).'
|
||||
)}
|
||||
keywords={[
|
||||
'osc 52',
|
||||
@@ -339,6 +339,7 @@ export function TerminalInteractionSection({
|
||||
'neovim',
|
||||
'nvim',
|
||||
'fzf',
|
||||
'grok',
|
||||
'ssh',
|
||||
'remote',
|
||||
'copy',
|
||||
@@ -352,7 +353,7 @@ export function TerminalInteractionSection({
|
||||
)}
|
||||
description={translate(
|
||||
'auto.components.settings.TerminalPane.6e6480a7df',
|
||||
'Let programs in the terminal (tmux, Neovim, fzf, SSH) copy to your system clipboard.'
|
||||
'Let programs in the terminal (Grok, tmux, Neovim, fzf, SSH) copy to your system clipboard.'
|
||||
)}
|
||||
checked={settings.terminalAllowOsc52Clipboard}
|
||||
onChange={() =>
|
||||
|
||||
@@ -10,7 +10,7 @@ export function getNativeChatExperimentalSearchEntry(): SettingsSearchEntry {
|
||||
),
|
||||
description: translate(
|
||||
'auto.components.settings.experimental.search.nativeChat.description',
|
||||
'Preview the desktop chat surface for Claude and Codex terminal sessions.'
|
||||
'Preview the desktop chat surface for supported agent terminal sessions.'
|
||||
),
|
||||
keywords: [
|
||||
...translateSearchKeyword(
|
||||
@@ -33,6 +33,10 @@ export function getNativeChatExperimentalSearchEntry(): SettingsSearchEntry {
|
||||
'auto.components.settings.experimental.search.nativeChat.codex',
|
||||
'codex'
|
||||
),
|
||||
...translateSearchKeyword(
|
||||
'auto.components.settings.experimental.search.nativeChat.grok',
|
||||
'grok'
|
||||
),
|
||||
...translateSearchKeyword(
|
||||
'auto.components.settings.experimental.search.nativeChat.terminal',
|
||||
'terminal'
|
||||
|
||||
@@ -79,8 +79,10 @@ import { useTabStripOverflowNavigation } from './tab-strip-overflow-navigation'
|
||||
import { useTabStripDragScrollHandlers } from './tab-strip-drag-scroll'
|
||||
import { shouldShowWindowsShellMenu } from './windows-shell-menu-visibility'
|
||||
import { canToggleNativeChat } from '../native-chat/native-chat-availability'
|
||||
import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability'
|
||||
import { selectTabAgentTypesByTabId } from './tab-agent-types-by-tab-id'
|
||||
import { resolveCommittedTitleAgentType } from '@/lib/pane-agent-evidence'
|
||||
import { getConnectionIdFromState } from '@/lib/connection-context'
|
||||
|
||||
const isWindows = navigator.userAgent.includes('Windows')
|
||||
const isMacOs = navigator.userAgent.includes('Mac')
|
||||
@@ -463,6 +465,9 @@ function TabBarInner({
|
||||
useShallow((s) => selectTabAgentTypesByTabId(s.agentStatusByPaneKey ?? {}))
|
||||
)
|
||||
const nativeChatEnabled = useAppStore((s) => s.settings?.experimentalNativeChat === true)
|
||||
const nativeChatTranscriptIsLocalReadable = useAppStore((s) =>
|
||||
isNativeChatTranscriptLocalReadable(getConnectionIdFromState(s, worktreeId))
|
||||
)
|
||||
|
||||
// Why: Electron <webview> elements run in a separate process, so clicking
|
||||
// inside one never dispatches a pointerdown on the renderer document.
|
||||
@@ -1124,6 +1129,7 @@ function TabBarInner({
|
||||
launchAgent: terminalTab.launchAgent,
|
||||
detectedAgent,
|
||||
resolvedAgent,
|
||||
nativeChatTranscriptIsLocalReadable,
|
||||
isChatViewMode: unifiedTabForItem.viewMode === 'chat'
|
||||
})
|
||||
return (
|
||||
|
||||
@@ -99,6 +99,7 @@ import {
|
||||
} from '@/lib/pane-manager/mobile-driver-state'
|
||||
import { shouldChatTakeOverMobileSurface } from '../native-chat/native-chat-send-eligibility'
|
||||
import { canToggleNativeChat } from '../native-chat/native-chat-availability'
|
||||
import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability'
|
||||
import type { AgentType } from '../../../../shared/agent-status-types'
|
||||
import { resolvePaneKeyForManager } from '@/lib/pane-manager/pane-key-resolution'
|
||||
import { safeFit } from '@/lib/pane-manager/pane-tree-ops'
|
||||
@@ -316,6 +317,9 @@ export default function TerminalPane({
|
||||
}
|
||||
return connectionId
|
||||
})
|
||||
const nativeChatTranscriptIsLocalReadable = useAppStore((store) =>
|
||||
isNativeChatTranscriptLocalReadable(getConnectionIdFromState(store, worktreeId))
|
||||
)
|
||||
// Which machine's SSH store this target belongs to: a remote Orca server's
|
||||
// per-environment bucket, or null for this machine's local SSH maps. The
|
||||
// explicit-owner resolver never lets a merely focused runtime make a
|
||||
@@ -719,6 +723,7 @@ export default function TerminalPane({
|
||||
launchAgent: detectedAgent ? null : terminalTab?.launchAgent,
|
||||
detectedAgent,
|
||||
resolvedAgent: detectedAgent ? null : resolveTitleAgentForLeaf(leafId),
|
||||
nativeChatTranscriptIsLocalReadable,
|
||||
isChatViewMode: isChatViewForLeaf
|
||||
})
|
||||
},
|
||||
@@ -727,6 +732,7 @@ export default function TerminalPane({
|
||||
effectiveChatViewMode,
|
||||
chatLeafId,
|
||||
nativeChatEnabled,
|
||||
nativeChatTranscriptIsLocalReadable,
|
||||
terminalTab?.launchAgent,
|
||||
resolveTitleAgentForLeaf
|
||||
]
|
||||
|
||||
@@ -5630,6 +5630,24 @@ describe('connectPanePty', () => {
|
||||
expect(transport.sendInput).toHaveBeenCalledWith('yes')
|
||||
expect(transport.sendInput).toHaveBeenCalledWith('\x1b[A')
|
||||
expect(transport.sendInputImmediate).not.toHaveBeenCalled()
|
||||
|
||||
// terminal-query-reply.test proves real xterm emits this as one fully framed
|
||||
// onData reply; this pins that production-shaped reply to the immediate path.
|
||||
transport.sendInputImmediate.mockClear()
|
||||
const xtversionReply = '\x1bP>|xterm.js(6.1.0-beta.287)\x1b\\'
|
||||
sendTerminalInputThroughPane(pane, xtversionReply)
|
||||
expect(transport.sendInputImmediate).toHaveBeenCalledWith(xtversionReply)
|
||||
|
||||
// Printable input is user-owned. Remote cooked echo comes back through PTY
|
||||
// output, not onData, so xterm/OSC-looking text must stay on normal input.
|
||||
transport.sendInput.mockClear()
|
||||
transport.sendInputImmediate.mockClear()
|
||||
const printableInputs = [']10;hello', '>|xterm.js(6.1.0-beta.287)', ']|literal-text']
|
||||
for (const data of printableInputs) {
|
||||
sendTerminalInputThroughPane(pane, data)
|
||||
expect(transport.sendInput).toHaveBeenCalledWith(data)
|
||||
}
|
||||
expect(transport.sendInputImmediate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('writes the onReplayData pendingEscapeTailAnsi meta last, after the replayed bytes (#7329)', async () => {
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildTerminalKeyboardProtocolOptions } from '@/lib/pane-manager/terminal-keyboard-protocol'
|
||||
import { buildDefaultTerminalOptions } from '@/lib/pane-manager/pane-terminal-options'
|
||||
import { resolvePaneKeyboardProtocolAgent } from './terminal-keyboard-protocol-pane-agent'
|
||||
|
||||
const localWindowsConpty = {
|
||||
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
|
||||
osRelease: '10.0.26100',
|
||||
connectionId: null,
|
||||
cwd: 'C:\\repo',
|
||||
shellOverride: 'powershell.exe',
|
||||
executionHostId: 'local' as const
|
||||
}
|
||||
|
||||
function resolvedKittyKeyboard(
|
||||
startup: { launchAgent?: 'grok' } | null | undefined,
|
||||
tabLaunchAgent: 'grok' | null = null
|
||||
): boolean | undefined {
|
||||
const tuiAgent = resolvePaneKeyboardProtocolAgent(startup, tabLaunchAgent)
|
||||
const options = {
|
||||
...buildDefaultTerminalOptions(),
|
||||
...buildTerminalKeyboardProtocolOptions({ ...localWindowsConpty, tuiAgent })
|
||||
}
|
||||
return options.vtExtensions?.kittyKeyboard
|
||||
}
|
||||
|
||||
describe('pane-scoped terminal keyboard protocol agent', () => {
|
||||
it('keeps KKP for the Grok startup pane but withholds it from a later shell split', () => {
|
||||
expect(resolvedKittyKeyboard({ launchAgent: 'grok' })).toBe(true)
|
||||
|
||||
// The lifecycle consumes its one-shot startup before a user-created split.
|
||||
expect(resolvedKittyKeyboard(null)).toBe(false)
|
||||
})
|
||||
|
||||
it('uses persisted Grok identity for a restored root but not its later sibling', () => {
|
||||
expect(resolvedKittyKeyboard(undefined, 'grok')).toBe(true)
|
||||
|
||||
// onPaneCreated changes the lifecycle startup sentinel from undefined to null.
|
||||
expect(resolvedKittyKeyboard(null, 'grok')).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps explicit pane startup identity ahead of a stale tab launch agent', () => {
|
||||
expect(resolvePaneKeyboardProtocolAgent({ launchAgent: 'claude' }, 'grok')).toBe('claude')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { TuiAgent } from '../../../../shared/types'
|
||||
|
||||
type PaneKeyboardProtocolStartup = {
|
||||
launchAgent?: TuiAgent
|
||||
}
|
||||
|
||||
/** Resolves only the agent owned by the startup payload for the pane being created. */
|
||||
export function resolvePaneKeyboardProtocolAgent(
|
||||
startup: PaneKeyboardProtocolStartup | null | undefined,
|
||||
tabLaunchAgent?: TuiAgent | null
|
||||
): TuiAgent | null {
|
||||
if (startup === undefined) {
|
||||
return tabLaunchAgent ?? null
|
||||
}
|
||||
return startup?.launchAgent ?? null
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { normalizeTerminalLineHeight } from '../../../../shared/terminal-line-he
|
||||
import { normalizeTerminalTuiMouseWheelMultiplier } from '@/lib/pane-manager/pane-terminal-mouse-wheel'
|
||||
import { buildWindowsPtyCompatibilityOptions } from '@/lib/pane-manager/windows-pty-compatibility'
|
||||
import { buildTerminalKeyboardProtocolOptions } from '@/lib/pane-manager/terminal-keyboard-protocol'
|
||||
import { resolvePaneKeyboardProtocolAgent } from './terminal-keyboard-protocol-pane-agent'
|
||||
import { useAppStore } from '@/store'
|
||||
import {
|
||||
createFilePathLinkProvider,
|
||||
@@ -1374,19 +1375,27 @@ export function useTerminalPaneLifecycle({
|
||||
(candidate) => candidate.id === tabId
|
||||
)
|
||||
const platformInfo = window.api.platform?.get?.()
|
||||
// Why: launch identity belongs only to the pane consuming this one-shot
|
||||
// startup. A tab-wide hint would leak Grok's KKP exception to shell splits.
|
||||
const knownTuiAgent = resolvePaneKeyboardProtocolAgent(
|
||||
ptyDeps.startup,
|
||||
currentTab?.launchAgent
|
||||
)
|
||||
const ptyBackendContext = {
|
||||
userAgent: navigator.userAgent,
|
||||
osRelease: platformInfo?.osRelease,
|
||||
connectionId: getConnectionId(worktreeId),
|
||||
cwd: startupCwd,
|
||||
shellOverride: currentTab?.shellOverride,
|
||||
executionHostId: getExecutionHostIdForWorktree(storeState, worktreeId)
|
||||
executionHostId: getExecutionHostIdForWorktree(storeState, worktreeId),
|
||||
tuiAgent: knownTuiAgent
|
||||
}
|
||||
const windowsPtyCompatibilityOptions =
|
||||
buildWindowsPtyCompatibilityOptions(ptyBackendContext)
|
||||
// Why: local Windows ConPTY CLIs read the Kitty keyboard advertisement but
|
||||
// do not decode CSI-u, so withhold it there to restore Enter/Up/Down nav
|
||||
// (issue #2434); SSH and macOS/Linux panes keep enhanced reporting.
|
||||
// Exception: Grok (tuiAgent) keeps the advertisement — see protocol module.
|
||||
const keyboardProtocolOptions = buildTerminalKeyboardProtocolOptions(ptyBackendContext)
|
||||
return {
|
||||
...windowsPtyCompatibilityOptions,
|
||||
|
||||
@@ -126,6 +126,8 @@ import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { closeTerminalTab } from '@/components/terminal/terminal-tab-actions'
|
||||
import { initialAgentTabViewModeProps } from '@/lib/native-chat-initial-view-mode'
|
||||
import { getConnectionIdFromState } from '@/lib/connection-context'
|
||||
import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability'
|
||||
|
||||
function getShortcutPlatform(): NodeJS.Platform {
|
||||
if (navigator.userAgent.includes('Mac')) {
|
||||
@@ -1484,7 +1486,11 @@ export function useIpcEvents(): void {
|
||||
? {
|
||||
launchAgent,
|
||||
...initialAgentTabViewModeProps(store.settings, {
|
||||
agent: launchAgent
|
||||
agent: launchAgent,
|
||||
nativeChatTranscriptIsLocalReadable:
|
||||
isNativeChatTranscriptLocalReadable(
|
||||
getConnectionIdFromState(store, worktreeId)
|
||||
)
|
||||
})
|
||||
}
|
||||
: {}),
|
||||
@@ -1666,7 +1672,10 @@ export function useIpcEvents(): void {
|
||||
...(shouldActivate ? {} : { activate: false, recordInteraction: false }),
|
||||
launchAgent: data.launchAgent,
|
||||
...initialAgentTabViewModeProps(store.settings, {
|
||||
agent: data.launchAgent
|
||||
agent: data.launchAgent,
|
||||
nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable(
|
||||
getConnectionIdFromState(store, worktreeId)
|
||||
)
|
||||
}),
|
||||
...(data.cwd ? { startupCwd: data.cwd } : {})
|
||||
}
|
||||
|
||||
@@ -5308,11 +5308,11 @@
|
||||
"0e89a574ae": "Floating animated pet in the bottom-right corner.",
|
||||
"nativeChat": {
|
||||
"title": "Native chat",
|
||||
"description": "Preview the desktop chat surface for Claude and Codex terminal sessions.",
|
||||
"copy": "Adds a native chat view you can switch to from supported Claude and Codex terminal panes. Experimental while we tune transcript fidelity, streaming, and terminal parity.",
|
||||
"description": "Preview the desktop chat surface for supported agent terminal sessions.",
|
||||
"copy": "Adds a native chat view you can switch to from supported agent terminal panes. Experimental while we tune transcript fidelity, streaming, and terminal parity.",
|
||||
"toggleLabel": "Toggle native chat",
|
||||
"defaultTitle": "Default view",
|
||||
"defaultCopy": "Choose how new Claude and Codex terminal tabs open.",
|
||||
"defaultCopy": "Choose how new supported agent terminal tabs open.",
|
||||
"defaultViewLabel": "Default native chat view",
|
||||
"defaultViewTerminal": "Terminal chat",
|
||||
"defaultViewNative": "Native chat"
|
||||
@@ -6723,9 +6723,9 @@
|
||||
"d23b43c5be": "Setup Script Location",
|
||||
"34a0dfa06e": "Where the repository setup script runs when a new workspace is created.",
|
||||
"21f8da2078": "Workspace Setup Script",
|
||||
"6e6480a7df": "Let programs in the terminal (tmux, Neovim, fzf, SSH) copy to your system clipboard.",
|
||||
"6e6480a7df": "Let programs in the terminal (Grok, tmux, Neovim, fzf, SSH) copy to your system clipboard.",
|
||||
"3338dcf8c1": "Allow TUI Clipboard Writes (OSC 52)",
|
||||
"69c64a479c": "Let tmux, Neovim, and fzf copy to the system clipboard over the PTY (including over SSH).",
|
||||
"69c64a479c": "Let Grok, tmux, Neovim, and fzf copy to the system clipboard over the PTY (including over SSH).",
|
||||
"4729c645fc": "Automatically copy terminal selections to the clipboard.",
|
||||
"902f5dee1f": "Copy on Select",
|
||||
"9129b7e805": "Hovering a terminal pane activates it without needing to click.",
|
||||
@@ -7517,7 +7517,8 @@
|
||||
"87d99e634b": "Pet",
|
||||
"nativeChat": {
|
||||
"title": "Native chat",
|
||||
"description": "Preview the desktop chat surface for Claude and Codex terminal sessions."
|
||||
"description": "Preview the desktop chat surface for supported agent terminal sessions.",
|
||||
"grok": "grok"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -5308,11 +5308,11 @@
|
||||
},
|
||||
"nativeChat": {
|
||||
"title": "Chat nativo",
|
||||
"description": "Previsualiza la superficie de chat de escritorio para sesiones de terminal de Claude y Codex.",
|
||||
"copy": "Agrega una vista de chat nativa a la que puedes cambiar desde paneles de terminal compatibles de Claude y Codex. Experimental mientras ajustamos la fidelidad de transcripción, streaming y paridad con el terminal.",
|
||||
"description": "Previsualiza la interfaz de chat de escritorio para sesiones de terminal de agentes compatibles.",
|
||||
"copy": "Añade una vista de chat nativo a la que puedes cambiar desde paneles de terminal de agentes compatibles. Es experimental mientras ajustamos la fidelidad de las transcripciones, la transmisión y la paridad con el terminal.",
|
||||
"toggleLabel": "Alternar chat nativo",
|
||||
"defaultTitle": "Vista predeterminada",
|
||||
"defaultCopy": "Elige cómo se abren las nuevas pestañas de terminal de Claude y Codex.",
|
||||
"defaultCopy": "Elige cómo se abren las nuevas pestañas de terminal de agentes compatibles.",
|
||||
"defaultViewLabel": "Vista predeterminada de chat nativo",
|
||||
"defaultViewTerminal": "Chat en terminal",
|
||||
"defaultViewNative": "Chat nativo"
|
||||
@@ -6686,9 +6686,9 @@
|
||||
"d23b43c5be": "Ubicación del script de configuración",
|
||||
"34a0dfa06e": "Dónde se ejecuta el script de configuración del repositorio cuando se crea un nuevo espacio de trabajo.",
|
||||
"21f8da2078": "Script de configuración del espacio de trabajo",
|
||||
"6e6480a7df": "Permite que los programas del terminal (tmux, Neovim, fzf, SSH) copien al portapapeles del sistema.",
|
||||
"6e6480a7df": "Permite que los programas del terminal (Grok, tmux, Neovim, fzf, SSH) copien al portapapeles del sistema.",
|
||||
"3338dcf8c1": "Permitir escrituras en el portapapeles TUI (OSC 52)",
|
||||
"69c64a479c": "Permite que tmux, Neovim y fzf copien al portapapeles del sistema a través de PTY (incluso por SSH).",
|
||||
"69c64a479c": "Permite que Grok, tmux, Neovim y fzf copien al portapapeles del sistema a través de PTY (incluso por SSH).",
|
||||
"4729c645fc": "Copia automáticamente las selecciones del terminal al portapapeles.",
|
||||
"902f5dee1f": "Copiar al seleccionar",
|
||||
"9129b7e805": "Al pasar el cursor sobre un panel de terminal, se activa sin necesidad de hacer clic.",
|
||||
@@ -7480,7 +7480,8 @@
|
||||
},
|
||||
"nativeChat": {
|
||||
"title": "Chat nativo",
|
||||
"description": "Previsualiza la vista de chat de escritorio para sesiones de terminal de Claude y Codex."
|
||||
"description": "Previsualiza la interfaz de chat de escritorio para sesiones de terminal de agentes compatibles.",
|
||||
"grok": "grok"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -5293,11 +5293,11 @@
|
||||
},
|
||||
"nativeChat": {
|
||||
"title": "ネイティブチャット",
|
||||
"description": "Claude と Codex の terminal セッションのデスクトップ チャット サーフェスをプレビューします。",
|
||||
"copy": "サポートされている Claude および Codex の terminal ペインから切り替えることができるネイティブ チャット ビューを追加します。トランスクリプトの忠実度、ストリーミング、ターミナルのパリティを調整するための実験です。",
|
||||
"description": "対応エージェントのターミナルセッション用デスクトップチャット画面をプレビューします。",
|
||||
"copy": "対応エージェントのターミナルペインから切り替えられるネイティブチャットビューを追加します。トランスクリプトの忠実度、ストリーミング、ターミナルとの同等性を調整しているため、試験運用中です。",
|
||||
"toggleLabel": "ネイティブチャットの切り替え",
|
||||
"defaultTitle": "デフォルトのビュー",
|
||||
"defaultCopy": "新規 Claude および Codex の terminal タブを開く方法を選択します。",
|
||||
"defaultCopy": "対応エージェントの新しいターミナルタブを開く方法を選択します。",
|
||||
"defaultViewLabel": "デフォルトのネイティブ チャット ビュー",
|
||||
"defaultViewTerminal": "Terminal チャット",
|
||||
"defaultViewNative": "ネイティブチャット"
|
||||
@@ -6708,9 +6708,9 @@
|
||||
"d23b43c5be": "セットアップスクリプトの場所",
|
||||
"34a0dfa06e": "新規ワークスペースの作成時に repos セットアップ スクリプトが実行される場所。",
|
||||
"21f8da2078": "ワークスペースセットアップスクリプト",
|
||||
"6e6480a7df": "terminal 内のプログラム (tmux、Neovim、fzf、SSH) をシステムのクリップボードにコピーします。",
|
||||
"6e6480a7df": "terminal 内のプログラム (Grok、tmux、Neovim、fzf、SSH) をシステムのクリップボードにコピーします。",
|
||||
"3338dcf8c1": "TUI クリップボードへの書き込みを許可する (OSC 52)",
|
||||
"69c64a479c": "tmux、Neovim、および fzf が PTY 経由 (SSH 経由を含む) でシステム クリップボードにコピーできるようにします。",
|
||||
"69c64a479c": "Grok、tmux、Neovim、および fzf が PTY 経由 (SSH 経由を含む) でシステム クリップボードにコピーできるようにします。",
|
||||
"4729c645fc": "terminal の選択内容をクリップボードに自動的にコピーします。",
|
||||
"902f5dee1f": "選択時にコピー",
|
||||
"9129b7e805": "terminal ペインにマウスを移動すると、クリックしなくても terminal ペインがアクティブになります。",
|
||||
@@ -7502,7 +7502,8 @@
|
||||
},
|
||||
"nativeChat": {
|
||||
"title": "ネイティブチャット",
|
||||
"description": "Claude と Codex の terminal セッションのデスクトップ チャット サーフェスをプレビューします。"
|
||||
"description": "対応エージェントのターミナルセッション用デスクトップチャット画面をプレビューします。",
|
||||
"grok": "grok"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -5293,11 +5293,11 @@
|
||||
},
|
||||
"nativeChat": {
|
||||
"title": "네이티브 채팅",
|
||||
"description": "Claude 및 Codex terminal 세션에 대한 데스크톱 채팅 화면을 미리 봅니다.",
|
||||
"copy": "지원되는 Claude 및 Codex terminal 창에서 전환할 수 있는 기본 채팅 보기를 추가합니다. 성적표 충실도, 스트리밍 및 terminal 패리티를 조정하는 동안 실험적입니다.",
|
||||
"description": "지원되는 에이전트 터미널 세션의 데스크톱 채팅 화면을 미리 봅니다.",
|
||||
"copy": "지원되는 에이전트 터미널 창에서 전환할 수 있는 네이티브 채팅 보기를 추가합니다. 대화 기록 충실도, 스트리밍, 터미널 동작 일치를 조정하는 동안 실험적으로 제공됩니다.",
|
||||
"toggleLabel": "기본 채팅 전환",
|
||||
"defaultTitle": "기본 보기",
|
||||
"defaultCopy": "새로운 Claude 및 Codex terminal 탭이 열리는 방식을 선택하세요.",
|
||||
"defaultCopy": "지원되는 에이전트의 새 터미널 탭을 여는 방식을 선택합니다.",
|
||||
"defaultViewLabel": "기본 기본 채팅 보기",
|
||||
"defaultViewTerminal": "Terminal 채팅",
|
||||
"defaultViewNative": "네이티브 채팅"
|
||||
@@ -6671,9 +6671,9 @@
|
||||
"d23b43c5be": "설정 스크립트 위치",
|
||||
"34a0dfa06e": "새 워크스페이스를 만들 때 repos 설정 스크립트를 실행할 위치입니다.",
|
||||
"21f8da2078": "워크스페이스 설정 스크립트",
|
||||
"6e6480a7df": "terminal의 프로그램(tmux, Neovim, fzf, SSH)이 시스템 클립보드에 복사할 수 있게 합니다.",
|
||||
"6e6480a7df": "terminal의 프로그램(Grok, tmux, Neovim, fzf, SSH)이 시스템 클립보드에 복사할 수 있게 합니다.",
|
||||
"3338dcf8c1": "TUI 클립보드 쓰기 허용(OSC 52)",
|
||||
"69c64a479c": "tmux, Neovim 및 fzf가 PTY(SSH 포함)를 통해 시스템 클립보드에 복사하도록 합니다.",
|
||||
"69c64a479c": "Grok, tmux, Neovim 및 fzf가 PTY(SSH 포함)를 통해 시스템 클립보드에 복사하도록 합니다.",
|
||||
"4729c645fc": "terminal 선택 사항을 클립보드에 자동으로 복사합니다.",
|
||||
"902f5dee1f": "선택 시 복사",
|
||||
"9129b7e805": "terminal 패널에 마우스를 가리키면 클릭하지 않고도 활성화됩니다.",
|
||||
@@ -7465,7 +7465,8 @@
|
||||
},
|
||||
"nativeChat": {
|
||||
"title": "네이티브 채팅",
|
||||
"description": "Claude 및 Codex terminal 세션에 대한 데스크톱 채팅 화면을 미리 봅니다."
|
||||
"description": "지원되는 에이전트 터미널 세션의 데스크톱 채팅 화면을 미리 봅니다.",
|
||||
"grok": "grok"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -5293,11 +5293,11 @@
|
||||
},
|
||||
"nativeChat": {
|
||||
"title": "原生聊天",
|
||||
"description": "预览 Claude 和 Codex 终端会话的桌面聊天界面。",
|
||||
"copy": "添加一个原生聊天视图,可从受支持的 Claude 和 Codex 终端窗格切换进入。在我们调校记录保真度、流式输出和终端一致性期间,此功能仍为实验性。",
|
||||
"description": "预览受支持的智能体终端会话的桌面聊天界面。",
|
||||
"copy": "添加可从受支持的智能体终端窗格切换的原生聊天视图。在我们调整记录保真度、流式传输和终端一致性期间,此功能仍处于实验阶段。",
|
||||
"toggleLabel": "切换原生聊天",
|
||||
"defaultTitle": "默认视图",
|
||||
"defaultCopy": "选择新的 Claude 和 Codex 终端标签页如何打开。",
|
||||
"defaultCopy": "选择如何打开受支持智能体的新终端标签页。",
|
||||
"defaultViewLabel": "默认原生聊天视图",
|
||||
"defaultViewTerminal": "终端聊天",
|
||||
"defaultViewNative": "原生聊天"
|
||||
@@ -6671,9 +6671,9 @@
|
||||
"d23b43c5be": "安装脚本位置",
|
||||
"34a0dfa06e": "创建新工作区时运行存储库设置脚本的位置。",
|
||||
"21f8da2078": "工作区设置脚本",
|
||||
"6e6480a7df": "让终端中的程序(tmux、Neovim、fzf、SSH)复制到系统剪贴板。",
|
||||
"6e6480a7df": "让终端中的程序(Grok、tmux、Neovim、fzf、SSH)复制到系统剪贴板。",
|
||||
"3338dcf8c1": "允许 TUI 剪贴板写入 (OSC 52)",
|
||||
"69c64a479c": "让 tmux、Neovim 和 fzf 通过 PTY(包括通过 SSH)复制到系统剪贴板。",
|
||||
"69c64a479c": "让 Grok、tmux、Neovim 和 fzf 通过 PTY(包括通过 SSH)复制到系统剪贴板。",
|
||||
"4729c645fc": "自动将终端选择复制到剪贴板。",
|
||||
"902f5dee1f": "选择时复制",
|
||||
"9129b7e805": "将鼠标悬停在终端窗格上即可将其激活,无需单击。",
|
||||
@@ -7465,7 +7465,8 @@
|
||||
},
|
||||
"nativeChat": {
|
||||
"title": "原生聊天",
|
||||
"description": "预览 Claude 和 Codex 终端会话的桌面聊天界面。"
|
||||
"description": "预览受支持的智能体终端会话的桌面聊天界面。",
|
||||
"grok": "grok"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import en from './locales/en.json'
|
||||
import es from './locales/es.json'
|
||||
import ja from './locales/ja.json'
|
||||
import ko from './locales/ko.json'
|
||||
import zh from './locales/zh.json'
|
||||
|
||||
const localizedCatalogs = { es, ja, ko, zh }
|
||||
const englishSetting = en.auto.components.settings.ExperimentalPane.nativeChat
|
||||
const englishSearch = en.auto.components.settings.experimental.search.nativeChat
|
||||
|
||||
describe('native chat locale copy', () => {
|
||||
it.each(Object.entries(localizedCatalogs))('%s keeps provider-neutral copy localized', (_code, catalog) => {
|
||||
const setting = catalog.auto.components.settings.ExperimentalPane.nativeChat
|
||||
const search = catalog.auto.components.settings.experimental.search.nativeChat
|
||||
for (const [localized, english] of [
|
||||
[setting.description, englishSetting.description],
|
||||
[setting.copy, englishSetting.copy],
|
||||
[setting.defaultCopy, englishSetting.defaultCopy],
|
||||
[search.description, englishSearch.description]
|
||||
]) {
|
||||
expect(localized.trim()).not.toBe('')
|
||||
expect(localized).not.toBe(english)
|
||||
}
|
||||
expect(search.grok).toBe('grok')
|
||||
})
|
||||
})
|
||||
@@ -65,7 +65,7 @@ describe('deliverLaunchPromptToAgentTab', () => {
|
||||
})
|
||||
await deliverLaunchPromptToAgentTab({
|
||||
tabId: 'unsupported-tab',
|
||||
agent: 'grok',
|
||||
agent: 'gemini',
|
||||
content: 'Fix failing checks',
|
||||
submit: true,
|
||||
forcePaste: true
|
||||
@@ -121,7 +121,7 @@ describe('deliverLaunchPromptToAgentTab', () => {
|
||||
|
||||
await deliverLaunchPromptToAgentTab({
|
||||
tabId: 'tab-1',
|
||||
agent: 'grok',
|
||||
agent: 'gemini',
|
||||
content: 'Large generated prompt',
|
||||
submit: true,
|
||||
forcePaste: true
|
||||
|
||||
@@ -201,7 +201,7 @@ describe('launchAgentInNewTab', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps unsupported submit-after-ready launches in terminal mode and does not seed chat', async () => {
|
||||
it('opens local Grok submit-after-ready launches in native chat', async () => {
|
||||
store.settings = {
|
||||
agentCmdOverrides: {},
|
||||
agentDefaultArgs: {},
|
||||
@@ -220,9 +220,36 @@ describe('launchAgentInNewTab', () => {
|
||||
})
|
||||
|
||||
expect(mockCreateTab).toHaveBeenCalledWith('wt-1', undefined, undefined, {
|
||||
launchAgent: 'grok'
|
||||
launchAgent: 'grok',
|
||||
quickCommandLabel: undefined,
|
||||
viewMode: 'chat'
|
||||
})
|
||||
expect(mockSeedNativeChatLaunchPrompt).toHaveBeenCalledWith({
|
||||
tabId: 'tab-1',
|
||||
agent: 'grok',
|
||||
text: 'large generated prompt',
|
||||
createdAt: expect.any(Number)
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps Model-A SSH Grok launches in terminal mode', async () => {
|
||||
store.settings = {
|
||||
agentCmdOverrides: {},
|
||||
agentDefaultArgs: {},
|
||||
agentDefaultEnv: {},
|
||||
activeRuntimeEnvironmentId: null,
|
||||
experimentalNativeChat: true,
|
||||
openAgentTabsInChatByDefault: true
|
||||
}
|
||||
store.repos = [{ id: 'repo-1', connectionId: 'ssh-target-1', path: '/repo' }]
|
||||
const { launchAgentInNewTab } = await import('./launch-agent-in-new-tab')
|
||||
|
||||
launchAgentInNewTab({ agent: 'grok', worktreeId: 'wt-1' })
|
||||
|
||||
expect(mockCreateTab).toHaveBeenCalledWith('wt-1', undefined, undefined, {
|
||||
launchAgent: 'grok',
|
||||
quickCommandLabel: undefined
|
||||
})
|
||||
expect(mockSeedNativeChatLaunchPrompt).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('passes quick command labels only to locally-created agent tabs', async () => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import { reconcileTabOrder } from '@/components/tab-bar/reconcile-order'
|
||||
import { track, tuiAgentToAgentKind } from '@/lib/telemetry'
|
||||
import { deliverLaunchPromptToAgentTab } from '@/lib/agent-launch-prompt-delivery'
|
||||
import { initialAgentTabViewModeProps } from '@/lib/native-chat-initial-view-mode'
|
||||
import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability'
|
||||
import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner'
|
||||
import { getLocalProjectExecutionRuntimeContext } from '@/lib/local-preflight-context'
|
||||
import {
|
||||
@@ -29,6 +30,7 @@ import { seedCommandCodeSubmittedPromptStatus } from '@/lib/command-code-prompt-
|
||||
import type { TuiAgent } from '../../../shared/types'
|
||||
import type { LaunchSource } from '../../../shared/telemetry-events'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { getConnectionIdFromState } from '@/lib/connection-context'
|
||||
|
||||
export type LaunchAgentInNewTabArgs = {
|
||||
agent: TuiAgent
|
||||
@@ -264,14 +266,14 @@ export function launchAgentInNewTab(args: LaunchAgentInNewTabArgs): LaunchAgentI
|
||||
// stays false), so gate the initial chat view like a `draft` launch —
|
||||
// otherwise a default `auto-submit` followup would open native chat with no
|
||||
// submitted turn to render.
|
||||
const viewModePromptDelivery =
|
||||
hasPrompt && isFollowupPath && promptDelivery === 'auto-submit' ? 'draft' : promptDelivery
|
||||
const viewModePromptDelivery = hasPrompt && isFollowupPath && promptDelivery === 'auto-submit' ? 'draft' : promptDelivery
|
||||
const tab = store.createTab(worktreeId, groupId, undefined, {
|
||||
launchAgent: agent,
|
||||
quickCommandLabel,
|
||||
...initialAgentTabViewModeProps(store.settings, {
|
||||
agent,
|
||||
promptDelivery: viewModePromptDelivery
|
||||
promptDelivery: viewModePromptDelivery,
|
||||
nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable(getConnectionIdFromState(store, worktreeId))
|
||||
})
|
||||
})
|
||||
store.queueTabStartupCommand(tab.id, {
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
decideInitialAgentTabViewMode,
|
||||
initialAgentTabViewModeProps
|
||||
} from './native-chat-initial-view-mode'
|
||||
import { isNativeChatTranscriptLocalReadable } from './native-chat-transcript-readability'
|
||||
|
||||
describe('decideInitialAgentTabViewMode', () => {
|
||||
it("returns 'chat' when native chat and the opt-in default setting are on", () => {
|
||||
@@ -50,11 +51,47 @@ describe('decideInitialAgentTabViewMode', () => {
|
||||
decideInitialAgentTabViewMode({
|
||||
experimentalNativeChat: true,
|
||||
openAgentTabsInChatByDefault: true,
|
||||
agent: 'grok'
|
||||
agent: 'gemini'
|
||||
})
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['local', null],
|
||||
['runtime-owned', 'runtime-ssh-env-1']
|
||||
] as const)('opens %s Grok in chat when configured', (_host, connectionId) => {
|
||||
expect(
|
||||
decideInitialAgentTabViewMode({
|
||||
experimentalNativeChat: true,
|
||||
openAgentTabsInChatByDefault: true,
|
||||
agent: 'grok',
|
||||
nativeChatTranscriptIsLocalReadable:
|
||||
isNativeChatTranscriptLocalReadable(connectionId)
|
||||
})
|
||||
).toBe('chat')
|
||||
})
|
||||
|
||||
it('keeps Model-A SSH Grok in the terminal view', () => {
|
||||
expect(
|
||||
decideInitialAgentTabViewMode({
|
||||
experimentalNativeChat: true,
|
||||
openAgentTabsInChatByDefault: true,
|
||||
agent: 'grok',
|
||||
nativeChatTranscriptIsLocalReadable:
|
||||
isNativeChatTranscriptLocalReadable('ssh-target-1')
|
||||
})
|
||||
).toBeUndefined()
|
||||
expect(
|
||||
initialAgentTabViewModeProps(
|
||||
{
|
||||
experimentalNativeChat: true,
|
||||
openAgentTabsInChatByDefault: true
|
||||
},
|
||||
{ agent: 'grok', nativeChatTranscriptIsLocalReadable: false }
|
||||
)
|
||||
).toEqual({})
|
||||
})
|
||||
|
||||
it('returns undefined for draft delivery', () => {
|
||||
expect(
|
||||
decideInitialAgentTabViewMode({
|
||||
|
||||
@@ -16,6 +16,7 @@ export function decideInitialAgentTabViewMode(args: {
|
||||
openAgentTabsInChatByDefault?: boolean
|
||||
agent?: TuiAgent | null
|
||||
promptDelivery?: NativeChatLaunchPromptDelivery
|
||||
nativeChatTranscriptIsLocalReadable?: boolean
|
||||
}): Tab['viewMode'] {
|
||||
if (args.experimentalNativeChat !== true || args.openAgentTabsInChatByDefault !== true) {
|
||||
return undefined
|
||||
@@ -23,6 +24,9 @@ export function decideInitialAgentTabViewMode(args: {
|
||||
if (!isNativeChatSupportedAgent(args.agent)) {
|
||||
return undefined
|
||||
}
|
||||
if (args.agent === 'grok' && args.nativeChatTranscriptIsLocalReadable !== true) {
|
||||
return undefined
|
||||
}
|
||||
if (args.promptDelivery === 'draft') {
|
||||
return undefined
|
||||
}
|
||||
@@ -37,13 +41,15 @@ export function initialAgentTabViewModeProps(
|
||||
options: {
|
||||
agent?: TuiAgent | null
|
||||
promptDelivery?: NativeChatLaunchPromptDelivery
|
||||
nativeChatTranscriptIsLocalReadable?: boolean
|
||||
} = {}
|
||||
): { viewMode?: Tab['viewMode'] } {
|
||||
const viewMode = decideInitialAgentTabViewMode({
|
||||
experimentalNativeChat: settings?.experimentalNativeChat,
|
||||
openAgentTabsInChatByDefault: settings?.openAgentTabsInChatByDefault,
|
||||
agent: options.agent,
|
||||
promptDelivery: options.promptDelivery
|
||||
promptDelivery: options.promptDelivery,
|
||||
nativeChatTranscriptIsLocalReadable: options.nativeChatTranscriptIsLocalReadable
|
||||
})
|
||||
return viewMode ? { viewMode } : {}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,11 @@ import type { TuiAgent } from '../../../shared/types'
|
||||
export const NATIVE_CHAT_SUPPORTED_AGENTS: ReadonlySet<string> = new Set<string>([
|
||||
'claude',
|
||||
'openclaude',
|
||||
'codex'
|
||||
'codex',
|
||||
// Why: Grok writes `~/.grok/sessions/<cwd-enc>/<id>/chat_history.jsonl` and
|
||||
// Orca already reads that for hooks/AI Vault — native chat reuses the same
|
||||
// path + a Grok JSONL decoder rather than leaving Grok TUI-only.
|
||||
'grok'
|
||||
])
|
||||
|
||||
export function isNativeChatSupportedAgent(
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isNativeChatTranscriptLocalReadable } from './native-chat-transcript-readability'
|
||||
|
||||
describe('native chat transcript readability', () => {
|
||||
it('allows local and runtime-owned hosts but rejects Model-A SSH and unresolved hosts', () => {
|
||||
expect(isNativeChatTranscriptLocalReadable(null)).toBe(true)
|
||||
expect(isNativeChatTranscriptLocalReadable('runtime-ssh-env-1')).toBe(true)
|
||||
expect(isNativeChatTranscriptLocalReadable('ssh-target-1')).toBe(false)
|
||||
expect(isNativeChatTranscriptLocalReadable(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
import { isRuntimeOwnedSshTargetId } from '../../../shared/execution-host'
|
||||
|
||||
/** Model-A SSH stores Grok transcripts on a host this renderer cannot read. */
|
||||
export function isNativeChatTranscriptLocalReadable(
|
||||
connectionId: string | null | undefined
|
||||
): boolean {
|
||||
return connectionId === null || isRuntimeOwnedSshTargetId(connectionId)
|
||||
}
|
||||
@@ -149,6 +149,25 @@ describe('buildDefaultTerminalOptions', () => {
|
||||
expect(merged.vtExtensions?.kittyKeyboard).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps kitty keyboard when a local Windows ConPTY pane is launching Grok', () => {
|
||||
// Why: Grok needs KKP for Ctrl+Enter interject / Shift+Enter newline; the
|
||||
// ConPTY withhold must not win when launchAgent (or tuiAgent) is grok.
|
||||
const merged = {
|
||||
...buildDefaultTerminalOptions(),
|
||||
...buildTerminalKeyboardProtocolOptions({
|
||||
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
|
||||
osRelease: '10.0.26100',
|
||||
connectionId: null,
|
||||
cwd: 'C:\\repo',
|
||||
shellOverride: 'powershell.exe',
|
||||
executionHostId: 'local',
|
||||
tuiAgent: 'grok'
|
||||
})
|
||||
}
|
||||
|
||||
expect(merged.vtExtensions?.kittyKeyboard).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps the advertised kitty keyboard default for SSH and macOS/Linux panes', () => {
|
||||
for (const context of [
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildTerminalKeyboardProtocolOptions,
|
||||
prefersKittyKeyboardDespiteWindowsConpty,
|
||||
shouldDisableKittyKeyboardForTerminal
|
||||
} from './terminal-keyboard-protocol'
|
||||
|
||||
@@ -8,19 +9,50 @@ const WINDOWS_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
|
||||
const MAC_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0)'
|
||||
const LINUX_UA = 'Mozilla/5.0 (X11; Linux x86_64)'
|
||||
|
||||
const localWindowsConpty = {
|
||||
userAgent: WINDOWS_UA,
|
||||
osRelease: '10.0.26100',
|
||||
connectionId: null as string | null,
|
||||
cwd: 'C:\\repo',
|
||||
shellOverride: 'powershell.exe' as string | null,
|
||||
executionHostId: 'local' as const
|
||||
}
|
||||
|
||||
describe('prefersKittyKeyboardDespiteWindowsConpty', () => {
|
||||
it('is true only for Grok (needs KKP for modified Enter on ConPTY)', () => {
|
||||
expect(prefersKittyKeyboardDespiteWindowsConpty('grok')).toBe(true)
|
||||
expect(prefersKittyKeyboardDespiteWindowsConpty('claude')).toBe(false)
|
||||
expect(prefersKittyKeyboardDespiteWindowsConpty('codex')).toBe(false)
|
||||
expect(prefersKittyKeyboardDespiteWindowsConpty(null)).toBe(false)
|
||||
expect(prefersKittyKeyboardDespiteWindowsConpty(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('shouldDisableKittyKeyboardForTerminal', () => {
|
||||
it('disables Kitty keyboard for a local native Windows ConPTY pane', () => {
|
||||
// Regression for #2434: local Windows CLIs (e.g. Antigravity agy) read the
|
||||
// advertisement but do not decode CSI-u, so enhanced reporting swallows
|
||||
// Enter/Up/Down navigation. The advertisement must be withheld here.
|
||||
expect(shouldDisableKittyKeyboardForTerminal(localWindowsConpty)).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps Kitty keyboard for Grok on a local Windows ConPTY pane', () => {
|
||||
// Why: Grok needs KKP to distinguish Ctrl+Enter (interject) / Shift+Enter
|
||||
// from plain Enter. Global ConPTY withhold must not apply when the pane's
|
||||
// known agent is Grok (Orca launchAgent or equivalent).
|
||||
expect(
|
||||
shouldDisableKittyKeyboardForTerminal({
|
||||
userAgent: WINDOWS_UA,
|
||||
osRelease: '10.0.26100',
|
||||
connectionId: null,
|
||||
cwd: 'C:\\repo',
|
||||
shellOverride: 'powershell.exe',
|
||||
executionHostId: 'local'
|
||||
...localWindowsConpty,
|
||||
tuiAgent: 'grok'
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('still withholds Kitty keyboard for non-Grok agents on local Windows ConPTY', () => {
|
||||
expect(
|
||||
shouldDisableKittyKeyboardForTerminal({
|
||||
...localWindowsConpty,
|
||||
tuiAgent: 'claude'
|
||||
})
|
||||
).toBe(true)
|
||||
})
|
||||
@@ -109,16 +141,18 @@ describe('shouldDisableKittyKeyboardForTerminal', () => {
|
||||
|
||||
describe('buildTerminalKeyboardProtocolOptions', () => {
|
||||
it('withholds the Kitty keyboard advertisement for a local Windows ConPTY pane', () => {
|
||||
expect(buildTerminalKeyboardProtocolOptions(localWindowsConpty)).toEqual({
|
||||
vtExtensions: { kittyKeyboard: false }
|
||||
})
|
||||
})
|
||||
|
||||
it('returns no override for Grok on local Windows ConPTY so KKP stays advertised', () => {
|
||||
expect(
|
||||
buildTerminalKeyboardProtocolOptions({
|
||||
userAgent: WINDOWS_UA,
|
||||
osRelease: '10.0.26100',
|
||||
connectionId: null,
|
||||
cwd: 'C:\\repo',
|
||||
shellOverride: 'powershell.exe',
|
||||
executionHostId: 'local'
|
||||
...localWindowsConpty,
|
||||
tuiAgent: 'grok'
|
||||
})
|
||||
).toEqual({ vtExtensions: { kittyKeyboard: false } })
|
||||
).toEqual({})
|
||||
})
|
||||
|
||||
it('returns no override for SSH panes so enhanced reporting stays advertised', () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ITerminalOptions } from '@xterm/xterm'
|
||||
import type { ExecutionHostId } from '../../../../shared/execution-host'
|
||||
import type { TuiAgent } from '../../../../shared/types'
|
||||
import {
|
||||
isLocalNativeWindowsConpty,
|
||||
type WindowsPtyCompatibilityContext
|
||||
@@ -7,6 +8,23 @@ import {
|
||||
|
||||
export type TerminalKeyboardProtocolContext = WindowsPtyCompatibilityContext & {
|
||||
executionHostId: ExecutionHostId
|
||||
/**
|
||||
* Known TUI agent for this pane when available (launchAgent / foreground).
|
||||
* Used only to opt specific agents out of the ConPTY KKP withhold.
|
||||
*/
|
||||
tuiAgent?: TuiAgent | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Agents that correctly decode Kitty CSI-u and need modified-Enter chords
|
||||
* (Shift/Ctrl+Enter) on local Windows ConPTY. Global ConPTY withhold (#2434)
|
||||
* targets CSI-u-blind CLIs (e.g. Antigravity); Grok is not in that set and
|
||||
* relies on KKP for interject vs newline (official Grok Build keyboard docs).
|
||||
*/
|
||||
export function prefersKittyKeyboardDespiteWindowsConpty(
|
||||
agent: TuiAgent | null | undefined
|
||||
): boolean {
|
||||
return agent === 'grok'
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -21,10 +39,16 @@ export type TerminalKeyboardProtocolContext = WindowsPtyCompatibilityContext & {
|
||||
* a genuine local Windows ConPTY pane restores standard navigation there while
|
||||
* preserving enhanced keyboard reporting for SSH and macOS/Linux panes (which
|
||||
* decode CSI-u correctly, including inside tmux).
|
||||
*
|
||||
* Exception: when `tuiAgent` is an agent known to need KKP on ConPTY (Grok),
|
||||
* keep the advertisement so modified-Enter chords stay usable.
|
||||
*/
|
||||
export function shouldDisableKittyKeyboardForTerminal(
|
||||
context: TerminalKeyboardProtocolContext
|
||||
): boolean {
|
||||
if (prefersKittyKeyboardDespiteWindowsConpty(context.tuiAgent)) {
|
||||
return false
|
||||
}
|
||||
return isLocalNativeWindowsConpty(context)
|
||||
}
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ describe('buildAgentStartupPlan', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('launches Grok first and injects the prompt after startup', () => {
|
||||
it('launches Grok with the prompt as a positional argv', () => {
|
||||
expect(
|
||||
buildAgentStartupPlan({
|
||||
agent: 'grok',
|
||||
@@ -176,9 +176,9 @@ describe('buildAgentStartupPlan', () => {
|
||||
})
|
||||
).toEqual({
|
||||
agent: 'grok',
|
||||
launchCommand: 'grok',
|
||||
launchCommand: "grok -- 'Trace the failing test'",
|
||||
expectedProcess: 'grok',
|
||||
followupPrompt: 'Trace the failing test',
|
||||
followupPrompt: null,
|
||||
launchConfig: emptyLaunchConfig('grok')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -63,6 +63,8 @@ import {
|
||||
} from './folder-workspace-path-status'
|
||||
import { toast } from 'sonner'
|
||||
import { initialAgentTabViewModeProps } from './native-chat-initial-view-mode'
|
||||
import { getConnectionId } from '@/lib/connection-context'
|
||||
import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability'
|
||||
|
||||
/** Telemetry payload threaded from the launch site to `pty:spawn`. Main
|
||||
* fires `agent_started` only after the spawn succeeds — see
|
||||
@@ -582,7 +584,10 @@ export function ensureWorktreeHasInitialTerminal(
|
||||
launchAgent,
|
||||
...initialAgentTabViewModeProps(store.settings ?? null, {
|
||||
agent: launchAgent,
|
||||
promptDelivery: sequencedStartup?.draftPrompt != null ? 'draft' : undefined
|
||||
promptDelivery: sequencedStartup?.draftPrompt != null ? 'draft' : undefined,
|
||||
nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable(
|
||||
getConnectionId(worktreeId)
|
||||
)
|
||||
})
|
||||
}
|
||||
: {}),
|
||||
@@ -647,7 +652,10 @@ function applyDefaultTerminalTabs(
|
||||
launchAgent,
|
||||
...initialAgentTabViewModeProps(store.settings ?? null, {
|
||||
agent: launchAgent,
|
||||
promptDelivery: isStartupTab && startup?.draftPrompt != null ? 'draft' : undefined
|
||||
promptDelivery: isStartupTab && startup?.draftPrompt != null ? 'draft' : undefined,
|
||||
nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable(
|
||||
getConnectionId(worktreeId)
|
||||
)
|
||||
})
|
||||
}
|
||||
: {}),
|
||||
|
||||
@@ -13,11 +13,16 @@ import {
|
||||
isShellSafeEndpointValue,
|
||||
normalizeHookPayload,
|
||||
parseFormEncodedBody,
|
||||
preparePendingGrokResultDiscovery,
|
||||
readRequestBody,
|
||||
resolveHookSource,
|
||||
writeEndpointFile,
|
||||
type HookListenerState
|
||||
} from './agent-hook-listener'
|
||||
import {
|
||||
clearGrokSessionPathLookupCacheForTests,
|
||||
findGrokChatHistoryBySessionId
|
||||
} from './grok-session-paths'
|
||||
import { makePaneKey } from './stable-pane-id'
|
||||
|
||||
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
|
||||
@@ -51,6 +56,7 @@ describe('shared agent-hook-listener', () => {
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
clearGrokSessionPathLookupCacheForTests()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
@@ -1420,6 +1426,18 @@ describe('shared agent-hook-listener', () => {
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('lets Copilot Stop consume a generic message without scheduling transcript retry', () => {
|
||||
expect(
|
||||
hasPendingAgentResultText('copilot', {
|
||||
payload: {
|
||||
hookEventName: 'Stop',
|
||||
message: 'Copilot final response',
|
||||
transcript_path: '/tmp/copilot-transcript.jsonl'
|
||||
}
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('normalizes Grok hookEventName payloads and keeps prompt across tool events', () => {
|
||||
const prompt = normalizeHookPayload(
|
||||
state,
|
||||
@@ -1463,6 +1481,141 @@ describe('shared agent-hook-listener', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('previews Grok-native tool names (run_terminal_command / search_replace)', () => {
|
||||
const shell = normalizeHookPayload(
|
||||
state,
|
||||
'grok',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: {
|
||||
hookEventName: 'PreToolUse',
|
||||
tool_name: 'run_terminal_command',
|
||||
tool_input: { command: 'git status' }
|
||||
}
|
||||
},
|
||||
'production'
|
||||
)
|
||||
const edit = normalizeHookPayload(
|
||||
state,
|
||||
'grok',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: {
|
||||
hookEventName: 'PreToolUse',
|
||||
toolName: 'search_replace',
|
||||
toolInput: { path: 'src/app.ts', old_string: 'a', new_string: 'b' }
|
||||
}
|
||||
},
|
||||
'production'
|
||||
)
|
||||
expect(shell?.payload).toMatchObject({
|
||||
agentType: 'grok',
|
||||
state: 'working',
|
||||
toolName: 'run_terminal_command',
|
||||
toolInput: 'git status'
|
||||
})
|
||||
expect(edit?.payload).toMatchObject({
|
||||
agentType: 'grok',
|
||||
state: 'working',
|
||||
toolName: 'search_replace',
|
||||
toolInput: 'src/app.ts'
|
||||
})
|
||||
})
|
||||
|
||||
it('maps Grok ask_user_question PreToolUse to waiting with interactivePrompt', () => {
|
||||
const questions = [
|
||||
{
|
||||
question: 'Ship to which region?',
|
||||
options: [{ label: 'us-east', description: 'US East' }]
|
||||
}
|
||||
]
|
||||
const waiting = normalizeHookPayload(
|
||||
state,
|
||||
'grok',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: {
|
||||
hookEventName: 'PreToolUse',
|
||||
tool_name: 'ask_user_question',
|
||||
tool_input: { questions }
|
||||
}
|
||||
},
|
||||
'production'
|
||||
)
|
||||
const answered = normalizeHookPayload(
|
||||
state,
|
||||
'grok',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: {
|
||||
hookEventName: 'post_tool_use',
|
||||
toolName: 'ask_user_question',
|
||||
toolInput: { questions },
|
||||
toolResponse: { selected: ['us-east'] }
|
||||
}
|
||||
},
|
||||
'production'
|
||||
)
|
||||
expect(waiting?.payload).toMatchObject({
|
||||
agentType: 'grok',
|
||||
state: 'waiting',
|
||||
toolName: 'ask_user_question'
|
||||
})
|
||||
expect(waiting?.payload.interactivePrompt).toContain('Ship to which region?')
|
||||
expect(answered?.payload).toMatchObject({
|
||||
agentType: 'grok',
|
||||
state: 'working',
|
||||
toolName: 'ask_user_question'
|
||||
})
|
||||
expect(answered?.payload.interactivePrompt).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not recreate a Grok question card on post_tool_use_failure', () => {
|
||||
const event = normalizeHookPayload(
|
||||
state,
|
||||
'grok',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: {
|
||||
hookEventName: 'post_tool_use_failure',
|
||||
toolName: 'ask_user_question',
|
||||
toolInput: { questions: [{ question: 'Retry?', options: ['yes', 'no'] }] },
|
||||
error: 'cancelled'
|
||||
}
|
||||
},
|
||||
'production'
|
||||
)
|
||||
|
||||
expect(event?.payload.state).toBe('working')
|
||||
expect(event?.payload.interactivePrompt).toBeUndefined()
|
||||
})
|
||||
|
||||
it('maps Grok StopFailure to done', () => {
|
||||
normalizeHookPayload(
|
||||
state,
|
||||
'grok',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: { hookEventName: 'UserPromptSubmit', prompt: 'do work' }
|
||||
},
|
||||
'production'
|
||||
)
|
||||
const done = normalizeHookPayload(
|
||||
state,
|
||||
'grok',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: { hookEventName: 'StopFailure', error: 'api timeout' }
|
||||
},
|
||||
'production'
|
||||
)
|
||||
expect(done?.payload).toMatchObject({
|
||||
agentType: 'grok',
|
||||
state: 'done',
|
||||
prompt: 'do work'
|
||||
})
|
||||
})
|
||||
|
||||
it('strips Grok internal user_query wrapper before caching the prompt', () => {
|
||||
const prompt = normalizeHookPayload(
|
||||
state,
|
||||
@@ -1600,7 +1753,7 @@ describe('shared agent-hook-listener', () => {
|
||||
expect(event).toBeNull()
|
||||
})
|
||||
|
||||
it('reads Grok final assistant text from chat history on Stop', () => {
|
||||
it('enriches Grok Stop from chat history despite a generic status message', () => {
|
||||
const tmpDir = mkdtempSync(join(tmpdir(), 'orca-grok-session-'))
|
||||
const sessionId = '019e37f4-5135-7b63-a4ab-6d13aa6bf528'
|
||||
const cwd = join(tmpDir, 'workspace')
|
||||
@@ -1624,18 +1777,82 @@ describe('shared agent-hook-listener', () => {
|
||||
'production'
|
||||
)
|
||||
|
||||
const body = {
|
||||
paneKey: PANE_KEY,
|
||||
payload: { hookEventName: 'Stop', sessionId, cwd, message: 'Session completed' }
|
||||
}
|
||||
expect(hasPendingAgentResultText('grok', body)).toBe(true)
|
||||
const done = normalizeHookPayload(state, 'grok', body, 'production')
|
||||
|
||||
expect(done?.payload.state).toBe('done')
|
||||
expect(done?.payload.lastAssistantMessage).toBe('Hi! How can I help you today?')
|
||||
} finally {
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('uses the hook envelope Grok home instead of the listener service environment', () => {
|
||||
const tmpDir = mkdtempSync(join(tmpdir(), 'orca-grok-envelope-home-'))
|
||||
const serviceGrokHome = join(tmpDir, 'service-grok')
|
||||
const hookGrokHome = join(tmpDir, 'hook-grok')
|
||||
const sessionId = '019e37f4-5135-7b63-a4ab-6d13aa6bf529'
|
||||
const cwd = join(tmpDir, 'workspace')
|
||||
const sessionDir = join(hookGrokHome, 'sessions', encodeURIComponent(cwd), sessionId)
|
||||
try {
|
||||
vi.stubEnv('GROK_HOME', serviceGrokHome)
|
||||
mkdirSync(sessionDir, { recursive: true })
|
||||
writeFileSync(
|
||||
join(sessionDir, 'chat_history.jsonl'),
|
||||
`${JSON.stringify({ type: 'assistant', content: 'from effective Grok home' })}\n`
|
||||
)
|
||||
|
||||
const done = normalizeHookPayload(
|
||||
state,
|
||||
'grok',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
grokHome: hookGrokHome,
|
||||
payload: { hookEventName: 'Stop', sessionId, cwd }
|
||||
},
|
||||
'production'
|
||||
)
|
||||
|
||||
expect(done?.payload.state).toBe('done')
|
||||
expect(done?.payload.lastAssistantMessage).toBe('Hi! How can I help you today?')
|
||||
expect(done?.payload.lastAssistantMessage).toBe('from effective Grok home')
|
||||
} finally {
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it.each([
|
||||
'relative/grok-home',
|
||||
join(tmpdir(), 'x'.repeat(4096)),
|
||||
`${join(tmpdir(), 'grok-home')}\ninvalid`
|
||||
])('ignores invalid hook-envelope Grok home %s', (grokHome) => {
|
||||
const tmpDir = mkdtempSync(join(tmpdir(), 'orca-grok-invalid-home-'))
|
||||
const serviceGrokHome = join(tmpDir, 'service-grok')
|
||||
const sessionId = '019e37f4-5135-7b63-a4ab-6d13aa6bf530'
|
||||
const cwd = join(tmpDir, 'workspace')
|
||||
const sessionDir = join(serviceGrokHome, 'sessions', encodeURIComponent(cwd), sessionId)
|
||||
try {
|
||||
vi.stubEnv('GROK_HOME', serviceGrokHome)
|
||||
mkdirSync(sessionDir, { recursive: true })
|
||||
writeFileSync(
|
||||
join(sessionDir, 'chat_history.jsonl'),
|
||||
`${JSON.stringify({ type: 'assistant', content: 'fallback result' })}\n`
|
||||
)
|
||||
|
||||
const done = normalizeHookPayload(
|
||||
state,
|
||||
'grok',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
grokHome,
|
||||
payload: { hookEventName: 'Stop', sessionId, cwd }
|
||||
},
|
||||
'production'
|
||||
)
|
||||
|
||||
expect(done?.payload.lastAssistantMessage).toBe('fallback result')
|
||||
} finally {
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
}
|
||||
@@ -1683,6 +1900,50 @@ describe('shared agent-hook-listener', () => {
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('enriches a long-cwd Grok result after async discovery completes', async () => {
|
||||
const tmpDir = mkdtempSync(join(tmpdir(), 'orca-grok-pending-home-'))
|
||||
const hookGrokHome = join(tmpDir, 'hook-grok')
|
||||
const sessionId = '019e37f4-5135-7b63-a4ab-6d13aa6bf531'
|
||||
const cwd = `/${'long-workspace/'.repeat(30)}`
|
||||
const sessionDir = join(hookGrokHome, 'sessions', 'workspace-slug', sessionId)
|
||||
try {
|
||||
mkdirSync(sessionDir, { recursive: true })
|
||||
writeFileSync(
|
||||
join(sessionDir, 'chat_history.jsonl'),
|
||||
`${JSON.stringify({ type: 'assistant', content: 'from slug session' })}\n`
|
||||
)
|
||||
|
||||
const body = {
|
||||
paneKey: PANE_KEY,
|
||||
grokHome: hookGrokHome,
|
||||
payload: { hookEventName: 'SessionEnd', sessionId, cwd }
|
||||
}
|
||||
const discovery = preparePendingGrokResultDiscovery('grok', body)
|
||||
expect(discovery).not.toBeNull()
|
||||
await discovery
|
||||
await expect(
|
||||
findGrokChatHistoryBySessionId(join(hookGrokHome, 'sessions'), sessionId)
|
||||
).resolves.toBe(join(sessionDir, 'chat_history.jsonl'))
|
||||
|
||||
const done = normalizeHookPayload(state, 'grok', body, 'production')
|
||||
expect(done?.payload.lastAssistantMessage).toBe('from slug session')
|
||||
} finally {
|
||||
rmSync(tmpDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('does not schedule Grok discovery for an invalid session id', () => {
|
||||
expect(
|
||||
hasPendingAgentResultText('grok', {
|
||||
payload: {
|
||||
hookEventName: 'SessionEnd',
|
||||
sessionId: '../escape',
|
||||
cwd: '/tmp/workspace'
|
||||
}
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('normalizes Hermes pre_llm_call to a working turn with prompt text', () => {
|
||||
const event = normalizeHookPayload(
|
||||
state,
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
unlinkSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { isAbsolute, join } from 'node:path'
|
||||
|
||||
import { parseAgentStatusPayload, type ParsedAgentStatusPayload } from './agent-status-types'
|
||||
import { ORCA_HOOK_PROTOCOL_VERSION } from './agent-hook-types'
|
||||
@@ -36,6 +36,15 @@ import {
|
||||
} from './agent-session-resume'
|
||||
import { parsePaneKey } from './stable-pane-id'
|
||||
import { isHarnessInjectedUserTurnText } from './harness-injected-user-turns'
|
||||
import {
|
||||
buildGrokChatHistoryPathCandidates,
|
||||
findGrokChatHistoryBySessionId,
|
||||
getCachedGrokChatHistoryBySessionId,
|
||||
GROK_SESSION_ID_MAX_LENGTH,
|
||||
isSafeGrokSessionId,
|
||||
resolveGrokChatHistoryPathSync,
|
||||
resolveGrokSessionsDir
|
||||
} from './grok-session-paths'
|
||||
|
||||
/** Maximum request body size accepted by the listener (1 MB). */
|
||||
export const HOOK_REQUEST_MAX_BYTES = 1_000_000
|
||||
@@ -492,11 +501,19 @@ const TOOL_INPUT_KEYS_BY_TOOL: Record<string, readonly string[]> = {
|
||||
exec_command: ['cmd', 'command'],
|
||||
shell_command: ['cmd', 'command'],
|
||||
run_terminal_cmd: ['command'],
|
||||
// Why: Grok maps Bash/Edit/Write to snake_case first-party tool names
|
||||
// (run_terminal_command, search_replace, …). Without these keys the status
|
||||
// row shows a blank toolInput for the bulk of Grok tool turns.
|
||||
run_terminal_command: ['command'],
|
||||
search_replace: ['file_path', 'path', 'filePath'],
|
||||
write_to_file: ['TargetFile', 'path', 'file_path'],
|
||||
execute_code: ['code', 'command', 'cmd'],
|
||||
apply_patch: ['path', 'file_path'],
|
||||
view_image: ['path', 'file_path'],
|
||||
AskUser: ['question', 'prompt', 'message'],
|
||||
ask_user: ['question', 'prompt', 'message'],
|
||||
AskUserQuestion: ['questions', 'question', 'prompt', 'message'],
|
||||
ask_user_question: ['questions', 'question', 'prompt', 'message'],
|
||||
bash: ['command'],
|
||||
powershell: ['command'],
|
||||
create: ['path', 'file_path'],
|
||||
@@ -517,7 +534,6 @@ const TOOL_INPUT_KEYS_BY_TOOL: Record<string, readonly string[]> = {
|
||||
skill_manage: ['action', 'name', 'file_path'],
|
||||
delegate_task: ['task', 'prompt', 'description'],
|
||||
view_file: ['AbsolutePath', 'path', 'file_path'],
|
||||
write_to_file: ['TargetFile', 'path', 'file_path'],
|
||||
replace_file_content: ['TargetFile', 'path', 'file_path'],
|
||||
multi_replace_file_content: ['TargetFile', 'path', 'file_path'],
|
||||
list_dir: ['DirectoryPath', 'path'],
|
||||
@@ -528,7 +544,9 @@ const TOOL_INPUT_KEYS_BY_TOOL: Record<string, readonly string[]> = {
|
||||
manage_task: ['TaskId', 'Action'],
|
||||
schedule: ['Prompt', 'DurationSeconds', 'CronExpression'],
|
||||
ask_question: ['question', 'questions'],
|
||||
ask_permission: ['Action', 'Target', 'Reason']
|
||||
ask_permission: ['Action', 'Target', 'Reason'],
|
||||
spawn_subagent: ['prompt', 'description', 'subagent_type'],
|
||||
open_page: ['url']
|
||||
}
|
||||
|
||||
const FALLBACK_TOOL_INPUT_KEYS = [
|
||||
@@ -673,14 +691,14 @@ function deriveInteractivePrompt(
|
||||
toolInput: unknown,
|
||||
eventName?: unknown
|
||||
): string | undefined {
|
||||
// Why: an AskUserQuestion is pending only on the Pre/Permission event. On
|
||||
// PostToolUse it has already been answered, so re-asserting the `{questions}`
|
||||
// prompt would re-show an answered card instead of letting it clear. The live
|
||||
// working indicator keys off agentStatus.state (not this prompt), so dropping
|
||||
// it here doesn't suppress it.
|
||||
// Why: providers vary event casing; any post-tool event means the question is
|
||||
// no longer pending and must not recreate its answered live card.
|
||||
const normalizedEventName = normalizeHookEventName(eventName)
|
||||
const isPostToolEvent =
|
||||
normalizedEventName === 'post_tool_use' || normalizedEventName === 'post_tool_use_failure'
|
||||
if (
|
||||
isAskUserQuestionTool(toolName) &&
|
||||
eventName !== 'PostToolUse' &&
|
||||
!isPostToolEvent &&
|
||||
toolInput !== undefined &&
|
||||
toolInput !== null
|
||||
) {
|
||||
@@ -761,8 +779,8 @@ const TRANSCRIPT_CHUNK_BYTES = 64 * 1024
|
||||
const TRANSCRIPT_MAX_SCAN_BYTES = 4 * 1024 * 1024
|
||||
const AMP_THREAD_ID_MAX_LENGTH = 256
|
||||
const AMP_MAX_SCOPED_THREAD_CACHE_KEYS = 32
|
||||
const GROK_SESSION_ID_MAX_LENGTH = 128
|
||||
const GROK_SESSION_CWD_MAX_LENGTH = 4096
|
||||
const GROK_HOME_ENVELOPE_MAX_LENGTH = 4096
|
||||
|
||||
function extractAssistantTextFromLine(line: string): string | undefined {
|
||||
let entry: unknown
|
||||
@@ -1031,38 +1049,92 @@ function readBoundedString(
|
||||
return value && value.length <= maxLength ? value : undefined
|
||||
}
|
||||
|
||||
function isSafeGrokSessionId(sessionId: string): boolean {
|
||||
return /^[A-Za-z0-9_-]+$/.test(sessionId) && sessionId.length <= GROK_SESSION_ID_MAX_LENGTH
|
||||
function readGrokHomeEnvelope(record: Record<string, unknown>): string | undefined {
|
||||
const value = readBoundedString(record, ['grokHome'], GROK_HOME_ENVELOPE_MAX_LENGTH)
|
||||
if (!value || value !== value.trim() || !isAbsolute(value) || hasControlCharacter(value)) {
|
||||
return undefined
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
function getGrokChatHistoryPath(hookPayload: Record<string, unknown>): string | undefined {
|
||||
function hasControlCharacter(value: string): boolean {
|
||||
return Array.from(value).some((character) => {
|
||||
const code = character.charCodeAt(0)
|
||||
return code <= 0x1f || code === 0x7f
|
||||
})
|
||||
}
|
||||
|
||||
type GrokSessionMetadata = {
|
||||
sessionId: string
|
||||
cwd?: string
|
||||
sessionsDir: string
|
||||
}
|
||||
|
||||
function readGrokSessionMetadata(
|
||||
hookPayload: Record<string, unknown>,
|
||||
grokHome?: string
|
||||
): GrokSessionMetadata | undefined {
|
||||
const sessionId = readBoundedString(
|
||||
hookPayload,
|
||||
['sessionId', 'session_id'],
|
||||
GROK_SESSION_ID_MAX_LENGTH
|
||||
)
|
||||
if (!sessionId || !isSafeGrokSessionId(sessionId)) {
|
||||
return undefined
|
||||
}
|
||||
const cwd = readBoundedString(
|
||||
hookPayload,
|
||||
['cwd', 'workspaceRoot', 'workspace_root'],
|
||||
GROK_SESSION_CWD_MAX_LENGTH
|
||||
)
|
||||
if (!sessionId || !cwd || !isSafeGrokSessionId(sessionId)) {
|
||||
// Why: hook scripts report the effective per-PTY/remote home; old scripts
|
||||
// fall back to the listener runtime's Grok home for compatibility.
|
||||
const sessionsDir = grokHome
|
||||
? join(grokHome, 'sessions')
|
||||
: resolveGrokSessionsDir(process.env, homedir())
|
||||
return { sessionId, cwd, sessionsDir }
|
||||
}
|
||||
|
||||
function getGrokChatHistoryPath(
|
||||
hookPayload: Record<string, unknown>,
|
||||
grokHome?: string
|
||||
): string | undefined {
|
||||
const metadata = readGrokSessionMetadata(hookPayload, grokHome)
|
||||
if (!metadata) {
|
||||
return undefined
|
||||
}
|
||||
return join(
|
||||
homedir(),
|
||||
'.grok',
|
||||
'sessions',
|
||||
encodeURIComponent(cwd),
|
||||
sessionId,
|
||||
'chat_history.jsonl'
|
||||
const resolved = resolveGrokChatHistoryPathSync({
|
||||
sessionId: metadata.sessionId,
|
||||
cwd: metadata.cwd ?? null,
|
||||
sessionsDir: metadata.sessionsDir
|
||||
})
|
||||
if (resolved) {
|
||||
return resolved
|
||||
}
|
||||
const cached = getCachedGrokChatHistoryBySessionId(metadata.sessionsDir, metadata.sessionId)
|
||||
if (cached) {
|
||||
return cached
|
||||
}
|
||||
// Why: hasPendingAgentResultText only needs a plausible on-disk target when
|
||||
// the file may not exist yet (SessionEnd can race the last write). Prefer a
|
||||
// short-cwd candidate when available; async discovery caches slug groups.
|
||||
if (!metadata.cwd) {
|
||||
return undefined
|
||||
}
|
||||
return (
|
||||
buildGrokChatHistoryPathCandidates({
|
||||
sessionId: metadata.sessionId,
|
||||
cwd: metadata.cwd,
|
||||
sessionsDir: metadata.sessionsDir
|
||||
})[0] ?? undefined
|
||||
)
|
||||
}
|
||||
|
||||
function readLastAssistantFromGrokChatHistory(
|
||||
hookPayload: Record<string, unknown>
|
||||
hookPayload: Record<string, unknown>,
|
||||
grokHome?: string
|
||||
): string | undefined {
|
||||
const chatHistoryPath = getGrokChatHistoryPath(hookPayload)
|
||||
const chatHistoryPath = getGrokChatHistoryPath(hookPayload, grokHome)
|
||||
if (!chatHistoryPath) {
|
||||
return undefined
|
||||
}
|
||||
@@ -1076,12 +1148,15 @@ export function hasPendingAgentResultText(source: AgentHookSource, body: unknown
|
||||
if (!record) {
|
||||
return false
|
||||
}
|
||||
const directMessage =
|
||||
record.last_assistant_message ?? record.lastAssistantMessage ?? record.message
|
||||
if (typeof directMessage === 'string' && directMessage.trim().length > 0) {
|
||||
if (hasExplicitLastAssistantResult(record)) {
|
||||
return false
|
||||
}
|
||||
if (source === 'copilot') {
|
||||
// Why: Copilot Stop consumes generic `message` as its final assistant text;
|
||||
// Grok and Antigravity use that field for status text instead.
|
||||
if (hasNonEmptyString(record.message)) {
|
||||
return false
|
||||
}
|
||||
const transcriptPath = record.transcript_path ?? record.transcriptPath
|
||||
return typeof transcriptPath === 'string' && transcriptPath.trim().length > 0
|
||||
}
|
||||
@@ -1097,15 +1172,61 @@ export function hasPendingAgentResultText(source: AgentHookSource, body: unknown
|
||||
const transcriptPath = record.transcriptPath ?? record.transcript_path
|
||||
return typeof transcriptPath === 'string' && transcriptPath.trim().length > 0
|
||||
}
|
||||
if (
|
||||
source === 'grok' &&
|
||||
isGrokEvent(record.hookEventName ?? record.hook_event_name, 'stop', 'session_end')
|
||||
) {
|
||||
return getGrokChatHistoryPath(record) !== undefined
|
||||
const pendingGrokDiscovery = preparePendingGrokResultDiscovery(source, body)
|
||||
if (pendingGrokDiscovery) {
|
||||
void pendingGrokDiscovery
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function hasNonEmptyString(value: unknown): boolean {
|
||||
return typeof value === 'string' && value.trim().length > 0
|
||||
}
|
||||
|
||||
function hasExplicitLastAssistantResult(record: Record<string, unknown>): boolean {
|
||||
return (
|
||||
hasNonEmptyString(record.last_assistant_message) ||
|
||||
hasNonEmptyString(record.lastAssistantMessage)
|
||||
)
|
||||
}
|
||||
|
||||
/** Start bounded discovery only for a Grok completion that still needs result text. */
|
||||
export function preparePendingGrokResultDiscovery(
|
||||
source: AgentHookSource,
|
||||
body: unknown
|
||||
): Promise<void> | null {
|
||||
if (source !== 'grok') {
|
||||
return null
|
||||
}
|
||||
const envelope =
|
||||
typeof body === 'object' && body !== null ? (body as Record<string, unknown>) : null
|
||||
const record = parseHookBodyPayloadRecord(body)
|
||||
if (!record || hasExplicitLastAssistantResult(record)) {
|
||||
return null
|
||||
}
|
||||
const eventName =
|
||||
envelope?.hook_event_name ??
|
||||
envelope?.hookEventName ??
|
||||
record.hook_event_name ??
|
||||
record.hookEventName
|
||||
if (!isGrokEvent(eventName, 'stop', 'session_end')) {
|
||||
return null
|
||||
}
|
||||
const metadata = readGrokSessionMetadata(
|
||||
record,
|
||||
envelope ? readGrokHomeEnvelope(envelope) : undefined
|
||||
)
|
||||
if (!metadata) {
|
||||
return null
|
||||
}
|
||||
// Why: the server can await this signal without moving filesystem discovery
|
||||
// back into the synchronous hook normalization path.
|
||||
return findGrokChatHistoryBySessionId(metadata.sessionsDir, metadata.sessionId).then(
|
||||
() => undefined
|
||||
)
|
||||
}
|
||||
|
||||
function readLastAssistantFromTranscriptOnce(transcriptPath: string): string | undefined {
|
||||
return readLastTextFromTranscriptOnce(transcriptPath, extractAssistantTextFromLine)
|
||||
}
|
||||
@@ -1842,20 +1963,24 @@ function isGrokEvent(eventName: unknown, ...expected: readonly string[]): boolea
|
||||
|
||||
function extractGrokToolFields(
|
||||
eventName: unknown,
|
||||
hookPayload: Record<string, unknown>
|
||||
hookPayload: Record<string, unknown>,
|
||||
grokHome?: string
|
||||
): ToolSnapshot {
|
||||
if (isGrokEvent(eventName, 'pre_tool_use', 'post_tool_use', 'post_tool_use_failure')) {
|
||||
const toolName =
|
||||
readString(hookPayload, 'toolName') ??
|
||||
readString(hookPayload, 'tool_name') ??
|
||||
readString(hookPayload, 'name')
|
||||
const rawInput =
|
||||
hookPayload.toolInput ?? hookPayload.tool_input ?? hookPayload.input ?? hookPayload.arguments
|
||||
const toolInput =
|
||||
deriveToolInputPreview(toolName, hookPayload.toolInput) ??
|
||||
deriveToolInputPreview(toolName, hookPayload.tool_input) ??
|
||||
deriveToolInputPreview(toolName, hookPayload.input) ??
|
||||
deriveToolInputPreview(toolName, hookPayload.arguments)
|
||||
deriveToolInputPreview(toolName, rawInput) ?? deriveFallbackToolInputPreview(rawInput)
|
||||
// Why: Grok's ask_user_question is auto-allowed and arrives as PreToolUse
|
||||
// (not PermissionRequest). Capture the full question payload so the live
|
||||
// card path can render options instead of only a waiting Notification.
|
||||
const interactivePrompt = deriveInteractivePrompt(toolName, rawInput, eventName)
|
||||
const update: ToolSnapshot = toolUpdate(
|
||||
{ toolName, toolInput },
|
||||
{ toolName, toolInput, interactivePrompt },
|
||||
{
|
||||
hasToolInputField: hasAnyOwnField(hookPayload, [
|
||||
'toolInput',
|
||||
@@ -1879,7 +2004,7 @@ function extractGrokToolFields(
|
||||
}
|
||||
return update
|
||||
}
|
||||
if (isGrokEvent(eventName, 'stop', 'session_end')) {
|
||||
if (isGrokEvent(eventName, 'stop', 'session_end', 'stop_failure')) {
|
||||
const direct =
|
||||
readString(hookPayload, 'lastAssistantMessage') ??
|
||||
readString(hookPayload, 'last_assistant_message')
|
||||
@@ -1892,7 +2017,7 @@ function extractGrokToolFields(
|
||||
if (fromTranscript) {
|
||||
return { lastAssistantMessage: fromTranscript }
|
||||
}
|
||||
const fromChatHistory = readLastAssistantFromGrokChatHistory(hookPayload)
|
||||
const fromChatHistory = readLastAssistantFromGrokChatHistory(hookPayload, grokHome)
|
||||
if (fromChatHistory) {
|
||||
return { lastAssistantMessage: fromChatHistory }
|
||||
}
|
||||
@@ -2115,7 +2240,8 @@ function hasExplicitUserPrompt(
|
||||
function extractToolFields(
|
||||
source: AgentHookSource,
|
||||
eventName: unknown,
|
||||
hookPayload: Record<string, unknown>
|
||||
hookPayload: Record<string, unknown>,
|
||||
options?: { grokHome?: string }
|
||||
): ToolSnapshot {
|
||||
// Why: exhaustive switch so adding a source to AgentHookSource fails
|
||||
// typecheck here instead of silently routing through OpenCode's extractor.
|
||||
@@ -2145,7 +2271,7 @@ function extractToolFields(
|
||||
case 'command-code':
|
||||
return extractCommandCodeToolFields(eventName, hookPayload)
|
||||
case 'grok':
|
||||
return extractGrokToolFields(eventName, hookPayload)
|
||||
return extractGrokToolFields(eventName, hookPayload, options?.grokHome)
|
||||
case 'copilot':
|
||||
return extractCopilotToolFields(normalizeCopilotEventName(eventName), hookPayload)
|
||||
case 'hermes':
|
||||
@@ -3013,7 +3139,8 @@ function normalizeGrokEvent(
|
||||
eventName: unknown,
|
||||
promptText: string,
|
||||
paneKey: string,
|
||||
hookPayload: Record<string, unknown>
|
||||
hookPayload: Record<string, unknown>,
|
||||
grokHome?: string
|
||||
): ParsedAgentStatusPayload | null {
|
||||
if (isGrokEvent(eventName, 'session_start')) {
|
||||
// Why: Grok emits SessionStart when the TUI opens/resumes. It should reset
|
||||
@@ -3026,18 +3153,25 @@ function normalizeGrokEvent(
|
||||
const notificationMessage = readString(hookPayload, 'message')
|
||||
const notificationType = getGrokNotificationType(hookPayload)
|
||||
const notificationLevel = readString(hookPayload, 'level')
|
||||
const preToolName =
|
||||
readString(hookPayload, 'toolName') ??
|
||||
readString(hookPayload, 'tool_name') ??
|
||||
readString(hookPayload, 'name')
|
||||
// Why: Grok's ask_user_question is auto-allowed, so it emits PreToolUse while
|
||||
// blocked on a human answer (same shape as Kimi). Map that to waiting so the
|
||||
// sidebar attention state matches Claude PermissionRequest UX.
|
||||
const isUserInputPreTool =
|
||||
isGrokEvent(eventName, 'pre_tool_use') && isAskUserQuestionTool(preToolName)
|
||||
|
||||
let stateName: 'working' | 'waiting' | 'done' | null = null
|
||||
if (
|
||||
isGrokEvent(
|
||||
eventName,
|
||||
'user_prompt_submit',
|
||||
'pre_tool_use',
|
||||
'post_tool_use',
|
||||
'post_tool_use_failure'
|
||||
)
|
||||
isGrokEvent(eventName, 'user_prompt_submit', 'post_tool_use', 'post_tool_use_failure') ||
|
||||
(isGrokEvent(eventName, 'pre_tool_use') && !isUserInputPreTool)
|
||||
) {
|
||||
stateName = 'working'
|
||||
} else if (isGrokEvent(eventName, 'stop', 'session_end')) {
|
||||
} else if (isUserInputPreTool) {
|
||||
stateName = 'waiting'
|
||||
} else if (isGrokEvent(eventName, 'stop', 'session_end', 'stop_failure')) {
|
||||
stateName = 'done'
|
||||
} else if (
|
||||
isGrokEvent(eventName, 'notification') &&
|
||||
@@ -3066,7 +3200,7 @@ function normalizeGrokEvent(
|
||||
const snapshot = resolveToolState(
|
||||
state,
|
||||
paneKey,
|
||||
extractToolFields('grok', eventName, hookPayload),
|
||||
extractToolFields('grok', eventName, hookPayload, { grokHome }),
|
||||
{ resetOnNewTurn: isNewTurnEvent('grok', eventName) }
|
||||
)
|
||||
|
||||
@@ -3300,7 +3434,14 @@ export function normalizeHookPayload(
|
||||
)
|
||||
break
|
||||
case 'grok':
|
||||
payload = normalizeGrokEvent(state, eventName, promptText, paneKey, hookPayloadRecord)
|
||||
payload = normalizeGrokEvent(
|
||||
state,
|
||||
eventName,
|
||||
promptText,
|
||||
paneKey,
|
||||
hookPayloadRecord,
|
||||
readGrokHomeEnvelope(record)
|
||||
)
|
||||
break
|
||||
case 'copilot':
|
||||
payload = normalizeCopilotEvent(state, eventName, promptText, paneKey, hookPayloadRecord)
|
||||
|
||||
@@ -261,6 +261,10 @@ export function getDefaultSettings(homedir: string): GlobalSettings {
|
||||
windowBackgroundBlur: false,
|
||||
minimizeToTrayOnClose: false,
|
||||
terminalClipboardOnSelect: false,
|
||||
// Why: OSC 52 is a classic data-exfiltration vector (any process piping
|
||||
// untrusted output into the terminal can rewrite the clipboard). Keep the
|
||||
// conservative default off; users who need Grok/tmux/nvim remote copy can
|
||||
// enable the toggle. OSC 52 *query* remains disabled separately.
|
||||
terminalAllowOsc52Clipboard: false,
|
||||
claudeAgentTeamsMode: 'off',
|
||||
setupScriptLaunchMode: 'new-tab',
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import { resolve } from 'node:path'
|
||||
|
||||
export const GROK_SESSION_PATH_CACHE_MAX_ENTRIES = 64
|
||||
export const GROK_SESSION_SCAN_ACTIVE_ROOT_MAX = 4
|
||||
export const GROK_SESSION_SCAN_QUEUE_MAX_ENTRIES = 64
|
||||
|
||||
export type GrokSessionPathScanner = (
|
||||
sessionsDir: string,
|
||||
sessionId: string,
|
||||
maxGroupEntries: number
|
||||
) => Promise<string | null>
|
||||
|
||||
type PendingLookup = {
|
||||
key: string
|
||||
rootKey: string
|
||||
sessionsDir: string
|
||||
sessionId: string
|
||||
maxGroupEntries: number
|
||||
resolve: (path: string | null) => void
|
||||
}
|
||||
|
||||
export class GrokSessionPathLookupQueue {
|
||||
private readonly successfulPaths = new Map<string, string>()
|
||||
private readonly inflight = new Map<string, Promise<string | null>>()
|
||||
private readonly activeRoots = new Set<string>()
|
||||
private readonly pending: PendingLookup[] = []
|
||||
private scanner: GrokSessionPathScanner
|
||||
|
||||
constructor(private readonly defaultScanner: GrokSessionPathScanner) {
|
||||
this.scanner = defaultScanner
|
||||
}
|
||||
|
||||
getCached(sessionsDir: string, sessionId: string): string | null {
|
||||
const key = this.lookupKey(sessionsDir, sessionId)
|
||||
const cached = this.successfulPaths.get(key)
|
||||
if (!cached) {
|
||||
return null
|
||||
}
|
||||
this.successfulPaths.delete(key)
|
||||
this.successfulPaths.set(key, cached)
|
||||
return cached
|
||||
}
|
||||
|
||||
find(sessionsDir: string, sessionId: string, maxGroupEntries: number): Promise<string | null> {
|
||||
const key = this.lookupKey(sessionsDir, sessionId)
|
||||
const cached = this.getCached(sessionsDir, sessionId)
|
||||
if (cached) {
|
||||
return Promise.resolve(cached)
|
||||
}
|
||||
const existing = this.inflight.get(key)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
const rootKey = this.rootKey(sessionsDir)
|
||||
let resolveLookup: (path: string | null) => void = () => undefined
|
||||
const lookup = new Promise<string | null>((resolvePromise) => {
|
||||
resolveLookup = resolvePromise
|
||||
})
|
||||
const pending = {
|
||||
key,
|
||||
rootKey,
|
||||
sessionsDir,
|
||||
sessionId,
|
||||
maxGroupEntries,
|
||||
resolve: resolveLookup
|
||||
}
|
||||
if (this.mustQueue(rootKey)) {
|
||||
if (this.pending.length >= GROK_SESSION_SCAN_QUEUE_MAX_ENTRIES) {
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
this.inflight.set(key, lookup)
|
||||
this.pending.push(pending)
|
||||
this.drain()
|
||||
return lookup
|
||||
}
|
||||
this.inflight.set(key, lookup)
|
||||
this.start(pending)
|
||||
return lookup
|
||||
}
|
||||
|
||||
clearForTests(): void {
|
||||
this.successfulPaths.clear()
|
||||
this.inflight.clear()
|
||||
this.activeRoots.clear()
|
||||
for (const pending of this.pending.splice(0)) {
|
||||
pending.resolve(null)
|
||||
}
|
||||
this.scanner = this.defaultScanner
|
||||
}
|
||||
|
||||
setScannerForTests(scanner: GrokSessionPathScanner): void {
|
||||
this.scanner = scanner
|
||||
}
|
||||
|
||||
private rootKey(sessionsDir: string): string {
|
||||
const root = resolve(sessionsDir)
|
||||
return process.platform === 'win32' ? root.toLowerCase() : root
|
||||
}
|
||||
|
||||
private lookupKey(sessionsDir: string, sessionId: string): string {
|
||||
return `${this.rootKey(sessionsDir)}\0${sessionId}`
|
||||
}
|
||||
|
||||
private mustQueue(rootKey: string): boolean {
|
||||
return (
|
||||
this.pending.length > 0 ||
|
||||
this.activeRoots.has(rootKey) ||
|
||||
this.activeRoots.size >= GROK_SESSION_SCAN_ACTIVE_ROOT_MAX
|
||||
)
|
||||
}
|
||||
|
||||
private cache(key: string, path: string): void {
|
||||
this.successfulPaths.delete(key)
|
||||
this.successfulPaths.set(key, path)
|
||||
while (this.successfulPaths.size > GROK_SESSION_PATH_CACHE_MAX_ENTRIES) {
|
||||
const oldest = this.successfulPaths.keys().next().value
|
||||
if (typeof oldest !== 'string') {
|
||||
return
|
||||
}
|
||||
this.successfulPaths.delete(oldest)
|
||||
}
|
||||
}
|
||||
|
||||
private start(pending: PendingLookup): void {
|
||||
this.activeRoots.add(pending.rootKey)
|
||||
void (async () => {
|
||||
try {
|
||||
const path = await this.scanner(
|
||||
pending.sessionsDir,
|
||||
pending.sessionId,
|
||||
pending.maxGroupEntries
|
||||
)
|
||||
if (path) {
|
||||
this.cache(pending.key, path)
|
||||
}
|
||||
pending.resolve(path)
|
||||
} catch {
|
||||
pending.resolve(null)
|
||||
} finally {
|
||||
this.activeRoots.delete(pending.rootKey)
|
||||
this.inflight.delete(pending.key)
|
||||
this.drain()
|
||||
}
|
||||
})()
|
||||
}
|
||||
|
||||
private drain(): void {
|
||||
while (this.pending.length > 0 && this.activeRoots.size < GROK_SESSION_SCAN_ACTIVE_ROOT_MAX) {
|
||||
const next = this.pending[0]
|
||||
// Why: strict FIFO avoids starving repeated lookups for one sessions root.
|
||||
if (this.activeRoots.has(next.rootKey)) {
|
||||
return
|
||||
}
|
||||
this.pending.shift()
|
||||
this.start(next)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
GROK_ENCODED_CWD_DIR_MAX_BYTES,
|
||||
GROK_SESSION_SCAN_ACTIVE_ROOT_MAX,
|
||||
GROK_SESSION_SCAN_QUEUE_MAX_ENTRIES,
|
||||
buildGrokChatHistoryPathCandidates,
|
||||
clearGrokSessionPathLookupCacheForTests,
|
||||
findGrokChatHistoryBySessionId,
|
||||
getCachedGrokChatHistoryBySessionId,
|
||||
grokEncodedCwdDirName,
|
||||
isGrokChatHistoryPath,
|
||||
isSafeGrokSessionId,
|
||||
resolveGrokChatHistoryPathSync,
|
||||
resolveGrokHomeDir,
|
||||
resolveGrokSessionsDir,
|
||||
setGrokSessionDirectoryOpenerForTests,
|
||||
setGrokSessionPathScannerForTests
|
||||
} from './grok-session-paths'
|
||||
|
||||
const tempDirs: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
clearGrokSessionPathLookupCacheForTests()
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
function makeRoot(): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'orca-grok-session-paths-'))
|
||||
tempDirs.push(dir)
|
||||
return dir
|
||||
}
|
||||
|
||||
function deferred<T>(): {
|
||||
promise: Promise<T>
|
||||
resolve: (value: T) => void
|
||||
reject: (error: Error) => void
|
||||
} {
|
||||
let resolvePromise: (value: T) => void = () => undefined
|
||||
let rejectPromise: (error: Error) => void = () => undefined
|
||||
const promise = new Promise<T>((resolve, reject) => {
|
||||
resolvePromise = resolve
|
||||
rejectPromise = reject
|
||||
})
|
||||
return { promise, resolve: resolvePromise, reject: rejectPromise }
|
||||
}
|
||||
|
||||
describe('grok-session-paths', () => {
|
||||
it('honors GROK_HOME for home and sessions roots', () => {
|
||||
const root = makeRoot()
|
||||
expect(resolveGrokHomeDir({ GROK_HOME: root }, '/unused')).toBe(root)
|
||||
expect(resolveGrokSessionsDir({ GROK_HOME: root }, '/unused')).toBe(join(root, 'sessions'))
|
||||
expect(resolveGrokHomeDir({}, '/home/ada')).toBe(join('/home/ada', '.grok'))
|
||||
})
|
||||
|
||||
it('refuses to invent encodeURIComponent names longer than 255 bytes', () => {
|
||||
const longCwd = `/${'a'.repeat(200)}/${'b'.repeat(200)}`
|
||||
expect(Buffer.byteLength(encodeURIComponent(longCwd), 'utf8')).toBeGreaterThan(
|
||||
GROK_ENCODED_CWD_DIR_MAX_BYTES
|
||||
)
|
||||
expect(grokEncodedCwdDirName(longCwd)).toBeNull()
|
||||
expect(
|
||||
buildGrokChatHistoryPathCandidates({
|
||||
sessionId: 'sess-1',
|
||||
cwd: longCwd,
|
||||
sessionsDir: '/tmp/sessions'
|
||||
})
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects unsafe session ids and path-special cwd components', async () => {
|
||||
const root = makeRoot()
|
||||
const sessionsDir = join(root, 'sessions')
|
||||
const invalidIds = ['../escape', 'nested/id', 'nested\\id', '.', '..', 'x'.repeat(129)]
|
||||
|
||||
for (const sessionId of invalidIds) {
|
||||
expect(isSafeGrokSessionId(sessionId)).toBe(false)
|
||||
expect(buildGrokChatHistoryPathCandidates({ sessionId, cwd: '/repo', sessionsDir })).toEqual(
|
||||
[]
|
||||
)
|
||||
await expect(findGrokChatHistoryBySessionId(sessionsDir, sessionId)).resolves.toBeNull()
|
||||
expect(isGrokChatHistoryPath('/repo/chat_history.jsonl', sessionId)).toBe(false)
|
||||
}
|
||||
|
||||
expect(isSafeGrokSessionId('019e37f4-5135-7b63-a4ab-6d13aa6bf528')).toBe(true)
|
||||
expect(grokEncodedCwdDirName('.')).toBeNull()
|
||||
expect(grokEncodedCwdDirName('..')).toBeNull()
|
||||
expect(
|
||||
buildGrokChatHistoryPathCandidates({ sessionId: 'safe-id', cwd: '..', sessionsDir })
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('resolves via encodeURIComponent(cwd) when the short path exists', () => {
|
||||
const root = makeRoot()
|
||||
const sessionsDir = join(root, 'sessions')
|
||||
const cwd = '/tmp/work'
|
||||
const sessionId = 'sess-short'
|
||||
const history = join(sessionsDir, encodeURIComponent(cwd), sessionId, 'chat_history.jsonl')
|
||||
mkdirSync(dirname(history), { recursive: true })
|
||||
writeFileSync(history, '{"type":"user"}\n')
|
||||
|
||||
expect(
|
||||
resolveGrokChatHistoryPathSync({
|
||||
sessionId,
|
||||
cwd,
|
||||
sessionsDir
|
||||
})
|
||||
).toBe(history)
|
||||
})
|
||||
|
||||
it('does not synchronously discover a long-cwd slug group', () => {
|
||||
const root = makeRoot()
|
||||
const sessionsDir = join(root, 'sessions')
|
||||
const sessionId = 'sess-long'
|
||||
// Simulate Grok's slug+hash group directory (not encodeURIComponent of cwd).
|
||||
const slugGroup = 'long-path-ab12cd34'
|
||||
const history = join(sessionsDir, slugGroup, sessionId, 'chat_history.jsonl')
|
||||
mkdirSync(dirname(history), { recursive: true })
|
||||
writeFileSync(join(sessionsDir, slugGroup, '.cwd'), '/very/long/path\n')
|
||||
writeFileSync(history, '{"type":"assistant","content":"hi"}\n')
|
||||
|
||||
expect(
|
||||
resolveGrokChatHistoryPathSync({
|
||||
sessionId,
|
||||
cwd: `/${'x'.repeat(300)}`,
|
||||
sessionsDir
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('finds the documented group/session layout asynchronously', async () => {
|
||||
const root = makeRoot()
|
||||
const sessionsDir = join(root, 'sessions')
|
||||
const history = join(sessionsDir, 'slug-hash', 'sess-async', 'chat_history.jsonl')
|
||||
mkdirSync(dirname(history), { recursive: true })
|
||||
writeFileSync(history, '{}\n')
|
||||
|
||||
await expect(findGrokChatHistoryBySessionId(sessionsDir, 'sess-async')).resolves.toBe(history)
|
||||
})
|
||||
|
||||
it('deduplicates concurrent async discovery', async () => {
|
||||
const root = makeRoot()
|
||||
const sessionsDir = join(root, 'sessions')
|
||||
const history = join(sessionsDir, 'slug-hash', 'sess-deduped', 'chat_history.jsonl')
|
||||
mkdirSync(dirname(history), { recursive: true })
|
||||
writeFileSync(history, '{}\n')
|
||||
|
||||
const first = findGrokChatHistoryBySessionId(sessionsDir, 'sess-deduped')
|
||||
const second = findGrokChatHistoryBySessionId(sessionsDir, 'sess-deduped')
|
||||
|
||||
expect(second).toBe(first)
|
||||
await expect(first).resolves.toBe(history)
|
||||
})
|
||||
|
||||
it('reuses a successful discovery from cache without another scan', async () => {
|
||||
const root = makeRoot()
|
||||
const sessionsDir = join(root, 'sessions')
|
||||
const history = join(sessionsDir, 'slug-hash', 'sess-cached', 'chat_history.jsonl')
|
||||
mkdirSync(dirname(history), { recursive: true })
|
||||
writeFileSync(history, '{}\n')
|
||||
|
||||
await expect(findGrokChatHistoryBySessionId(sessionsDir, 'sess-cached')).resolves.toBe(history)
|
||||
rmSync(join(sessionsDir, 'slug-hash'), { recursive: true, force: true })
|
||||
|
||||
expect(getCachedGrokChatHistoryBySessionId(sessionsDir, 'sess-cached')).toBe(history)
|
||||
await expect(findGrokChatHistoryBySessionId(sessionsDir, 'sess-cached')).resolves.toBe(history)
|
||||
})
|
||||
|
||||
it('does not descend below the documented group/session layout', async () => {
|
||||
const root = makeRoot()
|
||||
const sessionsDir = join(root, 'sessions')
|
||||
const nestedDecoy = join(
|
||||
sessionsDir,
|
||||
'group',
|
||||
'other-session',
|
||||
'cache',
|
||||
'sess-target',
|
||||
'chat_history.jsonl'
|
||||
)
|
||||
mkdirSync(dirname(nestedDecoy), { recursive: true })
|
||||
writeFileSync(nestedDecoy, '{}\n')
|
||||
|
||||
expect(
|
||||
resolveGrokChatHistoryPathSync({
|
||||
sessionId: 'sess-target',
|
||||
cwd: '/group',
|
||||
sessionsDir
|
||||
})
|
||||
).toBeNull()
|
||||
await expect(findGrokChatHistoryBySessionId(sessionsDir, 'sess-target')).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('applies the hard group-entry bound to the filesystem iteration subset', async () => {
|
||||
const root = makeRoot()
|
||||
const sessionsDir = join(root, 'sessions')
|
||||
for (const group of ['a-group', 'b-group']) {
|
||||
mkdirSync(join(sessionsDir, group), { recursive: true })
|
||||
}
|
||||
const beyondBound = join(sessionsDir, 'z-target-group', 'sess-bounded', 'chat_history.jsonl')
|
||||
mkdirSync(dirname(beyondBound), { recursive: true })
|
||||
writeFileSync(beyondBound, '{}\n')
|
||||
setGrokSessionDirectoryOpenerForTests(async () => ({
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const name of ['a-group', 'b-group', 'z-target-group']) {
|
||||
yield {
|
||||
name,
|
||||
isDirectory: () => true,
|
||||
isSymbolicLink: () => false
|
||||
}
|
||||
}
|
||||
},
|
||||
async close() {}
|
||||
}))
|
||||
|
||||
await expect(findGrokChatHistoryBySessionId(sessionsDir, 'sess-bounded', 2)).resolves.toBeNull()
|
||||
await expect(findGrokChatHistoryBySessionId(sessionsDir, 'sess-bounded', 3)).resolves.toBe(
|
||||
beyondBound
|
||||
)
|
||||
})
|
||||
|
||||
it('stops the directory iterator after the exact eligible-entry cap and closes it', async () => {
|
||||
let yielded = 0
|
||||
let closed = 0
|
||||
const entries = [
|
||||
{ name: 'file', directory: false, symlink: false },
|
||||
{ name: 'group-a', directory: true, symlink: false },
|
||||
{ name: 'group-b', directory: true, symlink: false },
|
||||
{ name: 'group-c', directory: true, symlink: false }
|
||||
]
|
||||
setGrokSessionDirectoryOpenerForTests(async () => ({
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const entry of entries) {
|
||||
yielded += 1
|
||||
yield {
|
||||
name: entry.name,
|
||||
isDirectory: () => entry.directory,
|
||||
isSymbolicLink: () => entry.symlink
|
||||
}
|
||||
}
|
||||
},
|
||||
async close() {
|
||||
closed += 1
|
||||
}
|
||||
}))
|
||||
|
||||
await expect(
|
||||
findGrokChatHistoryBySessionId('/missing/sessions', 'sess-iterator', 2)
|
||||
).resolves.toBeNull()
|
||||
|
||||
expect(yielded).toBe(3)
|
||||
expect(closed).toBe(1)
|
||||
})
|
||||
|
||||
it('deduplicates the exact promise while a scanner is deferred', async () => {
|
||||
const scan = deferred<string | null>()
|
||||
let calls = 0
|
||||
setGrokSessionPathScannerForTests(async () => {
|
||||
calls += 1
|
||||
return scan.promise
|
||||
})
|
||||
|
||||
const first = findGrokChatHistoryBySessionId('/sessions/a', 'sess-same')
|
||||
const second = findGrokChatHistoryBySessionId('/sessions/a', 'sess-same')
|
||||
expect(second).toBe(first)
|
||||
expect(calls).toBe(1)
|
||||
|
||||
scan.resolve(null)
|
||||
await expect(first).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('runs at most one scan per sessions root', async () => {
|
||||
const scans = new Map<string, ReturnType<typeof deferred<string | null>>>()
|
||||
const started: string[] = []
|
||||
setGrokSessionPathScannerForTests(async (root, sessionId) => {
|
||||
const key = `${root}:${sessionId}`
|
||||
started.push(key)
|
||||
const scan = deferred<string | null>()
|
||||
scans.set(key, scan)
|
||||
return scan.promise
|
||||
})
|
||||
|
||||
const first = findGrokChatHistoryBySessionId('/sessions/root', 'sess-1')
|
||||
const second = findGrokChatHistoryBySessionId('/sessions/root', 'sess-2')
|
||||
expect(started).toEqual(['/sessions/root:sess-1'])
|
||||
|
||||
scans.get('/sessions/root:sess-1')?.resolve(null)
|
||||
await first
|
||||
expect(started).toEqual(['/sessions/root:sess-1', '/sessions/root:sess-2'])
|
||||
scans.get('/sessions/root:sess-2')?.resolve(null)
|
||||
await second
|
||||
})
|
||||
|
||||
it('caps active roots globally and drains queued roots in FIFO order', async () => {
|
||||
const scans = new Map<string, ReturnType<typeof deferred<string | null>>>()
|
||||
const started: string[] = []
|
||||
setGrokSessionPathScannerForTests(async (root) => {
|
||||
started.push(root)
|
||||
const scan = deferred<string | null>()
|
||||
scans.set(root, scan)
|
||||
return scan.promise
|
||||
})
|
||||
const roots = Array.from(
|
||||
{ length: GROK_SESSION_SCAN_ACTIVE_ROOT_MAX + 2 },
|
||||
(_, index) => `/sessions/root-${index}`
|
||||
)
|
||||
const lookups = roots.map((root, index) =>
|
||||
findGrokChatHistoryBySessionId(root, `sess-${index}`)
|
||||
)
|
||||
|
||||
expect(started).toEqual(roots.slice(0, GROK_SESSION_SCAN_ACTIVE_ROOT_MAX))
|
||||
scans.get(roots[0])?.resolve(null)
|
||||
await lookups[0]
|
||||
expect(started.at(-1)).toBe(roots[GROK_SESSION_SCAN_ACTIVE_ROOT_MAX])
|
||||
scans.get(roots[1])?.resolve(null)
|
||||
await lookups[1]
|
||||
expect(started.at(-1)).toBe(roots[GROK_SESSION_SCAN_ACTIVE_ROOT_MAX + 1])
|
||||
|
||||
for (const root of roots.slice(2)) {
|
||||
scans.get(root)?.resolve(null)
|
||||
}
|
||||
await Promise.all(lookups)
|
||||
})
|
||||
|
||||
it('resolves queue overflow to null and drains the bounded queue', async () => {
|
||||
const firstScan = deferred<string | null>()
|
||||
let calls = 0
|
||||
setGrokSessionPathScannerForTests(async () => {
|
||||
calls += 1
|
||||
return calls === 1 ? firstScan.promise : null
|
||||
})
|
||||
const active = findGrokChatHistoryBySessionId('/sessions/overflow', 'sess-active')
|
||||
const queued = Array.from({ length: GROK_SESSION_SCAN_QUEUE_MAX_ENTRIES }, (_, index) =>
|
||||
findGrokChatHistoryBySessionId('/sessions/overflow', `sess-queued-${index}`)
|
||||
)
|
||||
const overflow = findGrokChatHistoryBySessionId('/sessions/overflow', 'sess-overflow')
|
||||
|
||||
await expect(overflow).resolves.toBeNull()
|
||||
expect(calls).toBe(1)
|
||||
firstScan.resolve(null)
|
||||
await expect(active).resolves.toBeNull()
|
||||
await expect(Promise.all(queued)).resolves.toEqual(
|
||||
Array.from({ length: GROK_SESSION_SCAN_QUEUE_MAX_ENTRIES }, () => null)
|
||||
)
|
||||
expect(calls).toBe(1 + GROK_SESSION_SCAN_QUEUE_MAX_ENTRIES)
|
||||
})
|
||||
|
||||
it('cleans up a rejected scan and starts the next queued lookup', async () => {
|
||||
const firstScan = deferred<string | null>()
|
||||
const started: string[] = []
|
||||
setGrokSessionPathScannerForTests(async (_root, sessionId) => {
|
||||
started.push(sessionId)
|
||||
if (sessionId === 'sess-reject') {
|
||||
return firstScan.promise
|
||||
}
|
||||
return null
|
||||
})
|
||||
const rejected = findGrokChatHistoryBySessionId('/sessions/reject', 'sess-reject')
|
||||
const next = findGrokChatHistoryBySessionId('/sessions/reject', 'sess-next')
|
||||
|
||||
firstScan.reject(new Error('scanner failed'))
|
||||
await expect(rejected).resolves.toBeNull()
|
||||
await expect(next).resolves.toBeNull()
|
||||
expect(started).toEqual(['sess-reject', 'sess-next'])
|
||||
})
|
||||
|
||||
it('does not synchronously scan sessions when cwd is absent', async () => {
|
||||
const root = makeRoot()
|
||||
const sessionsDir = join(root, 'sessions')
|
||||
const sessionId = 'sess-env'
|
||||
const history = join(sessionsDir, encodeURIComponent('/repo'), sessionId, 'chat_history.jsonl')
|
||||
mkdirSync(dirname(history), { recursive: true })
|
||||
writeFileSync(history, '{}\n')
|
||||
|
||||
expect(
|
||||
resolveGrokChatHistoryPathSync({
|
||||
sessionId,
|
||||
sessionsDir,
|
||||
env: { GROK_HOME: root }
|
||||
})
|
||||
).toBeNull()
|
||||
await expect(findGrokChatHistoryBySessionId(sessionsDir, sessionId)).resolves.toBe(history)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,294 @@
|
||||
import { lstatSync } from 'node:fs'
|
||||
import { lstat, opendir } from 'node:fs/promises'
|
||||
import { homedir } from 'node:os'
|
||||
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
||||
import {
|
||||
GrokSessionPathLookupQueue,
|
||||
type GrokSessionPathScanner
|
||||
} from './grok-session-path-lookup-queue'
|
||||
|
||||
export {
|
||||
GROK_SESSION_PATH_CACHE_MAX_ENTRIES,
|
||||
GROK_SESSION_SCAN_ACTIVE_ROOT_MAX,
|
||||
GROK_SESSION_SCAN_QUEUE_MAX_ENTRIES,
|
||||
type GrokSessionPathScanner
|
||||
} from './grok-session-path-lookup-queue'
|
||||
|
||||
export const GROK_CHAT_HISTORY_FILE = 'chat_history.jsonl'
|
||||
// Why: Grok URL-encodes the cwd for the sessions group directory. When that
|
||||
// encoded name exceeds 255 bytes it switches to a slug+hash layout.
|
||||
export const GROK_ENCODED_CWD_DIR_MAX_BYTES = 255
|
||||
export const GROK_SESSION_ID_MAX_LENGTH = 128
|
||||
// Why: session discovery runs in hook/main hot paths; one corrupt or enormous
|
||||
// sessions root must not cause unbounded candidate probes.
|
||||
export const GROK_SESSION_GROUP_SCAN_MAX_ENTRIES = 2_048
|
||||
|
||||
export type GrokSessionPathEnv =
|
||||
| NodeJS.ProcessEnv
|
||||
| Partial<Record<'GROK_HOME' | 'HOME' | 'USERPROFILE', string | undefined>>
|
||||
|
||||
/** Official ids are UUIDs; keep legacy/test token ids while rejecting paths. */
|
||||
export function isSafeGrokSessionId(sessionId: string): boolean {
|
||||
return (
|
||||
sessionId.length > 0 &&
|
||||
sessionId.length <= GROK_SESSION_ID_MAX_LENGTH &&
|
||||
/^[A-Za-z0-9_-]+$/.test(sessionId)
|
||||
)
|
||||
}
|
||||
|
||||
/** Resolve Grok's configured home, falling back to the runtime user's home. */
|
||||
export function resolveGrokHomeDir(
|
||||
env: GrokSessionPathEnv = process.env,
|
||||
homeDir: string = homedir()
|
||||
): string {
|
||||
const fromEnv = env.GROK_HOME?.trim()
|
||||
return fromEnv || join(homeDir, '.grok')
|
||||
}
|
||||
|
||||
export function resolveGrokSessionsDir(
|
||||
env: GrokSessionPathEnv = process.env,
|
||||
homeDir: string = homedir()
|
||||
): string {
|
||||
return join(resolveGrokHomeDir(env, homeDir), 'sessions')
|
||||
}
|
||||
|
||||
/** Return Grok's safe cwd-group component, or null for slug/invalid layouts. */
|
||||
export function grokEncodedCwdDirName(cwd: string): string | null {
|
||||
const trimmed = cwd.trim()
|
||||
if (!trimmed) {
|
||||
return null
|
||||
}
|
||||
let encoded: string
|
||||
try {
|
||||
encoded = encodeURIComponent(trimmed)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
// encodeURIComponent deliberately leaves dots untouched; reject path syntax.
|
||||
if (encoded === '.' || encoded === '..' || encoded.includes('/') || encoded.includes('\\')) {
|
||||
return null
|
||||
}
|
||||
return Buffer.byteLength(encoded, 'utf8') <= GROK_ENCODED_CWD_DIR_MAX_BYTES ? encoded : null
|
||||
}
|
||||
|
||||
/** Fast-path candidates when both session id and cwd are known. */
|
||||
export function buildGrokChatHistoryPathCandidates(args: {
|
||||
sessionId: string
|
||||
cwd?: string | null
|
||||
sessionsDir: string
|
||||
}): string[] {
|
||||
const sessionId = args.sessionId.trim()
|
||||
if (!isSafeGrokSessionId(sessionId)) {
|
||||
return []
|
||||
}
|
||||
const cwd = args.cwd?.trim()
|
||||
if (!cwd) {
|
||||
return []
|
||||
}
|
||||
const encoded = grokEncodedCwdDirName(cwd)
|
||||
if (!encoded) {
|
||||
return []
|
||||
}
|
||||
const candidate = join(args.sessionsDir, encoded, sessionId, GROK_CHAT_HISTORY_FILE)
|
||||
return isPathWithin(args.sessionsDir, candidate) ? [candidate] : []
|
||||
}
|
||||
|
||||
/** Resolve only the exact cwd candidate; safe for synchronous hook hot paths. */
|
||||
export function resolveGrokChatHistoryPathSync(args: {
|
||||
sessionId: string
|
||||
cwd?: string | null
|
||||
sessionsDir?: string
|
||||
env?: GrokSessionPathEnv
|
||||
homeDir?: string
|
||||
}): string | null {
|
||||
const sessionId = args.sessionId.trim()
|
||||
if (!isSafeGrokSessionId(sessionId)) {
|
||||
return null
|
||||
}
|
||||
const sessionsDir =
|
||||
args.sessionsDir ?? resolveGrokSessionsDir(args.env ?? process.env, args.homeDir ?? homedir())
|
||||
|
||||
for (const candidate of buildGrokChatHistoryPathCandidates({
|
||||
sessionId,
|
||||
cwd: args.cwd,
|
||||
sessionsDir
|
||||
})) {
|
||||
if (isSafeChatHistoryFileSync(sessionsDir, candidate)) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
type GrokSessionDirectoryEntry = {
|
||||
name: string
|
||||
isDirectory(): boolean
|
||||
isSymbolicLink(): boolean
|
||||
}
|
||||
|
||||
type GrokSessionDirectory = AsyncIterable<GrokSessionDirectoryEntry> & {
|
||||
close(): Promise<void>
|
||||
}
|
||||
|
||||
type GrokSessionDirectoryOpener = (sessionsDir: string) => Promise<GrokSessionDirectory>
|
||||
|
||||
const defaultSessionDirectoryOpener: GrokSessionDirectoryOpener = (sessionsDir) =>
|
||||
opendir(sessionsDir)
|
||||
let sessionDirectoryOpener = defaultSessionDirectoryOpener
|
||||
const sessionPathLookupQueue = new GrokSessionPathLookupQueue(scanGrokChatHistoryBySessionId)
|
||||
|
||||
/** Read a previously resolved path without filesystem work (hook retry path). */
|
||||
export function getCachedGrokChatHistoryBySessionId(
|
||||
sessionsDir: string,
|
||||
sessionId: string
|
||||
): string | null {
|
||||
const trimmedId = sessionId.trim()
|
||||
if (!isSafeGrokSessionId(trimmedId)) {
|
||||
return null
|
||||
}
|
||||
return sessionPathLookupQueue.getCached(sessionsDir, trimmedId)
|
||||
}
|
||||
|
||||
/** Async bounded lookup with inflight dedupe and a small successful-result cache. */
|
||||
export function findGrokChatHistoryBySessionId(
|
||||
sessionsDir: string,
|
||||
sessionId: string,
|
||||
maxGroupEntries = GROK_SESSION_GROUP_SCAN_MAX_ENTRIES
|
||||
): Promise<string | null> {
|
||||
const trimmedId = sessionId.trim()
|
||||
if (!isSafeGrokSessionId(trimmedId)) {
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
return sessionPathLookupQueue.find(sessionsDir, trimmedId, maxGroupEntries)
|
||||
}
|
||||
|
||||
async function scanGrokChatHistoryBySessionId(
|
||||
sessionsDir: string,
|
||||
sessionId: string,
|
||||
maxGroupEntries: number
|
||||
): Promise<string | null> {
|
||||
const max = normalizeGroupEntryLimit(maxGroupEntries)
|
||||
if (max === 0) {
|
||||
return null
|
||||
}
|
||||
let directory: GrokSessionDirectory | undefined
|
||||
try {
|
||||
directory = await sessionDirectoryOpener(sessionsDir)
|
||||
let eligibleEntries = 0
|
||||
// Why: the filesystem's iteration order defines the bounded subset; sorting
|
||||
// would first materialize an unbounded sessions root on the main process.
|
||||
for await (const entry of directory) {
|
||||
if (!entry.isDirectory() || entry.isSymbolicLink()) {
|
||||
continue
|
||||
}
|
||||
eligibleEntries += 1
|
||||
const history = join(sessionsDir, entry.name, sessionId, GROK_CHAT_HISTORY_FILE)
|
||||
if (await isSafeChatHistoryFile(sessionsDir, history)) {
|
||||
return history
|
||||
}
|
||||
if (eligibleEntries >= max) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
return null
|
||||
} catch {
|
||||
return null
|
||||
} finally {
|
||||
if (directory) {
|
||||
try {
|
||||
await directory.close()
|
||||
} catch {
|
||||
// Async iteration closes Node Dir handles automatically; custom/test
|
||||
// iterators still get the explicit close attempt above.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Test isolation for the module-level inflight/success caches. */
|
||||
export function clearGrokSessionPathLookupCacheForTests(): void {
|
||||
sessionPathLookupQueue.clearForTests()
|
||||
sessionDirectoryOpener = defaultSessionDirectoryOpener
|
||||
}
|
||||
|
||||
function normalizeGroupEntryLimit(requestedMax: number): number {
|
||||
return Math.min(
|
||||
GROK_SESSION_GROUP_SCAN_MAX_ENTRIES,
|
||||
Math.max(0, Math.floor(Number.isFinite(requestedMax) ? requestedMax : 0))
|
||||
)
|
||||
}
|
||||
|
||||
/** Replace directory IO for bounded-iterator tests. */
|
||||
export function setGrokSessionDirectoryOpenerForTests(opener: GrokSessionDirectoryOpener): void {
|
||||
sessionDirectoryOpener = opener
|
||||
}
|
||||
|
||||
/** Replace scan IO for queue/concurrency tests. */
|
||||
export function setGrokSessionPathScannerForTests(scanner: GrokSessionPathScanner): void {
|
||||
sessionPathLookupQueue.setScannerForTests(scanner)
|
||||
}
|
||||
|
||||
function isPathWithin(root: string, candidate: string): boolean {
|
||||
const rel = relative(resolve(root), resolve(candidate))
|
||||
return rel.length > 0 && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
|
||||
}
|
||||
|
||||
function candidateSessionDir(candidate: string): string {
|
||||
return dirname(candidate)
|
||||
}
|
||||
|
||||
function isSafeChatHistoryFileSync(sessionsDir: string, candidate: string): boolean {
|
||||
if (!isPathWithin(sessionsDir, candidate)) {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const sessionDir = candidateSessionDir(candidate)
|
||||
const groupStat = lstatSync(dirname(sessionDir))
|
||||
const sessionStat = lstatSync(sessionDir)
|
||||
const fileStat = lstatSync(candidate)
|
||||
return (
|
||||
groupStat.isDirectory() &&
|
||||
!groupStat.isSymbolicLink() &&
|
||||
sessionStat.isDirectory() &&
|
||||
!sessionStat.isSymbolicLink() &&
|
||||
fileStat.isFile() &&
|
||||
!fileStat.isSymbolicLink()
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function isSafeChatHistoryFile(sessionsDir: string, candidate: string): Promise<boolean> {
|
||||
if (!isPathWithin(sessionsDir, candidate)) {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const sessionDir = candidateSessionDir(candidate)
|
||||
const [groupStat, sessionStat, fileStat] = await Promise.all([
|
||||
lstat(dirname(sessionDir)),
|
||||
lstat(sessionDir),
|
||||
lstat(candidate)
|
||||
])
|
||||
return (
|
||||
groupStat.isDirectory() &&
|
||||
!groupStat.isSymbolicLink() &&
|
||||
sessionStat.isDirectory() &&
|
||||
!sessionStat.isSymbolicLink() &&
|
||||
fileStat.isFile() &&
|
||||
!fileStat.isSymbolicLink()
|
||||
)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** True when path looks like a Grok chat history under a safe session id. */
|
||||
export function isGrokChatHistoryPath(path: string, sessionId: string): boolean {
|
||||
const trimmedId = sessionId.trim()
|
||||
return (
|
||||
isSafeGrokSessionId(trimmedId) &&
|
||||
basename(path) === GROK_CHAT_HISTORY_FILE &&
|
||||
basename(dirname(path)) === trimmedId
|
||||
)
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Terminal } from '@xterm/headless'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isTerminalQueryReply } from './terminal-query-reply'
|
||||
|
||||
@@ -36,6 +37,23 @@ describe('isTerminalQueryReply', () => {
|
||||
expect(isTerminalQueryReply('\x1bP>|xterm.js(5.6.0)\x1b\\')).toBe(true)
|
||||
})
|
||||
|
||||
it('classifies the fully framed XTVERSION reply emitted by real xterm', async () => {
|
||||
const terminal = new Terminal()
|
||||
const replies: string[] = []
|
||||
const disposable = terminal.onData((data) => replies.push(data))
|
||||
try {
|
||||
await new Promise<void>((resolve) => terminal.write('\x1b[>q', resolve))
|
||||
expect(replies).toHaveLength(1)
|
||||
const reply = replies[0]
|
||||
expect(reply.startsWith('\x1bP>|xterm.js(')).toBe(true)
|
||||
expect(reply.endsWith(')\x1b\\')).toBe(true)
|
||||
expect(isTerminalQueryReply(reply)).toBe(true)
|
||||
} finally {
|
||||
disposable.dispose()
|
||||
terminal.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('documents the accepted modified-F3/CPR collision', () => {
|
||||
// xterm.js encodes Shift+F3 as CSI 1;2R — byte-identical to a CPR report.
|
||||
// Classified as a reply on purpose: order is still preserved (the immediate
|
||||
|
||||
@@ -28,6 +28,8 @@ export type TuiAgentConfig = {
|
||||
launchCmdByPlatform?: Partial<Record<NodeJS.Platform, string>>
|
||||
expectedProcess: string
|
||||
promptInjectionMode: AgentPromptInjectionMode
|
||||
/** Option terminator required before positional prompts that may look like CLI syntax. */
|
||||
argvPromptSeparator?: '--'
|
||||
/** Why: flag that launches the TUI with the given text already in the
|
||||
* input box but NOT submitted, so the user still gets a reviewable draft.
|
||||
* Only set when the CLI documents native support — e.g. Claude's
|
||||
@@ -345,7 +347,14 @@ export const TUI_AGENT_CONFIG: Record<TuiAgent, TuiAgentConfig> = {
|
||||
detectCmd: 'grok',
|
||||
launchCmd: 'grok',
|
||||
expectedProcess: 'grok',
|
||||
promptInjectionMode: 'stdin-after-start'
|
||||
// Why: Grok CLI accepts an initial prompt as a positional argv
|
||||
// (`grok "fix the bug"`). Prefer argv over stdin-after-start so multi-line
|
||||
// / special-character prompts are not typed as raw PTY keystrokes, and so
|
||||
// clipboard-derived launch text is not mangled by line-edit shortcuts.
|
||||
promptInjectionMode: 'argv',
|
||||
// Why: prompts such as `help` or `--version` otherwise select Grok CLI
|
||||
// syntax instead of starting an interactive turn with that literal text.
|
||||
argvPromptSeparator: '--'
|
||||
},
|
||||
devin: {
|
||||
detectCmd: 'devin',
|
||||
|
||||
@@ -49,6 +49,63 @@ describe('tui agent startup plans', () => {
|
||||
expect(plan?.launchCommand).toBe('claude "fix ^"quoted^" ^& ^%PATH^%"')
|
||||
})
|
||||
|
||||
it('terminates Grok options before a flag-shaped POSIX prompt', () => {
|
||||
const plan = buildAgentStartupPlan({
|
||||
agent: 'grok',
|
||||
prompt: '--version',
|
||||
cmdOverrides: {},
|
||||
platform: 'linux'
|
||||
})
|
||||
|
||||
expect(plan?.launchCommand).toBe("grok -- '--version'")
|
||||
})
|
||||
|
||||
it('terminates Grok options before a flag-shaped PowerShell prompt', () => {
|
||||
const plan = buildAgentStartupPlan({
|
||||
agent: 'grok',
|
||||
prompt: '-h',
|
||||
cmdOverrides: {},
|
||||
platform: 'win32'
|
||||
})
|
||||
|
||||
expect(plan?.launchCommand).toBe("grok -- '-h'")
|
||||
})
|
||||
|
||||
it('terminates Grok options before a subcommand-shaped cmd prompt', () => {
|
||||
const plan = buildAgentStartupPlan({
|
||||
agent: 'grok',
|
||||
prompt: 'help',
|
||||
cmdOverrides: {},
|
||||
platform: 'win32',
|
||||
shell: 'cmd'
|
||||
})
|
||||
|
||||
expect(plan?.launchCommand).toBe('grok -- "help"')
|
||||
})
|
||||
|
||||
it('places the Grok prompt separator after configured agent arguments', () => {
|
||||
const plan = buildAgentStartupPlan({
|
||||
agent: 'grok',
|
||||
prompt: '--version',
|
||||
cmdOverrides: {},
|
||||
agentArgs: '--always-approve',
|
||||
platform: 'win32'
|
||||
})
|
||||
|
||||
expect(plan?.launchCommand).toBe("grok '--always-approve' -- '--version'")
|
||||
})
|
||||
|
||||
it('does not add the Grok prompt separator to other argv agents', () => {
|
||||
const plan = buildAgentStartupPlan({
|
||||
agent: 'codex',
|
||||
prompt: '--version',
|
||||
cmdOverrides: {},
|
||||
platform: 'linux'
|
||||
})
|
||||
|
||||
expect(plan?.launchCommand).toBe("codex '--version'")
|
||||
})
|
||||
|
||||
it('does not launch Codex with the Orca profile when agent status hooks are enabled', () => {
|
||||
const plan = buildAgentStartupPlan({
|
||||
agent: 'codex',
|
||||
|
||||
@@ -118,9 +118,10 @@ export function buildAgentStartupPlan(args: {
|
||||
const quotedPrompt = quoteStartupArg(trimmedPrompt, shell)
|
||||
|
||||
if (config.promptInjectionMode === 'argv') {
|
||||
const promptSeparator = config.argvPromptSeparator ? ` ${config.argvPromptSeparator}` : ''
|
||||
return {
|
||||
agent,
|
||||
launchCommand: `${baseCommand.command} ${quotedPrompt}`,
|
||||
launchCommand: `${baseCommand.command}${promptSeparator} ${quotedPrompt}`,
|
||||
expectedProcess: config.expectedProcess,
|
||||
followupPrompt: null,
|
||||
launchConfig,
|
||||
|
||||
+2
-2
@@ -2597,8 +2597,8 @@ export type GlobalSettings = {
|
||||
* paste with Cmd/Ctrl+V without an intervening Cmd/Ctrl+Shift+C. Defaults
|
||||
* to false so existing users keep the explicit-copy behavior. */
|
||||
terminalClipboardOnSelect: boolean
|
||||
/** Why: lets TUIs like tmux, nvim, and fzf copy to the system clipboard via
|
||||
* the OSC 52 escape sequence — essential for SSH-hosted workflows where
|
||||
/** Why: lets TUIs like Grok, tmux, nvim, and fzf copy to the system clipboard
|
||||
* via the OSC 52 escape sequence — essential for SSH-hosted workflows where
|
||||
* the terminal is the only bridge to the local clipboard. Defaults to
|
||||
* false because OSC 52 is a classic data-exfiltration vector (any
|
||||
* process piping untrusted output into the terminal — `cat attacker.log`
|
||||
|
||||
Reference in New Issue
Block a user