Skip to content

Commit d0a2ce3

Browse files
authored
feat(tui): report pending session status to the terminal (#55172)
1 parent 8396de1 commit d0a2ce3

8 files changed

Lines changed: 212 additions & 22 deletions

File tree

‎bun.lock‎

Lines changed: 16 additions & 16 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,9 @@
5454
"@octokit/rest": "22.0.0",
5555
"@hono/standard-validator": "0.2.0",
5656
"@hono/zod-validator": "0.4.2",
57-
"@opentui/core": "0.6.2",
58-
"@opentui/keymap": "0.6.2",
59-
"@opentui/solid": "0.6.2",
57+
"@opentui/core": "0.6.3",
58+
"@opentui/keymap": "0.6.3",
59+
"@opentui/solid": "0.6.3",
6060
"@tanstack/solid-virtual": "3.13.37",
6161
"@shikijs/stream": "4.4.3",
6262
"@standard-schema/spec": "1.1.0",

‎packages/plugin/package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@
3838
},
3939
"peerDependencies": {
4040
"@opencode/theme": "workspace:*",
41-
"@opentui/core": ">=0.6.2",
42-
"@opentui/solid": ">=0.6.2",
41+
"@opentui/core": ">=0.6.3",
42+
"@opentui/solid": ">=0.6.3",
4343
"solid-js": ">=1.9.0"
4444
},
4545
"peerDependenciesMeta": {

‎packages/tui/bunfig.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
preload = ["@opentui/solid/preload"]
22

33
[test]
4-
preload = ["@opentui/solid/preload"]
4+
preload = ["@opentui/solid/preload", "./test/preload.ts"]
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import type { ProgramStatus, ProgramStatusKind } from "@opentui/core"
2+
import { createEffect, onCleanup } from "solid-js"
3+
4+
export type PendingSession = { id: string; title?: string } & (
5+
| { state: "blocked"; kind: ProgramStatusKind; message?: string }
6+
| { state: "working" }
7+
)
8+
9+
const APP = "opencode"
10+
const ROOT = ""
11+
const encoder = new TextEncoder()
12+
const decoder = new TextDecoder()
13+
14+
// Mirrors pending session state into OSC 7501 records: one root summary plus one child record per
15+
// pending session. Terminals drop working and blocked records when the process exits.
16+
export function createProgramStatus(input: {
17+
renderer: { setProgramStatus(status: ProgramStatus): boolean }
18+
sessions: () => PendingSession[]
19+
}) {
20+
const sent = new Map<string, string>()
21+
22+
const send = (key: string, status: ProgramStatus) => {
23+
if (!input.renderer.setProgramStatus(status)) return
24+
if (status.state === "clear") {
25+
sent.delete(key)
26+
return
27+
}
28+
sent.set(key, JSON.stringify(status))
29+
}
30+
31+
createEffect(() => {
32+
const reports = programStatusReports(input.sessions())
33+
Array.from(sent.keys())
34+
.filter((key) => key !== ROOT && !reports.has(key))
35+
.forEach((key) => send(key, { state: "clear", id: key }))
36+
reports.forEach((status, key) => {
37+
if (sent.get(key) !== JSON.stringify(status)) send(key, status)
38+
})
39+
})
40+
41+
onCleanup(() => send(ROOT, { state: "clear" }))
42+
}
43+
44+
export function programStatusReports(sessions: PendingSession[]) {
45+
return new Map<string, ProgramStatus>([
46+
[ROOT, root(sessions)],
47+
...sessions.map((session): [string, ProgramStatus] => [session.id, record(session, session.id)]),
48+
])
49+
}
50+
51+
function root(sessions: PendingSession[]): ProgramStatus {
52+
const blocked = sessions.filter((session) => session.state === "blocked")
53+
const working = sessions.filter((session) => session.state === "working")
54+
if (blocked.length === 1) return record(blocked[0])
55+
if (blocked.length > 1)
56+
return {
57+
state: "blocked",
58+
kind: blocked.every((session) => session.kind === blocked[0].kind) ? blocked[0].kind : undefined,
59+
app: APP,
60+
message: `${blocked.length} sessions need input`,
61+
}
62+
if (working.length === 1) return record(working[0])
63+
if (working.length > 1) return { state: "working", app: APP, message: `${working.length} sessions working` }
64+
return { state: "idle", app: APP }
65+
}
66+
67+
function record(session: PendingSession, id?: string): ProgramStatus {
68+
const title = clip(session.title, 192)
69+
if (session.state === "working") return { state: "working", id, app: APP, title }
70+
return { state: "blocked", kind: session.kind, id, app: APP, title, message: clip(session.message, 2048) }
71+
}
72+
73+
// Records reject control characters and oversized fields, so normalize to one line within the byte limit.
74+
function clip(input: string | undefined, bytes: number) {
75+
const text = (input ?? "")
76+
.replace(/[\u0000-\u001F\u007F-\u009F]+/g, " ")
77+
.replace(/\s+/g, " ")
78+
.trim()
79+
if (!text) return
80+
const encoded = encoder.encode(text)
81+
if (encoded.byteLength <= bytes) return text
82+
// Leave room for the 3-byte ellipsis and drop a code point the byte cut split.
83+
return decoder.decode(encoded.subarray(0, bytes - 3)).replace(/\uFFFD+$/, "") + "…"
84+
}

‎packages/tui/src/context/session-tabs.tsx‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { useStorage } from "./storage"
1414
import { useTuiPaths } from "./runtime"
1515
import { newSessionLocation } from "../config/new-session-location"
1616
import { createSessionRetention } from "./session-retention"
17+
import { createProgramStatus, type PendingSession } from "./program-status"
1718
import { anchorKey, type AnchorTarget } from "../routes/session/anchors"
1819
import {
1920
closeSessionTab,
@@ -176,6 +177,29 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
176177
}
177178
}
178179

