Skip to content

Commit 8d33e45

Browse files
agustifivanmilevtues
authored andcommitted
feat(tui): restart approval dialog
(cherry picked from commit 9152632) Co-authored-by: Ivan Milev <ivanmilevtues@gmail.com>
1 parent 17260d7 commit 8d33e45

3 files changed

Lines changed: 307 additions & 7 deletions

File tree

‎packages/tui/src/app.tsx‎

Lines changed: 64 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ import { PromptRefProvider, usePromptRef } from "./context/prompt"
9494
import { Config, ConfigProvider, useConfig } from "./config"
9595
import { newSessionLocation } from "./config/new-session-location"
9696
import { UpdateNotificationProvider, useUpdateNotification, type UpdateSource } from "./context/update-notification"
97+
import { RestartApprovalProvider } from "./context/restart-approval"
9798
import { PluginProvider, usePlugin, type PackageSource } from "./plugin/context"
9899
import { localPluginDirectories } from "./plugin/discovery"
99100
import { PluginRoute, Slot } from "./plugin/render"
@@ -398,14 +399,16 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {
398399
<UpdateNotificationProvider
399400
updater={input.updater}
400401
>
401-
<PanelProvider>
402+
<RestartApprovalProvider>
403+
<PanelProvider>
402404
<PluginProvider
403405
packages={input.packages}
404406
directories={pluginDirectories}
405407
>
406408
<App />
407409
</PluginProvider>
408410
</PanelProvider>
411+
</RestartApprovalProvider>
409412
</UpdateNotificationProvider>
410413
</AttentionProvider>
411414
</EditorContextProvider>
@@ -1046,12 +1049,66 @@ function App() {
10461049
const restart = client.restart
10471050
if (!restart) return
10481051
dialog.clear()
1049-
toast.show({ variant: "info", message: "Restarting service…", duration: 30000 })
1050-
// restart resolves once the replacement service is healthy; the
1051-
// event stream reattaches through the reconnect loop.
1052-
await restart()
1053-
.then(() => toast.show({ variant: "success", message: "Service restarted" }))
1054-
.catch(toast.error)
1052+
const restartNow = () => {
1053+
toast.show({ variant: "info", message: "Restarting service…", duration: 30000 })
1054+
// restart resolves once the replacement service is healthy; the
1055+
// event stream reattaches through the reconnect loop.
1056+
return restart()
1057+
.then(() => toast.show({ variant: "success", message: "Service restarted" }))
1058+
.catch(toast.error)
1059+
}
1060+
const waitForIdle = async () => {
1061+
for (;;) {
1062+
const active = await client.api.session.active().catch(() => undefined)
1063+
if (!active || Object.keys(active).length === 0) return
1064+
await new Promise((resolve) => setTimeout(resolve, 2000))
1065+
}
1066+
}
1067+
const waitForDecision = () =>
1068+
new Promise<"now" | "idle" | "cancel">((resolve, reject) => {
1069+
const timer = setTimeout(() => reject(new Error("Restart request expired with no approver")), 120000)
1070+
const dispose = event.on("server.restart.resolved", (evt) => {
1071+
clearTimeout(timer)
1072+
dispose()
1073+
resolve(evt.data.decision)
1074+
})
1075+
})
1076+
const active = await client.api.session.active().catch(() => undefined)
1077+
if (!active || Object.keys(active).length === 0) {
1078+
await restartNow()
1079+
return
1080+
}
1081+
let requested
1082+
try {
1083+
requested = await client.api.server.restart.request()
1084+
} catch {
1085+
// Servers older than restart intents cannot approve; fall back.
1086+
toast.show({
1087+
variant: "warning",
1088+
message: "Server does not support restart approval; restarting directly…",
1089+
})
1090+
await restartNow()
1091+
return
1092+
}
1093+
if (Object.keys(requested.active).length === 0) {
1094+
await restartNow()
1095+
return
1096+
}
1097+
toast.show({
1098+
variant: "info",
1099+
message: `Waiting for restart approval (${Object.keys(requested.active).length} running)…`,
1100+
duration: 120000,
1101+
})
1102+
const winner = await waitForDecision().catch(async () => {
1103+
await client.api.server.restart.resolve({ decision: "cancel" }).catch(() => undefined)
1104+
return "cancel" as const
1105+
})
1106+
if (winner === "now") await restartNow()
1107+
else if (winner === "idle") {
1108+
toast.show({ variant: "info", message: "Restart queued; waiting for sessions to finish…" })
1109+
await waitForIdle()
1110+
await restartNow()
1111+
} else toast.show({ variant: "info", message: "Restart cancelled" })
10551112
},
10561113
category: "System",
10571114
},
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import type { ServiceEvent } from "@opencode/schema/service-event"
2+
import { createSignal, For, Show } from "solid-js"
3+
import { SessionQuestion } from "../routes/session/permission"
4+
import { useDialog } from "../ui/dialog"
5+
import { useToast } from "../ui/toast"
6+
import { errorMessage } from "../util/error"
7+
import { useClient } from "./client"
8+
import { useData } from "./data"
9+
import { useEvent } from "./event"
10+
import { createSimpleContext } from "./helper"
11+
12+
export const { use: useRestartApproval, provider: RestartApprovalProvider } =
13+
createSimpleContext({
14+
name: "RestartApproval",
15+
init: () => {
16+
const client = useClient()
17+
const dialog = useDialog()
18+
const event = useEvent()
19+
const toast = useToast()
20+
const [active, setActive] = createSignal<ReadonlyArray<string>>([])
21+
22+
function open(sessions: ReadonlyArray<string>) {
23+
setActive(sessions)
24+
dialog.replace(() => (
25+
<RestartApprovalDialog
26+
active={active()}
27+
onSelect={(decision) => void decide(decision)}
28+
/>
29+
))
30+
}
31+
32+
function close() {
33+
setActive([])
34+
dialog.clear()
35+
}
36+
37+
async function decide(decision: ServiceEvent.Decision) {
38+
try {
39+
await client.api.server.restart.resolve({ decision })
40+
} catch (error) {
41+
toast.show({
42+
title: "Failed to resolve restart",
43+
message: errorMessage(error),
44+
variant: "error",
45+
})
46+
}
47+
close()
48+
}
49+
50+
event.on("server.restart.requested", (evt) => open(evt.data.active))
51+
event.on("server.restart.resolved", () => close())
52+
53+
return { open, close, decide }
54+
},
55+
})
56+
57+
function RestartApprovalDialog(props: {
58+
active: ReadonlyArray<string>
59+
onSelect: (decision: ServiceEvent.Decision) => void
60+
}) {
61+
const data = useData()
62+
63+
return (
64+
<SessionQuestion
65+
id="service.restart-approval"
66+
group="Service"
67+
choicesLabel="Restart options"
68+
instance={props.active.join(", ")}
69+
title="Restart service with running agents?"
70+
body={
71+
<box paddingLeft={1} gap={1}>
72+
<text>
73+
The following sessions have running agents and would be interrupted:
74+
</text>
75+
<box flexDirection="column" paddingLeft={1}>
76+
<For each={props.active}>
77+
{(sessionID) => (
78+
<text>- {data.session.get(sessionID)?.title ?? sessionID}</text>
79+
)}
80+
</For>
81+
</box>
82+
<Show when={props.active.length === 0}>
83+
<text>No sessions are running anymore.</text>
84+
</Show>
85+
</box>
86+
}
87+
options={{
88+
now: "Restart now",
89+
idle: "When idle",
90+
cancel: "Cancel restart",
91+
}}
92+
escapeKey="cancel"
93+
onSelect={(option) => props.onSelect(option)}
94+
/>
95+
)
96+
}
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
/** @jsxImportSource @opentui/solid */
2+
import { expect, test } from "bun:test"
3+
import { testRender } from "@opentui/solid"
4+
import { ConfigProvider } from "../../../src/config"
5+
import { ClientProvider } from "../../../src/context/client"
6+
import { DataProvider, useData } from "../../../src/context/data"
7+
import { Keymap } from "../../../src/context/keymap"
8+
import {
9+
RestartApprovalProvider,
10+
useRestartApproval,
11+
} from "../../../src/context/restart-approval"
12+
import { ThemeProvider } from "../../../src/context/theme"
13+
import { DialogProvider } from "../../../src/ui/dialog"
14+
import { ToastProvider } from "../../../src/ui/toast"
15+
import { emptyThemeSource } from "../../fixture/fixture"
16+
import {
17+
createApi,
18+
createEventStream,
19+
createFetch,
20+
json,
21+
} from "../../fixture/tui-client"
22+
import { TestTuiContexts } from "../../fixture/tui-environment"
23+
import { createTuiResolvedConfig } from "../../fixture/tui-runtime"
24+
25+
const directory = "/tmp/opencode/restart-approval"
26+
27+
test("restart request opens approval dialog and deciding resolves the intent", async () => {
28+
const fixture = await renderApproval()
29+
try {
30+
await fixture.data.session.sync("ses_1")
31+
fixture.events.emit({
32+
id: "evt_restart_requested",
33+
type: "server.restart.requested",
34+
created: 1,
35+
data: { active: ["ses_1", "ses_2"] },
36+
})
37+
await fixture.app.waitForFrame((frame) =>
38+
frame.includes("Restart service with running agents?"),
39+
)
40+
const frame = await fixture.app.waitForFrame((frame) =>
41+
frame.includes("Lane one"),
42+
)
43+
expect(frame).toContain("ses_2")
44+
45+
await fixture.approval.decide("idle")
46+
47+
await fixture.app.waitFor(() => fixture.resolves.length === 1)
48+
expect(fixture.resolves).toEqual([{ decision: "idle" }])
49+
} finally {
50+
fixture.app.renderer.destroy()
51+
}
52+
})
53+
54+
test("resolution from another surface dismisses the dialog", async () => {
55+
const fixture = await renderApproval()
56+
try {
57+
fixture.events.emit({
58+
id: "evt_restart_requested",
59+
type: "server.restart.requested",
60+
created: 1,
61+
data: { active: ["ses_1"] },
62+
})
63+
await fixture.app.waitForFrame((frame) =>
64+
frame.includes("Restart service with running agents?"),
65+
)
66+
fixture.events.emit({
67+
id: "evt_restart_resolved",
68+
type: "server.restart.resolved",
69+
created: 2,
70+
data: { decision: "now" },
71+
})
72+
await fixture.app.waitForFrame(
73+
(frame) => !frame.includes("Restart service with running agents?"),
74+
)
75+
expect(fixture.resolves).toEqual([])
76+
} finally {
77+
fixture.app.renderer.destroy()
78+
}
79+
})
80+
81+
async function renderApproval() {
82+
const resolves: unknown[] = []
83+
const events = createEventStream()
84+
const calls = createFetch(async (url, request) => {
85+
if (url.pathname === "/api/server/restart/resolve") {
86+
const payload = await request.json()
87+
resolves.push(payload)
88+
return json({ decision: payload.decision })
89+
}
90+
if (url.pathname === "/api/session/ses_1") {
91+
return json({
92+
data: {
93+
id: "ses_1",
94+
projectID: "proj_test",
95+
location: { directory },
96+
title: "Lane one",
97+
cost: 0,
98+
tokens: {
99+
input: 0,
100+
output: 0,
101+
reasoning: 0,
102+
cache: { read: 0, write: 0 },
103+
},
104+
time: { created: 1, updated: 1 },
105+
},
106+
})
107+
}
108+
return undefined
109+
}, events)
110+
let data!: ReturnType<typeof useData>
111+
let approval!: ReturnType<typeof useRestartApproval>
112+
113+
function Probe() {
114+
data = useData()
115+
approval = useRestartApproval()
116+
return null
117+
}
118+
119+
const app = await testRender(
120+
() => (
121+
<TestTuiContexts cwd={directory}>
122+
<ConfigProvider config={createTuiResolvedConfig()}>
123+
<Keymap.Provider>
124+
<ToastProvider>
125+
<ClientProvider api={createApi(calls.fetch)}>
126+
<DataProvider directory={directory}>
127+
<ThemeProvider mode="dark" source={emptyThemeSource}>
128+
<DialogProvider>
129+
<RestartApprovalProvider>
130+
<Probe />
131+
</RestartApprovalProvider>
132+
</DialogProvider>
133+
</ThemeProvider>
134+
</DataProvider>
135+
</ClientProvider>
136+
</ToastProvider>
137+
</Keymap.Provider>
138+
</ConfigProvider>
139+
</TestTuiContexts>
140+
),
141+
{ width: 100, height: 30, kittyKeyboard: true },
142+
)
143+
app.renderer.start()
144+
await app.waitFor(() => approval !== undefined)
145+
146+
return { app, data, approval, events, resolves }
147+
}

0 commit comments

Comments
 (0)