Compare commits

...

6 Commits

Author SHA1 Message Date
Kit Langton 7b73f20fcc fix(core): preserve approvals across location cleanup 2026-08-31 20:45:18 -04:00
opencode-agent[bot] b0402f5a34 fix(session-ui): reduce inline code height (#46500)
Co-authored-by: David Hill <1879069+iamdavidhill@users.noreply.github.com>
2026-09-01 08:26:46 +08:00
Kit Langton 54b00ec5fe test(tui): capture flushed Mini scrollback output (#46505) 2026-08-31 20:26:36 -04:00
Kit Langton 6dd1733bbf fix(core): preserve continuation across chained moves
Carry unfinished model work across consecutive Location handoffs without resetting the logical step allowance. Keep idle moves and queued prompt admission unchanged. Cover steered and queued second moves, preserved tool history, and durable event ordering.
2026-08-31 20:12:47 -04:00
opencode-agent[bot] 663c2dc1ce fix(app): raise composer only in dark mode (#46503)
Co-authored-by: Brendonovich <14191578+Brendonovich@users.noreply.github.com>
2026-09-01 08:12:09 +08:00
Kit Langton 01eda4c178 refactor(codemode): name only supported operations (#46082) 2026-08-31 20:00:13 -04:00
15 changed files with 304 additions and 66 deletions
@@ -1,5 +1,16 @@
import { expect, story } from "../../storybook/playwright/story"
story("raises the docked composer only in dark mode", async ({ mount, page }) => {
const component = await mount("opencode-composer-flow--empty-draft")
const composer = component.locator('[data-component="composer"]')
await page.locator("html").evaluate((root) => root.setAttribute("data-color-scheme", "light"))
await expect(composer).toHaveCSS("background-color", "rgb(255, 255, 255)")
await page.locator("html").evaluate((root) => root.setAttribute("data-color-scheme", "dark"))
await expect(composer).toHaveCSS("background-color", "rgb(36, 36, 36)")
})
for (const draft of ["empty-draft", "multiline-draft", "mixed-attachments"]) {
story(`select all stays inside the composer with ${draft}`, async ({ mount, page }) => {
const component = await mount(`opencode-composer-flow--${draft}`)
@@ -1,3 +1,7 @@
[data-component="composer-editor"]:empty::before {
content: "\200B";
}
[data-color-scheme="dark"] [data-component="composer"][data-dock-border-underlay="true"] {
background: var(--v2-background-bg-layer-01);
}
+1 -3
View File
@@ -114,10 +114,8 @@ export function ComposerEditor(props: ComposerEditorProps) {
<form
data-component="composer"
data-dock-border-underlay={props.borderUnderlay ? "true" : undefined}
class="group/composer relative min-h-[96px] w-full overflow-clip rounded-xl"
class="group/composer relative min-h-[96px] w-full overflow-clip rounded-xl bg-v2-background-bg-base"
classList={{
"bg-v2-background-bg-layer-01": props.borderUnderlay,
"bg-v2-background-bg-base": !props.borderUnderlay,
"shadow-[var(--v2-elevation-raised)]": !props.borderUnderlay,
"border border-v2-icon-icon-info border-dashed": state.drag === "active",
}}
+1 -1
View File
@@ -53,7 +53,6 @@ export const fromSpec = (options: Options): Result => {
if (!isRecord(pathValue)) continue
for (const [method, operationValue] of Object.entries(pathValue)) {
if (!methods.has(method) || !isRecord(operationValue)) continue
const segments = operationPath(method, path, operationValue, used, namespaces)
const operation: Operation = {
operationId: nonEmptyString(operationValue.operationId),
method: method.toUpperCase(),
@@ -99,6 +98,7 @@ export const fromSpec = (options: Options): Result => {
auth: options.auth,
headers: options.headers ?? {},
}
const segments = operationPath(method, path, operationValue, used, namespaces)
used.add(segments.join("."))
for (const index of segments.slice(0, -1).keys()) namespaces.add(segments.slice(0, index + 1).join("."))
setTool(
+24
View File
@@ -282,6 +282,30 @@ describe("OpenAPI.fromSpec", () => {
expect(Tool.isTool(toolAt(result.tools, "group.operation.other"))).toBe(true)
})
test("does not reserve names for unsupported operations between duplicate operation IDs", () => {
const operation = { operationId: "group.item", responses: { 200: { description: "Success" } } }
for (const unsupported of [false, true]) {
const result = OpenAPI.fromSpec({
baseUrl,
spec: {
openapi: "3.1.0",
paths: {
"/first": { get: operation },
...(unsupported ? { "/unsupported": { get: { ...operation, "x-websocket": true } } } : {}),
"/last": { get: operation },
},
},
})
expect(Object.keys(result.tools)).toEqual(["group", "group_item_2"])
expect(toolAt(result.tools, "group.item")).toMatchObject({ _tag: "CodeModeTool", description: "GET /first" })
expect(toolAt(result.tools, "group_item_2")).toMatchObject({ _tag: "CodeModeTool", description: "GET /last" })
expect(result.skipped).toEqual(
unsupported ? [{ method: "GET", path: "/unsupported", reason: "WebSocket operations are not supported" }] : [],
)
}
})
test("synthesizes flat operation IDs from methods and paths", () => {
const response = { responses: { 200: { description: "Success" } } }
const tools = OpenAPI.fromSpec({
+15 -13
View File
@@ -1,6 +1,6 @@
export * as LocationActivity from "./location-activity.js"
import { Clock, Context, Duration, Effect, Layer, RcMap, Schema } from "effect"
import { Clock, Context, Duration, Effect, Layer, MutableHashMap, RcMap, References, Schema } from "effect"
import { Bus } from "./bus.js"
import { Location } from "./location.js"
import { LocationServiceMap } from "./location-service-map.js"
@@ -39,11 +39,7 @@ export function layer(options: { readonly timeToLive?: Duration.Input; readonly
yield* Effect.sleep(options.sweepInterval ?? "1 minute")
const refs = Array.from(yield* RcMap.keys(locations.rcMap))
const cached = new Set(refs.map(key))
yield* Effect.forEach(
refs,
(ref) => (entries.has(key(ref)) ? Effect.void : touch(ref)),
{ discard: true },
)
yield* Effect.forEach(refs, (ref) => (entries.has(key(ref)) ? Effect.void : touch(ref)), { discard: true })
for (const id of entries.keys()) {
if (!cached.has(id)) entries.delete(id)
}
@@ -51,13 +47,19 @@ export function layer(options: { readonly timeToLive?: Duration.Input; readonly
const expired = Array.from(entries.values()).filter((entry) => entry.expiresAt <= now)
yield* Effect.forEach(
expired,
(entry) => {
entries.delete(key(entry.ref))
return Effect.logInfo("location services evicted", {
directory: entry.ref.directory,
workspaceID: entry.ref.workspaceID,
}).pipe(Effect.andThen(locations.invalidate(entry.ref)))
},
// A new borrower must not arrive between the ref-count check and cache removal.
(entry) =>
Effect.suspend(() => {
if (locations.rcMap.state._tag === "Closed") return Effect.void
const cached = MutableHashMap.get(locations.rcMap.state.map, entry.ref)
// Invalidation detaches even borrowed entries, hiding live permissions and forms from later readers.
if (cached._tag === "Some" && cached.value.refCount > 0) return Effect.void
entries.delete(key(entry.ref))
return Effect.logInfo("location services evicted", {
directory: entry.ref.directory,
workspaceID: entry.ref.workspaceID,
}).pipe(Effect.andThen(locations.invalidate(entry.ref)))
}).pipe(Effect.provideService(References.PreventSchedulerYield, true)),
{ discard: true },
)
}).pipe(Effect.forever, Effect.forkScoped)
+1 -1
View File
@@ -96,7 +96,7 @@ const layer = Layer.effect(
step = 1
}
if (pending?.type === "move")
return DrainResult.Moved({ continuation: !entering && continuing ? { step } : undefined })
return DrainResult.Moved({ continuation: continuing ? { step } : undefined })
if (pending?.type === "compaction") {
const session = yield* store.get(sessionID)
if (!session) return yield* Effect.die(new Error(`Session not found: ${sessionID}`))
+24
View File
@@ -5,10 +5,12 @@ import { Config } from "@opencode-ai/schema/config"
import { Money } from "@opencode-ai/schema/money"
import {
DateTime,
Context,
Deferred,
Duration,
Effect,
Equal,
Exit,
Fiber,
Hash,
Layer,
@@ -16,6 +18,7 @@ import {
Option,
RcMap,
Schema,
Scope,
Stream,
} from "effect"
import { TestClock } from "effect/testing"
@@ -82,6 +85,27 @@ const itWithActivity = testEffect(
)
describe("LocationServiceMap", () => {
itWithActivity.effect("keeps borrowed locations discoverable after the activity timeout", () =>
Effect.gen(function* () {
const locations = yield* LocationServiceMap.Service
const ref = Location.Ref.make({ directory: AbsolutePath.make("/project") })
const scope = yield* Scope.make()
yield* Effect.addFinalizer((exit) => Scope.close(scope, exit))
const context = yield* locations.contextEffect(ref).pipe(Scope.provide(scope))
// A permission wait owns the Location without producing new Session events.
yield* TestClock.adjust("61 minutes")
const cached = yield* locations.contextEffectOption(ref).pipe(Effect.scoped)
expect(Option.getOrUndefined(Option.map(cached, (value) => Context.get(value, Location.Service)))).toBe(
Context.get(context, Location.Service),
)
yield* Scope.close(scope, Exit.void)
yield* TestClock.adjust("1 minute")
expect(Array.from(yield* RcMap.keys(locations.rcMap))).toEqual([])
}),
)
itWithActivity.effect("does not refresh lifetime from inferred Session routing", () =>
Effect.gen(function* () {
const locations = yield* LocationServiceMap.Service
+42 -25
View File
@@ -1454,32 +1454,49 @@ describe("SessionRunnerLLM", () => {
).toEqual([Bus.versionedType(SessionEvent.Moved.type, 1), Bus.versionedType(SessionEvent.InboxDelivered.type, 1)])
})
scenario("preserves a tool continuation across a steered move", function* (s) {
yield* s.admit("Echo before moving")
yield* s.llm.push(TestLLM.tool("call-move", "echo", { text: "moving" }), TestLLM.text("Done", "text-after-move"))
const tools = yield* s.blockTools()
const run = yield* s.resume.pipe(Effect.forkChild)
yield* tools.started
yield* s.sessionInbox.admit({
id: SessionMessage.ID.create(),
sessionID,
item: {
type: "move",
payload: {
location: Location.Ref.make({ directory: AbsolutePath.make("/project") }),
projectID: Project.ID.global,
},
delivery: "steer",
},
for (const delivery of ["steer", "queue"] as const) {
scenario(`preserves a tool continuation and step allowance across chained moves (${delivery})`, function* (s) {
const agents = yield* Agent.Service
yield* agents.transform((editor) =>
editor.update(Agent.ID.make("build"), (agent) => {
agent.steps = 2
}),
)
yield* s.admit("Echo before moving")
yield* s.llm.push(TestLLM.tool("call-move", "echo", { text: "moving" }), TestLLM.text("Done", "text-after-move"))
const tools = yield* s.blockTools()
const run = yield* s.resume.pipe(Effect.forkChild)
yield* tools.started
yield* Effect.forEach(["steer", delivery] as const, (delivery) =>
s.sessionInbox.admit({
id: SessionMessage.ID.create(),
sessionID,
item: {
type: "move",
payload: {
location: Location.Ref.make({ directory: AbsolutePath.make("/project") }),
projectID: Project.ID.global,
},
delivery,
},
}),
)
yield* tools.release
yield* Fiber.join(run)
expect(s.requests).toHaveLength(2)
expect(messageRoles(s.requests[1])?.slice(0, 3)).toEqual(["user", "assistant", "tool"])
expect(s.requests[0]?.toolChoice).toBeUndefined()
expect(s.requests[1]?.toolChoice).toMatchObject({ type: "none" })
expect(
(yield* recordedEventTypes(sessionID)).filter(
(type) => type === "session.step.started.1" || type === "session.moved.1",
),
).toEqual(["session.step.started.1", "session.moved.1", "session.moved.1", "session.step.started.1"])
expect(yield* s.inbox).toEqual([])
})
yield* tools.release
yield* Fiber.join(run)
expect(s.requests).toHaveLength(2)
expect(s.requests.map(messageRoles).at(1)?.slice(0, 3)).toEqual(["user", "assistant", "tool"])
expect(yield* s.inbox).toEqual([])
})
}
scenario("keeps queued input parked across a mid-turn move", function* (s) {
yield* s.admit("Echo before moving")
@@ -153,6 +153,19 @@ story("mounts cached completed Markdown with sanitized HTML and decorations", as
await expect(markdown).toHaveAttribute("data-markdown-ready", "")
})
story("keeps inline code backgrounds 18px tall", async ({ page }) => {
await page.evaluate(async (fixture) => {
const { mountMarkdown } = await import(fixture)
await mountMarkdown({ text: "`value` and `src/file.ts`" })
}, fixture)
const code = page.getByTestId("markdown-fixture").locator(":not(pre) > code")
await expect(code).toHaveCount(2)
await expect(code.nth(1)).toHaveAttribute("data-inline-code-kind", "path")
expect(
await code.evaluateAll((elements) => elements.map((element) => element.getBoundingClientRect().height)),
).toEqual([18, 18])
})
story("shares in-flight Markdown rendering without overwriting a reclaimed cache entry", async ({ page }) => {
const result = await page.evaluate(async (fixture) => {
const { getCachedMarkdown, renderCachedMarkdown } = await import(fixture)
@@ -283,7 +283,7 @@
font-feature-settings: var(--font-family-mono--font-feature-settings);
color: var(--v2-text-text-base);
font-weight: var(--font-weight-medium);
padding: 2px 4px;
padding: 0 4px;
border-radius: 4px;
background: color-mix(in oklch, var(--v2-text-text-base) var(--markdown-inline-code-bg-mix), transparent);
}
@@ -93,6 +93,8 @@ async function setup(
return {
renderer: out.renderer,
renderOnce: out.renderOnce,
externalOutput: out.externalOutput,
scrollback: new RunScrollbackStream(out.renderer, input.theme ?? RUN_THEME_FALLBACK, {
treeSitterClient,
wrote: input.wrote ?? false,
@@ -220,28 +222,22 @@ test.each([false, true])("monochrome switches preserve printed blocks and open f
await out.scrollback.setMono(mono)
out.scrollback.setTheme(mono ? RUN_THEME_MONO : RUN_THEME_FALLBACK)
await out.scrollback.append(assistant('Printed block\n\n```ts\nconst arrow = "'))
const printed = claim(out.renderer)
try {
expect(render(printed)).toContain("Printed block")
expect(render(printed)).not.toContain("const arrow")
await out.scrollback.setMono(!mono)
out.scrollback.setTheme(mono ? RUN_THEME_FALLBACK : RUN_THEME_MONO)
expect(render(claim(out.renderer))).toBe("")
await out.scrollback.append(assistant('\u2192"\n```\n\nNext block'))
await out.scrollback.complete()
const next = claim(out.renderer)
try {
expect(render(next)).toContain(mono ? 'const arrow = "\u2192"' : 'const arrow = "->"')
expect(render(next)).toContain("Next block")
expect(render(next)).not.toContain("Printed block")
expect(render(next)).not.toContain("```")
expect(render(printed)).toContain("Printed block")
} finally {
destroy(next)
}
} finally {
destroy(printed)
}
await out.renderOnce()
const printed = out.externalOutput.takeText()
expect(printed).toContain("Printed block")
expect(printed).not.toContain("const arrow")
await out.scrollback.setMono(!mono)
out.scrollback.setTheme(mono ? RUN_THEME_FALLBACK : RUN_THEME_MONO)
expect(out.externalOutput.takeText()).toBe("")
await out.scrollback.append(assistant('\u2192"\n```\n\nNext block'))
// A frame can flush the code block while completion is awaiting highlighting.
await out.renderOnce()
await out.scrollback.complete()
const next = out.externalOutput.takeText()
expect(next).toContain(mono ? 'const arrow = "\u2192"' : 'const arrow = "->"')
expect(next).toContain("Next block")
expect(next).not.toContain("Printed block")
expect(next).not.toContain("```")
} finally {
out.scrollback.destroy()
destroy(claim(out.renderer))
+19
View File
@@ -0,0 +1,19 @@
import { plugin } from "bun"
// Filming only: accelerate the existing cleanup policy without modifying either checkout.
plugin({
name: "hidden-approval-clock",
setup(build) {
build.onLoad({ filter: /[/\\]location-activity\.ts$/ }, async (args) => {
const source = await Bun.file(args.path).text()
if (!source.includes("layer: layer(),")) throw new Error("LocationActivity timing seam changed")
return {
loader: "ts",
contents: source.replace(
"layer: layer(),",
'layer: layer({ timeToLive: "8 seconds", sweepInterval: "1 second" }),',
),
}
})
},
})
+42
View File
@@ -0,0 +1,42 @@
# Hidden Approval Reproducer
Requires Bun, FFmpeg, and `opencode-drive` v2.0.0. Run from the fix checkout after
`bun install --frozen-lockfile`. The target base checkout also needs its dependencies installed.
```sh
export OPENCODE_DRIVE_MEDIA_DIR="$PWD/.cache/hidden-approval"
# Unmodified base revision in a separate worktree.
OPENCODE_REPRO_BEFORE=1 OPENCODE_DEV=/path/to/base \
opencode-drive run script/repro/hidden-approval.ts
# Fixed revision.
OPENCODE_DEV="$PWD" opencode-drive run script/repro/hidden-approval.ts
```
Both runs use the same isolated project, simulated model, real `glob` tool, real
permission service, and production TUI. The preload changes only the automatic
cleanup timing: eight seconds instead of one hour, swept every second instead
of every minute. It does not edit either checkout or manually invalidate the cache.
The scenario requests a search, leaves its permission unanswered through cleanup,
closes the TUI, opens the same session in a fresh TUI, and presses Enter. It asserts
the server's permission count, retained request ID, and execution status:
| Checkpoint | Before | After |
| ------------------ | -------------------- | ---------------------- |
| Initial permission | One request | One request |
| After cleanup | No request | Same request |
| Reopened TUI | Spinner, no approval | Allow once available |
| After Enter | Still active | Search completed, idle |
Each run prints its annotated MP4 path and retains screenshots. The fixture
interrupts its own session afterward; it never connects to the user's live server.
The deterministic unit regression advances 61 virtual minutes and also verifies
that cleanup still occurs after the final borrower releases the location:
```sh
cd packages/core
bun run test test/location-layer.test.ts -t 'keeps borrowed locations discoverable'
```
+88
View File
@@ -0,0 +1,88 @@
import { Effect, Stream } from "effect"
import { Llm, OpenCodeDriver } from "opencode-drive"
import path from "node:path"
// Run from this checkout; OPENCODE_DEV selects the unmodified base or the fix checkout.
// OPENCODE_REPRO_BEFORE=1 OPENCODE_DEV=/path/to/base opencode-drive run script/repro/hidden-approval.ts
// OPENCODE_DEV=$PWD opencode-drive run script/repro/hidden-approval.ts
const before = process.env.OPENCODE_REPRO_BEFORE === "1"
const label = before ? "BEFORE" : "AFTER"
const viewport = { cols: 100, rows: 30 }
export default OpenCodeDriver.use(
{
opencode: {
dev: process.env.OPENCODE_DEV ?? process.cwd(),
env: { BUN_OPTIONS: `--preload=${path.resolve("script/repro/hidden-approval-preload.ts")}` },
},
project: { git: true, files: { "src/example.ts": "export const example = true\n" } },
config: {
autoupdate: false,
permissions: [
{ action: "*", resource: "*", effect: "allow" },
{ action: "glob", resource: "*", effect: "ask" },
],
},
tui: { viewport },
keepArtifacts: true,
},
({ ui, tui, tuis, llm, opencode }) =>
Effect.gen(function* () {
yield* llm.title(() => Effect.succeed("Waiting for search approval"))
yield* llm.serve((_request, index) =>
index === 0
? Stream.make(
Llm.text("I will find the TypeScript files once you approve the search."),
Llm.toolCall({
index: 0,
id: "call_search",
name: "glob",
input: { pattern: "**/*.ts", path: ".", limit: 10 },
}),
Llm.finish("tool-calls"),
)
: Stream.make(Llm.text("Search complete. Found src/example.ts.")),
)
yield* ui.submit("Find the TypeScript files.")
yield* ui.waitFor("Allow once", { timeout: 20_000 })
const session = (yield* opencode.session.list({ limit: 1 })).data[0]
if (!session) return yield* Effect.die("No session created")
const initial = yield* opencode.permission.list({ sessionID: session.id })
if (initial.length !== 1) return yield* Effect.die("Expected one pending approval")
yield* ui.screenshot(`${label.toLowerCase()}-initial-approval`)
// This is the real automatic sweep, not a manual cache invalidation.
yield* Effect.sleep("10 seconds")
const pending = yield* opencode.permission.list({ sessionID: session.id })
if (pending.length !== (before ? 0 : 1))
return yield* Effect.die(`Unexpected pending approval count: ${pending.length}`)
if (pending[0] && pending[0].id !== initial[0]?.id) return yield* Effect.die("Approval identity changed")
yield* tui.close()
const reopened = yield* tuis.launch({ viewport, recording: true })
if (!reopened.recording) return yield* Effect.die("Recording unavailable")
yield* reopened.ui.submit("/sessions")
yield* reopened.ui.waitFor("Waiting for search approval")
yield* reopened.ui.enter()
yield* reopened.ui.waitFor("Find the TypeScript files.", { timeout: 20_000 })
if (before && (yield* reopened.ui.matches("Allow once")))
return yield* Effect.die("Baseline unexpectedly retained its approval")
if (!before) yield* reopened.ui.waitFor("Allow once")
yield* reopened.recording.mark(
`${label}: reopened after cleanup (${before ? "approval lost; still active" : "same approval retained"})`,
)
yield* reopened.ui.screenshot(`${label.toLowerCase()}-reopened`)
yield* Effect.sleep("3 seconds")
yield* reopened.recording.mark(`${label}: press Enter to approve`)
yield* reopened.ui.enter()
if (!before) yield* reopened.ui.waitFor("Search complete.", { timeout: 15_000 })
yield* Effect.sleep("3 seconds")
yield* reopened.ui.screenshot(`${label.toLowerCase()}-result`)
const active = yield* opencode.session.active()
if (Boolean(active[session.id]) !== before) return yield* Effect.die("Unexpected execution status")
console.log(JSON.stringify({ label, pending: pending.length, active: Boolean(active[session.id]) }))
console.log("video:", yield* reopened.recording.finish())
yield* opencode.session.interrupt({ sessionID: session.id })
yield* opencode.session.wait({ sessionID: session.id })
}),
)