Skip to content

Commit 7b73f20

Browse files
committed
fix(core): preserve approvals across location cleanup
1 parent b0402f5 commit 7b73f20

5 files changed

Lines changed: 188 additions & 13 deletions

File tree

‎packages/core/src/location-activity.ts‎

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
export * as LocationActivity from "./location-activity.js"
22

3-
import { Clock, Context, Duration, Effect, Layer, RcMap, Schema } from "effect"
3+
import { Clock, Context, Duration, Effect, Layer, MutableHashMap, RcMap, References, Schema } from "effect"
44
import { Bus } from "./bus.js"
55
import { Location } from "./location.js"
66
import { LocationServiceMap } from "./location-service-map.js"
@@ -39,25 +39,27 @@ export function layer(options: { readonly timeToLive?: Duration.Input; readonly
3939
yield* Effect.sleep(options.sweepInterval ?? "1 minute")
4040
const refs = Array.from(yield* RcMap.keys(locations.rcMap))
4141
const cached = new Set(refs.map(key))
42-
yield* Effect.forEach(
43-
refs,
44-
(ref) => (entries.has(key(ref)) ? Effect.void : touch(ref)),
45-
{ discard: true },
46-
)
42+
yield* Effect.forEach(refs, (ref) => (entries.has(key(ref)) ? Effect.void : touch(ref)), { discard: true })
4743
for (const id of entries.keys()) {
4844
if (!cached.has(id)) entries.delete(id)
4945
}
5046
const now = clock.currentTimeMillisUnsafe()
5147
const expired = Array.from(entries.values()).filter((entry) => entry.expiresAt <= now)
5248
yield* Effect.forEach(
5349
expired,
54-
(entry) => {
55-
entries.delete(key(entry.ref))
56-
return Effect.logInfo("location services evicted", {
57-
directory: entry.ref.directory,
58-
workspaceID: entry.ref.workspaceID,
59-
}).pipe(Effect.andThen(locations.invalidate(entry.ref)))
60-
},
50+
// A new borrower must not arrive between the ref-count check and cache removal.
51+
(entry) =>
52+
Effect.suspend(() => {
53+
if (locations.rcMap.state._tag === "Closed") return Effect.void
54+
const cached = MutableHashMap.get(locations.rcMap.state.map, entry.ref)
55+
// Invalidation detaches even borrowed entries, hiding live permissions and forms from later readers.
56+
if (cached._tag === "Some" && cached.value.refCount > 0) return Effect.void
57+
entries.delete(key(entry.ref))
58+
return Effect.logInfo("location services evicted", {
59+
directory: entry.ref.directory,
60+
workspaceID: entry.ref.workspaceID,
61+
}).pipe(Effect.andThen(locations.invalidate(entry.ref)))
62+
}).pipe(Effect.provideService(References.PreventSchedulerYield, true)),
6163
{ discard: true },
6264
)
6365
}).pipe(Effect.forever, Effect.forkScoped)

‎packages/core/test/location-layer.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,20 @@ import { Config } from "@opencode-ai/schema/config"
55
import { Money } from "@opencode-ai/schema/money"
66
import {
77
DateTime,
8+
Context,
89
Deferred,
910
Duration,
1011
Effect,
1112
Equal,
13+
Exit,
1214
Fiber,
1315
Hash,
1416
Layer,
1517
LayerMap,
1618
Option,
1719
RcMap,
1820
Schema,
21+
Scope,
1922
Stream,
2023
} from "effect"
2124
import { TestClock } from "effect/testing"
@@ -82,6 +85,27 @@ const itWithActivity = testEffect(
8285
)
8386

