Skip to content

Commit 338655f

Browse files
authored
fix(desktop-terminal): keep a fast command's output when its start and end markers share a read (#10504)
* fix(desktop-terminal): keep a fast command's output when its start and end markers share a read The session applied every shell marker in a PTY chunk before looking at the chunk's text. When a quick command's start marker, output and end marker arrived in one read, the command finished before its text was examined, so terminal_run returned completed with empty output. Marker offsets now place each piece of text before or after the markers around it. * fix(desktop-terminal): judge a full-screen command only after the whole read is applied A program that opened and closed the alternate screen and finished within one read was resolved as interactive before its finish marker ran. Interactive resolution now waits until every marker in the read is applied and requires the alternate screen to still be held.
1 parent 397e191 commit 338655f

3 files changed

Lines changed: 94 additions & 14 deletions

File tree

‎apps/desktop/src/main/terminal/session.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,59 @@ describe('stripTerminalQueries', () => {
7575
})
7676

7777
describe('TerminalSession command lifecycle', () => {
78+
it('returns the output of a command whose start, output and end arrive in one read', async () => {
79+
const originalShell = process.env.SHELL
80+
process.env.SHELL = '/bin/zsh'
81+
const session = TerminalSession.create({
82+
terminalId: 'terminal-1',
83+
cwd: '/tmp',
84+
cols: 80,
85+
rows: 24,
86+
callbacks: { onData: () => {}, onState: () => {}, onCommand: () => {}, onExit: () => {} },
87+
})
88+
89+
try {
90+
const resultPromise = session.runCommand('printf done', 'tool-call-fast', 5_000)
91+
// A fast command's echo, start marker, output, end marker and next prompt can share one read.
92+
ptyStub.dataHandler?.(
93+
'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% '
94+
)
95+
expect(await resultPromise).toMatchObject({
96+
status: 'completed',
97+
exitCode: 0,
98+
output: 'done',
99+
})
100+
} finally {
101+
session.dispose()
102+
if (originalShell === undefined) process.env.SHELL = undefined
103+
else process.env.SHELL = originalShell
104+
}
105+
})
106+
107+
it('reports a full-screen program that exits within one read as completed, with its exit code', async () => {
108+
const originalShell = process.env.SHELL
109+
process.env.SHELL = '/bin/zsh'
110+
const session = TerminalSession.create({
111+
terminalId: 'terminal-1',
112+
cwd: '/tmp',
113+
cols: 80,
114+
rows: 24,
115+
callbacks: { onData: () => {}, onState: () => {}, onCommand: () => {}, onExit: () => {} },
116+
})
117+
118+
try {
119+
const resultPromise = session.runCommand("vim -c 'cq'", 'tool-call-vim', 5_000)
120+
ptyStub.dataHandler?.(
121+
'\u001b]633;C;test-nonce\u0007\u001b[?1049h\u001b[?1049l\u001b]633;D;1;test-nonce\u0007\u001b]633;A;test-nonce\u0007'
122+
)
123+
expect(await resultPromise).toMatchObject({ status: 'completed', exitCode: 1 })
124+
} finally {
125+
session.dispose()
126+
if (originalShell === undefined) process.env.SHELL = undefined
127+
else process.env.SHELL = originalShell
128+
}
129+
})
130+
78131
it('keeps normal long-command activity until the foreground process exits', async () => {
79132
vi.useFakeTimers()
80133
const originalShell = process.env.SHELL

‎apps/desktop/src/main/terminal/session.ts‎

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -824,11 +824,7 @@ export class TerminalSession {
824824
}
825825

826826
private handleData(chunk: string): void {
827-
const { text, markers } = this.parser.parse(chunk)
828-
829-
for (const marker of markers) {
830-
this.applyMarker(marker)
831-
}
827+
const { text, markers, offsets } = this.parser.parse(chunk)
832828

833829
if (text) {
834830
this.lastOutputAt = Date.now()
@@ -837,18 +833,39 @@ export class TerminalSession {
837833
if (this.scrollback.length > MAX_SCROLLBACK_CHARS + TRIM_SLACK_CHARS) {
838834
this.scrollback = this.scrollback.slice(-MAX_SCROLLBACK_CHARS)
839835
}
840-
if (this.pendingCommand?.capturing) {
841-
this.pendingCommand.lastActivityAt = Date.now()
842-
this.captureOutput(this.pendingCommand, text)
843-
if (text.includes(ALT_SCREEN_ENTER)) {
844-
this.resolveInteractiveCommand()
845-
}
846-
}
836+
}
837+
838+
// Text is attributed in stream order, so a command keeps only the output between its own
839+
// start and end markers even when they share this chunk with the output.
840+
let from = 0
841+
let enteredFullScreen = false
842+
markers.forEach((marker, index) => {
843+
enteredFullScreen =
844+
this.captureCommandOutput(text.slice(from, offsets[index])) || enteredFullScreen
845+
from = offsets[index]
846+
this.applyMarker(marker)
847+
})
848+
enteredFullScreen = this.captureCommandOutput(text.slice(from)) || enteredFullScreen
849+
// Judged once the whole read is applied: a program that opened and closed the alternate
850+
// screen and finished within it already has its result, and one that left it is not holding it.
851+
if (enteredFullScreen && this.pendingCommand?.capturing && this.altScreen) {
852+
this.resolveInteractiveCommand()
853+
}
854+
855+
if (text) {
847856
this.pendingOutput += text
848857
this.scheduleFlush()
849858
}
850859
}
851860

861+
/** Adds text to the running command's output; true when it entered the alternate screen. */
862+
private captureCommandOutput(text: string): boolean {
863+
if (!text || !this.pendingCommand?.capturing) return false
864+
this.pendingCommand.lastActivityAt = Date.now()
865+
this.captureOutput(this.pendingCommand, text)
866+
return text.includes(ALT_SCREEN_ENTER)
867+
}
868+
852869
private applyMarker(
853870
marker: ReturnType<ShellIntegrationParser['parse']>['markers'][number]
854871
): void {

‎apps/desktop/src/main/terminal/shell-integration.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,12 @@ export interface ParseResult {
5353
/** Stream with the OSC 633 sequences removed, safe to hand to xterm.js. */
5454
text: string
5555
markers: ShellMarker[]
56+
/**
57+
* Where each marker fell in `text`: `markers[i]` came after `text.slice(0, offsets[i])`. A fast
58+
* command's start, output and end can share one chunk, so output belongs to a command only
59+
* between its own markers.
60+
*/
61+
offsets: number[]
5662
}
5763

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

8692
const markers: ShellMarker[] = []
93+
const offsets: number[] = []
8794
let text = ''
8895
let index = 0
8996

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

111118
const body = buffer.slice(start + '\u001b]633;'.length, terminator.index)
112119
const marker = this.toMarker(body)
113-
if (marker) markers.push(marker)
120+
if (marker) {
121+
markers.push(marker)
122+
offsets.push(text.length)
123+
}
114124
index = terminator.index + terminator.length
115125
}
116126

117-
return { text, markers }
127+
return { text, markers, offsets }
118128
}
119129

120130
private toMarker(body: string): ShellMarker | null {

0 commit comments

Comments
 (0)