Skip to content

Commit 7c158b6

Browse files
antoinedcwozcode
andcommitted
fix(chat): scope /question and /permission list+reply by directory
opencode's WorkspaceRoutingMiddleware filters the in-memory pending maps for /question, /permission, and their /reply endpoints by the request's `?directory=` query (or the matching header / cwd fallback). bui was calling all four unscoped, with three consequences for any session whose worktree wasn't the server's default: 1. Initial-mount fetch of /question returned [] even when a question was live. The transcript's `question` tool sat `state: running` forever and the QuestionCard never appeared. The `que_…` reply token was already broadcast once on the scoped SSE stream, so panels that mounted late lost the only handle they had on it. Manual recovery required a CLI curl with `?directory=` set. 2. Same shape for /permission: PermissionCards never appeared on non-default-workspace sessions, blocking the tool indefinitely. 3. /permission/:id/reply silently no-op'd when posted unscoped — the UI flipped optimistically, the server kept the request pending, the tool stayed paused until the user noticed. Thread `sessionId` through opencodePermissions / opencodeQuestions / opencodePermissionReply (renderer → preload → ipc → main → fetch). In main/opencode.ts, append `?directory=` from the existing `getSessionDirectoryQuery` helper before issuing the request. The helper already powers prompt_async, replyQuestion, rejectQuestion, and others — list/reply are the last unscoped holdouts. Update the obsolete chatUtils.ts comment that claimed `GET /question` always returns empty for live questions; the fix makes that path authoritative, with the SSE event still driving live in-session updates as a no-round-trip optimization. Verified live against opencode 1.15.5: curl /question → [] curl /question?directory=<session-cwd> → full pending list with que_… References anomalyco/opencode#27907 (busy-session deadlock symptom) and the prior tilde-directory fix (memory: opencode-tilde-directory-corruption). All 238 tests pass; tsc clean on web + node configs. Co-Authored-By: WOZCODE <[email protected]>
1 parent f1b7341 commit 7c158b6

6 files changed

Lines changed: 116 additions & 39 deletions

File tree

‎src/main/index.ts‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -873,20 +873,37 @@ function registerHandlers(): void {
873873
opencodeAbortSession(config, sessionId),
874874
);
875875