180+
createProgramStatus({
181+
renderer,
182+
sessions: () => {
183+
const viewed = route.data.type === "session" && route.data.sessionID !== "dummy" ? current() : undefined
184+
const tabs = enabled() ? state().tabs.map((tab) => tab.sessionID) : []
185+
return Array.from(new Set(viewed ? [...tabs, viewed] : tabs)).flatMap((sessionID): PendingSession[] => {
186+
const session = status(sessionID)
187+
if (session.attention)
188+
return [
189+
{
190+
id: sessionID,
191+
title: title(sessionID),
192+
state: "blocked",
193+
kind: session.attention,
194+
message: session.attention === "permission" ? "Permission needs input" : "Input needs response",
195+
},
196+
]
197+
if (session.busy) return [{ id: sessionID, title: title(sessionID), state: "working" }]
198+
return []
199+
})
200+
},
201+
})
202+
179203
// Shared storage updates must not re-admit a tab unless this client changes route or scope.
180204
createEffect(
181205
on(
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { expect, test } from "bun:test"
2+
import type { ProgramStatus } from "@opentui/core"
3+
import { createRoot, createSignal } from "solid-js"
4+
import { createProgramStatus, type PendingSession } from "../../src/context/program-status"
5+
6+
function setup(initial: PendingSession[] = []) {
7+
return createRoot((dispose) => {
8+
const reports: ProgramStatus[] = []
9+
const [sessions, setSessions] = createSignal(initial)
10+
createProgramStatus({
11+
renderer: {
12+
setProgramStatus(status) {
13+
reports.push(status)
14+
return true
15+
},
16+
},
17+
sessions,
18+
})
19+
return { reports, setSessions, dispose }
20+
})
21+
}
22+
23+
test("reports a blocked session on the root and its own record", () => {
24+
const status = setup()
25+
expect(status.reports).toEqual([{ state: "idle", app: "opencode" }])
26+
status.reports.length = 0
27+
28+
status.setSessions([
29+
{ id: "ses_a", title: "Fix\nbuild", state: "blocked", kind: "permission", message: "Allow bash?" },
30+
])
31+
expect(status.reports).toEqual([
32+
{ state: "blocked", kind: "permission", app: "opencode", title: "Fix build", message: "Allow bash?" },
33+
{ state: "blocked", kind: "permission", id: "ses_a", app: "opencode", title: "Fix build", message: "Allow bash?" },
34+
])
35+
status.dispose()
36+
})
37+
38+
test("summarizes several pending sessions and clears resolved ones", () => {
39+
const status = setup([
40+
{ id: "ses_a", state: "blocked", kind: "permission", message: "Allow bash?" },
41+
{ id: "ses_b", state: "blocked", kind: "question", message: "Pick one" },
42+
{ id: "ses_c", state: "working" },
43+
])
44+
expect(status.reports[0]).toEqual({ state: "blocked", app: "opencode", message: "2 sessions need input" })
45+
status.reports.length = 0
46+
47+
status.setSessions([{ id: "ses_c", state: "working" }])
48+
expect(status.reports).toEqual([
49+
{ state: "clear", id: "ses_a" },
50+
{ state: "clear", id: "ses_b" },
51+
{ state: "working", app: "opencode" },
52+
])
53+
status.reports.length = 0
54+
55+
status.dispose()
56+
expect(status.reports).toEqual([{ state: "clear" }])
57+
})
58+
59+
test("clips long titles to the protocol byte limit", () => {
60+
const status = setup([{ id: "ses_a", title: "é".repeat(200), state: "working" }])
61+
const title = status.reports[0].state === "working" ? status.reports[0].title : undefined
62+
expect(new TextEncoder().encode(title).byteLength).toBeLessThanOrEqual(192)
63+
expect(title?.endsWith("é…")).toBe(true)
64+
status.dispose()
65+
})

‎packages/tui/test/preload.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { NativeError, NativeStatus, OptimizedBuffer } from "@opentui/core"
2+
3+
// Workaround: OpenTUI's test renderer can read a frame while the native writer is still flushing
4+
// output, which throws OutputBusy until the event loop runs. Frame reads poll, so fall back to the
5+
// last frame read from the buffer. Remove once captureCharFrame waits for output idle upstream.
6+
const frames = new WeakMap<OptimizedBuffer, Uint8Array>()
7+
const getRealCharBytes = OptimizedBuffer.prototype.getRealCharBytes
8+
OptimizedBuffer.prototype.getRealCharBytes = function (addLineBreaks) {
9+
try {
10+
const bytes = getRealCharBytes.call(this, addLineBreaks)
11+
frames.set(this, bytes)
12+
return bytes
13+
} catch (error) {
14+
if (!(error instanceof NativeError) || error.status !== NativeStatus.OutputBusy) throw error
15+
return frames.get(this) ?? new Uint8Array()
16+
}
17+
}

0 commit comments

Comments
 (0)