The best way to control Claude Code, Codex and more from any computer or phone
fix(server): /logout in chat needs providers:manage (#39027)
Julius Marminge committed
Nov 19, 2026 at 12:43 UTC
b5bef4d9391117ad0d95b3a8f91a63200861ed54
14 files changed
+391
-22
apps/server/src/auth/RpcAuthorization.test.ts
+78
@@ -17,6 +17,10 @@ import {
17
AuthSourceControlWriteScope,
18
AuthTerminalReadScope,
19
AuthTerminalOperateScope,
20
+ CommandId,
21
+ MessageId,
22
+ ORCHESTRATION_V2_WS_METHODS,
23
+ RunId,
24
WS_METHODS,
25
WsRpcGroup,
26
} from "@t3tools/contracts";
@@ -606,3 +610,77 @@ it.effect("denies manual cleanup before the handler without settings permission"
610
expect(handled).toBe(false);
611
}),
612
);
613
+
614
+it.effect("requires provider management to send /logout through chat", () =>
615
+ Effect.gen(function* () {
616
+ const group = WsRpcGroup.omit(
617
+ ...[...WsRpcGroup.requests.keys()].filter(
618
+ (
619
+ tag,
620
+ ): tag is Exclude<
621
+ keyof typeof RPC_REQUIRED_SCOPES,
622
+ typeof ORCHESTRATION_V2_WS_METHODS.dispatchCommand
623
+ > => tag !== ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
624
+ ),
625
+ );
626
+ const handled: string[] = [];
627
+ const handler = group.toLayerHandler(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, (command) =>
628
+ Effect.sync(() => {
629
+ handled.push(command.commandId);
630
+ return { sequence: 1 };
631
+ }),
632
+ );
633
+ const message = (commandId: string, text: string) => ({
634
+ type: "message.dispatch" as const,
635
+ createdBy: "user" as const,
636
+ creationSource: "web" as const,
637
+ commandId: CommandId.make(commandId),
638
+ threadId: ThreadId.make("thread"),
639
+ messageId: MessageId.make(commandId),
640
+ text,
641
+ attachments: [],
642
+ dispatchMode: { type: "start_immediately" as const },
643
+ });
644
+ const edit = (commandId: string) => ({
645
+ type: "queued-run.edit" as const,
646
+ commandId: CommandId.make(commandId),
647
+ threadId: ThreadId.make("thread"),
648
+ runId: RunId.make("run"),
649
+ text: "/logout",
650
+ });
651
+ // With an attachment, `/logout` reaches the provider as a prompt, not a sign-out.
652
+ const attachments = [
653
+ { type: "image" as const, id: "shot", name: "shot.png", mimeType: "image/png", sizeBytes: 1 },
654
+ ];
655
+ const operator = yield* RpcTest.makeClient(group).pipe(
656
+ Effect.provide(Layer.merge(handler, RpcAuthorization.layer([AuthOrchestrationOperateScope]))),
657
+ );
658
+ const dispatch = operator[ORCHESTRATION_V2_WS_METHODS.dispatchCommand];
659
+ yield* dispatch(message("hello", "hello"));
660
+ yield* dispatch({ ...message("attached", "/logout"), attachments });
661
+ yield* dispatch({ ...edit("attached-edit"), attachments });
662
+ // This edit keeps the queued attachments; message intake decides it.
663
+ yield* dispatch(edit("kept-attachments-edit"));
664
+ for (const command of [message("logout", " /LOGOUT "), { ...edit("edit"), attachments: [] }]) {
665
+ expect(yield* dispatch(command).pipe(Effect.flip)).toMatchObject({
666
+ requiredPermission: AuthProvidersManageScope,
667
+ });
668
+ }
669
+ const manager = yield* RpcTest.makeClient(group).pipe(
670
+ Effect.provide(
671
+ Layer.merge(
672
+ handler,
673
+ RpcAuthorization.layer([AuthOrchestrationOperateScope, AuthProvidersManageScope]),
674
+ ),
675
+ ),
676
+ );
677
+ yield* manager[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](message("manager", "/logout"));
678
+ expect(handled).toEqual([
679
+ "hello",
680
+ "attached",
681
+ "attached-edit",
682
+ "kept-attachments-edit",
683
+ "manager",
684
+ ]);
685
+ }).pipe(Effect.scoped),
686
+);
apps/server/src/auth/RpcAuthorization.ts
+33
-2
@@ -24,6 +24,8 @@ import {
24
AuthRelayWriteScope,
25
AuthTerminalOperateScope,
26
ORCHESTRATION_V2_WS_METHODS,
27
+ type OrchestrationV2Command,
28
+ type OrchestrationV2ThreadLaunchInput,
29
AuthTerminalReadScope,
30
type AuthEnvironmentScope,
31
EnvironmentAuthorizationError,
@@ -35,6 +37,7 @@ import * as Effect from "effect/Effect";
37
import * as Schema from "effect/Schema";
38
import * as Layer from "effect/Layer";
39
import type * as RpcGroup from "effect/rpc/RpcGroup";
40
+import { isProviderSignOutPrompt } from "../orchestration-v2/CommandPolicy.ts";
41
42
type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
43
@@ -265,6 +268,32 @@ const requiredScopesForSettingsUpdate = (payload: unknown) => {
268
const decodeProjectMutation = Schema.decodeUnknownSync(ProjectMutation);
269
const decodeAssetCreateUrlInput = Schema.decodeUnknownSync(AssetCreateUrlInput);
270
271
+/**
272
+ * A queued edit that omits `attachments` keeps the queued ones, which a payload cannot show;
273
+ * ThreadMessageIntake.dispatchCommand decides that case.
274
+ */
275
+const sendsProviderSignOutPrompt = (method: string, payload: unknown): boolean => {
276
+ if (method === ORCHESTRATION_V2_WS_METHODS.launchThread) {
277
+ const message = (payload as OrchestrationV2ThreadLaunchInput).initialMessage;
278
+ return message !== undefined && isProviderSignOutPrompt(message);
279
+ }
280
+ if (method !== ORCHESTRATION_V2_WS_METHODS.dispatchCommand) return false;
281
+ const command = payload as OrchestrationV2Command;
282
+ switch (command.type) {
283
+ case "message.dispatch":
284
+ return isProviderSignOutPrompt(command);
285
+ case "queued-run.edit":
286
+ return (
287
+ command.attachments !== undefined &&
288
+ isProviderSignOutPrompt({ text: command.text, attachments: command.attachments })
289
+ );
290
+ case "delegated_task.request":
291
+ return isProviderSignOutPrompt({ text: command.task, attachments: [] });
292
+ default:
293
+ return false;
294
+ }
295
+};
296
+
297
const requiredScopesForRpcCall = (
298
method: string,
299
payload: unknown,
@@ -297,8 +326,10 @@ const requiredScopesForRpcCall = (
326
return requiredScopesForProjectMutation(decodeProjectMutation(payload));
327
}
328
const guarded = clientRpcRequiredScopes(method, payload);
300
- if (guarded.length > 0) return guarded;
301
- return [requiredScopeForRpcMethod(method)];
329
+ const scopes = guarded.length > 0 ? guarded : [requiredScopeForRpcMethod(method)];
330
+ return sendsProviderSignOutPrompt(method, payload)
331
+ ? [...scopes, AuthProvidersManageScope]
332
+ : scopes;
333
};
334
335
/**
apps/server/src/mcp/toolkits/core.test.ts
+34
-5
@@ -473,7 +473,10 @@ it.effect("records only failed calls of tools that hand off no work", () => {
473
});
474
475
// A thread read whose runs or messages are bounded by nothing but the thread.
476
-const historyReads = (reads: Array<string>) => {
476
+const historyReads = (
477
+ reads: Array<string>,
478
+ queued?: { readonly attachments: ReadonlyArray<unknown>; readonly dispatched: Array<unknown> },
479
+) => {
480
const record = (
481
fields: ReadonlyArray<string>,
482
filter: ProjectionStore.ProjectionRecordFilter | undefined,
@@ -499,9 +502,20 @@ const historyReads = (reads: Array<string>) => {
502
getProjectThreadRecords: (_target, fields, filter) =>
503
Effect.sync(() => record(fields, filter)).pipe(Effect.as(projection as never)),
504
getThreadRecords: (_id, fields, filter) =>
502
- Effect.sync(() => record(fields, filter)).pipe(Effect.as(projection as never)),
503
- getMessagesById: () => Effect.succeed(new Map()),
504
- dispatch: () => Effect.succeed({ sequence: 1 } as never),
505
+ Effect.sync(() => record(fields, filter)).pipe(
506
+ Effect.as({
507
+ ...projection,
508
+ runs:
509
+ queued === undefined
510
+ ? projection.runs
511
+ : [{ id: "run:queued", status: "queued", userMessageId: "message:queued" }],
512
+ } as never),
513
+ ),
514
+ getMessagesById: () =>
515
+ Effect.succeed(new Map(queued === undefined ? [] : [["message:queued", queued]]) as never),
516
+ hasReceipt: () => Effect.succeed(false),
517
+ dispatch: (command) =>
518
+ Effect.sync(() => queued?.dispatched.push(command)).pipe(Effect.as({ sequence: 1 } as never)),
519
});
520
};
521
@@ -532,6 +546,8 @@ it.effect("t3_queue list and read load only the queued runs and their messages",
546
547
it.effect("handoff analytics read only the caller's active run and its message", () => {
548
const reads: Array<string> = [];
549
+ const attachments = [{ type: "image", id: "shot", name: "shot.png" }];
550
+ const dispatched: Array<unknown> = [];
551
const recorded = Deferred.makeUnsafe<void>();
552
return Effect.gen(function* () {
553
const server = yield* McpServer.McpServer;
@@ -546,12 +562,25 @@ it.effect("handoff analytics read only the caller's active run and its message",
562
);
563
yield* Deferred.await(recorded);
564
expect(reads).toEqual([]);
565
+ // The edit keeps the queued image, so `/logout` stays an ordinary prompt and is not refused.
566
+ const attached = yield* server
567
+ .callTool({
568
+ name: "t3_queue",
569
+ arguments: { action: "edit", queuedRunId: "run:queued", text: " /LOGOUT " },
570
+ })
571
+ .pipe(
572
+ Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
573
+ Effect.provideService(McpSchema.McpServerClient, client),
574
+ );
575
+ expect(attached.isError).not.toBe(true);
576
+ expect(dispatched).toMatchObject([{ text: "Edited" }, { text: " /LOGOUT ", attachments }]);
577
+ expect(dispatched[0]).not.toHaveProperty("attachments");
578
}).pipe(
579
Effect.provide(
580
layerThreadToolkit.pipe(
581
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
582
Layer.provide(NodeCrypto.layer),
554
- Layer.provide(historyReads(reads)),
583
+ Layer.provide(historyReads(reads, { attachments, dispatched })),
584
Layer.provide(
585
Layer.succeed(
586
AnalyticsService.AnalyticsService,
apps/server/src/mcp/toolkits/thread/handlers.ts
+18
-3
@@ -21,6 +21,7 @@ import {
21
unavailable,
22
} from "../../threadAccess.ts";
23
import type * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
24
+import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
25
import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts";
26
import * as ScheduledTasks from "../../../scheduledTasks/ScheduledTaskService.ts";
27
import { queuedRunsInDeliveryOrder } from "../../../orchestration-v2/QueuedRunOrder.ts";
@@ -324,12 +325,26 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
325
switch (input.action) {
326
case "edit": {
327
const text = yield* required(input.text, "text");
327
- return yield* dispatch(input.threadId, (common) => ({
328
- ...common,
328
+ const { threads, projection } = yield* readThread(input.threadId);
329
+ // An agent must not turn a person's queued message into a provider sign-out.
330
+ const command = yield* ThreadMessageIntake.withQueuedAttachmentsOnSignOutText({
331
type: "queued-run.edit",
332
+ commandId: yield* newCommandId(),
333
+ threadId: projection.thread.id,
334
runId,
335
text,
332
- }));
336
+ }).pipe(
337
+ Effect.mapError((error) =>
338
+ error._tag === "EnvironmentAuthorizationError"
339
+ ? new OrchestratorMcpFailure({
340
+ code: "invalid_request",
341
+ message: "A queued message cannot be edited into a provider sign-out.",
342
+ })
343
+ : dispatchFailure(error),
344
+ ),
345
+ );
346
+ const result = yield* threads.dispatch(command).pipe(Effect.mapError(dispatchFailure));
347
+ return { sequence: result.sequence };
348
}
349
case "reorder": {
350
const beforeRunId = yield* required(input.beforeRunId, "beforeRunId");
apps/server/src/orchestration-v2/CommandPolicy.ts
+11
@@ -59,6 +59,17 @@ type MessageDispatchMode = Extract<
59
{ readonly type: "message.dispatch" }
60
>["dispatchMode"];
61
62
+/**
63
+ * A message that signs a provider account out at turn start, as `providerAuthLogout` does.
64
+ * With attachments the same text is an ordinary prompt.
65
+ */
66
+export function isProviderSignOutPrompt(message: {
67
+ readonly text: string;
68
+ readonly attachments: ReadonlyArray<ChatAttachment>;
69
+}): boolean {
70
+ return message.attachments.length === 0 && message.text.trim().toLowerCase() === "/logout";
71
+}
72
+
73
export function isNativeMaintenanceCommand(message: {
74
readonly text: string;
75
readonly attachments: ReadonlyArray<ChatAttachment>;
apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
+26
-2
@@ -467,6 +467,8 @@ function makeLocalCommandHarness(input: {
467
readonly fileSystem?: FileSystem.FileSystem;
468
readonly previousNativeSession?: boolean;
469
readonly previousMessages?: ReadonlyArray<string>;
470
+ readonly createdBy?: "agent" | "system";
471
+ readonly scheduledTaskId?: ScheduledTaskId;
472
readonly logoutFailure?: string;
473
readonly openFailure?: unknown;
474
readonly ensureThreadFailure?: unknown;
@@ -565,8 +567,9 @@ function makeLocalCommandHarness(input: {
567
text: input.text,
568
attachments: [],
569
streaming: false,
568
- createdBy: "user",
569
- creationSource: "web",
570
+ createdBy: input.createdBy ?? "user",
571
+ creationSource: input.createdBy === undefined ? "web" : "mcp",
572
+ ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }),
573
createdAt: now,
574
updatedAt: now,
575
};
@@ -3301,6 +3304,7 @@ effectIt.effect.each(["not_loaded", "error"] as const)(
3304
instanceId: harness.oldInstanceId,
3305
text: "/logout",
3306
hasAttachments: false,
3307
+ sentByPerson: true,
3308
});
3309
expect(harness.open).not.toHaveBeenCalled();
3310
expect(harness.startRootRun).not.toHaveBeenCalled();
@@ -3324,6 +3328,26 @@ effectIt.effect.each(["not_loaded", "error"] as const)(
3328
}),
3329
);
3330
3331
+effectIt.effect.each([
3332
+ { name: "an agent", createdBy: "agent" as const },
3333
+ // A scheduled delivery keeps its task author's createdBy.
3334
+ { name: "a scheduled task", scheduledTaskId: ScheduledTaskId.make("task") },
3335
+])("does not let $name sign a provider out", ({ name: _name, ...sender }) =>
3336
+ Effect.gen(function* () {
3337
+ const harness = makeLocalCommandHarness({
3338
+ text: "/logout",
3339
+ ...sender,
3340
+ previousNativeSession: true,
3341
+ });
3342
+
3343
+ yield* harness.start;
3344
+
3345
+ expect(harness.tryHandlePromptCommand).toHaveBeenCalledExactlyOnceWith(
3346
+ expect.objectContaining({ sentByPerson: false }),
3347
+ );
3348
+ }),
3349
+);
3350
+
3351
for (const previousMessages of [[], ["/compact", " /COMPACT "]]) {
3352
effectIt.effect(
3353
`rejects compaction without conversation context after ${previousMessages.length} prior compactions`,
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+4
@@ -741,6 +741,10 @@ export const layer: Layer.Layer<
741
records: providerMessage.context?.records ?? [],
742
}),
743
hasAttachments: false,
744
+ // A scheduled delivery keeps its task author's createdBy.
745
+ sentByPerson:
746
+ providerMessage.createdBy === "user" &&
747
+ providerMessage.scheduledTaskId === undefined,
748
}),
749
);
750
if (isEmptyCompaction || authResult?._tag === "Failure" || authResult?.success) {
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+7
-4
@@ -77,6 +77,9 @@ import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAda
77
const projectId = ProjectId.make("project:launch-test");
78
const otherProjectId = ProjectId.make("project:launch-other");
79
const encodeThreadProjection = Schema.encodeEffect(OrchestrationV2ThreadProjectionJson);
80
+const dispatchIntakeCommand = (
81
+ command: Parameters<typeof ThreadMessageIntake.dispatchCommand>[0],
82
+) => ThreadMessageIntake.dispatchCommand(command, { managesProviders: true });
83
const modelSelection = {
84
instanceId: ProviderInstanceId.make("codex"),
85
model: "gpt-5.1-codex",
@@ -2672,7 +2675,7 @@ it.effect("shared intake preserves durable attachment bytes after a lost launch
2675
}).pipe(Effect.flip);
2676
assert.equal(missingProject._tag, "ThreadLaunchError");
2677
assert.equal((yield* claimedFiles).length, 1);
2675
- const missingThread = yield* ThreadMessageIntake.dispatchCommand({
2678
+ const missingThread = yield* dispatchIntakeCommand({
2679
type: "message.dispatch",
2680
commandId: CommandId.make("intake-no-thread"),
2681
threadId: ThreadId.make("missing-thread"),
@@ -2686,7 +2689,7 @@ it.effect("shared intake preserves durable attachment bytes after a lost launch
2689
assert.equal(missingThread._tag, "OrchestratorProjectionError");
2690
assert.equal((yield* claimedFiles).length, 1);
2691
2689
- const dispatch = ThreadMessageIntake.dispatchCommand({
2692
+ const dispatch = dispatchIntakeCommand({
2693
type: "message.dispatch",
2694
commandId: CommandId.make("intake-dispatch"),
2695
threadId: input.threadId,
@@ -2722,7 +2725,7 @@ it.effect("shared intake preserves durable attachment bytes after a lost launch
2725
});
2726
assert.isNotNull(filePath);
2727
yield* fs.writeFile(filePath, new Uint8Array([5, 6, 7, 8]));
2725
- const edit = ThreadMessageIntake.dispatchCommand({
2728
+ const edit = dispatchIntakeCommand({
2729
type: "queued-run.edit",
2730
commandId: CommandId.make("intake-edit"),
2731
threadId: input.threadId,
@@ -2748,7 +2751,7 @@ it.effect("shared intake preserves durable attachment bytes after a lost launch
2751
assert.deepEqual(yield* fs.readFile(durableFilePath), new Uint8Array([5, 6, 7, 8]));
2752
assert.deepEqual(yield* fs.readFile(filePath), new Uint8Array([5, 6, 7, 8]));
2753
const beforeRejectedEdit = (yield* claimedFiles).length;
2751
- const rejectedEdit = yield* ThreadMessageIntake.dispatchCommand({
2754
+ const rejectedEdit = yield* dispatchIntakeCommand({
2755
type: "queued-run.edit",
2756
commandId: CommandId.make("intake-edit-rejected"),
2757
threadId: input.threadId,
apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts
+71
-1
@@ -34,7 +34,10 @@ import {
34
OrchestratorDispatchError,
35
} from "./Orchestrator.ts";
36
import * as ThreadManagementService from "./ThreadManagementService.ts";
37
-import { dispatchCommand } from "./ThreadMessageIntake.ts";
37
+import * as ThreadMessageIntake from "./ThreadMessageIntake.ts";
38
+
39
+const dispatchCommand = (command: OrchestrationV2Command, sender = { managesProviders: true }) =>
40
+ ThreadMessageIntake.dispatchCommand(command, sender);
41
42
const layerIntakeTest = ServerConfig.layerTest(process.cwd(), {
43
prefix: "t3-question-intake-",
@@ -475,3 +478,70 @@ it.effect("refuses a queued edit that keeps a file another edit already deleted"
478
expect(captured).toHaveLength(2);
479
}).pipe(Effect.provide(layerIntakeTest)),
480
);
481
+
482
+it.effect("a queued /logout edit without provider management must keep an attachment", () =>
483
+ Effect.gen(function* () {
484
+ const threadId = ThreadId.make("thread-sign-out-edit");
485
+ const image = {
486
+ type: "image" as const,
487
+ id: ChatAttachmentId.make(createAttachmentId(threadId)!),
488
+ name: "shot.png",
489
+ mimeType: "image/png",
490
+ sizeBytes: 3,
491
+ };
492
+ const config = yield* ServerConfig.ServerConfig;
493
+ NodeFS.writeFileSync(
494
+ NodePath.join(config.attachmentsDir, `${image.id}.png`),
495
+ new Uint8Array([1, 2, 3]),
496
+ );
497
+ const captured: OrchestrationV2ServerCommand[] = [];
498
+ // The edit omits `attachments`, as an older client's does, so the queued ones stay.
499
+ const edit = (run: string, managesProviders: boolean) =>
500
+ dispatchCommand(
501
+ {
502
+ type: "queued-run.edit",
503
+ commandId: CommandId.make(`edit-${run}-${managesProviders}`),
504
+ threadId,
505
+ runId: RunId.make(run),
506
+ text: " /LOGOUT ",
507
+ },
508
+ { managesProviders },
509
+ ).pipe(
510
+ Effect.provide(
511
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
512
+ dispatch: layerFailingDispatchHandler(captured),
513
+ hasReceipt: (commandId) => Effect.succeed(commandId === "edit-replayed-false"),
514
+ getThreadRecords: () =>
515
+ Effect.succeed({
516
+ runs: ["attached", "bare"].map((id) => ({
517
+ id: RunId.make(id),
518
+ status: "queued",
519
+ userMessageId: MessageId.make(id),
520
+ })),
521
+ } as never),
522
+ getMessagesById: (_threadId, [id]) =>
523
+ Effect.succeed(
524
+ new Map([[id, { attachments: id === "attached" ? [image] : [] }]]) as never,
525
+ ),
526
+ }),
527
+ ),
528
+ Effect.flip,
529
+ );
530
+
531
+ expect((yield* edit("bare", false))._tag).toBe("EnvironmentAuthorizationError");
532
+ expect((yield* edit("started", false))._tag).toBe("EnvironmentAuthorizationError");
533
+ expect(captured).toEqual([]);
534
+ yield* edit("attached", false);
535
+ yield* edit("bare", true);
536
+ // A retry of an accepted edit reaches its receipt after its run left the queue.
537
+ yield* edit("replayed", false);
538
+ // The kept files are pinned, so an edit racing this one cannot strip them afterwards.
539
+ expect(captured).toMatchObject([
540
+ { runId: "attached", attachments: [image] },
541
+ { runId: "bare" },
542
+ { runId: "replayed" },
543
+ ]);
544
+ expect(captured[1]).not.toHaveProperty("attachments");
545
+ expect(captured[2]).not.toHaveProperty("attachments");
546
+ }).pipe(Effect.provide(layerIntakeTest)),
547
+);
apps/server/src/orchestration-v2/ThreadMessageIntake.ts
+49
-2
@@ -1,14 +1,20 @@
1
import { remapComposerContextAttachments } from "@t3tools/shared/composerContextReferences";
2
import { appendUserInputAttachmentPaths } from "../provider/userInputAttachments.ts";
3
-import type { ChatAttachment, OrchestrationV2Command } from "@t3tools/contracts";
3
+import {
4
+ AuthProvidersManageScope,
5
+ type ChatAttachment,
6
+ type OrchestrationV2Command,
7
+} from "@t3tools/contracts";
8
import * as Effect from "effect/Effect";
9
import * as FileSystem from "effect/FileSystem";
10
import * as Schema from "effect/Schema";
11
import { resolveAttachmentPath } from "../attachmentStore.ts";
12
+import { rpcAuthorizationError } from "../auth/RpcAuthorization.ts";
13
import * as ServerConfig from "../config.ts";
14
import * as Orchestrator from "./Orchestrator.ts";
15
16
import * as AttachmentClaims from "./AttachmentClaims.ts";
17
+import { isProviderSignOutPrompt } from "./CommandPolicy.ts";
18
import * as ThreadLaunch from "./ThreadLaunchService.ts";
19
import * as ThreadManagement from "./ThreadManagementService.ts";
20
@@ -85,11 +91,52 @@ const withGuestAttachments = Effect.fn("ThreadMessageIntake.withGuestAttachments
91
return { ...command, attachments: message?.attachments ?? [] };
92
});
93
94
+/**
95
+ * For a caller without `providers:manage`. An edit that omits `attachments` keeps the queued
96
+ * ones, so `/logout` signs out only when the queued message has none. The edit goes on with
97
+ * the files read here, so an edit racing this one cannot strip them afterwards.
98
+ */
99
+export const withQueuedAttachmentsOnSignOutText = Effect.fn(
100
+ "ThreadMessageIntake.withQueuedAttachmentsOnSignOutText",
101
+)(function* (command: Extract<OrchestrationV2Command, { readonly type: "queued-run.edit" }>) {
102
+ if (
103
+ command.attachments !== undefined ||
104
+ !isProviderSignOutPrompt({ text: command.text, attachments: [] })
105
+ ) {
106
+ return command;
107
+ }
108
+ const threads = yield* ThreadManagement.ThreadManagementService;
109
+ // A retry of an accepted edit replays its receipt, even after its run left the queue.
110
+ if (yield* threads.hasReceipt(command.commandId)) return command;
111
+ const { runs } = yield* threads.getThreadRecords(command.threadId, ["runs"], {
112
+ runIds: [command.runId],
113
+ });
114
+ const queuedRun = runs.find((run) => run.id === command.runId && run.status === "queued");
115
+ const attachments =
116
+ queuedRun === undefined
117
+ ? []
118
+ : ((yield* threads.getMessagesById(command.threadId, [queuedRun.userMessageId])).get(
119
+ queuedRun.userMessageId,
120
+ )?.attachments ?? []);
121
+ if (attachments.length === 0) return yield* rpcAuthorizationError(AuthProvidersManageScope);
122
+ return { ...command, attachments };
123
+});
124
+
125
+/**
126
+ * `sender.managesProviders` is whether the caller holds `providers:manage`. RPC authorization
127
+ * has already checked every command whose payload shows a provider sign-out; a queued edit
128
+ * that keeps its attachments is the one case decided here.
129
+ */
130
export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")(function* (
131
incoming: OrchestrationV2Command,
132
+ sender: { readonly managesProviders: boolean },
133
) {
134
const command =
92
- incoming.type === "message.dispatch" ? yield* withGuestAttachments(incoming) : incoming;
135
+ incoming.type === "message.dispatch"
136
+ ? yield* withGuestAttachments(incoming)
137
+ : incoming.type === "queued-run.edit" && !sender.managesProviders
138
+ ? yield* withQueuedAttachmentsOnSignOutText(incoming)
139
+ : incoming;
140
const threads = yield* ThreadManagement.ThreadManagementService;
141
if (command.type === "runtime-request.respond" && command.attachmentsByQuestionId) {
142
const config = yield* ServerConfig.ServerConfig;
apps/server/src/provider/ProviderAuthService.test.ts
+39
-2
@@ -679,6 +679,32 @@ describe("ProviderAuthService", () => {
679
}),
680
);
681
682
+ it.effect("refuses a chat sign-out that no person sent", () =>
683
+ Effect.gen(function* () {
684
+ const { service, actions } = yield* makeHarness({});
685
+ const error = yield* Effect.flip(
686
+ service.tryHandlePromptCommand({
687
+ instanceId,
688
+ text: "/logout",
689
+ hasAttachments: false,
690
+ sentByPerson: false,
691
+ }),
692
+ );
693
+
694
+ assert.strictEqual(error.operation, "logout");
695
+ assert.deepStrictEqual(actions, []);
696
+ // Any other prompt still goes to the provider.
697
+ assert.isFalse(
698
+ yield* service.tryHandlePromptCommand({
699
+ instanceId,
700
+ text: "hello",
701
+ hasAttachments: false,
702
+ sentByPerson: false,
703
+ }),
704
+ );
705
+ }),
706
+ );
707
+
708
it.effect("does not log out or consume the command when stopping a session fails", () =>
709
Effect.gen(function* () {
710
const { service, actions, released } = yield* makeHarness({
@@ -687,7 +713,12 @@ describe("ProviderAuthService", () => {
713
stopError: true,
714
});
715
const error = yield* Effect.flip(
690
- service.tryHandlePromptCommand({ instanceId, text: "/logout", hasAttachments: false }),
716
+ service.tryHandlePromptCommand({
717
+ instanceId,
718
+ text: "/logout",
719
+ hasAttachments: false,
720
+ sentByPerson: true,
721
+ }),
722
);
723
724
assert.instanceOf(error, ProviderSetupError);
@@ -722,7 +753,12 @@ it.effect("queued logout prompts resolve the current controller after provider r
753
yield* Deferred.await(entered);
754
observeLookup = true;
755
const queued = yield* harness.service
725
- .tryHandlePromptCommand({ instanceId, text: "/logout", hasAttachments: false })
756
+ .tryHandlePromptCommand({
757
+ instanceId,
758
+ text: "/logout",
759
+ hasAttachments: false,
760
+ sentByPerson: true,
761
+ })
762
.pipe(Effect.forkChild);
763
yield* Deferred.await(lookup);
764
let replacementLoggedOut = false;
@@ -787,6 +823,7 @@ it.effect.each(["start", "logout", "prompt"] as const)(
823
instanceId,
824
text: "/logout",
825
hasAttachments: false,
826
+ sentByPerson: true,
827
});
828
const running = yield* operation.pipe(Effect.forkChild);
829
yield* Deferred.await(checked);
apps/server/src/provider/ProviderAuthService.ts
+13
-1
@@ -62,7 +62,12 @@ export class ProviderAuthService extends Context.Service<
62
ownerSessionId: string,
63
) => Stream.Stream<ProviderAuthState, ProviderSetupError>;
64
readonly tryHandlePromptCommand: (
65
- input: ProviderAuthTarget & { readonly text: string; readonly hasAttachments: boolean },
65
+ input: ProviderAuthTarget & {
66
+ readonly text: string;
67
+ readonly hasAttachments: boolean;
68
+ /** False for agent, system and scheduled messages: no RPC scope check covered them. */
69
+ readonly sentByPerson: boolean;
70
+ },
71
) => Effect.Effect<boolean, ProviderSetupError>;
72
}
73
>()("t3/provider/ProviderAuthService") {}
@@ -306,6 +311,13 @@ export const makeProviderAuthService = Effect.gen(function* () {
311
if (!instance?.auth?.isLogoutPrompt?.(input.text, input.hasAttachments)) {
312
return false;
313
}
314
+ if (!input.sentByPerson) {
315
+ return yield* new ProviderSetupError({
316
+ instanceId: input.instanceId,
317
+ operation: "logout",
318
+ detail: "Only a person can sign out of a provider from chat. Sign out in Settings.",
319
+ });
320
+ }
321
return yield* credentialChanges.withPermit(
322
Effect.gen(function* () {
323
const auth = yield* getController(input.instanceId, "logout");
apps/server/src/ws.ts
+6
@@ -31,6 +31,7 @@ import {
31
AuthAccessStreamError,
32
type AuthAccessStreamEvent,
33
AuthOrchestrationOperateScope,
34
+ AuthProvidersManageScope,
35
type AuthEnvironmentScope,
36
type ScheduledTaskListResult,
37
AuthSessionId,
@@ -2018,6 +2019,10 @@ export const layerWsRpc = (
2019
creationSource:
2020
"creationSource" in command ? command.creationSource : "web",
2021
}),
2022
+ {
2023
+ managesProviders:
2024
+ currentSession.scopes.includes(AuthProvidersManageScope),
2025
+ },
2026
)
2027
).pipe(Effect.provide(intakeContext)),
2028
)
@@ -2027,6 +2032,7 @@ export const layerWsRpc = (
2032
),
2033
Effect.map((result) => ({ sequence: result.sequence })),
2034
Effect.mapError((cause) => {
2035
+ if (cause._tag === "EnvironmentAuthorizationError") return cause;
2036
const detail = userFacingDispatchErrorMessage(cause);
2037
return new OrchestrationV2DispatchCommandError({
2038
commandId: command.commandId,
docs/user/providers-antigravity.md
+2
@@ -142,6 +142,8 @@ runtimes are shared on the environment.
142
143
All three keep thread history and workspace files. Sending `/logout` by itself in
144
a thread signs out its instance, including stopping that instance's other sessions.
145
+That needs a client allowed to manage providers, and it has to be your own message:
146
+`/logout` from an agent or a scheduled task is refused.
147
Sign out, then sign in again to replace an account.
148
149
Before removing a managed runtime, disable its instances and cancel any active