Skip to content

Commit a45feb3

Browse files
committed
fix: gate chat session mutations exactly
1 parent 467c77d commit a45feb3

15 files changed

Lines changed: 264 additions & 27 deletions

‎ui/src/pages/chat/chat-composer-capability-host.test.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ function createContext(configSnapshot: ConfigSnapshot | null): ApplicationContex
1010
return {
1111
gateway: {
1212
snapshot: {
13+
client: {} as GatewayBrowserClient,
1314
phase: "connected",
1415
hello: {
1516
auth: { role: "operator", scopes: ["operator.admin", "operator.write"] },
@@ -232,6 +233,34 @@ describe("ChatComposerCapabilityHost", () => {
232233
expect(props.webSearchBaseEnabled).toBe(false);
233234
});
234235

236+
it("blocks tool override patches without exact sessions.patch access", async () => {
237+
const host = new ChatComposerCapabilityHost(vi.fn());
238+
const context = createContext({ runtimeConfig: {} });
239+
context.gateway.snapshot.hello = {
240+
auth: { role: "operator", scopes: ["operator.write"] },
241+
features: { methods: ["tools.effective"] },
242+
} as NonNullable<typeof context.gateway.snapshot.hello>;
243+
const request = vi.fn();
244+
const state = createState();
245+
state.client = { request } as unknown as GatewayBrowserClient;
246+
const session = { key: "main" } as GatewaySessionRow;
247+
248+
const props = host.props(context, state, session, "main");
249+
expect(props.mutationBlockedReason).toBeTruthy();
250+
const result = await (
251+
host as unknown as {
252+
patch: (
253+
context: ApplicationContext,
254+
state: ChatPageHost,
255+
next: { skills: Record<string, boolean> },
256+
) => Promise<{ ok: true } | { ok: false; error: string }>;
257+
}
258+
).patch(context, state, { skills: { release: true } });
259+
260+
expect(result).toEqual({ ok: false, error: props.mutationBlockedReason });
261+
expect(request).not.toHaveBeenCalled();
262+
});
263+
235264
it("keeps Everywhere selectable while a missing session row blocks session submit", async () => {
236265
const host = new ChatComposerCapabilityHost(vi.fn());
237266
const context = createContext({ runtimeConfig: {} });
@@ -340,7 +369,7 @@ describe("ChatComposerCapabilityHost", () => {
340369
const host = new ChatComposerCapabilityHost(notify);
341370
const context = createContext({ runtimeConfig: {} });
342371
context.gateway.snapshot.hello = {
343-
features: { methods: ["tools.effective"] },
372+
features: { methods: ["sessions.patch", "tools.effective"] },
344373
} as NonNullable<typeof context.gateway.snapshot.hello>;
345374
let stateReads = 0;
346375
Object.defineProperty(context.sessions, "state", {

‎ui/src/pages/chat/chat-composer-capability-host.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
summarizeMcpServers,
2828
} from "../../lib/config/mcp-servers.ts";
2929
import { isGatewayMethodAdvertised } from "../../lib/gateway-methods.ts";
30+
import { readSessionMethodAccess } from "../../lib/session-method-access.ts";
3031
import {
3132
scopedAgentListParamsForSession,
3233
scopedAgentParamsForSession,
@@ -300,8 +301,12 @@ export class ChatComposerCapabilityHost {
300301
if (!state.connected || !state.client) {
301302
return { ok: false, error: t("chat.composer.menu.offlineBlocked") };
302303
}
303-
if (!readGatewayOperatorAccess(context.gateway.snapshot).canWrite) {
304-
return { ok: false, error: t("chat.composer.menu.readOnlyBlocked") };
304+
const access = readSessionMethodAccess(context.gateway.snapshot, {
305+
method: "sessions.patch",
306+
params: { key: state.sessionKey, toolOverrides: next },
307+
});
308+
if (!access.allowed) {
309+
return { ok: false, error: access.reason };
305310
}
306311
const sessionKey = state.sessionKey;
307312
if (this.patchTokens.has(sessionKey)) {
@@ -595,12 +600,16 @@ export class ChatComposerCapabilityHost {
595600
const toolsEffectiveError =
596601
effectiveToolsKey !== null && this.effectiveToolsErrorKey === effectiveToolsKey;
597602
const capabilitiesReady = gatewayAvailable && session !== undefined && runtimeConfig !== null;
603+
const toolPatchAccess = readSessionMethodAccess(context.gateway.snapshot, {
604+
method: "sessions.patch",
605+
params: { key: state.sessionKey, toolOverrides: null },
606+
});
598607
const mutationBlockedReason = !gatewayAvailable
599608
? t("chat.composer.menu.offlineBlocked")
600609
: !capabilitiesReady
601610
? t("common.loading")
602-
: !access.canWrite
603-
? t("chat.composer.menu.readOnlyBlocked")
611+
: !toolPatchAccess.allowed
612+
? toolPatchAccess.reason
604613
: this.patchTokens.has(state.sessionKey)
605614
? t("chat.composer.menu.savingBlocked")
606615
: null;

‎ui/src/pages/chat/chat-composer.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,29 @@ describe("renderChatComposer controls", () => {
221221
expect(onAbort).toHaveBeenCalledOnce();
222222
});
223223

224+
it("disables an archived-session action with its mutation reason", () => {
225+
const onAction = vi.fn();
226+
const reason = "Operator write access is required.";
227+
const { container } = renderComposer({
228+
canSend: false,
229+
disabledBanner: {
230+
kind: "composer-replacement",
231+
text: "This session is archived. Unarchive it to continue the conversation.",
232+
actionLabel: "Unarchive",
233+
disabledReason: reason,
234+
onAction,
235+
},
236+
});
237+
238+
const action = container.querySelector<HTMLButtonElement>(
239+
".agent-chat__disabled-banner button",
240+
);
241+
expect(action?.disabled).toBe(true);
242+
expect(action?.title).toBe(reason);
243+
action?.click();
244+
expect(onAction).not.toHaveBeenCalled();
245+
});
246+
224247
it("keeps the disabled composer mounted for a catalog read-only state", () => {
225248
const { container } = renderComposer({
226249
canSend: false,

‎ui/src/pages/chat/chat-pane-header.ts‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import type {
99
} from "../../../../packages/gateway-protocol/src/index.js";
1010
import type { GatewayBrowserClient } from "../../api/gateway.ts";
1111
import type { GatewaySessionRow } from "../../api/types.ts";
12-
import { hasOperatorWriteAccess, hasOperatorAdminAccess } from "../../app/operator-access.ts";
12+
import { hasOperatorAdminAccess, hasOperatorWriteAccess } from "../../app/operator-access.ts";
1313
import { icons } from "../../components/icons.ts";
1414
import { listSessionCreators } from "../../components/session-owner-chip.ts";
1515
import { isCloudWorkerPlacementState } from "../../components/session-row-badges.ts";
@@ -122,6 +122,18 @@ export abstract class ChatPaneHeader extends ChatPaneContext {
122122
method: "session.members.remove",
123123
requiredScope: "operator.write",
124124
});
125+
const renameAccess = row
126+
? readSessionMethodAccess(this.context.gateway.snapshot, {
127+
method: "sessions.patch",
128+
params: { key: row.key, label: null },
129+
})
130+
: null;
131+
const renameDisabledReason =
132+
this.state?.connected !== true || !renameAccess
133+
? t("sessionsView.actionRequiresConnection")
134+
: renameAccess.allowed
135+
? undefined
136+
: renameAccess.reason;
125137
return renderChatPaneHeader({
126138
paneId: this.paneId,
127139
narrow: this.narrow,
@@ -148,9 +160,7 @@ export abstract class ChatPaneHeader extends ChatPaneContext {
148160
platform: this.headerPlatform,
149161
canReveal,
150162
copiedAction: this.headerCopiedAction,
151-
canRename:
152-
this.state?.connected === true &&
153-
hasOperatorWriteAccess(this.context.gateway.snapshot.hello?.auth ?? null),
163+
renameDisabledReason,
154164
terminalAction: renderCatalogTerminalButton(this.state, this.catalogSession),
155165
discussionAction: this.renderSessionDiscussionAction(),
156166
diffAction: renderSessionDiffToggle(sessionWorkspace),
@@ -260,6 +270,14 @@ export abstract class ChatPaneHeader extends ChatPaneContext {
260270
}
261271

262272
protected beginHeaderRename(row: GatewaySessionRow): void {
273+
const access = readSessionMethodAccess(this.context.gateway.snapshot, {
274+
method: "sessions.patch",
275+
params: { key: row.key, label: null },
276+
});
277+
if (!access.allowed) {
278+
this.publishHeaderError(access.reason);
279+
return;
280+
}
263281
const customLabel = row.label?.trim() || null;
264282
this.headerRenameSessionKey = row.key;
265283
this.headerRenameInitialLabel = customLabel;
@@ -294,6 +312,14 @@ export abstract class ChatPaneHeader extends ChatPaneContext {
294312
if (!key || !state || unchangedDerivedTitle || unchangedLabel) {
295313
return;
296314
}
315+
const access = readSessionMethodAccess(this.context.gateway.snapshot, {
316+
method: "sessions.patch",
317+
params: { key, label },
318+
});
319+
if (!access.allowed) {
320+
this.publishHeaderError(access.reason);
321+
return;
322+
}
297323
void patchChatSessionLabel(state, this.context.sessions, key, label).catch((error: unknown) =>
298324
this.publishHeaderError(error),
299325
);

‎ui/src/pages/chat/chat-pane-render.ts‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
projectSessionObserverDigest,
1717
resolveChatPaneObserverRunId,
1818
} from "../../lib/observer-digest.ts";
19+
import { readSessionMethodAccess } from "../../lib/session-method-access.ts";
1920
import { buildAgentMainSessionKey } from "../../lib/sessions/session-key.ts";
2021
import { renderBoardSessionSurface } from "./board-session-surface.ts";
2122
import { clearChatHistory } from "./chat-history.ts";
@@ -79,6 +80,14 @@ export class ChatPane extends ChatPaneHeader {
7980
return html`<main class="app-shell app-shell--booting" aria-busy="true"></main>`;
8081
}
8182
const selectedSession = selectedChatSessionRow(state);
83+
const runtimePatchAccess = readSessionMethodAccess(this.context.gateway.snapshot, {
84+
method: "sessions.patch",
85+
params: { key: state.sessionKey, model: null },
86+
});
87+
const unarchiveAccess = readSessionMethodAccess(this.context.gateway.snapshot, {
88+
method: "sessions.patch",
89+
params: { key: state.sessionKey, archived: false },
90+
});
8291
const projectedObserverDigest = projectSessionObserverDigest(
8392
selectedSession?.key ?? state.sessionKey,
8493
selectedSession?.observerDigest,
@@ -336,7 +345,12 @@ export class ChatPane extends ChatPaneHeader {
336345
kind: "composer-replacement",
337346
text: t("chat.archivedSessionDisabled"),
338347
actionLabel: t("common.unarchive"),
339-
onAction: () => void this.restoreArchivedSession(state.sessionKey),
348+
disabledReason: unarchiveAccess.allowed ? undefined : unarchiveAccess.reason,
349+
onAction: () => {
350+
if (unarchiveAccess.allowed) {
351+
void this.restoreArchivedSession(state.sessionKey);
352+
}
353+
},
340354
}
341355
: modelSetupRequired
342356
? createChatModelSetupBanner(() => this.context.navigate("model-setup"))
@@ -395,17 +409,26 @@ export class ChatPane extends ChatPaneHeader {
395409
modelSelectionRuntimeId: selectedSession?.agentRuntime?.id,
396410
modelSwitching: Boolean(state.chatModelSwitchPromises[state.sessionKey]),
397411
modelsLoading: state.chatModelsLoading,
412+
mutationDisabledReason: runtimePatchAccess.allowed
413+
? undefined
414+
: runtimePatchAccess.reason,
398415
sending: state.chatSending,
399416
sessionKey: state.sessionKey,
400417
sessionsResult: state.sessionsResult,
401418
stream: state.chatStream,
402419
onRequestUpdate: () => state.requestUpdate?.(),
403420
onFastModeSelect: (next, targetSessionKey) =>
404-
switchChatFastMode(state, next, targetSessionKey),
421+
runtimePatchAccess.allowed
422+
? switchChatFastMode(state, next, targetSessionKey)
423+
: Promise.resolve(false),
405424
onModelSelect: (next, targetSessionKey) =>
406-
switchChatModel(state, next, targetSessionKey),
425+
runtimePatchAccess.allowed
426+
? switchChatModel(state, next, targetSessionKey)
427+
: Promise.resolve(false),
407428
onThinkingSelect: (next, targetSessionKey) =>
408-
switchChatThinkingLevel(state, next, targetSessionKey),
429+
runtimePatchAccess.allowed
430+
? switchChatThinkingLevel(state, next, targetSessionKey)
431+
: Promise.resolve(false),
409432
},
410433
onboarding: state.onboarding,
411434
settings: state.settings,

‎ui/src/pages/chat/chat-pane-session.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { selectApplicationSession } from "../../app/agent-selection.ts";
1212
import { clampText } from "../../lib/format.ts";
1313
import { isGatewayMethodAdvertised } from "../../lib/gateway-methods.ts";
1414
import { resolveSessionDisplayName } from "../../lib/session-display.ts";
15+
import { readSessionMethodAccess } from "../../lib/session-method-access.ts";
1516
import {
1617
scopedSessionPullRequestKey,
1718
SESSION_PULL_REQUESTS_SUBSCRIBE_METHOD,
@@ -338,6 +339,16 @@ export abstract class ChatPaneSession extends ChatPaneSharing {
338339
if (!scope || scope.state.sessionKey !== sessionKey) {
339340
return;
340341
}
342+
const access = readSessionMethodAccess(scope.context.gateway.snapshot, {
343+
method: "sessions.patch",
344+
params: { key: sessionKey, archived: false },
345+
});
346+
if (!access.allowed) {
347+
scope.state.lastError = access.reason;
348+
scope.state.chatError = access.reason;
349+
scope.state.requestUpdate?.();
350+
return;
351+
}
341352
const agentId = parseAgentSessionKey(sessionKey)?.agentId ?? resolveChatAgentId(scope.state);
342353
let failure: string | null = null;
343354
try {

‎ui/src/pages/chat/chat-pane-sharing.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,53 @@ describe.each(mutations)("chat pane $name mutation connection ownership", (mutat
391391
},
392392
);
393393

394+
it.each(["resolve", "reject"] as const)(
395+
"drops a stale same-key mutation when the replaced session later %s",
396+
async (completion) => {
397+
const response = createDeferred<unknown>();
398+
const request = vi.fn((method: string) => {
399+
if (method !== mutation.method) {
400+
throw new Error(`unexpected request: ${method}`);
401+
}
402+
return response.promise;
403+
});
404+
const sessions = {
405+
refreshReplacement: vi.fn(),
406+
} as unknown as SessionCapability;
407+
const { pane: testPane, state } = createSharingTestChatPane({
408+
client: { request } as unknown as GatewayBrowserClient,
409+
sessions,
410+
});
411+
const pane = testPane as SharingPane;
412+
const stale = sessionRow();
413+
const pending = mutation.invoke(pane, stale);
414+
expect(request).toHaveBeenCalledWith(
415+
mutation.method,
416+
expect.objectContaining({ sessionKey: stale.key }),
417+
);
418+
419+
const replacement = { ...stale, sessionId: "session-replacement" };
420+
state.sessionsResult = sharingSessionsResult(replacement);
421+
const cacheKey = pane.sessionSharingCacheKey(replacement.key);
422+
const replacementState: ChatSessionSharingState = {
423+
loading: false,
424+
result: sharingResult(replacement),
425+
};
426+
pane.sessionSharingStates = new Map([[cacheKey, replacementState]]);
427+
428+
if (completion === "resolve") {
429+
response.resolve({});
430+
} else {
431+
response.reject(new Error("stale mutation failed"));
432+
}
433+
await pending;
434+
435+
expect(request).toHaveBeenCalledTimes(1);
436+
expect(sessions.refreshReplacement).not.toHaveBeenCalled();
437+
expect(pane.sessionSharingStates.get(cacheKey)).toBe(replacementState);
438+
},
439+
);
440+
394441
it("preserves the current connection failure in the sharing cache", async () => {
395442
const request = vi.fn(async (method: string) => {
396443
if (method === mutation.method) {

‎ui/src/pages/chat/chat-pane-sharing.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,10 @@ export abstract class ChatPaneSharing extends ChatPaneBase {
162162
}
163163
try {
164164
await scope.client.request("session.visibility.set", params);
165-
if (!this.isConnectionScopeCurrent(scope)) {
165+
if (
166+
!this.isConnectionScopeCurrent(scope) ||
167+
!this.currentSessionSharingRow(scope, currentRow)
168+
) {
166169
return;
167170
}
168171
await scope.sessions.refreshReplacement(agentId);
@@ -172,7 +175,10 @@ export abstract class ChatPaneSharing extends ChatPaneBase {
172175
}
173176
await this.loadSessionSharing(refreshedRow, true);
174177
} catch (error) {
175-
if (!this.isConnectionScopeCurrent(scope)) {
178+
if (
179+
!this.isConnectionScopeCurrent(scope) ||
180+
!this.currentSessionSharingRow(scope, currentRow)
181+
) {
176182
return;
177183
}
178184
this.setSessionSharingState(cacheKey, {
@@ -211,16 +217,25 @@ export abstract class ChatPaneSharing extends ChatPaneBase {
211217
}
212218
try {
213219
await scope.client.request(method, params);
214-
if (!this.isConnectionScopeCurrent(scope)) {
220+
if (
221+
!this.isConnectionScopeCurrent(scope) ||
222+
!this.currentSessionSharingRow(scope, currentRow)
223+
) {
215224
return;
216225
}
217226
await this.loadSessionSharing(currentRow, true);
218-
if (!this.isConnectionScopeCurrent(scope)) {
227+
if (
228+
!this.isConnectionScopeCurrent(scope) ||
229+
!this.currentSessionSharingRow(scope, currentRow)
230+
) {
219231
return;
220232
}
221233
await scope.sessions.refreshReplacement(agentId);
222234
} catch (error) {
223-
if (!this.isConnectionScopeCurrent(scope)) {
235+
if (
236+
!this.isConnectionScopeCurrent(scope) ||
237+
!this.currentSessionSharingRow(scope, currentRow)
238+
) {
224239
return;
225240
}
226241
this.setSessionSharingState(cacheKey, {

‎ui/src/pages/chat/chat-pane.test-support.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ export type TestChatPane = HTMLElement & {
3636
connectedCallback: () => void;
3737
connectionGeneration: number;
3838
createSession: () => Promise<boolean>;
39+
restoreArchivedSession: (sessionKey: string) => Promise<void>;
3940
disconnectedCallback: () => void;
4041
acceptTaskSuggestion: (suggestion: TaskSuggestion) => Promise<void>;
4142
handleDocumentKeydown: (event: KeyboardEvent) => void;

0 commit comments

Comments
 (0)