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
53 changes: 53 additions & 0 deletions apps/desktop/src/main/terminal/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,59 @@ describe('stripTerminalQueries', () => {
})

describe('TerminalSession command lifecycle', () => {
it('returns the output of a command whose start, output and end arrive in one read', async () => {
const originalShell = process.env.SHELL
process.env.SHELL = '/bin/zsh'
const session = TerminalSession.create({
terminalId: 'terminal-1',
cwd: '/tmp',
cols: 80,
rows: 24,
callbacks: { onData: () => {}, onState: () => {}, onCommand: () => {}, onExit: () => {} },
})

try {
const resultPromise = session.runCommand('printf done', 'tool-call-fast', 5_000)
// A fast command's echo, start marker, output, end marker and next prompt can share one read.
ptyStub.dataHandler?.(
'printf done\r\n\u001b]633;C;test-nonce\u0007done\u001b]633;P;Cwd=/tmp;test-nonce\u0007\u001b]633;D;0;test-nonce\u0007\u001b]633;A;test-nonce\u0007% '
)
expect(await resultPromise).toMatchObject({
status: 'completed',
exitCode: 0,
output: 'done',
})
} finally {
session.dispose()
if (originalShell === undefined) process.env.SHELL = undefined
else process.env.SHELL = originalShell
}
})

it('reports a full-screen program that exits within one read as completed, with its exit code', async () => {
const originalShell = process.env.SHELL
process.env.SHELL = '/bin/zsh'
const session = TerminalSession.create({
terminalId: 'terminal-1',
cwd: '/tmp',
cols: 80,
rows: 24,
callbacks: { onData: () => {}, onState: () => {}, onCommand: () => {}, onExit: () => {} },
})

try {
const resultPromise = session.runCommand("vim -c 'cq'", 'tool-call-vim', 5_000)
ptyStub.dataHandler?.(
'\u001b]633;C;test-nonce\u0007\u001b[?1049h\u001b[?1049l\u001b]633;D;1;test-nonce\u0007\u001b]633;A;test-nonce\u0007'
)
expect(await resultPromise).toMatchObject({ status: 'completed', exitCode: 1 })
} finally {
session.dispose()
if (originalShell === undefined) process.env.SHELL = undefined
else process.env.SHELL = originalShell
}
})

it('keeps normal long-command activity until the foreground process exits', async () => {
vi.useFakeTimers()
const originalShell = process.env.SHELL
Expand Down
41 changes: 29 additions & 12 deletions apps/desktop/src/main/terminal/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -824,11 +824,7 @@ export class TerminalSession {
}

private handleData(chunk: string): void {
const { text, markers } = this.parser.parse(chunk)

for (const marker of markers) {
this.applyMarker(marker)
}
const { text, markers, offsets } = this.parser.parse(chunk)

if (text) {
this.lastOutputAt = Date.now()
Expand All @@ -837,18 +833,39 @@ export class TerminalSession {
if (this.scrollback.length > MAX_SCROLLBACK_CHARS + TRIM_SLACK_CHARS) {
this.scrollback = this.scrollback.slice(-MAX_SCROLLBACK_CHARS)
}
if (this.pendingCommand?.capturing) {
this.pendingCommand.lastActivityAt = Date.now()
this.captureOutput(this.pendingCommand, text)
if (text.includes(ALT_SCREEN_ENTER)) {
this.resolveInteractiveCommand()
}
}
}

// Text is attributed in stream order, so a command keeps only the output between its own
// start and end markers even when they share this chunk with the output.
let from = 0
let enteredFullScreen = false
markers.forEach((marker, index) => {
enteredFullScreen =
this.captureCommandOutput(text.slice(from, offsets[index])) || enteredFullScreen
from = offsets[index]
this.applyMarker(marker)
})
enteredFullScreen = this.captureCommandOutput(text.slice(from)) || enteredFullScreen
// Judged once the whole read is applied: a program that opened and closed the alternate
// screen and finished within it already has its result, and one that left it is not holding it.
if (enteredFullScreen && this.pendingCommand?.capturing && this.altScreen) {
this.resolveInteractiveCommand()
}

if (text) {
this.pendingOutput += text
this.scheduleFlush()
}
}

/** Adds text to the running command's output; true when it entered the alternate screen. */
private captureCommandOutput(text: string): boolean {
if (!text || !this.pendingCommand?.capturing) return false
this.pendingCommand.lastActivityAt = Date.now()
this.captureOutput(this.pendingCommand, text)
return text.includes(ALT_SCREEN_ENTER)
}

private applyMarker(
marker: ReturnType<ShellIntegrationParser['parse']>['markers'][number]
): void {
Expand Down
14 changes: 12 additions & 2 deletions apps/desktop/src/main/terminal/shell-integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ export interface ParseResult {
/** Stream with the OSC 633 sequences removed, safe to hand to xterm.js. */
text: string
markers: ShellMarker[]
/**
* Where each marker fell in `text`: `markers[i]` came after `text.slice(0, offsets[i])`. A fast
* command's start, output and end can share one chunk, so output belongs to a command only
* between its own markers.
*/
offsets: number[]
}

/** Undoes the escaping applied by the shell hooks. */
Expand Down Expand Up @@ -84,6 +90,7 @@ export class ShellIntegrationParser {
this.pending = ''

const markers: ShellMarker[] = []
const offsets: number[] = []
let text = ''
let index = 0

Expand All @@ -110,11 +117,14 @@ export class ShellIntegrationParser {

const body = buffer.slice(start + '\u001b]633;'.length, terminator.index)
const marker = this.toMarker(body)
if (marker) markers.push(marker)
if (marker) {
markers.push(marker)
offsets.push(text.length)
}
index = terminator.index + terminator.length
}

return { text, markers }
return { text, markers, offsets }
}

private toMarker(body: string): ShellMarker | null {
Expand Down
Loading