Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
254 changes: 253 additions & 1 deletion config/reliability-gates.jsonc

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion src/main/daemon/daemon-errors.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// Error classes shared across the daemon protocol boundary (client, server,
// host). Split from types.ts, which is capped for wire-shape declarations.

export class TerminalAttachCanceledError extends Error {
constructor(sessionId: string) {
super(`Attach canceled for session ${sessionId}`)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { describe, expect, it } from 'vitest'
import { PREVIOUS_DAEMON_PROTOCOL_VERSIONS, PROTOCOL_VERSION } from './types'

describe('foreground-confirmation daemon protocol', () => {
it('rejects daemons from before the fresh-confirmation RPC', () => {
expect(PROTOCOL_VERSION).toBeGreaterThan(19)
expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(19)
})
})
11 changes: 11 additions & 0 deletions src/main/daemon/daemon-foreground-process-protocol.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export type GetForegroundProcessRequest = {
id: string
type: 'getForegroundProcess'
payload: {
sessionId: string
}
}

export type ConfirmForegroundProcessRequest = Omit<GetForegroundProcessRequest, 'type'> & {
type: 'confirmForegroundProcess'
}
4 changes: 3 additions & 1 deletion src/main/daemon/daemon-pty-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -489,9 +489,10 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => {
describe('spawn with sessionId (reattach)', () => {
it('returns full snapshot and isReattach when reattaching', async () => {
const sessionId = 'reattach-test-session'
const first = await adapter.spawn({ cols: 80, rows: 24, sessionId })
const first = await adapter.spawn({ cols: 80, rows: 24, sessionId, launchAgent: 'droid' })
expect(first.id).toBe(sessionId)
expect(first.isReattach).toBeUndefined()
expect(first.launchAgent).toBe('droid')

// Write data so the headless emulator captures it
lastSubprocess._simulateData('hello from shell\r\n')
Expand All @@ -501,6 +502,7 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => {
const second = await adapter.spawn({ cols: 80, rows: 24, sessionId })
expect(second.id).toBe(sessionId)
expect(second.isReattach).toBe(true)
expect(second.launchAgent).toBe('droid')
expect(second.snapshot).toBeDefined()
expect(second.snapshot).toContain('hello from shell')
})
Expand Down
27 changes: 25 additions & 2 deletions src/main/daemon/daemon-pty-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ export class DaemonPtyAdapter implements IPtyProvider {
envToDelete: opts.envToDelete,
command: opts.command,
startupCommandDelivery: opts.startupCommandDelivery,
launchAgent: opts.launchAgent,
// Why: without this, the daemon always spawns cmd.exe (COMSPEC) or
// PowerShell as a fallback — regardless of which shell the renderer
// asked for in the "+" menu or persisted as the default. Forwarding
Expand All @@ -252,6 +253,8 @@ export class DaemonPtyAdapter implements IPtyProvider {

let scrollback = restoreInfo ? getRecoveredHistorySeed(restoreInfo) : null
let result = await createOrAttach(scrollback)
const launchIdentity = (): { launchAgent?: NonNullable<typeof result.launchAgent> } =>
result.launchAgent ? { launchAgent: result.launchAgent } : {}

if (effectiveCwd) {
this.initialCwds.set(sessionId, effectiveCwd)
Expand All @@ -278,6 +281,7 @@ export class DaemonPtyAdapter implements IPtyProvider {
return {
id: sessionId,
pid,
...launchIdentity(),
coldRestore: cachedRestore,
...(!result.isNew ? { isReattach: true } : {})
}
Expand Down Expand Up @@ -342,11 +346,12 @@ export class DaemonPtyAdapter implements IPtyProvider {
return {
id: sessionId,
pid,
...launchIdentity(),
coldRestore,
...(!result.isNew ? { isReattach: true } : {})
}
}
return { id: sessionId, pid }
return { id: sessionId, pid, ...launchIdentity() }
}

if (this.historyManager && result.isNew) {
Expand Down Expand Up @@ -380,7 +385,12 @@ export class DaemonPtyAdapter implements IPtyProvider {

const isReattach = !result.isNew
if (!isReattach || !result.snapshot) {
return { id: sessionId, pid, ...(isReattach ? { isReattach: true } : {}) }
return {
id: sessionId,
pid,
...launchIdentity(),
...(isReattach ? { isReattach: true } : {})
}
}

const isAltScreen = result.snapshot.modes.alternateScreen
Expand All @@ -396,6 +406,7 @@ export class DaemonPtyAdapter implements IPtyProvider {
return {
id: sessionId,
pid,
...launchIdentity(),
snapshot: snapshotPayload,
snapshotCols: result.snapshot.cols,
snapshotRows: result.snapshot.rows,
Expand Down Expand Up @@ -658,6 +669,18 @@ export class DaemonPtyAdapter implements IPtyProvider {
}
}

async confirmForegroundProcess(id: string): Promise<string | null> {
try {
const result = await this.client.request<{ foregroundProcess: string | null }>(
'confirmForegroundProcess',
{ sessionId: id }
)
return result.foregroundProcess
} catch {
return null
}
}

async serialize(ids: string[]): Promise<string> {
const sessions: Record<string, { initialCwd?: string }> = {}
for (const id of ids) {
Expand Down
17 changes: 17 additions & 0 deletions src/main/daemon/daemon-pty-router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ function createAdapter(
acknowledgeDataEvent: vi.fn(),
hasChildProcesses: vi.fn(async () => false),
getForegroundProcess: vi.fn(async () => null),
confirmForegroundProcess: vi.fn(async () => `${label}-confirmed`),
serialize: vi.fn(async () => '{}'),
revive: vi.fn(async () => {}),
getDefaultShell: vi.fn(async () => '/bin/zsh'),
Expand Down Expand Up @@ -121,6 +122,22 @@ function createAdapter(
}

describe('DaemonPtyRouter', () => {
it('routes fresh foreground confirmation to the session-owning daemon', async () => {
const current = createAdapter('current', ['current-session'])
const legacy = createAdapter('legacy', ['legacy-session'])
const router = new DaemonPtyRouter({ current, legacy: [legacy] })
await router.discoverLegacySessions()

await expect(router.confirmForegroundProcess('legacy-session')).resolves.toBe(
'legacy-confirmed'
)
await expect(router.confirmForegroundProcess('current-session')).resolves.toBe(
'current-confirmed'
)
expect(legacy.confirmForegroundProcess).toHaveBeenCalledWith('legacy-session')
expect(current.confirmForegroundProcess).toHaveBeenCalledWith('current-session')
})

it('routes existing legacy sessions to their old daemon and new sessions to current daemon', async () => {
const current = createAdapter('current')
const legacy = createAdapter('legacy', ['legacy-session'])
Expand Down
4 changes: 4 additions & 0 deletions src/main/daemon/daemon-pty-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,10 @@ export class DaemonPtyRouter implements IPtyProvider {
return this.adapterFor(id).getForegroundProcess(id)
}

async confirmForegroundProcess(id: string): Promise<string | null> {
return this.adapterFor(id).confirmForegroundProcess(id)
}

async serialize(ids: string[]): Promise<string> {
return this.current.serialize(ids)
}
Expand Down
45 changes: 45 additions & 0 deletions src/main/daemon/daemon-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { PROTOCOL_VERSION, type DaemonRequest } from './types'
import type { SubprocessHandle } from './session'
import { getDaemonSocketPath } from './daemon-spawner'

const confirmForegroundProcessMock = vi.fn(async () => 'droid')

function createTestDir(): string {
return mkdtempSync(join(tmpdir(), 'daemon-server-test-'))
}
Expand All @@ -23,6 +25,7 @@ function createMockSubprocess(): SubprocessHandle & {
return {
pid: 55555,
getForegroundProcess: vi.fn(() => null),
confirmForegroundProcess: confirmForegroundProcessMock,
write: vi.fn(),
resize: vi.fn(),
kill: vi.fn(() => setTimeout(() => onExitCb?.(0), 5)),
Expand Down Expand Up @@ -65,6 +68,7 @@ describe('DaemonServer', () => {
let client: DaemonClient

beforeEach(() => {
confirmForegroundProcessMock.mockClear()
dir = createTestDir()
socketPath = getDaemonSocketPath(dir)
tokenPath = join(dir, 'test.token')
Expand Down Expand Up @@ -174,6 +178,34 @@ describe('DaemonServer', () => {
})
})

it('persists only an allowlisted launch identity across reattach', async () => {
await startServer()
const c = await connectClient()

const first = await c.request('createOrAttach', {
sessionId: 'agent-session',
cols: 80,
rows: 24,
launchAgent: 'droid'
})
expect(first).toMatchObject({ isNew: true, launchAgent: 'droid' })

const second = await c.request('createOrAttach', {
sessionId: 'agent-session',
cols: 80,
rows: 24
})
expect(second).toMatchObject({ isNew: false, launchAgent: 'droid' })

const unknown = await c.request('createOrAttach', {
sessionId: 'unknown-agent-session',
cols: 80,
rows: 24,
launchAgent: 'not-an-agent'
} as never)
expect(unknown).not.toHaveProperty('launchAgent')
})

it('handles listSessions', async () => {
await startServer()
const c = await connectClient()
Expand Down Expand Up @@ -279,6 +311,19 @@ describe('DaemonServer', () => {
expect(result.cwd === null || typeof result.cwd === 'string').toBe(true)
})

it('awaits fresh foreground confirmation', async () => {
await startServer()
const c = await connectClient()
await c.request('createOrAttach', { sessionId: 'test-session', cols: 80, rows: 24 })

await expect(
c.request<{ foregroundProcess: string | null }>('confirmForegroundProcess', {
sessionId: 'test-session'
})
).resolves.toEqual({ foregroundProcess: 'droid' })
expect(confirmForegroundProcessMock).toHaveBeenCalledTimes(1)
})

it('returns error for unknown session operations', async () => {
await startServer()
const c = await connectClient()
Expand Down
10 changes: 10 additions & 0 deletions src/main/daemon/daemon-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { readCurrentProcessMacSystemResolverHealth } from '../network/macos-syst
import type { SubprocessHandle } from './session'
import { checkPtySpawnHealth } from './pty-subprocess'
import { createNoopDaemonFileLog, type DaemonFileLog } from './daemon-file-log'
import { isTuiAgent } from '../../shared/tui-agent-config'
import {
PROTOCOL_VERSION,
NOTIFY_PREFIX,
Expand Down Expand Up @@ -341,6 +342,9 @@ export class DaemonServer {
envToDelete: p.envToDelete,
command: p.command,
startupCommandDelivery: p.startupCommandDelivery,
// Why: daemon RPC payloads are untrusted JSON. Persist only the
// allowlisted enum used for byte routing, never arbitrary identity.
...(isTuiAgent(p.launchAgent) ? { launchAgent: p.launchAgent } : {}),
shellOverride: p.shellOverride,
terminalWindowsWslDistro: p.terminalWindowsWslDistro,
terminalWindowsPowerShellImplementation: p.terminalWindowsPowerShellImplementation,
Expand Down Expand Up @@ -406,6 +410,7 @@ export class DaemonServer {
snapshot: result.snapshot,
pid: result.pid,
shellState: result.shellState,
...(result.launchAgent ? { launchAgent: result.launchAgent } : {}),
...(result.historySeeded !== undefined ? { historySeeded: result.historySeeded } : {})
}
}
Expand Down Expand Up @@ -512,6 +517,11 @@ export class DaemonServer {
case 'getForegroundProcess':
return { foregroundProcess: this.host.getForegroundProcess(request.payload.sessionId) }

case 'confirmForegroundProcess':
return {
foregroundProcess: await this.host.confirmForegroundProcess(request.payload.sessionId)
}

case 'clearScrollback':
this.host.clearScrollback(request.payload.sessionId)
return {}
Expand Down
14 changes: 14 additions & 0 deletions src/main/daemon/degraded-daemon-pty-provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ function createProvider(label: string, sessions: string[] = []): ProviderMock {
acknowledgeDataEvent: vi.fn(),
hasChildProcesses: vi.fn(async () => false),
getForegroundProcess: vi.fn(async () => null),
confirmForegroundProcess: vi.fn(async () => `${label}-confirmed`),
serialize: vi.fn(async () => '{}'),
revive: vi.fn(async () => {}),
listProcesses: vi.fn(async () => sessions.map((id) => ({ id, cwd: '', title: label }))),
Expand Down Expand Up @@ -108,6 +109,19 @@ function createDaemonAdapter(
}

describe('DegradedDaemonPtyProvider', () => {
it('routes fresh foreground confirmation to the session owner', async () => {
const current = createDaemonAdapter('daemon', ['daemon-session'])
const fallback = createProvider('fallback')
const provider = new DegradedDaemonPtyProvider({ current, legacy: [], fallback })
await provider.discoverDaemonSessions()
const fresh = await provider.spawn({ cols: 80, rows: 24 })

await expect(provider.confirmForegroundProcess('daemon-session')).resolves.toBe(
'daemon-confirmed'
)
await expect(provider.confirmForegroundProcess(fresh.id)).resolves.toBe('fallback-confirmed')
})

it('routes discovered daemon sessions to the daemon and fresh PTYs to the fallback', async () => {
const current = createDaemonAdapter('daemon', ['daemon-session'])
const fallback = createProvider('fallback')
Expand Down
4 changes: 4 additions & 0 deletions src/main/daemon/degraded-daemon-pty-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ export class DegradedDaemonPtyProvider implements IPtyProvider {
return this.providerFor(id).getForegroundProcess(id)
}

async confirmForegroundProcess(id: string): Promise<string | null> {
return this.providerFor(id).confirmForegroundProcess?.(id) ?? null
}

async serialize(ids: string[]): Promise<string> {
return this.fallback.serialize(ids)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ vi.mock('../providers/windows-powershell-executable', () => ({
}))

vi.mock('../providers/agent-foreground-process', () => ({
resolveAgentForegroundProcess: resolveAgentForegroundProcessMock
resolveAgentForegroundProcessWithAvailability: async (...args: unknown[]) => ({
available: true,
processName: await resolveAgentForegroundProcessMock(...args)
})
}))

import { createPtySubprocess } from './pty-subprocess'
Expand Down
Loading
Loading