Skip to content

Commit 59a41a5

Browse files
committed
fix(session): preserve active agent for isolated aside (anomalyco#89)
2 parents 961cc65 + 2be4d85 commit 59a41a5

8 files changed

Lines changed: 593 additions & 79 deletions

File tree

‎packages/opencode/src/session/aside.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,9 @@ const live = Layer.effect(
122122
.join("\n"),
123123
}))
124124
const previous = selectedHistory.previous
125-
const agent = yield* agents.get(input.agent ?? previous?.agent ?? (yield* agents.defaultAgent()))
125+
const agent = yield* agents.get(
126+
input.agent ?? captured.parent.agent ?? previous?.agent ?? (yield* agents.defaultAgent()),
127+
)
126128
if (!agent) return yield* new AsideError({ message: "Aside agent not found" })
127129
const selected =
128130
input.model ??

‎packages/opencode/test/server/httpapi-aside.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,51 @@ const writeAssistant = Effect.fn("test.writeAsideAssistant")(function* (
115115
return info
116116
})
117117

118+
it.live("aside uses the active agent before its promoted user has an assistant", () =>
119+
Effect.gen(function* () {
120+
const llm = yield* TestLLMServer
121+
const directory = yield* tmpdirScoped({
122+
config: {
123+
...testProviderConfig(llm.url),
124+
agent: { build: { top_p: 0.2 }, plan: { top_p: 0.8 } },
125+
},
126+
})
127+
yield* Effect.gen(function* () {
128+
const session = yield* Session.Service
129+
const parent = yield* session.create({ title: "Promoted agent" })
130+
const user = yield* writeUser(parent, 1, "Completed build task")
131+
const answer = yield* writeAssistant(parent, user.id, { created: 2, completed: 3, text: "Build answer" })
132+
const promoted = yield* writeUser(parent, 4, "New plan task excluded from snapshot")
133+
yield* session.updateMessage({ ...promoted, agent: "plan" })
134+
yield* session.setAgentModel({
135+
sessionID: parent.id,
136+
agent: "plan",
137+
model: { providerID: promoted.model.providerID, id: promoted.model.modelID },
138+
time: 4,
139+
})
140+
const before = yield* session.messages({ sessionID: parent.id })
141+
yield* llm.text("Using the active agent")
142+
const response = yield* aside(directory, parent.id)
143+
expect(response.status).toBe(200)
144+
expect(yield* response.json).toMatchObject({
145+
snapshot: { throughMessageID: answer.id, excludedMessageCount: 1 },
146+
})
147+
expect((yield* llm.inputs)[0]).toMatchObject({ top_p: 0.8 })
148+
expect(JSON.stringify((yield* llm.inputs)[0])).not.toContain("New plan task excluded from snapshot")
149+
expect(yield* session.messages({ sessionID: parent.id })).toEqual(before)
150+
yield* llm.text("Using the explicit agent")
151+
const explicit = yield* post(directory, `/session/${parent.id}/aside`, {
152+
requestID: "explicit-agent",
153+
question: "Explain with build",
154+
agent: "build",
155+
})
156+
expect(explicit.status).toBe(200)
157+
expect((yield* llm.inputs)[1]).toMatchObject({ top_p: 0.2 })
158+
expect((yield* session.get(parent.id)).agent).toBe("plan")
159+
}).pipe(provideInstanceEffect(directory))
160+
}).pipe(Effect.provide(Layer.fresh(TestLLMServer.layer))),
161+
)
162+
118163
it.live("untrusted compaction markers cannot reorder a previous trusted retained tail", () =>
119164
Effect.gen(function* () {
120165
const llm = yield* TestLLMServer

‎packages/tui/src/app.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,7 @@ function App(props: { onSnapshot?: () => Promise<string[]>; pluginHost: TuiPlugi
682682
category: "Agent",
683683
slashName: "agents",
684684
run: () => {
685+
if (promptRef.current?.agent) return promptRef.current.agent.select()
685686
dialog.replace(() => <DialogAgent />)
686687
},
687688
},
@@ -700,6 +701,7 @@ function App(props: { onSnapshot?: () => Promise<string[]>; pluginHost: TuiPlugi
700701
category: "Agent",
701702
hidden: true,
702703
run: () => {
704+
if (promptRef.current?.agent) return promptRef.current.agent.cycle(1)
703705
local.agent.move(1)
704706
},
705707
},
@@ -734,6 +736,7 @@ function App(props: { onSnapshot?: () => Promise<string[]>; pluginHost: TuiPlugi
734736
category: "Agent",
735737
hidden: true,
736738
run: () => {
739+
if (promptRef.current?.agent) return promptRef.current.agent.cycle(-1)
737740
local.agent.move(-1)
738741
},
739742
},

‎packages/tui/src/component/dialog-agent.tsx‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { useLocal } from "../context/local"
33
import { DialogSelect } from "../ui/dialog-select"
44
import { useDialog } from "../ui/dialog"
55

6-
export function DialogAgent() {
6+
export function DialogAgent(props: { selection?: { current?: string; select: (agent: string) => void } } = {}) {
77
const local = useLocal()
88
const dialog = useDialog()
99

@@ -19,11 +19,12 @@ export function DialogAgent() {
1919

2020
return (
2121
<DialogSelect
22-
title="Select agent"
23-
current={local.agent.current()?.name}
22+
title={props.selection ? "Queue agent" : "Select agent"}
23+
current={props.selection ? props.selection.current : local.agent.current()?.name}
2424
options={options()}
2525
onSelect={(option) => {
26-
local.agent.set(option.value)
26+
if (props.selection) props.selection.select(option.value)
27+
if (!props.selection) local.agent.set(option.value)
2728
dialog.clear()
2829
}}
2930
/>

‎packages/tui/src/component/prompt/delivery.tsx‎

Lines changed: 58 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,20 @@ const empty = (): Buffer => ({ prompt: { input: "", parts: [] }, cursor: 0, revi
1616
const createComposerState = () =>
1717
createStore({
1818
mode: "send" as Delivery,
19+
queueAgent: undefined as string | undefined,
1920
task: empty(),
2021
aside: undefined as Buffer | undefined,
2122
result: undefined as AsideResult | undefined,
2223
question: "",
2324
transaction: undefined as
24-
| { requestID: string; delivery: "queue" | "steer"; text: string; revision: number; uncertain?: boolean }
25+
| {
26+
requestID: string
27+
delivery: "queue" | "steer"
28+
text: string
29+
revision: number
30+
agent?: string
31+
uncertain?: boolean
32+
}
2533
| undefined,
2634
sending: false,
2735
cleared: 0,
@@ -79,6 +87,12 @@ export const useComposerDelivery = (props: {
7987
restore()
8088
}
8189
const cycle = () => select(state.mode === "aside" ? "queue" : state.mode === "queue" ? "steer" : "aside")
90+
const chooseAgent = (agent: string) => {
91+
if (!mounted || state.queueAgent === agent) return
92+
save()
93+
setState("queueAgent", agent)
94+
setState("task", "revision", (value) => value + 1)
95+
}
8296
const cancelAside = () => {
8397
if (!active) return
8498
const request = active
@@ -218,6 +232,7 @@ export const useComposerDelivery = (props: {
218232
delivery: state.mode,
219233
text,
220234
revision: state.task.revision,
235+
agent: state.mode === "queue" ? state.queueAgent : undefined,
221236
})
222237
await retry()
223238
return true
@@ -234,6 +249,7 @@ export const useComposerDelivery = (props: {
234249
requestID: transaction.requestID,
235250
delivery: transaction.delivery,
236251
text: transaction.text,
252+
agent: transaction.agent,
237253
},
238254
},
239255
{ throwOnError: false, signal: AbortSignal.timeout(15_000) },
@@ -327,6 +343,7 @@ export const useComposerDelivery = (props: {
327343
save,
328344
select,
329345
cycle,
346+
chooseAgent,
330347
submit,
331348
retry,
332349
reconcile,
@@ -342,13 +359,7 @@ export const useComposerDelivery = (props: {
342359
}
343360
}
344361

345-
export const ComposerDelivery = (props: {
346-
controller: ReturnType<typeof useComposerDelivery>
347-
busy: boolean
348-
activate?: () => void
349-
submit: () => void
350-
useSessionModel?: () => void
351-
}) => {
362+
export const ComposerDelivery = (props: { controller: ReturnType<typeof useComposerDelivery> }) => {
352363
const c = props.controller
353364
const { theme } = useTheme()
354365
const renderer = useRenderer()
@@ -357,7 +368,6 @@ export const ComposerDelivery = (props: {
357368
action()
358369
}
359370
const dimensions = useTerminalDimensions()
360-
const shortcut = useCommandShortcut("prompt.delivery.cycle")
361371
const [now, setNow] = createSignal(Date.now())
362372
onMount(() => {
363373
const timer = setInterval(() => setNow(Date.now()), 5_000)
@@ -420,58 +430,57 @@ export const ComposerDelivery = (props: {
420430
</scrollbox>
421431
</box>
422432
</Show>
423-
<Show when={c.state.mode !== "send" || props.busy}>
424-
<box flexDirection="row" gap={1} flexWrap="wrap">
433+
</>
434+
)
435+
}
436+
437+
export const ComposerModes = (props: {
438+
controller: ReturnType<typeof useComposerDelivery>
439+
busy: boolean
440+
activate?: () => void
441+
}) => {
442+
const c = props.controller
443+
const { theme } = useTheme()
444+
const renderer = useRenderer()
445+
const dimensions = useTerminalDimensions()
446+
const shortcut = useCommandShortcut("prompt.delivery.cycle")
447+
const click = (action: () => void) => () => {
448+
if (renderer.getSelection()?.getSelectedText()) return
449+
props.activate?.()
450+
action()
451+
}
452+
return (
453+
<Show when={c.state.mode !== "send" || props.busy}>
454+
<box id="composer-modes" flexDirection="row" gap={1} flexShrink={0}>
455+
<Show
456+
when={dimensions().width >= 80}
457+
fallback={
458+
<text id="composer-mode-cycle" fg={theme.primary} onMouseUp={click(c.cycle)}>
459+
{`[${c.state.mode[0].toUpperCase()}${c.state.mode.slice(1)}]`}
460+
</text>
461+
}
462+
>
425463
<For each={["aside", "queue", "steer"] as const}>
426464
{(mode) => (
427465
<text
428466
id={`composer-${mode}`}
429467
fg={c.state.mode === mode ? theme.primary : theme.textMuted}
430-
onMouseUp={click(() => {
431-
props.activate?.()
432-
c.select(mode)
433-
})}
468+
onMouseUp={click(() => c.select(mode))}
434469
>
435470
{c.state.mode === mode
436471
? `[${mode[0].toUpperCase()}${mode.slice(1)}]`
437-
: ` ${mode[0].toUpperCase()}${mode.slice(1)} `}
472+
: `${mode[0].toUpperCase()}${mode.slice(1)}`}
438473
</text>
439474
)}
440475
</For>
441-
<text fg={theme.textMuted}>{shortcut()} mode</text>
442-
<Show when={!props.busy && !c.state.transaction}>
443-
<text id="composer-send" fg={theme.textMuted} onMouseUp={click(() => c.select("send"))}>
444-
Use normal Send
445-
</text>
446-
</Show>
447-
</box>
448-
<text fg={theme.textMuted}>
449-
{c.state.mode === "aside"
450-
? "Task draft saved. Snapshot only; no tools. Esc closes Aside."
451-
: c.state.mode === "queue"
452-
? "After task is idle. Uses session agent/model."
453-
: "At next safe boundary. Uses session agent/model."}
454-
</text>
455-
<text minHeight={1} fg={theme.warning}>
456-
{c.blocked() ?? ""}
457-
</text>
458-
<Show when={props.useSessionModel}>
459-
<text id="composer-session-model" fg={theme.primary} onMouseUp={click(() => props.useSessionModel?.())}>
460-
Use session model
476+
</Show>
477+
<text fg={theme.textMuted}>{shortcut()}</text>
478+
<Show when={!props.busy && !c.state.transaction}>
479+
<text id="composer-send" fg={theme.textMuted} onMouseUp={click(() => c.select("send"))}>
480+
Send
461481
</text>
462482
</Show>
463-
<text id="composer-submit" fg={c.blocked() ? theme.textMuted : theme.primary} onMouseUp={click(props.submit)}>
464-
{c.state.mode === "aside"
465-
? c.asideBusy()
466-
? "Asking Aside..."
467-
: "Enter: Ask aside"
468-
: c.state.sending
469-
? "Admitting..."
470-
: c.state.mode === "queue"
471-
? "Enter: Queue message"
472-
: "Enter: Steer task"}
473-
</text>
474-
</Show>
475-
</>
483+
</box>
484+
</Show>
476485
)
477486
}

0 commit comments

Comments
 (0)