Skip to content

Commit 91e2fb9

Browse files
author
Grzegorz Grabarz
committed
fix(tui): only offer a new directory when the location is missing
The TUI mounted the blocking "Session location unavailable" recovery prompt after any failed location sync, even when the folder was still there. The sync fans out to a dozen catalog endpoints under one Promise.all, so a single transient failure failed the whole sync and the TUI offered to move the session to another directory. Only the server's typed LocationNotFoundError proves the folder is gone, so the location state now separates `missing` from `error`, and a failed sync is retried before it is reported. The missing directory is compared with sameDirectory, and the duplicated location read is dropped.
1 parent a13c48b commit 91e2fb9

7 files changed

Lines changed: 288 additions & 7 deletions

File tree

‎packages/tui/src/app.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -766,7 +766,7 @@ function App() {
766766
config.data.session.new_location,
767767
data.location.default().directory,
768768
current,
769-
location.error?.location,
769+
location.missing,
770770
),
771771
})
772772
if (agent) local.agent.set(agent.id)
@@ -793,7 +793,7 @@ function App() {
793793
config.data.session.new_location,
794794
data.location.default().directory,
795795
current,
796-
location.error?.location,
796+
location.missing,
797797
),
798798
})
799799
if (agent) local.agent.set(agent.id)