8487
describe("LocationServiceMap", () => {
88+
itWithActivity.effect("keeps borrowed locations discoverable after the activity timeout", () =>
89+
Effect.gen(function* () {
90+
const locations = yield* LocationServiceMap.Service
91+
const ref = Location.Ref.make({ directory: AbsolutePath.make("/project") })
92+
const scope = yield* Scope.make()
93+
yield* Effect.addFinalizer((exit) => Scope.close(scope, exit))
94+
const context = yield* locations.contextEffect(ref).pipe(Scope.provide(scope))
95+
96+
// A permission wait owns the Location without producing new Session events.
97+
yield* TestClock.adjust("61 minutes")
98+
const cached = yield* locations.contextEffectOption(ref).pipe(Effect.scoped)
99+
expect(Option.getOrUndefined(Option.map(cached, (value) => Context.get(value, Location.Service)))).toBe(
100+
Context.get(context, Location.Service),
101+
)
102+
103+
yield* Scope.close(scope, Exit.void)
104+
yield* TestClock.adjust("1 minute")
105+
expect(Array.from(yield* RcMap.keys(locations.rcMap))).toEqual([])
106+
}),
107+
)
108+
85109
itWithActivity.effect("does not refresh lifetime from inferred Session routing", () =>
86110
Effect.gen(function* () {
87111
const locations = yield* LocationServiceMap.Service
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { plugin } from "bun"
2+
3+
// Filming only: accelerate the existing cleanup policy without modifying either checkout.
4+
plugin({
5+
name: "hidden-approval-clock",
6+
setup(build) {
7+
build.onLoad({ filter: /[/\\]location-activity\.ts$/ }, async (args) => {
8+
const source = await Bun.file(args.path).text()
9+
if (!source.includes("layer: layer(),")) throw new Error("LocationActivity timing seam changed")
10+
return {
11+
loader: "ts",
12+
contents: source.replace(
13+
"layer: layer(),",
14+
'layer: layer({ timeToLive: "8 seconds", sweepInterval: "1 second" }),',
15+
),
16+
}
17+
})
18+
},
19+
})

‎script/repro/hidden-approval.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Hidden Approval Reproducer
2+
3+
Requires Bun, FFmpeg, and `opencode-drive` v2.0.0. Run from the fix checkout after
4+
`bun install --frozen-lockfile`. The target base checkout also needs its dependencies installed.
5+
6+
```sh
7+
export OPENCODE_DRIVE_MEDIA_DIR="$PWD/.cache/hidden-approval"
8+
9+
# Unmodified base revision in a separate worktree.
10+
OPENCODE_REPRO_BEFORE=1 OPENCODE_DEV=/path/to/base \
11+
opencode-drive run script/repro/hidden-approval.ts
12+
13+
# Fixed revision.
14+
OPENCODE_DEV="$PWD" opencode-drive run script/repro/hidden-approval.ts
15+
```
16+
17+
Both runs use the same isolated project, simulated model, real `glob` tool, real
18+
permission service, and production TUI. The preload changes only the automatic
19+
cleanup timing: eight seconds instead of one hour, swept every second instead
20+
of every minute. It does not edit either checkout or manually invalidate the cache.
21+
22+
The scenario requests a search, leaves its permission unanswered through cleanup,
23+
closes the TUI, opens the same session in a fresh TUI, and presses Enter. It asserts
24+
the server's permission count, retained request ID, and execution status:
25+
26+
| Checkpoint | Before | After |
27+
| ------------------ | -------------------- | ---------------------- |
28+
| Initial permission | One request | One request |
29+
| After cleanup | No request | Same request |
30+
| Reopened TUI | Spinner, no approval | Allow once available |
31+
| After Enter | Still active | Search completed, idle |
32+
33+
Each run prints its annotated MP4 path and retains screenshots. The fixture
34+
interrupts its own session afterward; it never connects to the user's live server.
35+
36+
The deterministic unit regression advances 61 virtual minutes and also verifies
37+
that cleanup still occurs after the final borrower releases the location:
38+
39+
```sh
40+
cd packages/core
41+
bun run test test/location-layer.test.ts -t 'keeps borrowed locations discoverable'
42+
```

‎script/repro/hidden-approval.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { Effect, Stream } from "effect"
2+
import { Llm, OpenCodeDriver } from "opencode-drive"
3+
import path from "node:path"
4+
5+
// Run from this checkout; OPENCODE_DEV selects the unmodified base or the fix checkout.
6+
// OPENCODE_REPRO_BEFORE=1 OPENCODE_DEV=/path/to/base opencode-drive run script/repro/hidden-approval.ts
7+
// OPENCODE_DEV=$PWD opencode-drive run script/repro/hidden-approval.ts
8+
const before = process.env.OPENCODE_REPRO_BEFORE === "1"
9+
const label = before ? "BEFORE" : "AFTER"
10+
const viewport = { cols: 100, rows: 30 }
11+
12+
export default OpenCodeDriver.use(
13+
{
14+
opencode: {
15+
dev: process.env.OPENCODE_DEV ?? process.cwd(),
16+
env: { BUN_OPTIONS: `--preload=${path.resolve("script/repro/hidden-approval-preload.ts")}` },
17+
},
18+
project: { git: true, files: { "src/example.ts": "export const example = true\n" } },
19+
config: {
20+
autoupdate: false,
21+
permissions: [
22+
{ action: "*", resource: "*", effect: "allow" },
23+
{ action: "glob", resource: "*", effect: "ask" },
24+
],
25+
},
26+
tui: { viewport },
27+
keepArtifacts: true,
28+
},
29+
({ ui, tui, tuis, llm, opencode }) =>
30+
Effect.gen(function* () {
31+
yield* llm.title(() => Effect.succeed("Waiting for search approval"))
32+
yield* llm.serve((_request, index) =>
33+
index === 0
34+
? Stream.make(
35+
Llm.text("I will find the TypeScript files once you approve the search."),
36+
Llm.toolCall({
37+
index: 0,
38+
id: "call_search",
39+
name: "glob",
40+
input: { pattern: "**/*.ts", path: ".", limit: 10 },
41+
}),
42+
Llm.finish("tool-calls"),
43+
)
44+
: Stream.make(Llm.text("Search complete. Found src/example.ts.")),
45+
)
46+
yield* ui.submit("Find the TypeScript files.")
47+
yield* ui.waitFor("Allow once", { timeout: 20_000 })
48+
const session = (yield* opencode.session.list({ limit: 1 })).data[0]
49+
if (!session) return yield* Effect.die("No session created")
50+
const initial = yield* opencode.permission.list({ sessionID: session.id })
51+
if (initial.length !== 1) return yield* Effect.die("Expected one pending approval")
52+
yield* ui.screenshot(`${label.toLowerCase()}-initial-approval`)
53+
54+
// This is the real automatic sweep, not a manual cache invalidation.
55+
yield* Effect.sleep("10 seconds")
56+
const pending = yield* opencode.permission.list({ sessionID: session.id })
57+
if (pending.length !== (before ? 0 : 1))
58+
return yield* Effect.die(`Unexpected pending approval count: ${pending.length}`)
59+
if (pending[0] && pending[0].id !== initial[0]?.id) return yield* Effect.die("Approval identity changed")
60+
61+
yield* tui.close()
62+
const reopened = yield* tuis.launch({ viewport, recording: true })
63+
if (!reopened.recording) return yield* Effect.die("Recording unavailable")
64+
yield* reopened.ui.submit("/sessions")
65+
yield* reopened.ui.waitFor("Waiting for search approval")
66+
yield* reopened.ui.enter()
67+
yield* reopened.ui.waitFor("Find the TypeScript files.", { timeout: 20_000 })
68+
if (before && (yield* reopened.ui.matches("Allow once")))
69+
return yield* Effect.die("Baseline unexpectedly retained its approval")
70+
if (!before) yield* reopened.ui.waitFor("Allow once")
71+
yield* reopened.recording.mark(
72+
`${label}: reopened after cleanup (${before ? "approval lost; still active" : "same approval retained"})`,
73+
)
74+
yield* reopened.ui.screenshot(`${label.toLowerCase()}-reopened`)
75+
yield* Effect.sleep("3 seconds")
76+
yield* reopened.recording.mark(`${label}: press Enter to approve`)
77+
yield* reopened.ui.enter()
78+
if (!before) yield* reopened.ui.waitFor("Search complete.", { timeout: 15_000 })
79+
yield* Effect.sleep("3 seconds")
80+
yield* reopened.ui.screenshot(`${label.toLowerCase()}-result`)
81+
const active = yield* opencode.session.active()
82+
if (Boolean(active[session.id]) !== before) return yield* Effect.die("Unexpected execution status")
83+
console.log(JSON.stringify({ label, pending: pending.length, active: Boolean(active[session.id]) }))
84+
console.log("video:", yield* reopened.recording.finish())
85+
yield* opencode.session.interrupt({ sessionID: session.id })
86+
yield* opencode.session.wait({ sessionID: session.id })
87+
}),
88+
)

0 commit comments

Comments
 (0)