Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Fix stale terminal input and show the installed version after update checks (#432)

Dee37a741cfbfd0
diff --git a/cli/src/lib/remoteRelay.spec.ts b/cli/src/lib/remoteRelay.spec.ts
index a2846916b..899c37bd2 100644
--- a/cli/src/lib/remoteRelay.spec.ts
+++ b/cli/src/lib/remoteRelay.spec.ts
@@ -558,12 +558,36 @@ describe('RemoteRelayPool shares one upstream between every local client selecte
onClosed: ((code: number, reason: string) => void) | null
lingerTimer: ReturnType<typeof setTimeout> | null
viewers: { reset: ReturnType<typeof vi.fn>; close: ReturnType<typeof vi.fn> }
+ ws: { send: ReturnType<typeof vi.fn> }
+ p2p: { isReady: boolean; send: ReturnType<typeof vi.fn> } | null
}
;(pool as unknown as { entries: Map<string, unknown> }).entries.set('m1', entry)
return { pool, entry }
}
const sink = () => ({ sendFrame: vi.fn(() => true), sendBinary: vi.fn(() => true) })
+ it.each(['relay', 'p2p'])('preserves distinct view ownership on terminal opens over %s', async (transport) => {
+ const { pool, entry } = poolWithEntry()
+ if (transport === 'p2p') entry.p2p = { isReady: true, send: vi.fn(() => true) }
+ const a = await pool.acquire('m1', 'env', { type: 'machine_select', payload: {} }, sink(), vi.fn())
+ const b = await pool.acquire('m1', 'env', { type: 'machine_select', payload: {} }, sink(), vi.fn())
+ const open = { type: 'terminal_open', payload: { requestId: 'one', agentId: 'agent-1', takeover: false, viewId: 'caller-value' } }
+ await a.send(open)
+ await b.send(open)
+ await a.send({ ...open, payload: { ...open.payload, requestId: 'reopen' } })
+ const send = entry.p2p?.send ?? entry.ws.send
+ const frames = send.mock.calls.map(([raw]) => JSON.parse(raw as string))
+ expect(frames[0].payload).toMatchObject({ requestId: 'one', agentId: 'agent-1', takeover: false })
+ expect(frames[0].payload.viewId).toMatch(/^[a-f0-9-]{36}$/)
+ expect(frames[1].payload.viewId).not.toBe(frames[0].payload.viewId)
+ expect(frames[2].payload.viewId).toBe(frames[0].payload.viewId)
+ expect(open.payload.viewId).toBe('caller-value')
+ await a.send({ type: 'terminal_alive', payload: { streamId: 'stream-a' } })
+ expect(JSON.parse(entry.ws.send.mock.calls.at(-1)![0])).toEqual({ type: 'terminal_alive', payload: { streamId: 'stream-a' } })
+ a.detach(); b.detach()
+ clearTimeout(entry.lingerTimer!)
+ })
+
it('a second client joins the first, both get every frame, and detaching one leaves the other on', async () => {
const { pool, entry } = poolWithEntry()
const desktop = sink()
diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.ts
index 7f6e2555a..bcc1281b7 100644
--- a/cli/src/lib/remoteRelay.ts
+++ b/cli/src/lib/remoteRelay.ts
@@ -12,6 +12,7 @@
* every machine, relayed or not. A machine with no pinned peer fails the relay with `NO_PEER_LINK`
* instead of ever reaching pipe mode.
*/
+import { randomUUID } from 'node:crypto'
import { WebSocket, type RawData } from 'ws'
import { watchSocketLiveness, type LivenessWatch } from './wsLiveness.js'
import type { Frame, LocalClientSink } from '../backendSocket.js'
@@ -669,8 +670,14 @@ export class RemoteRelayPool {
}
private sessionFor(machineId: string, entry: Entry, client: AttachedClient | null = null): RelaySession {
+ // Several local views share this upstream connection. Keep each view's terminal lease
+ // distinct, but stable across its opens (and across relay/P2P transport changes).
+ const viewId = randomUUID()
return {
send: async (frame) => {
+ if (frame.type === 'terminal_open') {
+ frame = { ...frame, payload: { ...framePayload(frame), viewId } }
+ }
const payload = framePayload(frame)
let useP2p = typeof payload.streamId === 'string' && entry.p2pStreams.has(payload.streamId)
if (frame.type === 'terminal_open' && typeof payload.requestId === 'string' && entry.p2p) {
diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.ts
index 0ad98da38..ccc287839 100644
--- a/cli/src/lib/terminalStreamManager.spec.ts
+++ b/cli/src/lib/terminalStreamManager.spec.ts
@@ -475,7 +475,7 @@ describe('TerminalStreamManager', () => {
})
expect(lastResult()).toMatchObject({
type: 'terminal_chunked_upload_begin_result',
- payload: { streamId: 'stream-does-not-exist', accepted: false },
+ payload: { streamId: 'stream-does-not-exist', accepted: false, code: 'TERMINAL_STREAM_NOT_FOUND' },
})
})
@@ -736,8 +736,8 @@ describe('TerminalStreamManager', () => {
requestId: 'open-2', protocolVersion: 3, agentId: 'agent-2', cols: 100, rows: 30,
})
- // Observed through a resize rather than a close frame: replacing a stream is deliberately
- // silent, so the only way to tell a live stream from a dead one is whether it still acts.
+ expect(sent.some((frame) => frame.type === 'terminal_closed')).toBe(false)
+ // The other pane still accepts operations on its original stream.
const before = stream.sizes.length
await manager.handleFrame('app-1', 'terminal_resize', {
streamId: first, resizeSeq: 1, cols: 90, rows: 25,
@@ -745,7 +745,7 @@ describe('TerminalStreamManager', () => {
expect(stream.sizes.length).toBe(before + 1)
})
- it('still replaces its own stream when the same terminal is reopened', async () => {
+ it('notifies legacy views when a shared connection reopens the same terminal', async () => {
await manager.handleFrame('app-1', 'terminal_open', {
requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
})
@@ -753,8 +753,27 @@ describe('TerminalStreamManager', () => {
await manager.handleFrame('app-1', 'terminal_open', {
requestId: 'open-2', protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
+ client: { kind: 'desktop', name: 'Other window' },
})
+ expect(sent.filter((frame) => frame.type === 'terminal_closed')).toEqual([{
+ connId: 'app-1',
+ type: 'terminal_closed',
+ payload: {
+ protocolVersion: 3,
+ streamId: first,
+ reason: 'terminal reopened in another view',
+ code: 'TERMINAL_TAKEN_OVER',
+ },
+ }])
+ expect(sent.at(-1)).toMatchObject({ type: 'terminal_ready', payload: { requestId: 'open-2' } })
+ const replacement = sent.at(-1)!.payload.streamId as string
+ expect(replacement).not.toBe(first)
+ await manager.handleBinary('app-1', {
+ kind: TerminalBinaryKind.input, streamId: replacement, seq: 0, compressed: false, bytes: Buffer.from('new input'),
+ })
+ expect(Buffer.from(stream.writes.at(-1)!).toString()).toBe('new input')
+
// Two tmux clients on one window is the thing this must never allow.
const before = stream.sizes.length
await manager.handleFrame('app-1', 'terminal_resize', {
@@ -763,6 +782,75 @@ describe('TerminalStreamManager', () => {
expect(stream.sizes.length).toBe(before)
})
+ it.each(['agent-1', 'agent-alias'])('keeps relay views independent when watching and taking over %s', async (secondAgent) => {
+ agents.set('agent-alias', session('codex', 'agent-alias'))
+ const handles: FakeStream[] = []
+ terminals.openStream = vi.fn(async () => {
+ const handle = new FakeStream()
+ handles.push(handle)
+ return { state: 'succeeded' as const, value: handle }
+ })
+ const open = async (viewId: string, takeover: boolean, agentId = 'agent-1') => {
+ await manager.handleFrame('shared-relay', 'terminal_open', {
+ requestId: `${viewId}-${handles.length}`, protocolVersion: 3, agentId,
+ cols: 100, rows: 30, viewId, takeover, client: { kind: 'desktop', name: viewId },
+ })
+ return sent.findLast((frame) => frame.type === 'terminal_ready')!.payload
+ }
+ const type = (streamId: unknown, text: string, seq = 0) => manager.handleBinary('shared-relay', {
+ kind: TerminalBinaryKind.input, streamId: streamId as string, seq,
+ compressed: false, bytes: Buffer.from(text),
+ })
+
+ const controller = await open('view-a', true)
+ const watcher = await open('view-b', false, secondAgent)
+ expect(watcher).toMatchObject({ readOnly: true, heldBy: { name: 'view-a' } })
+ expect(handles[0].closed).toBe(false)
+ expect(sent.filter((frame) => frame.type === 'terminal_closed')).toEqual([])
+ await type(controller.streamId, 'still typing')
+ await type(watcher.streamId, 'ignored')
+ expect(Buffer.from(handles[0].writes[0]).toString()).toBe('still typing')
+ expect(handles[1].writes).toEqual([])
+
+ // Reopening the watcher only replaces that view's own stream.
+ const watchingAgain = await open('view-b', false, secondAgent)
+ expect(watchingAgain.readOnly).toBe(true)
+ expect(handles[0].closed).toBe(false)
+ expect(handles[1].closed).toBe(true)
+ expect(sent.filter((frame) => frame.type === 'terminal_closed').map((frame) => frame.payload.streamId))
+ .toEqual([watcher.streamId])
+
+ const nextController = await open('view-b', true, secondAgent)
+ expect(nextController.readOnly).toBe(false)
+ expect(sent.find((frame) => frame.type === 'terminal_closed' && frame.payload.streamId === controller.streamId)?.payload)
+ .toMatchObject({ code: 'TERMINAL_TAKEN_OVER', takenBy: { name: 'view-b' } })
+ expect(handles[0].closed).toBe(true)
+
+ // A displaced client (including the TUI's automatic watch) must never take control back.
+ const displacedWatcher = await open('view-a', false)
+ expect(displacedWatcher).toMatchObject({ readOnly: true, heldBy: { name: 'view-b' } })
+ expect(handles[3].closed).toBe(false)
+ await type(nextController.streamId, 'new owner')
+ await type(displacedWatcher.streamId, 'ignored')
+ expect(Buffer.from(handles[3].writes[0]).toString()).toBe('new owner')
+ expect(handles[4].writes).toEqual([])
+ await manager.handleFrame('shared-relay', 'terminal_close', { streamId: displacedWatcher.streamId })
+ expect((await open('view-c', false)).heldBy).toEqual({ kind: 'desktop', name: 'view-b' })
+ expect(handles[3].closed).toBe(false)
+ })
+
+ it('scopes identical view IDs to their authenticated connection', async () => {
+ for (const connId of ['first', 'second']) {
+ await manager.handleFrame(connId, 'terminal_open', {
+ requestId: connId, protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
+ viewId: 'same-view-id', takeover: false,
+ })
+ }
+ expect(sent.filter((frame) => frame.type === 'terminal_ready').map((frame) => frame.payload.readOnly))
+ .toEqual([false, true])
+ expect(sent.filter((frame) => frame.type === 'terminal_closed')).toEqual([])
+ })
+
it('uses frequent ACKs rather than the five-second heartbeat for output backpressure', async () => {
await manager.handleFrame('web-1', 'terminal_open', {
requestId: 'open-1', protocolVersion: 3, agentId: 'agent-1', cols: 100, rows: 30,
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index 2b9d202e5..3fbf2fa5c 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -101,6 +101,8 @@ interface PendingOutput {
interface ActiveStream {
connId: string
+ /** A local view can share its upstream connection with other independent terminal owners. */
+ ownerId: string
/** What the client declared on open, or what `describeClient` could tell; absent when neither knew. */
client?: TerminalClientDescriptor
streamId: string
@@ -428,11 +430,16 @@ export class TerminalStreamManager {
// it, and the client asks again, without the key, once a person actually lands there. Absent
// (every older client) is the takeover it has always been.
const takeover = payload.takeover !== false
+ // Older clients have one owner per connection. A pooled relay supplies a stable identity
+ // for each attached view; this partitions leases, not authentication or stream access.
+ const viewId = typeof payload.viewId === 'string' && payload.viewId.length > 0 && payload.viewId.length <= 128
+ ? payload.viewId : null
+ const ownerId = JSON.stringify([connId, viewId])
// The fallback is read as strictly as a claim: a machine name the backend handed out is not
// this module's to trust with the wire shape either.
const client = clientDescriptorFrom(payload.client) ?? clientDescriptorFrom(this.deps.describeClient?.(connId))
await this.withLeaseLock(reservedPlacement, async () => {
- const incumbents = this.incumbentsFor(session.agentId, reservedPlacement, connId)
+ const incumbents = this.incumbentsFor(session.agentId, reservedPlacement, ownerId)
// Inside the lock, so the answer cannot go stale against an open racing this one for the
// same placement.
//
@@ -449,9 +456,9 @@ export class TerminalStreamManager {
// receives a targeted close notification; it must not be broadcast to other clients. The
// notification names the winner when it can (`takenBy`), so the incumbent's banner can too.
if (!this.deps.readOnly && !watching) {
- await this.closeStreamsForTakeover(session.agentId, reservedPlacement, connId, client)
+ await this.closeStreamsForTakeover(session.agentId, reservedPlacement, ownerId, client)
}
- // Only THIS connection's stream for THIS terminal, not every stream it holds.
+ // Only THIS view's stream for THIS terminal, not every stream the connection holds.
//
// It used to be closeConnection(connId), i.e. "opening a terminal ends every other terminal
// this client had". That was invisible while a client could only ever show one terminal at a
@@ -460,10 +467,10 @@ export class TerminalStreamManager {
// after handing it its opening keyframe. The pane kept rendering that stale keyframe and
// looked alive, but its session never reached `controlling`, so every keystroke into it was
// dropped in silence.
- await this.closeOwnStreamsFor(connId, session.agentId, reservedPlacement)
+ await this.closeOwnStreamsFor(ownerId, session.agentId, reservedPlacement)
// A watcher never becomes the controller — that is the whole point of it.
- if (!this.deps.readOnly && !watching) this.controllerByAgent.set(session.agentId, connId)
- if (!this.deps.readOnly && !watching) this.controllerByPlacement.set(reservedPlacement, connId)
+ if (!this.deps.readOnly && !watching) this.controllerByAgent.set(session.agentId, ownerId)
+ if (!this.deps.readOnly && !watching) this.controllerByPlacement.set(reservedPlacement, ownerId)
const streamId = randomUUID()
const buffered: Buffer[] = []
let state: ActiveStream | null = null
@@ -479,31 +486,31 @@ export class TerminalStreamManager {
},
}, this.deps.readOnly || watching)
} catch {
- if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
- if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
+ if (this.controllerByAgent.get(session.agentId) === ownerId) this.controllerByAgent.delete(session.agentId)
+ if (this.controllerByPlacement.get(reservedPlacement) === ownerId) this.controllerByPlacement.delete(reservedPlacement)
this.sendError(connId, 'TERMINAL_OPEN_FAILED', { requestId })
return
}
if (opened.state !== 'succeeded') {
- if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
- if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
+ if (this.controllerByAgent.get(session.agentId) === ownerId) this.controllerByAgent.delete(session.agentId)
+ if (this.controllerByPlacement.get(reservedPlacement) === ownerId) this.controllerByPlacement.delete(reservedPlacement)
this.sendError(connId, opened.reason, { requestId })
return
}
const placementKey = terminalPlacementKey(opened.value.runtime)
const actualController = this.controllerByPlacement.get(placementKey)
- if (!this.deps.readOnly && !watching && actualController && actualController !== connId) {
- if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
- if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
+ if (!this.deps.readOnly && !watching && actualController && actualController !== ownerId) {
+ if (this.controllerByAgent.get(session.agentId) === ownerId) this.controllerByAgent.delete(session.agentId)
+ if (this.controllerByPlacement.get(reservedPlacement) === ownerId) this.controllerByPlacement.delete(reservedPlacement)
await opened.value.close().catch(() => { /* best effort */ })
this.sendError(connId, 'CONTROL_LEASE_HELD', { requestId })
return
}
- if (reservedPlacement !== placementKey && this.controllerByPlacement.get(reservedPlacement) === connId) {
+ if (reservedPlacement !== placementKey && this.controllerByPlacement.get(reservedPlacement) === ownerId) {
this.controllerByPlacement.delete(reservedPlacement)
}
- if (!this.deps.readOnly && !watching) this.controllerByPlacement.set(placementKey, connId)
+ if (!this.deps.readOnly && !watching) this.controllerByPlacement.set(placementKey, ownerId)
const requestedCompression = Array.isArray(payload.compression) ? payload.compression : []
// Never compress for the loopback desktop, whatever it asks for: the bytes cross 127.0.0.1,
@@ -515,6 +522,7 @@ export class TerminalStreamManager {
const wantsZlib = requestedCompression.includes('zlib') && !loopback
state = {
connId,
+ ownerId,
...(client ? { client } : {}),
streamId,
watching,
@@ -826,6 +834,7 @@ export class TerminalStreamManager {
this.deps.sendTarget(connId, 'terminal_chunked_upload_begin_result', {
streamId: claimedStreamId,
accepted: false,
+ code: 'TERMINAL_STREAM_NOT_FOUND',
reason: 'no live terminal stream for this pane (reopen it and try again)',
})
return
@@ -1206,24 +1215,27 @@ export class TerminalStreamManager {
})
}
- /// Replace this connection's own stream for the same terminal.
+ /// Replace this view's own stream for the same terminal.
///
/// Reopening is routine — a resync, a relay that came back — and the old stream has to go or the
/// agent would have two tmux clients on one window. Matched on agent AND placement so a client
- /// holding several different terminals keeps the ones it did not ask about. No notification: the
- /// client that asked for this is the one being replaced, and it already knows.
- private async closeOwnStreamsFor(connId: string, agentId: string, placementKey: string): Promise<void> {
+ /// holding several different terminals keeps the ones it did not ask about. Notify even older
+ /// pooled clients that omit viewId: a different view may still be using the old stream. Omit
+ /// takenBy here, since older clients automatically watch a named taker using the same owner ID.
+ private async closeOwnStreamsFor(ownerId: string, agentId: string, placementKey: string): Promise<void> {
const own = [...this.streams.values()].filter((state) =>
- !state.closing && state.connId === connId
+ !state.closing && state.ownerId === ownerId
&& (state.agentId === agentId || state.placementKey === placementKey))
- await Promise.all(own.map((state) => this.closeStream(state, 'replaced', false)))
+ await Promise.all(own.map((state) => this.closeStream(
+ state, 'terminal reopened in another view', true, 'TERMINAL_TAKEN_OVER',
+ )))
}
- /// The live streams OTHER connections hold on this terminal — exactly the ones a takeover would
+ /// The live streams OTHER views hold on this terminal — exactly the ones a takeover would
/// close, which is what makes it the right question for an open that must not take over.
- private incumbentsFor(agentId: string, placementKey: string, nextConnId: string): ActiveStream[] {
+ private incumbentsFor(agentId: string, placementKey: string, nextOwnerId: string): ActiveStream[] {
return [...this.streams.values()].filter((state) =>
- !state.closing && state.connId !== nextConnId
+ !state.closing && state.ownerId !== nextOwnerId
&& (state.agentId === agentId || state.placementKey === placementKey))
}
@@ -1232,17 +1244,17 @@ export class TerminalStreamManager {
* "another app", as it always has. */
private holderOf(incumbents: ActiveStream[], placementKey: string): TerminalClientDescriptor | undefined {
const controller = this.controllerByPlacement.get(placementKey)
- return (incumbents.find((state) => state.connId === controller && state.client)
+ return (incumbents.find((state) => state.ownerId === controller && state.client)
?? incumbents.find((state) => state.client))?.client
}
private async closeStreamsForTakeover(
agentId: string,
placementKey: string,
- nextConnId: string,
+ nextOwnerId: string,
takenBy?: TerminalClientDescriptor,
): Promise<void> {
- const incumbents = this.incumbentsFor(agentId, placementKey, nextConnId)
+ const incumbents = this.incumbentsFor(agentId, placementKey, nextOwnerId)
await Promise.all(incumbents.map((state) => this.closeStream(
state,
'another client connected',
@@ -1279,8 +1291,8 @@ export class TerminalStreamManager {
state.flushTimer = null
state.stallTimer = null
this.streams.delete(state.streamId)
- if (this.controllerByAgent.get(state.agentId) === state.connId) this.controllerByAgent.delete(state.agentId)
- if (this.controllerByPlacement.get(state.placementKey) === state.connId) this.controllerByPlacement.delete(state.placementKey)
+ if (this.controllerByAgent.get(state.agentId) === state.ownerId) this.controllerByAgent.delete(state.agentId)
+ if (this.controllerByPlacement.get(state.placementKey) === state.ownerId) this.controllerByPlacement.delete(state.placementKey)
if (state.outputPaused) await state.handle.resumeOutput().catch(() => { /* best effort */ })
await state.handle.close().catch(() => { /* best effort */ })
if (notify) this.deps.sendTarget(state.connId, 'terminal_closed', {
diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dart
index 808d41946..dc1c3d422 100644
--- a/desktop/lib/terminal/terminal_session.dart
+++ b/desktop/lib/terminal/terminal_session.dart
@@ -270,6 +270,7 @@ class TerminalSession extends ChangeNotifier {
List<int> _utf8Tail = const [];
final List<int> _inputBytes = [];
Timer? _heartbeat;
+ DateTime? _lastStreamActivityAt;
Timer? _ackTimer;
Timer? _inputTimer;
Timer? _resizeTimer;
@@ -368,6 +369,7 @@ class TerminalSession extends ChangeNotifier {
_pendingScrollLines = 0;
_lastInputFlushAt = null;
_lastResizeFlushAt = null;
+ _lastStreamActivityAt = null;
_renderTail = Future<void>.value();
_inputSendTail = Future<void>.value();
streamId = null;
@@ -577,6 +579,14 @@ class TerminalSession extends ChangeNotifier {
if (_activeUpload?.beginAccepted.isCompleted == false) {
_activeUpload!.beginAccepted.complete(accepted);
}
+ // Older daemons only sent this text. A vanished stream cannot accept input or upload
+ // chunks; retain its screen and reopen once, without replaying the failed paste.
+ if (!accepted &&
+ (payload['code'] == 'TERMINAL_STREAM_NOT_FOUND' ||
+ payload['reason'] ==
+ 'no live terminal stream for this pane (reopen it and try again)')) {
+ await _recoverByReopen(reason: 'TERMINAL_STREAM_NOT_FOUND');
+ }
return true;
case 'terminal_chunked_upload_progress':
if (!_matchesStream(payload)) return true;
@@ -767,6 +777,7 @@ class TerminalSession extends ChangeNotifier {
_resyncTimer?.cancel();
_resyncTimer = null;
status = TerminalSessionStatus.controlling;
+ _lastStreamActivityAt = _now();
_markForAck(bytes.length);
notifyListeners();
final measured = _measuredViewport;
@@ -787,6 +798,7 @@ class TerminalSession extends ChangeNotifier {
}
_expectedSeq = frame.seq + 1;
_lastRenderedSeq = frame.seq;
+ _lastStreamActivityAt = _now();
_markForAck(0);
return;
}
@@ -804,6 +816,7 @@ class TerminalSession extends ChangeNotifier {
}
_expectedSeq = frame.seq + 1;
_lastRenderedSeq = frame.seq;
+ _lastStreamActivityAt = _now();
_markForAck(bytes.length);
})
.catchError((Object error, StackTrace stackTrace) async {
@@ -1458,6 +1471,16 @@ class TerminalSession extends ChangeNotifier {
final sent = await send('terminal_alive', {'streamId': streamId});
if (!sent && _isCurrent(generation)) {
transportLost('Terminal heartbeat was not sent');
+ return;
+ }
+ // The daemon sends sync frames every five seconds even when the terminal is idle. Sending
+ // successfully only proves the shared socket is open, not that THIS stream still exists.
+ final lastActivity = _lastStreamActivityAt;
+ if (_isCurrent(generation) &&
+ status == TerminalSessionStatus.controlling &&
+ lastActivity != null &&
+ _now().difference(lastActivity) >= const Duration(seconds: 15)) {
+ await _requestResync('TERMINAL_STREAM_TIMEOUT');
}
}
diff --git a/desktop/lib/widgets/update_notice.dart b/desktop/lib/widgets/update_notice.dart
index 79a0db85a..06b79ab74 100644
--- a/desktop/lib/widgets/update_notice.dart
+++ b/desktop/lib/widgets/update_notice.dart
@@ -301,6 +301,7 @@ Future<void> showUpdateCheckDialog(
AppNotifier notifier,
ManualUpdateCheck result,
) {
+ Future<String>? installedVersion;
return showAppDialog<void>(
context: context,
builder: (dialogContext) {
@@ -355,11 +356,16 @@ Future<void> showUpdateCheckDialog(
}
final update = current.update;
if (update == null) {
- return const _UpdateDialog(
- icon: LucideIcons.circleCheck300,
- tone: _DialogTone.ok,
- title: 'You’re up to date',
- body: 'This copy of Harness already has the latest version.',
+ return FutureBuilder<String>(
+ future: installedVersion ??= runningAppVersion(),
+ builder: (context, snapshot) => _UpdateDialog(
+ icon: LucideIcons.circleCheck300,
+ tone: _DialogTone.ok,
+ title: 'You’re up to date',
+ body: snapshot.hasData
+ ? 'Harness ${snapshot.data} is the latest version.'
+ : 'This copy of Harness already has the latest version.',
+ ),
);
}
return PopScope(
diff --git a/desktop/test/manual_update_check_test.dart b/desktop/test/manual_update_check_test.dart
index 41e1d33b3..2fdec09c4 100644
--- a/desktop/test/manual_update_check_test.dart
+++ b/desktop/test/manual_update_check_test.dart
@@ -271,6 +271,7 @@ void main() {
manifest.answer(version: '1.0.0');
await tester.pumpAndSettle();
expect(find.text('You’re up to date'), findsOneWidget);
+ expect(find.text('Harness 1.0.0 is the latest version.'), findsOneWidget);
expect(find.text('Up to date'), findsOneWidget);
expect(app.isCheckingForUpdate, isFalse);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
@@ -567,6 +568,7 @@ void main() {
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsOneWidget, reason: 'it does not vanish');
expect(find.textContaining('up to date'), findsWidgets);
+ expect(find.text('Harness 1.0.0 is the latest version.'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
await dialog;
diff --git a/desktop/test/terminal_session_test.dart b/desktop/test/terminal_session_test.dart
index 7cf915e94..f0f64dd66 100644
--- a/desktop/test/terminal_session_test.dart
+++ b/desktop/test/terminal_session_test.dart
@@ -1115,6 +1115,197 @@ void main() {
},
);
+ group('stream liveness', () {
+ setUp(() => controlledNow = DateTime.utc(2026));
+
+ Future<void> tick(WidgetTester tester, Duration elapsed) async {
+ controlledNow = controlledNow!.add(elapsed);
+ await tester.pump(elapsed);
+ }
+
+ Future<void> live() async {
+ await ready();
+ await session.handleBinary(
+ output(
+ 0,
+ utf8.encode('retained screen'),
+ keyframe: true,
+ cols: 100,
+ rows: 30,
+ ),
+ );
+ }
+
+ TerminalBinaryFrame sync(int seq, {String id = streamId}) =>
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.sync,
+ streamId: id,
+ seq: seq,
+ bytes: Uint8List(0),
+ compressed: false,
+ );
+
+ for (final watching in [false, true]) {
+ testWidgets(
+ 'a silently replaced stream recovers without replaying input (watching=$watching)',
+ (tester) async {
+ await live();
+ final retained = session.terminal;
+ session.terminal.textInput('sent before disconnect');
+ await tester.pump(const Duration(milliseconds: 5));
+ binarySent.clear();
+
+ for (var i = 0; i < 3; i++) {
+ await tick(tester, const Duration(seconds: 5));
+ }
+ expect(session.status, TerminalSessionStatus.resyncing);
+ expect(session.errorCode, 'TERMINAL_STREAM_TIMEOUT');
+ expect(session.acceptsInput, isFalse);
+ expect(session.terminal, same(retained));
+ // Nothing answers for the vanished stream. Use the existing bounded ladder.
+ for (var i = 0; i < 3; i++) {
+ await tick(tester, const Duration(seconds: 4));
+ }
+ final opens = sent
+ .where((frame) => frame.type == 'terminal_open')
+ .toList();
+ expect(opens, hasLength(2));
+ expect(opens.last.payload['takeover'], isFalse);
+ expect(session.status, TerminalSessionStatus.opening);
+ expect(session.terminal, same(retained));
+
+ // The daemon now reports replacement explicitly. A late close for the old
+ // stream must not kill the reopen this view already asked for.
+ await session.handleFrame('terminal_closed', {
+ 'streamId': streamId,
+ 'code': 'TERMINAL_TAKEN_OVER',
+ 'reason': 'terminal reopened in another view',
+ });
+ expect(session.status, TerminalSessionStatus.opening);
+ const replacementId = '11112233-4455-6677-8899-aabbccddeeff';
+ await session.handleFrame('terminal_ready', {
+ 'requestId': opens.last.payload['requestId'],
+ 'protocolVersion': 3,
+ 'streamId': replacementId,
+ 'agentId': 'agent-1',
+ 'readOnly': watching,
+ });
+ expect(session.acceptsInput, isFalse);
+ await session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: replacementId,
+ seq: 0,
+ bytes: Uint8List.fromList(utf8.encode('reconnected screen')),
+ compressed: false,
+ cols: 100,
+ rows: 30,
+ ),
+ );
+ expect(session.acceptsInput, !watching);
+ expect(
+ binarySent,
+ isEmpty,
+ reason: 'Input on the retired stream is never replayed',
+ );
+ session.terminal.textInput('new input');
+ await tester.pump(const Duration(milliseconds: 5));
+ if (watching) {
+ expect(binarySent, isEmpty);
+ } else {
+ expect(binarySent.single.streamId, replacementId);
+ expect(utf8.decode(binarySent.single.bytes), 'new input');
+ }
+ await session.close();
+ },
+ );
+ }
+
+ testWidgets('a live stream that answers resync keeps its lease', (
+ tester,
+ ) async {
+ await live();
+ await tick(tester, const Duration(seconds: 15));
+ expect(session.status, TerminalSessionStatus.resyncing);
+ await session.handleBinary(
+ output(
+ 5,
+ utf8.encode('fresh snapshot'),
+ keyframe: true,
+ cols: 100,
+ rows: 30,
+ ),
+ );
+ expect(session.acceptsInput, isTrue);
+ expect(session.errorCode, isNull);
+ await tick(tester, const Duration(seconds: 5));
+ await session.handleBinary(sync(6));
+ expect(session.acceptsInput, isTrue);
+ expect(
+ sent.where((frame) => frame.type == 'terminal_open'),
+ hasLength(1),
+ );
+ await session.close();
+ });
+
+ for (final kind in ['sync', 'output']) {
+ testWidgets('$kind frames keep a live terminal healthy', (tester) async {
+ await live();
+ for (var seq = 1; seq <= 8; seq++) {
+ await tick(tester, const Duration(seconds: 5));
+ await session.handleBinary(
+ kind == 'sync' ? sync(seq) : output(seq, utf8.encode('text')),
+ );
+ }
+ expect(session.acceptsInput, isTrue);
+ expect(sent.where((frame) => frame.type == 'terminal_resync'), isEmpty);
+ expect(
+ sent.where((frame) => frame.type == 'terminal_open'),
+ hasLength(1),
+ );
+ await session.close();
+ });
+ }
+
+ testWidgets('traffic for other panes cannot hide a stale terminal', (
+ tester,
+ ) async {
+ await live();
+ for (var seq = 1; seq <= 3; seq++) {
+ await session.handleBinary(sync(seq, id: 'another-pane'));
+ await session.handleFrame('terminal_link_mode', {
+ 'streamId': streamId,
+ 'mode': 'turn',
+ });
+ await tick(tester, const Duration(seconds: 5));
+ }
+ expect(session.status, TerminalSessionStatus.resyncing);
+ expect(session.errorCode, 'TERMINAL_STREAM_TIMEOUT');
+ await session.close();
+ });
+
+ testWidgets(
+ 'a reported takeover waits for the user instead of reconnecting',
+ (tester) async {
+ await live();
+ await session.handleFrame('terminal_closed', {
+ 'streamId': streamId,
+ 'code': 'TERMINAL_TAKEN_OVER',
+ 'reason': 'terminal reopened in another view',
+ });
+ await tick(tester, const Duration(seconds: 60));
+ expect(session.status, TerminalSessionStatus.takenOver);
+ expect(session.acceptsInput, isFalse);
+ expect(
+ sent.where((frame) => frame.type == 'terminal_open'),
+ hasLength(1),
+ );
+ expect(sent.where((frame) => frame.type == 'terminal_resync'), isEmpty);
+ await session.close();
+ },
+ );
+ });
+
testWidgets('resync retries three times, reopens once, then fails closed', (
tester,
) async {
@@ -1499,9 +1690,49 @@ void main() {
expect(await future, isFalse);
expect(imagePastes(), isEmpty);
expect(session.uploadProgress, isNull);
+ expect(session.acceptsInput, isTrue);
+ expect(sent.where((frame) => frame.type == 'terminal_open'), isEmpty);
},
);
+ for (final coded in [true, false]) {
+ test(
+ 'a missing-stream upload rejection reopens once without replay (coded=$coded)',
+ () async {
+ await live();
+ final retained = session.terminal;
+ final uploading = session.pasteImage(Uint8List.fromList([1, 2, 3]));
+ await pump();
+ final rejection = <String, dynamic>{
+ 'streamId': streamId,
+ 'accepted': false,
+ if (coded) 'code': 'TERMINAL_STREAM_NOT_FOUND',
+ 'reason': coded ? 'stream unavailable' : 'no live terminal stream for this pane (reopen it and try again)',
+ };
+ await session.handleFrame(
+ 'terminal_chunked_upload_begin_result',
+ rejection,
+ );
+ expect(await uploading, isFalse);
+ expect(session.status, TerminalSessionStatus.opening);
+ expect(session.terminal, same(retained));
+ expect(session.uploadProgress, isNull);
+ expect(imagePastes(), isEmpty);
+ final opens = sent.where((frame) => frame.type == 'terminal_open');
+ expect(opens, hasLength(1));
+ expect(opens.single.payload['takeover'], isFalse);
+ await session.handleFrame(
+ 'terminal_chunked_upload_begin_result',
+ rejection,
+ );
+ expect(
+ sent.where((frame) => frame.type == 'terminal_open'),
+ hasLength(1),
+ );
+ },
+ );
+ }
+
test(
'a malformed-chunk error clears the upload without freezing the session',
() async {