‎packages/tui/src/context/data.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ export const { use: useData, provider: DataProvider } = createSimpleContext({
2525
location: {
2626
...data.location,
2727
async sync(ref?: LocationRef) {
28-
await data.location.syncInfo(ref)
28+
// The client reads the location before its resources, so the location is not read twice.
2929
await Promise.all([data.location.sync(ref), data.location.config.sync(ref)])
3030
},
3131
},

‎packages/tui/src/context/location.tsx‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import type { LocationGetOutput, LocationRef } from "@opencode/client"
1+
import { isLocationNotFoundError, type LocationGetOutput, type LocationRef } from "@opencode/client"
2+
import { retry } from "@opencode/util/retry"
23
import { createContext, createMemo, createSignal, onCleanup, useContext, type ParentProps } from "solid-js"
34
import { useClient } from "./client"
45
import { useData } from "./data"
@@ -7,6 +8,9 @@ const context = createContext<{
78
readonly current: LocationGetOutput | undefined
89
// The target location as set, available before the server-synced info in `current` arrives.
910
readonly ref: LocationRef | undefined
11+
// Set only when the server reports that this location's folder does not exist.
12+
readonly missing: LocationRef | undefined
13+
// The location could not be read for a reason that may resolve on its own.
1014
readonly error: { readonly location: LocationRef; readonly cause: unknown } | undefined
1115
set: (location?: LocationRef) => void
1216
}>()
@@ -15,6 +19,7 @@ export function LocationProvider(props: ParentProps) {
1519
const client = useClient()
1620
const data = useData()
1721
const [ref, setRef] = createSignal<LocationRef>()
22+
const [missing, setMissing] = createSignal<LocationRef>()
1823
const [error, setError] = createSignal<{ readonly location: LocationRef; readonly cause: unknown }>()
1924
let generation = 0
2025
const current = createMemo(() => data.location.info(ref()))
@@ -28,14 +33,23 @@ export function LocationProvider(props: ParentProps) {
2833
? undefined
2934
: location
3035
setError(undefined)
31-
void data.location.sync(target).catch((cause) => {
36+
setMissing(undefined)
37+
// A failed catalog read does not prove the folder is gone. Only the server's typed
38+
// LocationNotFoundError does, and retrying it cannot succeed until the folder changes.
39+
void retry(() => data.location.sync(target), {
40+
retryIf: (cause) => generation === attempt && !isLocationNotFoundError(cause),
41+
}).catch((cause) => {
3242
const current = ref()
3343
if (
3444
generation !== attempt ||
3545
current?.directory !== location.directory ||
3646
current.workspaceID !== location.workspaceID
3747
)
3848
return
49+
if (isLocationNotFoundError(cause)) {
50+
setMissing(location)
51+
return
52+
}
3953
setError({ location, cause })
4054
})
4155
}
@@ -56,6 +70,9 @@ export function LocationProvider(props: ParentProps) {
5670
get ref() {
5771
return ref()
5872
},
73+
get missing() {
74+
return missing()
75+
},
5976
get error() {
6077
return error()
6178
},

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,7 @@ export const { use: useSessionTabs, provider: SessionTabsProvider } = createSimp
437437
config.session.new_location,
438438
data.location.default().directory,
439439
currentLocation,
440-
location.error?.location,
440+
location.missing,
441441
),
442442
})
443443
},

‎packages/tui/src/routes/session/index.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ import { findMessageBoundary, messageNavigationSlack } from "./message-navigatio
116116
import { stringWidth } from "../../util/string-width"
117117
import { useArgs } from "../../context/args"
118118
import { withTimestampedFallback } from "@opencode/util/session-title-fallback"
119+
import { sameDirectory } from "@opencode/util/path"
119120
import { useSessionTabs, type ScrollAnchor } from "../../context/session-tabs"
120121
import { createSingleFlight } from "../../util/single-flight"
121122
import { createDelayedPresence } from "../../util/delayed-presence"
@@ -1510,7 +1511,8 @@ export function Session(props: {
15101511
<Match
15111512
when={
15121513
session() &&
1513-
currentLocation.error?.location.directory === session()!.location.directory
1514+
currentLocation.missing &&
1515+
sameDirectory(currentLocation.missing.directory, session()!.location.directory)
15141516
}
15151517
>
15161518
<SessionLocationMissing
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
/** @jsxImportSource @opentui/solid */
2+
import { expect, test } from "bun:test"
3+
import { testRender } from "@opentui/solid"
4+
import { onMount } from "solid-js"
5+
import { ClientProvider, useClient } from "../../../src/context/client"
6+
import { DataProvider } from "../../../src/context/data"
7+
import { LocationProvider, useLocation } from "../../../src/context/location"
8+
import { createApi, createEventStream, createFetch, directory, json } from "../../fixture/tui-client"
9+
import { TestTuiContexts } from "../../fixture/tui-environment"
10+
11+
const target = "/tmp/opencode/other-clone"
12+
13+
async function wait(predicate: () => boolean, timeout = 20_000) {
14+
const start = Date.now()
15+
while (!predicate()) {
16+
if (Date.now() - start > timeout) throw new Error("timed out waiting for condition")
17+
await Bun.sleep(10)
18+
}
19+
}
20+
21+
function render(fail: (url: URL) => Response | undefined) {
22+
const calls = createFetch(fail, createEventStream())
23+
const connected = Promise.withResolvers<void>()
24+
let location!: ReturnType<typeof useLocation>
25+
let client!: ReturnType<typeof useClient>
26+
27+
function Probe() {
28+
location = useLocation()
29+
client = useClient()
30+
// The client syncs the current location again once the server connects, so wait for that
31+
// event before asking for a location of its own.
32+
onMount(() => client.event.on("server.connected", () => connected.resolve()))
33+
return null
34+
}
35+
36+
const app = testRender(
37+
() => (
38+
<TestTuiContexts cwd={directory}>
39+
<ClientProvider api={createApi(calls.fetch)}>
40+
<DataProvider directory={directory}>
41+
<LocationProvider>
42+
<Probe />
43+
</LocationProvider>
44+
</DataProvider>
45+
</ClientProvider>
46+
</TestTuiContexts>
47+
),
48+
{ width: 100, height: 30, kittyKeyboard: true },
49+
)
50+
return {
51+
app,
52+
connected: connected.promise,
53+
get location() {
54+
return location
55+
},
56+
get client() {
57+
return client
58+
},
59+
}
60+
}
61+
62+
test("a location the server reports as missing is asked once", async () => {
63+
let requests = 0
64+
const fixture = render((url) => {
65+
if (url.pathname !== "/api/location") return undefined
66+
if (url.searchParams.get("location[directory]") !== target) return undefined
67+
requests++
68+
return json(
69+
{
70+
_tag: "LocationNotFoundError",
71+
location: { directory: target },
72+
message: `Location not found: ${target}`,
73+
},
74+
{ status: 404 },
75+
)
76+
})
77+
const app = await fixture.app
78+
try {
79+
await fixture.connected
80+
fixture.location.set({ directory: target })
81+
await wait(() => fixture.location.missing !== undefined)
82+
// A missing folder cannot be fixed by retrying, so the client asks once.
83+
expect(requests).toBe(1)
84+
expect(fixture.location.missing?.directory).toBe(target)
85+
expect(fixture.location.error).toBeUndefined()
86+
} finally {
87+
app.renderer.destroy()
88+
}
89+
})
90+
91+
test("a location that fails for another reason is retried", async () => {
92+
let requests = 0
93+
const fixture = render((url) => {
94+
if (url.pathname !== "/api/location") return undefined
95+
if (url.searchParams.get("location[directory]") !== target) return undefined
96+
requests++
97+
return json({ message: "offline" }, { status: 503 })
98+
})
99+
const app = await fixture.app
100+
try {
101+
await fixture.connected
102+
fixture.location.set({ directory: target })
103+
await wait(() => fixture.location.error !== undefined)
104+
expect(requests).toBe(3)
105+
// The folder may still be there, so the client does not offer to move the session.
106+
expect(fixture.location.missing).toBeUndefined()
107+
expect(fixture.location.error?.location.directory).toBe(target)
108+
} finally {
109+
app.renderer.destroy()
110+
}
111+
})
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
import { expect, test } from "bun:test"
2+
import { createTestRenderer } from "@opentui/core/testing"
3+
import { Effect, FileSystem } from "effect"
4+
import path from "node:path"
5+
import { Global } from "@opencode/util/global"
6+
import { createEventStream, createFetch, json } from "./fixture/tui-client"
7+
import { tmpdir } from "./fixture/fixture"
8+
9+
// The session lives in another directory than the client's own location, so the client syncs
10+
// that location instead of the default one.
11+
const session = {
12+
id: "ses_test",
13+
title: "Location sync",
14+
projectID: "proj_test",
15+
location: { directory: "/tmp/opencode/other-clone" },
16+
cost: 0,
17+
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
18+
time: { created: 0, updated: 0 },
19+
}
20+
21+
const unavailable = "Session location unavailable"
22+
23+
async function wait(predicate: () => boolean, timeout = 20_000) {
24+
const start = Date.now()
25+
while (!predicate()) {
26+
if (Date.now() - start > timeout) throw new Error("timed out waiting for condition")
27+
await Bun.sleep(10)
28+
}
29+
}
30+
31+
async function boot(root: string, fail: (url: URL) => Response | undefined) {
32+
const setup = await createTestRenderer({ width: 100, height: 30, kittyKeyboard: true })
33+
await setup.renderer.setupTerminal()
34+
setup.renderer.start()
35+
const events = createEventStream()
36+
const calls = createFetch(async (url) => {
37+
if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
38+
if (url.pathname === "/api/session/ses_test") return json({ data: session })
39+
if (url.pathname === "/api/session/ses_test/message") return json({ data: [], cursor: {} })
40+
if (url.pathname === "/api/session/ses_test/inbox") return json({ data: [] })
41+
if (url.pathname === "/api/session/ses_test/permission") return json({ data: [] })
42+
return fail(url)
43+
}, events)
44+
const server = Bun.serve({ port: 0, idleTimeout: 0, fetch: (request) => calls.fetch(request) })
45+
const { run } = await import("../src/app")
46+
const task = Effect.runPromise(
47+
run({
48+
app: { name: "test", version: "test", channel: "test" },
49+
server: { endpoint: { url: server.url.toString() } },
50+
config: { get: async () => ({ animations: false }), update: async () => ({}) },
51+
packages: { prepare: async () => ({ directory: "" }) },
52+
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
53+
args: { sessionID: "ses_test" },
54+
log: () => {},
55+
}).pipe(
56+
Effect.provide(
57+
Global.layerWith({
58+
home: path.join(root, "home"),
59+
data: path.join(root, "data"),
60+
cache: path.join(root, "cache"),
61+
config: path.join(root, "config"),
62+
state: path.join(root, "state"),
63+
bin: path.join(root, "cache", "bin"),
64+
log: path.join(root, "data", "log"),
65+
repos: path.join(root, "data", "repos"),
66+
tmp: path.join(root, "tmp"),
67+
}),
68+
),
69+
Effect.provide(FileSystem.layerNoop({})),
70+
),
71+
)
72+
return { setup, task, server }
73+
}
74+
75+
function serviceUnavailable() {
76+
return json(
77+
{ _tag: "ServiceUnavailableError", message: "Location plugins did not finish activating", service: "plugin" },
78+
{ status: 503 },
79+
)
80+
}
81+
82+
test("a location read that fails for a transient reason is retried", async () => {
83+
await using state = await tmpdir()
84+
let attempts = 0
85+
const app = await boot(state.path, (url) => {
86+
if (url.pathname !== "/api/model") return undefined
87+
if (url.searchParams.get("location[directory]") !== session.location.directory) return undefined
88+
attempts++
89+
return attempts === 1 ? serviceUnavailable() : undefined
90+
})
91+
try {
92+
await wait(() => attempts >= 2 || app.setup.captureCharFrame().includes(unavailable))
93+
expect(app.setup.captureCharFrame()).not.toContain(unavailable)
94+
expect(attempts).toBeGreaterThanOrEqual(2)
95+
} finally {
96+
if (!app.setup.renderer.isDestroyed) app.setup.renderer.destroy()
97+
await app.task.finally(() => app.server.stop(true))
98+
}
99+
})
100+
101+
test("a location read that keeps failing keeps the composer", async () => {
102+
await using state = await tmpdir()
103+
let attempts = 0
104+
const app = await boot(state.path, (url) => {
105+
if (url.pathname !== "/api/model") return undefined
106+
if (url.searchParams.get("location[directory]") !== session.location.directory) return undefined
107+
attempts++
108+
return serviceUnavailable()
109+
})
110+
try {
111+
// The retry gives up after three attempts.
112+
await wait(() => attempts >= 3 || app.setup.captureCharFrame().includes(unavailable))
113+
await app.setup.waitForVisualIdle()
114+
const frame = app.setup.captureCharFrame()
115+
expect(frame).not.toContain(unavailable)
116+
expect(frame).not.toContain("Choose another directory to continue this session.")
117+
app.setup.mockInput.typeText("still typing")
118+
await app.setup.waitForVisualIdle()
119+
expect(app.setup.captureCharFrame()).toContain("still typing")
120+
} finally {
121+
if (!app.setup.renderer.isDestroyed) app.setup.renderer.destroy()
122+
await app.task.finally(() => app.server.stop(true))
123+
}
124+
})
125+
126+
test("a location the server reports as missing asks for another directory", async () => {
127+
await using state = await tmpdir()
128+
let attempts = 0
129+
const app = await boot(state.path, (url) => {
130+
if (url.pathname !== "/api/location") return undefined
131+
if (url.searchParams.get("location[directory]") !== session.location.directory) return undefined
132+
attempts++
133+
return json(
134+
{
135+
_tag: "LocationNotFoundError",
136+
location: { directory: session.location.directory },
137+
message: `Location not found: ${session.location.directory}`,
138+
},
139+
{ status: 404 },
140+
)
141+
})
142+
try {
143+
await app.setup.waitForFrame((frame) => frame.includes(unavailable))
144+
const frame = app.setup.captureCharFrame()
145+
expect(frame).toContain(session.location.directory)
146+
expect(frame).toContain("Choose another directory to continue this session.")
147+
} finally {
148+
if (!app.setup.renderer.isDestroyed) app.setup.renderer.destroy()
149+
await app.task.finally(() => app.server.stop(true))
150+
}
151+
})

0 commit comments

Comments
 (0)