Skip to content

Commit f1d250d

Browse files
committed
fix(ui): harden cloud draft recovery
Refs #120953.
1 parent f67da42 commit f1d250d

20 files changed

Lines changed: 492 additions & 87 deletions

‎ui/src/components/app-sidebar-session-narration.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ function runningRow(key: string): SidebarRecentSession {
2121
hasActiveRun: true,
2222
modelSelectionLocked: false,
2323
pinned: false,
24-
cloudWorkerActive: false,
24+
cloudWorkerStopAction: null,
2525
hasAutomation: false,
2626
unread: false,
2727
attention: { kind: "none" },

‎ui/src/components/app-sidebar-session-navigation-logic.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,12 @@ import {
4444
type SidebarSessionStatusFilter,
4545
} from "./app-sidebar-session-types.ts";
4646
import type { SidebarWorkboardBoard } from "./app-sidebar-workboard.ts";
47+
import { resolveCloudWorkerStopAction } from "./cloud-worker-stop.ts";
4748
import {
4849
listSessionCreators,
4950
type SessionCreatedActor,
5051
type SessionCreatorOption,
5152
} from "./session-owner-chip.ts";
52-
import { isStoppableCloudWorkerPlacement } from "./session-row-badges.ts";
5353

5454
type SessionRow = SessionsListResult["sessions"][number];
5555

@@ -164,7 +164,7 @@ export function buildSidebarSessionNavigationState(input: {
164164
row.placement.workspaceResultConflict?.totalCount ?? 0,
165165
) || undefined
166166
: undefined,
167-
cloudWorkerActive: isStoppableCloudWorkerPlacement(row.placement),
167+
cloudWorkerStopAction: resolveCloudWorkerStopAction(row.placement),
168168
hasAutomation: row.hasAutomation === true,
169169
pullRequest: context?.sessions.pullRequestSummary(row.key),
170170
outboxCount: input.outboxCountForSessionKey(row.key),

‎ui/src/components/app-sidebar-session-types.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
} from "../lib/sessions/grouping.ts";
1919
import type { SessionCapability } from "../lib/sessions/index.ts";
2020
import { getSafeLocalStorage } from "../local-storage.ts";
21+
import type { CloudWorkerStopAction } from "./cloud-worker-stop.ts";
2122
import type { SessionPlacementState } from "./session-row-badges.ts";
2223

2324
export type SidebarSessionAttention =
@@ -83,7 +84,7 @@ export type SidebarRecentSession = {
8384
worktreeId?: string;
8485
placementState?: SessionPlacementState;
8586
workspaceConflictCount?: number;
86-
cloudWorkerActive: boolean;
87+
cloudWorkerStopAction: CloudWorkerStopAction | null;
8788
hasAutomation: boolean;
8889
pullRequest?: SessionCatalogPullRequestSummary;
8990
outboxCount?: number;
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import type { EnvironmentsDestroyResult } from "../../../packages/gateway-protocol/src/schema/environments.ts";
2+
import { isCloudWorkerPlacementState } from "../../../packages/gateway-protocol/src/schema/session-placement-state.js";
3+
import type { GatewayBrowserClient } from "../api/gateway.ts";
4+
import type { GatewaySessionRow } from "../api/types.ts";
5+
6+
export type CloudWorkerStopAction =
7+
| { method: "sessions.reclaim"; requiredScope: "operator.admin" }
8+
| {
9+
method: "environments.destroy";
10+
params: { environmentId: string };
11+
requiredScope: "operator.admin";
12+
};
13+
14+
export function resolveCloudWorkerStopAction(
15+
placement: GatewaySessionRow["placement"],
16+
): CloudWorkerStopAction | null {
17+
if (!placement || !isCloudWorkerPlacementState(placement.state)) {
18+
return null;
19+
}
20+
if (placement.state === "active") {
21+
return { method: "sessions.reclaim", requiredScope: "operator.admin" };
22+
}
23+
return "environmentId" in placement && placement.environmentId
24+
? {
25+
method: "environments.destroy",
26+
params: { environmentId: placement.environmentId },
27+
requiredScope: "operator.admin",
28+
}
29+
: null;
30+
}
31+
32+
export async function requestCloudWorkerStop(
33+
client: GatewayBrowserClient,
34+
action: CloudWorkerStopAction,
35+
session: { key: string; agentId?: string },
36+
): Promise<EnvironmentsDestroyResult | null> {
37+
if (action.method === "environments.destroy") {
38+
return client.request<EnvironmentsDestroyResult>("environments.destroy", action.params);
39+
}
40+
await client.request(
41+
"sessions.reclaim",
42+
{ key: session.key, ...(session.agentId ? { agentId: session.agentId } : {}) },
43+
{ timeoutMs: 10 * 60_000 },
44+
);
45+
return null;
46+
}

‎ui/src/components/session-organizer-operations.runtime.ts‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import type {
1414
SidebarSessionMutationScope,
1515
SidebarSessionPatch,
1616
} from "./app-sidebar-session-types.ts";
17+
import { requestCloudWorkerStop } from "./cloud-worker-stop.ts";
1718
import type { SessionMenuAction } from "./session-menu.ts";
1819
import {
1920
patchSessionRows,
@@ -554,31 +555,34 @@ export async function stopCloudWorker(
554555
session: SidebarRecentSession,
555556
scope: SidebarSessionMutationScope,
556557
) {
558+
const stopAction = session.cloudWorkerStopAction;
557559
if (
558-
!session.cloudWorkerActive ||
559-
session.hasActiveRun ||
560+
!stopAction ||
561+
(stopAction.method === "sessions.reclaim" && session.hasActiveRun) ||
560562
!window.confirm(t("sessionsView.stopCloudWorkerConfirm", { session: session.label }))
561563
) {
562564
return;
563565
}
564566
if (!host.sessionData.isSessionMutationScopeCurrent(scope)) {
565567
return;
566568
}
567-
const agentId = parseAgentSessionKey(session.key)?.agentId ?? scope.selectedAgentId;
568-
if (
569-
!requireSessionMutationAccess(host, scope, {
570-
method: "sessions.reclaim",
571-
requiredScope: "operator.admin",
572-
})
573-
) {
569+
if (!requireSessionMutationAccess(host, scope, stopAction)) {
574570
return;
575571
}
576572
try {
577-
await scope.client.request(
578-
"sessions.reclaim",
579-
{ key: session.key, agentId },
580-
{ timeoutMs: 10 * 60_000 },
581-
);
573+
const agentId = parseAgentSessionKey(session.key)?.agentId ?? scope.selectedAgentId;
574+
const result = await requestCloudWorkerStop(scope.client, stopAction, {
575+
key: session.key,
576+
agentId,
577+
});
578+
if (result && host.sessionData.isSessionMutationScopeCurrent(scope)) {
579+
showToast({
580+
message: t("sessionsView.cloudWorkerStopResult", {
581+
session: session.label,
582+
state: result.worker?.state ?? result.status,
583+
}),
584+
});
585+
}
582586
if (!host.sessionData.isSessionMutationScopeCurrent(scope)) {
583587
return;
584588
}

‎ui/src/components/session-row-badges.ts‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,6 @@ export type SessionPlacementState = NonNullable<GatewaySessionRow["placement"]>[
1111

1212
export { isCloudWorkerPlacementState } from "../../../packages/gateway-protocol/src/schema/session-placement-state.js";
1313

14-
export function isStoppableCloudWorkerPlacement(
15-
placement: GatewaySessionRow["placement"],
16-
): boolean {
17-
return placement?.state === "active";
18-
}
19-
2014
function pullRequestStateLabel(state: SessionCatalogPullRequestSummary["state"]): string {
2115
switch (state) {
2216
case "open":

‎ui/src/components/sidebar-menus-render.ts‎

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@ function sessionMenuActionDisabledReasons(
6969
requiredScope: "operator.write",
7070
});
7171
const deleteRows = batchRows ?? [session];
72+
const cloudWorkerStopReason = session.cloudWorkerStopAction
73+
? reason(session.cloudWorkerStopAction)
74+
: undefined;
7275
const deleteReason = deleteRows
7376
.map((row) =>
7477
reason({
@@ -104,14 +107,7 @@ function sessionMenuActionDisabledReasons(
104107
}),
105108
}
106109
: {}),
107-
...(reason({ method: "sessions.reclaim", requiredScope: "operator.admin" })
108-
? {
109-
"stop-cloud-worker": reason({
110-
method: "sessions.reclaim",
111-
requiredScope: "operator.admin",
112-
}),
113-
}
114-
: {}),
110+
...(cloudWorkerStopReason ? { "stop-cloud-worker": cloudWorkerStopReason } : {}),
115111
}),
116112
};
117113
}
@@ -248,6 +244,14 @@ export function renderSidebarSessionMenuForController(controller: SidebarMenusCo
248244
const sharedCategory = rows.every((row) => (row.category ?? null) === (rows[0]?.category ?? null))
249245
? (rows[0]?.category ?? null)
250246
: null;
247+
const cloudWorkerStopAction = session.cloudWorkerStopAction;
248+
const cloudWorkerStopAllowed = Boolean(
249+
!batchRows &&
250+
cloudWorkerStopAction &&
251+
(cloudWorkerStopAction.method !== "sessions.reclaim" || !session.hasActiveRun) &&
252+
context &&
253+
isGatewayMethodAdvertised(context.gateway.snapshot, cloudWorkerStopAction.method) === true,
254+
);
251255
return keyed(
252256
menu,
253257
html`
@@ -272,13 +276,7 @@ export function renderSidebarSessionMenuForController(controller: SidebarMenusCo
272276
)}
273277
.forkDisabled=${host.sessionData.sessionsLoading || session.modelSelectionLocked}
274278
.archiveAllowed=${archiveAllowed}
275-
.cloudWorkerStopAllowed=${Boolean(
276-
!batchRows &&
277-
session.cloudWorkerActive &&
278-
!session.hasActiveRun &&
279-
context &&
280-
isGatewayMethodAdvertised(context.gateway.snapshot, "sessions.reclaim") === true,
281-
)}
279+
.cloudWorkerStopAllowed=${cloudWorkerStopAllowed}
282280
.groups=${host.knownSessionGroups()}
283281
.canOpenChat=${true}
284282
.work=${batchRows ? null : controller.sessionMenuWork}

‎ui/src/e2e/new-session-page.cloud-startup.e2e.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,9 @@ suite.define(() => {
502502
await expect
503503
.poll(() => page.locator(".new-session-page__message").inputValue())
504504
.toBe(message);
505+
await pollLocatorText(page.locator(".new-session-page__error")).toContain(
506+
"This cloud session's setup was interrupted. Check recent sessions before starting this task again.",
507+
);
505508
await page.locator('.chat-attachment-thumb img[alt="Attachment preview"]').waitFor();
506509
await expect
507510
.poll(() => page.getByRole("button", { name: "Remove attachment" }).isDisabled())

‎ui/src/i18n/locales/en.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -702,9 +702,13 @@ export const en: TranslationMap = {
702702
start: "Start session",
703703
starting: "Starting…",
704704
createFailed: "Couldn't create the session.",
705+
cloudOwnershipLost:
706+
"Another window took over this cloud session. Check recent sessions before starting this task again.",
705707
createOutcomeUnknown:
706708
"The Gateway changed while this session was starting. Check recent sessions before starting this task again.",
707709
cliAgentsGroup: "CLI agents",
710+
cloudSetupInterrupted:
711+
"This cloud session's setup was interrupted. Check recent sessions before starting this task again.",
708712
catalogUnavailable: "This session target is unavailable.",
709713
},
710714
dashboardsPage: {
@@ -888,6 +892,7 @@ export const en: TranslationMap = {
888892
stopCloudWorker: "Stop cloud worker…",
889893
stopCloudWorkerConfirm: 'Stop the cloud worker for "{session}"?',
890894
stopCloudWorkerConfirmAction: "Stop worker",
895+
cloudWorkerStopResult: 'Cloud worker for "{session}" is {state}.',
891896
deleteSessionMenu: "Delete…",
892897
deleteSessionCount: "Delete {count}…",
893898
deleteSessionConfirm: 'Delete "{session}" and its transcript?',

‎ui/src/pages/new-session/cloud-recovery-state.test.ts‎

Lines changed: 61 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,38 @@
11
import { beforeEach, describe, expect, it } from "vitest";
2-
import { PendingCloudRecoveryState } from "./cloud-recovery-state.ts";
3-
import { readCloudSessionRecovery } from "./cloud-recovery.ts";
2+
import {
3+
PendingCloudRecoveryState,
4+
resolveSubmissionOutcomeReason,
5+
} from "./cloud-recovery-state.ts";
6+
import { readCloudSessionRecovery, writeCloudSessionRecovery } from "./cloud-recovery.ts";
47

58
describe("pending cloud recovery state", () => {
69
beforeEach(() => sessionStorage.clear());
710

11+
it.each([
12+
{
13+
name: "a replacement Gateway",
14+
gatewayIdentityChanged: true,
15+
cloudDraftOwned: true,
16+
expected: "gateway-changed",
17+
},
18+
{
19+
name: "a normal local submission",
20+
gatewayIdentityChanged: false,
21+
cloudDraftOwned: false,
22+
expected: "gateway-changed",
23+
},
24+
{
25+
name: "an interrupted cloud draft",
26+
gatewayIdentityChanged: false,
27+
cloudDraftOwned: true,
28+
expected: "cloud-interrupted",
29+
},
30+
])("classifies $name accurately", ({ expected, gatewayIdentityChanged, cloudDraftOwned }) => {
31+
expect(resolveSubmissionOutcomeReason({ gatewayIdentityChanged, cloudDraftOwned })).toBe(
32+
expected,
33+
);
34+
});
35+
836
it("stages an idempotent create before the Gateway request", () => {
937
const pending = new PendingCloudRecoveryState();
1038
const createParams = pending.stageCreate({
@@ -130,4 +158,35 @@ describe("pending cloud recovery state", () => {
130158
expect(captured?.attachments).not.toBe(pending.attachments);
131159
expect(captured?.createParams).not.toBe(pending.createParams);
132160
});
161+
162+
it("neutralizes a stale local owner without clearing newer durable recovery", () => {
163+
const pending = new PendingCloudRecoveryState();
164+
expect(
165+
pending.stageCreate({
166+
agentId: "cloud",
167+
profileId: "aws",
168+
message: "stale task",
169+
gatewayUrl: "ws://gateway.example",
170+
recoveryScope: "principal-a",
171+
createParams: { agentId: "cloud", message: "", worktree: true },
172+
}),
173+
).not.toBeNull();
174+
const staleKey = pending.sessionKey;
175+
const newerRecovery = {
176+
sessionKey: "agent:cloud:newer",
177+
messageId: "message-newer",
178+
message: "newer task",
179+
profileId: "aws",
180+
agentId: "cloud",
181+
gatewayUrl: "ws://gateway.example",
182+
recoveryScope: "principal-a",
183+
phase: "dispatching" as const,
184+
};
185+
expect(writeCloudSessionRecovery(newerRecovery)).toBe(true);
186+
187+
pending.clearFor("ws://gateway.example", "principal-a", staleKey);
188+
189+
expect(pending.sessionKey).toBe("");
190+
expect(readCloudSessionRecovery("ws://gateway.example", "principal-a")).toEqual(newerRecovery);
191+
});
133192
});

0 commit comments

Comments
 (0)