876-
// Permission approval. Returns the full list; renderer filters by sessionID.
877-
ipcMain.handle(IPC.opencodePermissions, () =>
878-
opencodeListPermissions(config),
876+
// Permission approval. `sessionId` is required for workspace-scoped routing
877+
// — without it the server returns [] for non-default-workspace sessions
878+
// and reply requests silently no-op (see listPermissions comment in
879+
// opencode.ts). Legacy callers without sessionId still work but only see
880+
// the default workspace's pending entries.
881+
ipcMain.handle(IPC.opencodePermissions, (_e, sessionId?: string) =>
882+
opencodeListPermissions(config, sessionId),
879883
);
880884
ipcMain.handle(
881885
IPC.opencodePermissionReply,
882-
(_e, input: { requestId: string; reply: "once" | "always" | "reject" }) =>
883-
opencodeReplyPermission(config, input.requestId, input.reply),
886+
(
887+
_e,
888+
input: {
889+
requestId: string;
890+
reply: "once" | "always" | "reject";
891+
sessionId?: string;
892+
},
893+
) =>
894+
opencodeReplyPermission(
895+
config,
896+
input.requestId,
897+
input.reply,
898+
input.sessionId,
899+
),
884900
);
885901

886-
// Question tool. Returns the full list; renderer filters by sessionID.
902+
// Question tool. Same workspace-scoping rule as permissions above —
903+
// `sessionId` is what makes the live `que_…` visible.
887904
// No chatAutoAllow auto-handling — questions need explicit user choice.
888-
ipcMain.handle(IPC.opencodeQuestions, () =>
889-
opencodeListQuestions(config),
905+
ipcMain.handle(IPC.opencodeQuestions, (_e, sessionId?: string) =>
906+
opencodeListQuestions(config, sessionId),
890907
);
891908
ipcMain.handle(
892909
IPC.opencodeQuestionReply,

‎src/main/opencode.ts‎

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -756,24 +756,46 @@ export type PermissionRequest = {
756756
tool?: { messageID: string; callID: string };
757757
};
758758

759+
// `sessionId` is optional. When present we scope the list to that session's
760+
// worktree directory — opencode's `WorkspaceRoutingMiddleware` makes the
761+
// unscoped endpoint return [] for sessions bound to a non-default directory
762+
// (verified live against 1.15.5). Skipping `?directory=` here was the root
763+
// cause of "PermissionCard never appears" wedges: the live `per_…` was
764+
// sitting in the server's pending map, we just couldn't see it.
759765
export async function listPermissions(
760766
config: AppConfig,
767+
sessionId?: string,
761768
): Promise<PermissionRequest[]> {
762769
await ensureForward(config);
763-
const res = await fetch(apiUrl(config, "/permission"));
770+
const dirQ = sessionId
771+
? await getSessionDirectoryQuery(config, sessionId)
772+
: "";
773+
const res = await fetch(apiUrl(config, `/permission${dirQ}`));
764774
if (!res.ok) {
765775
throw new Error(`opencode listPermissions ${res.status}: ${await res.text()}`);
766776
}
767777
return (await res.json()) as PermissionRequest[];
768778
}
769779

780+
// Same workspace-routing rule as listPermissions: the reply endpoint silently
781+
// no-ops if the request is routed to the wrong workspace. Pass `sessionId`
782+
// so the reply lands on the pending entry's scope. Without this, bui-side
783+
// "Allow"/"Deny" clicks looked like they worked client-side but never
784+
// reached the server — the tool stayed pending forever.
770785
export async function replyPermission(
771786
config: AppConfig,
772787
requestId: string,
773788
reply: "once" | "always" | "reject",
789+
sessionId?: string,
774790
): Promise<void> {
775791
await ensureForward(config);
776-
const url = apiUrl(config, `/permission/${encodeURIComponent(requestId)}/reply`);
792+
const dirQ = sessionId
793+
? await getSessionDirectoryQuery(config, sessionId)
794+
: "";
795+
const url = apiUrl(
796+
config,
797+
`/permission/${encodeURIComponent(requestId)}/reply${dirQ}`,
798+
);
777799
const res = await fetch(url, {
778800
method: "POST",
779801
headers: { "content-type": "application/json" },
@@ -811,14 +833,26 @@ export type QuestionRequest = {
811833
// list/reply/reject — so after a question fires on the scoped channel, an
812834
// UNSCOPED reply is accepted (HTTP 200) yet the scoped session's blocked
813835
// tool never receives it: the agent hangs in "processing" forever. Append
814-
// the session's scoped query the same way prompt_async does. `sessionId`
815-
// is optional (listQuestions has no session context — it lists globally);
816-
// when present we scope to that session's worktree directory.
836+
// the session's scoped query the same way prompt_async does.
837+
//
838+
// The same workspace scoping applies to LIST: `GET /question` (unscoped)
839+
// returns [] for sessions whose worktree isn't the server's default. The
840+
// live `que_…` IDs are sitting in the server's pending map; we just can't
841+
// see them without the right `?directory=`. (Verified live against 1.15.5;
842+
// matches packages/opencode/src/server/routes/instance/httpapi/middleware/
843+
// workspace-routing.ts behavior.) This was the root cause of the
844+
// "QuestionCard never appears" wedge: bui's initial-mount fetch returned
845+
// [], the `que_` was already consumed by the live SSE event we missed,
846+
// and the question stayed unrenderable until manual recovery.
817847
export async function listQuestions(
818848
config: AppConfig,
849+
sessionId?: string,
819850
): Promise<QuestionRequest[]> {
820851
await ensureForward(config);
821-
const res = await fetch(apiUrl(config, "/question"));
852+
const dirQ = sessionId
853+
? await getSessionDirectoryQuery(config, sessionId)
854+
: "";
855+
const res = await fetch(apiUrl(config, `/question${dirQ}`));
822856
if (!res.ok) {
823857
throw new Error(`opencode listQuestions ${res.status}: ${await res.text()}`);
824858
}

‎src/preload/index.ts‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -139,17 +139,26 @@ const api = {
139139
}),
140140
opencodeAbort: (sessionId: string): Promise<void> =>
141141
ipcRenderer.invoke(IPC.opencodeAbort, sessionId),
142-
opencodePermissions: (): Promise<PermissionRequest[]> =>
143-
ipcRenderer.invoke(IPC.opencodePermissions),
142+
// `sessionId` scopes the list to the session's workspace directory —
143+
// without it the server returns [] for sessions outside the default
144+
// workspace (see listPermissions in opencode.ts).
145+
opencodePermissions: (sessionId?: string): Promise<PermissionRequest[]> =>
146+
ipcRenderer.invoke(IPC.opencodePermissions, sessionId),
144147
opencodePermissionReply: (
145148
requestId: string,
146149
reply: "once" | "always" | "reject",
150+
sessionId?: string,
147151
): Promise<void> =>
148-
ipcRenderer.invoke(IPC.opencodePermissionReply, { requestId, reply }),
152+
ipcRenderer.invoke(IPC.opencodePermissionReply, {
153+
requestId,
154+
reply,
155+
sessionId,
156+
}),
149157

150-
// Question tool — v2 API only.
151-
opencodeQuestions: (): Promise<QuestionRequest[]> =>
152-
ipcRenderer.invoke(IPC.opencodeQuestions),
158+
// Question tool — v2 API only. `sessionId` scopes the list the same way
159+
// permissions are scoped (see opencodePermissions above).
160+
opencodeQuestions: (sessionId?: string): Promise<QuestionRequest[]> =>
161+
ipcRenderer.invoke(IPC.opencodeQuestions, sessionId),
153162
opencodeQuestionReply: (
154163
requestId: string,
155164
answers: string[][],

‎src/renderer/ChatPanel.tsx‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -789,18 +789,24 @@ export function ChatPanel({ sessionId, tmuxSession, windowIndex, cwd, isActive }
789789
})
790790
.catch(() => { /* non-fatal */ });
791791
// Pull current pending permissions (e.g. a tool that was waiting from a
792-
// previous bui session before we mounted).
792+
// previous bui session before we mounted). `sessionId` is required so
793+
// the main process can append `?directory=` — opencode's workspace
794+
// routing returns [] for non-default-workspace sessions otherwise, and
795+
// we'd render no PermissionCard even though one is live on the server.
793796
window.api
794-
.opencodePermissions()
797+
.opencodePermissions(sessionId)
795798
.then((all) => {
796799
if (!cancelled) {
797800
setPermissions(all.filter((p) => p.sessionID === sessionId));
798801
}
799802
})
800803
.catch(() => { /* non-fatal */ });
801-
// Pull current pending questions (v2 API — may return 404 on older servers).
804+
// Pull current pending questions. Same workspace-scoping rule as
805+
// permissions above — without `sessionId` the live `que_…` is invisible
806+
// and the QuestionCard never appears (was the root-cause wedge before
807+
// the `?directory=` fix on listQuestions).
802808
window.api
803-
.opencodeQuestions()
809+
.opencodeQuestions(sessionId)
804810
.then((all) => {
805811
if (!cancelled) {
806812
setQuestions(all.filter((q) => q.sessionID === sessionId));
@@ -814,9 +820,11 @@ export function ChatPanel({ sessionId, tmuxSession, windowIndex, cwd, isActive }
814820
}, [sessionId, cwd]);
815821

816822
// Refresh permissions list. Called on any permission event.
823+
// Passes `sessionId` so the main process scopes the request to this
824+
// session's workspace directory (see opencodePermissions in opencode.ts).
817825
const refreshPermissions = useCallback(() => {
818826
window.api
819-
.opencodePermissions()
827+
.opencodePermissions(sessionId)
820828
.then((all) =>
821829
setPermissions(all.filter((p) => p.sessionID === sessionId)),
822830
)
@@ -826,7 +834,7 @@ export function ChatPanel({ sessionId, tmuxSession, windowIndex, cwd, isActive }
826834
// Refresh question list. Called on any question event.
827835
const refreshQuestions = useCallback(() => {
828836
window.api
829-
.opencodeQuestions()
837+
.opencodeQuestions(sessionId)
830838
.then((all) =>
831839
setQuestions(all.filter((q) => q.sessionID === sessionId)),
832840
)
@@ -1920,14 +1928,17 @@ export function ChatPanel({ sessionId, tmuxSession, windowIndex, cwd, isActive }
19201928
// the SSE permission.replied event will reconcile if anything diverges.
19211929
setPermissions((prev) => prev.filter((p) => p.id !== requestId));
19221930
try {
1923-
await window.api.opencodePermissionReply(requestId, reply);
1931+
// Pass `sessionId` so the reply lands on this session's workspace
1932+
// scope — without it the server silently routes to the default
1933+
// workspace and the permission never clears (verified live).
1934+
await window.api.opencodePermissionReply(requestId, reply, sessionId);
19241935
} catch (e) {
19251936
setSendError(String((e as Error)?.message ?? e));
19261937
// Re-pull on failure so the card comes back if reply didn't land.
19271938
refreshPermissions();
19281939
}
19291940
},
1930-
[refreshPermissions],
1941+
[refreshPermissions, sessionId],
19311942
);
19321943

19331944
// opencode's reply/reject API is keyed STRICTLY on the `que_…` requestID

‎src/renderer/api/httpApi.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -342,16 +342,17 @@ export const httpApi: Api = {
342342
rpc(IPC.opencodePrompt, { sessionId, text, model, attachments, mentions }),
343343

344344
opencodeAbort: (sessionId) => rpc(IPC.opencodeAbort, sessionId),
345-
opencodePermissions: () => rpc(IPC.opencodePermissions),
345+
opencodePermissions: (sessionId) =>
346+
rpc(IPC.opencodePermissions, sessionId),
346347

347348
/**
348-
* Preload packs: ipcRenderer.invoke(IPC.opencodePermissionReply, { requestId, reply })
349+
* Preload packs: ipcRenderer.invoke(IPC.opencodePermissionReply, { requestId, reply, sessionId })
349350
*/
350-
opencodePermissionReply: (requestId, reply) =>
351-
rpc(IPC.opencodePermissionReply, { requestId, reply }),
351+
opencodePermissionReply: (requestId, reply, sessionId) =>
352+
rpc(IPC.opencodePermissionReply, { requestId, reply, sessionId }),
352353

353354
// -- question tool --
354-
opencodeQuestions: () => rpc(IPC.opencodeQuestions),
355+
opencodeQuestions: (sessionId) => rpc(IPC.opencodeQuestions, sessionId),
355356

356357
/**
357358
* Preload packs: ipcRenderer.invoke(IPC.opencodeQuestionReply, { requestId, answers })

‎src/renderer/chatUtils.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -732,12 +732,17 @@ export function shouldDropEventForSessionFilter(
732732
*
733733
* THE regression this fixes (present since 1a5a336, the feature's first
734734
* commit): the handler called refreshQuestions() → GET /question on every
735-
* question.* event. But in opencode v1.15 `GET /question` stays EMPTY for
736-
* live questions — the question payload is delivered in the
737-
* `question.asked` EVENT itself (verified live: event.properties is a full
738-
* QuestionRequest = {id, sessionID, questions, tool}). Re-polling the empty
739-
* endpoint set questions to [] and the card never appeared. The event is
740-
* the source of truth; use its payload directly.
735+
* question.* event. Originally `GET /question` appeared to stay EMPTY for
736+
* live questions, and we concluded the question payload was only deliverable
737+
* via the live `question.asked` event. UPDATE: the real cause was a missing
738+
* `?directory=` query — opencode's `GET /question` IS authoritative when
739+
* called workspace-scoped (see listQuestions in main/opencode.ts). The
740+
* event still drives live in-session updates (avoids a round-trip per event
741+
* and carries the full payload), but initial-mount hydration now works too,
742+
* so a question fired before the panel mounted is recoverable on attach.
743+
*
744+
* `applyQuestionEvent` is the live-update path; `refreshQuestions`/mount
745+
* hydration is the missed-event recovery path. Both must agree on shape.
741746
*
742747
* - question.asked → upsert the QuestionRequest from the event payload
743748
* - question.replied → remove it (answered)

0 commit comments

Comments
 (0)