@devries-cameron20 / t3code Mirror · read-only / commits / 7f7bf263a8
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 02:00 UTC

fix(web): recover ACP settings when projects change (#32409)

Co-authored-by: GPT 6.1 Sol <codex@openai.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Wout Stiens committed Nov 7, 2026 at 11:41 UTC 7f7bf263a8367418fd1eafc4e55b58f20ddb8f6d
2 files changed +302 -20
apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx
+227 -6
@@ -7,6 +7,7 @@ import {
7 type ServerProvider,
8 type AcpRegistryConfigurableProvider,
9 } from "@t3tools/contracts";
10 +import type { ComponentProps } from "react";
11 import { expect, it, vi } from "vite-plus/test";
12 import { userEvent } from "vite-plus/test/browser";
13
@@ -79,16 +80,28 @@ const provider = {
80 skills: [],
81 } satisfies ServerProvider;
82
82 -async function renderSection(readOnly = false) {
83 - const screen = await render(
83 +const project = { id: projectId, title: "Antigravity", workspaceRoot: session.cwd };
84 +const replacement = {
85 + id: ProjectId.make("replacement"),
86 + title: "Replacement",
87 + workspaceRoot: "/replacement",
88 +};
89 +type Projects = ComponentProps<typeof AcpSessionManagementSection>["projects"];
90 +
91 +async function renderSection(options: { canList?: boolean; projects?: Projects } = {}) {
92 + const section = (projects = options.projects ?? [project]) => (
93 <AcpSessionManagementSection
94 environmentId={environmentId}
95 instanceId={instanceId}
87 - provider={provider}
88 - projects={[{ id: projectId, title: "Antigravity", workspaceRoot: session.cwd }]}
89 - readOnly={readOnly}
90 - />,
96 + provider={{
97 + ...provider,
98 + nativeSessions: { ...provider.nativeSessions, canList: options.canList ?? true },
99 + }}
100 + projects={projects}
101 + readOnly={false}
102 + />
103 );
104 + const screen = await render(section());
105 const button = (label: string) => {
106 const found = [...screen.container.querySelectorAll("button")].find(
107 (element) => element.textContent === label,
@@ -99,6 +112,7 @@ async function renderSection(readOnly = false) {
112 return Object.assign(screen, {
113 button,
114 click: (label: string) => act(async () => button(label).click()),
115 + setProjects: (projects: Projects) => screen.rerender(section(projects)),
116 });
117 }
118
@@ -224,3 +238,210 @@ it.each(["Save", "Disable"])("keeps other provider edits through a %s refetch",
238 expect(input("other base URL").value).toBe("https://api.example.test/v1");
239 expect(input("other write-only headers JSON").value).toBe("");
240 });
241 +
242 +it.each([true, false])(
243 + "enables project actions after projects arrive (sessions: %s)",
244 + async (canList) => {
245 + setup();
246 + await using screen = await renderSection({ canList, projects: [] });
247 + await screen.setProjects([project]);
248 + const action = screen.getByRole("button", {
249 + name: canList ? "List sessions" : "List providers",
250 + });
251 + await expect.element(action).toBeEnabled();
252 + if (!canList) {
253 + await expect.element(screen.getByRole("combobox")).not.toBeInTheDocument();
254 + }
255 + await action.click();
256 + if (canList) {
257 + await expect.element(screen.getByText(session.title)).toBeVisible();
258 + expect(commands.list).toHaveBeenCalledWith({
259 + environmentId,
260 + input: { instanceId, projectId },
261 + });
262 + } else {
263 + await expect
264 + .element(screen.getByRole("textbox", { name: "google base URL" }))
265 + .toHaveValue("https://api.example.test/v1");
266 + expect(commands.listProviders).toHaveBeenCalledWith({
267 + environmentId,
268 + input: { instanceId, projectId },
269 + });
270 + }
271 + },
272 +);
273 +
274 +it.each([true, false])(
275 + "preserves a valid selection and clears a removed project's data (sessions: %s)",
276 + async (canList) => {
277 + setup();
278 + const second = { id: ProjectId.make("second"), title: "Second", workspaceRoot: "/second" };
279 + commands.list.mockResolvedValue({
280 + _tag: "Success",
281 + value: { sessions: [session], nextCursor: "page-2" },
282 + });
283 + await using screen = await renderSection({ canList, projects: [project, second] });
284 + await screen.getByRole("combobox").click();
285 + if (canList) await userEvent.keyboard("{ArrowDown}{Enter}");
286 + else await screen.getByRole("option", { name: "Second", exact: true }).click();
287 + await expect
288 + .element(
289 + screen.getByRole("combobox", {
290 + name: canList ? "Project for ACP sessions" : "Project for ACP providers",
291 + }),
292 + )
293 + .toHaveFocus();
294 + if (canList) await screen.getByRole("button", { name: "List sessions" }).click();
295 + await screen.getByRole("button", { name: "List providers" }).click();
296 + await userEvent.fill(
297 + screen.getByRole("textbox", { name: "google base URL" }),
298 + "https://draft.test",
299 + );
300 + await userEvent.fill(
301 + screen.getByLabelText("google write-only headers JSON"),
302 + '{"Secret":"draft"}',
303 + );
304 +
305 + await screen.setProjects([project, replacement, second]);
306 + await expect
307 + .element(
308 + screen.getByRole("combobox", {
309 + name: canList ? "Project for ACP sessions" : "Project for ACP providers",
310 + }),
311 + )
312 + .toHaveTextContent("Second");
313 + await expect
314 + .element(screen.getByRole("textbox", { name: "google base URL" }))
315 + .toHaveValue("https://draft.test");
316 + await screen.getByRole("button", { name: "Save", exact: true }).click();
317 + expect(commands.setProvider).toHaveBeenLastCalledWith({
318 + environmentId,
319 + input: {
320 + instanceId,
321 + projectId: second.id,
322 + providerId: "google",
323 + apiType: "openai",
324 + baseUrl: "https://draft.test",
325 + headers: { Secret: "draft" },
326 + },
327 + });
328 +
329 + await screen.setProjects([project]);
330 + await expect.element(screen.getByText(session.title)).not.toBeInTheDocument();
331 + await expect.element(screen.getByRole("button", { name: "Load more" })).not.toBeInTheDocument();
332 + await expect
333 + .element(screen.getByRole("textbox", { name: "google base URL" }))
334 + .not.toBeInTheDocument();
335 + await screen.getByRole("button", { name: "List providers" }).click();
336 + expect(commands.listProviders).toHaveBeenLastCalledWith({
337 + environmentId,
338 + input: { instanceId, projectId },
339 + });
340 + await expect.element(screen.getByLabelText("google write-only headers JSON")).toHaveValue("");
341 + await expect
342 + .element(screen.getByRole("textbox", { name: "google base URL" }))
343 + .toHaveValue("https://api.example.test/v1");
344 +
345 + await screen.setProjects([second, project]);
346 + await expect
347 + .element(
348 + screen.getByRole("combobox", {
349 + name: canList ? "Project for ACP sessions" : "Project for ACP providers",
350 + }),
351 + )
352 + .toHaveTextContent("Antigravity");
353 + await expect
354 + .element(screen.getByRole("textbox", { name: "google base URL" }))
355 + .toHaveValue("https://api.example.test/v1");
356 +
357 + await screen.setProjects([]);
358 + await expect.element(screen.getByRole("button", { name: "List providers" })).toBeDisabled();
359 + await expect
360 + .element(screen.getByRole("textbox", { name: "google base URL" }))
361 + .not.toBeInTheDocument();
362 + },
363 +);
364 +
365 +it("ignores a late listing after project replacement", async () => {
366 + setup();
367 + let finish!: (value: unknown) => void;
368 + commands.list.mockReturnValueOnce(
369 + new Promise((resolve) => {
370 + finish = resolve;
371 + }),
372 + );
373 + await using screen = await renderSection();
374 + await screen.click("List sessions");
375 + await screen.setProjects([replacement]);
376 + await act(async () =>
377 + finish({ _tag: "Success", value: { sessions: [session], nextCursor: "old-page" } }),
378 + );
379 + await expect.element(screen.getByText(session.title)).not.toBeInTheDocument();
380 + await expect.element(screen.getByRole("button", { name: "Load more" })).not.toBeInTheDocument();
381 + await expect.element(screen.getByRole("button", { name: "List sessions" })).toBeEnabled();
382 +});
383 +
384 +it.each(["Save", "Disable"])("does not refetch the old project after a late %s", async (action) => {
385 + setup();
386 + const command = action === "Save" ? commands.setProvider : commands.disableProvider;
387 + let finish!: () => void;
388 + command.mockReturnValueOnce(
389 + new Promise<void>((resolve) => {
390 + finish = resolve;
391 + }).then(() => ({
392 + _tag: "Success",
393 + value: action === "Save" ? { configured: true } : { disabled: true },
394 + })),
395 + );
396 + await using screen = await renderSection();
397 + await screen.click("List providers");
398 + await screen.click(action);
399 + expect(command).toHaveBeenCalledOnce();
400 + await screen.setProjects([replacement]);
401 + await act(async () => finish());
402 + expect(commands.listProviders).toHaveBeenCalledOnce();
403 + await expect.element(screen.getByRole("button", { name: "List providers" })).toBeEnabled();
404 +});
405 +
406 +it.each(["Delete", "Disable"])(
407 + "does not act on a replaced project after confirming %s",
408 + async (action) => {
409 + setup();
410 + let finish!: (confirmed: boolean) => void;
411 + dialogs.confirm.mockReturnValueOnce(
412 + new Promise<boolean>((resolve) => {
413 + finish = resolve;
414 + }),
415 + );
416 + await using screen = await renderSection();
417 + await screen.click(action === "Delete" ? "List sessions" : "List providers");
418 + await screen.click(action);
419 + await screen.setProjects([replacement]);
420 + await act(async () => finish(true));
421 + expect(action === "Delete" ? commands.delete : commands.disableProvider).not.toHaveBeenCalled();
422 + },
423 +);
424 +
425 +it("keeps logout pending across project replacement and clears replacement sessions", async () => {
426 + setup();
427 + let finish!: () => void;
428 + commands.logout.mockReturnValueOnce(
429 + new Promise<void>((resolve) => {
430 + finish = resolve;
431 + }).then(() => ({
432 + _tag: "Success",
433 + value: { loggedOut: true },
434 + })),
435 + );
436 + await using screen = await renderSection();
437 + await screen.click("Log out");
438 + await screen.setProjects([replacement]);
439 + await screen.click("List sessions");
440 + await expect.element(screen.getByText(session.title)).toBeVisible();
441 + await expect.element(screen.getByRole("button", { name: "Logging out" })).toBeDisabled();
442 + await screen.click("Logging out");
443 + expect(commands.logout).toHaveBeenCalledOnce();
444 + await act(async () => finish());
445 + await expect.element(screen.getByText(session.title)).not.toBeInTheDocument();
446 + await expect.element(screen.getByRole("button", { name: "Log out", exact: true })).toBeEnabled();
447 +});
apps/web/src/components/settings/AcpSessionManagementSection.tsx
+75 -14
@@ -17,7 +17,7 @@ import {
17 squashAtomCommandFailure,
18 type AtomCommandResult,
19 } from "@t3tools/client-runtime/state/runtime";
20 -import { useState } from "react";
20 +import { useLayoutEffect, useRef, useState } from "react";
21
22 import { ensureLocalApi } from "../../localApi";
23 import { serverEnvironment } from "../../state/server";
@@ -70,16 +70,49 @@ function parseProviderHeaders(
70 return { ok: true, headers: parsed as Record<string, string> };
71 }
72
73 -export function AcpSessionManagementSection(props: {
73 +interface AcpSessionManagementProps {
74 readonly environmentId: EnvironmentId;
75 readonly instanceId: ProviderInstanceId;
76 readonly provider: ServerProvider;
77 readonly projects: ReadonlyArray<AcpSessionProject>;
78 readonly readOnly: boolean;
79 -}) {
79 +}
80 +
81 +export function AcpSessionManagementSection(props: AcpSessionManagementProps) {
82 + const [selectedProjectId, setSelectedProjectId] = useState<ProjectId | null>(null);
83 + const projectId =
84 + props.projects.find((project) => project.id === selectedProjectId)?.id ??
85 + props.projects[0]?.id ??
86 + null;
87 + if (selectedProjectId !== projectId) setSelectedProjectId(projectId);
88 +
89 + return (
90 + <InstanceSessionManagement
91 + key={JSON.stringify([props.environmentId, props.instanceId])}
92 + {...props}
93 + projectId={projectId}
94 + onProjectChange={setSelectedProjectId}
95 + />
96 + );
97 +}
98 +
99 +function InstanceSessionManagement(
100 + props: AcpSessionManagementProps & {
101 + readonly projectId: ProjectId | null;
102 + readonly onProjectChange: (projectId: ProjectId) => void;
103 + },
104 +) {
105 const canOperate = useEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope);
106 const canRead = useEnvironmentScope(props.environmentId, AuthOrchestrationReadScope);
82 - const [projectId, setProjectId] = useState<ProjectId | null>(props.projects[0]?.id ?? null);
107 + const { projectId } = props;
108 + const projectGeneration = useRef(0);
109 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Late continuations must not act on a replaced project scope.
110 + useLayoutEffect(() => {
111 + return () => {
112 + projectGeneration.current += 1;
113 + };
114 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retiring a project invalidates its pending operations even when the instance stays mounted.
115 + }, [projectId]);
116 const [sessions, setSessions] = useState<ReadonlyArray<AcpRegistrySession>>([]);
117 const [nextCursor, setNextCursor] = useState<string | null>(null);
118 const [loading, setLoading] = useState(false);
@@ -92,6 +125,19 @@ export function AcpSessionManagementSection(props: {
125 const [providerDrafts, setProviderDrafts] = useState<
126 Readonly<Record<string, { apiType: string; baseUrl: string; headers: string }>>
127 >({});
128 + const [previousProjectId, setPreviousProjectId] = useState(projectId);
129 + if (previousProjectId !== projectId) {
130 + setPreviousProjectId(projectId);
131 + setSessions([]);
132 + setNextCursor(null);
133 + setLoading(false);
134 + setImportingSessionId(null);
135 + setDeletingSessionId(null);
136 + setProviders([]);
137 + setLoadingProviders(false);
138 + setSavingProviderId(null);
139 + setProviderDrafts({});
140 + }
141 const listSessions = useAtomCommand(serverEnvironment.listAcpRegistrySessions, {
142 reportFailure: false,
143 });
@@ -129,6 +175,7 @@ export function AcpSessionManagementSection(props: {
175 if (!canList && !canLogout && !canConfigureProviders) return null;
176
177 const loadSessions = async (cursor?: string) => {
178 + const generation = projectGeneration.current;
179 if (projectId === null || loading) return;
180 setLoading(true);
181 const result = await listSessions({
@@ -139,6 +186,7 @@ export function AcpSessionManagementSection(props: {
186 ...(cursor === undefined ? {} : { cursor }),
187 },
188 });
189 + if (generation !== projectGeneration.current) return;
190 setLoading(false);
191 if (result._tag === "Success") {
192 setSessions((current) =>
@@ -151,6 +199,7 @@ export function AcpSessionManagementSection(props: {
199 };
200
201 const importNativeSession = async (session: AcpRegistrySession) => {
202 + const generation = projectGeneration.current;
203 if (
204 !readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope) ||
205 projectId === null ||
@@ -168,6 +217,7 @@ export function AcpSessionManagementSection(props: {
217 updatedAt: session.updatedAt,
218 },
219 });
220 + if (generation !== projectGeneration.current) return;
221 setImportingSessionId(null);
222 if (result._tag === "Success") {
223 setSessions((current) =>
@@ -187,19 +237,25 @@ export function AcpSessionManagementSection(props: {
237 };
238
239 const deleteNativeSession = async (session: AcpRegistrySession) => {
240 + const generation = projectGeneration.current;
241 if (projectId === null || deletingSessionId !== null || session.importedThreadId !== null)
242 return;
243 const confirmed = await ensureLocalApi().dialogs.confirm(
244 `Permanently delete native ACP session "${session.title ?? session.sessionId}"?`,
245 { variant: "destructive" },
246 );
196 - if (!confirmed || !readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope))
247 + if (
248 + generation !== projectGeneration.current ||
249 + !confirmed ||
250 + !readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope)
251 + )
252 return;
253 setDeletingSessionId(session.sessionId);
254 const result = await deleteSession({
255 environmentId: props.environmentId,
256 input: { instanceId: props.instanceId, projectId, sessionId: session.sessionId },
257 });
258 + if (generation !== projectGeneration.current) return;
259 setDeletingSessionId(null);
260 if (result._tag === "Success") {
261 setSessions((current) =>
@@ -212,12 +268,14 @@ export function AcpSessionManagementSection(props: {
268 };
269
270 const loadProviders = async (resetProviderId?: string) => {
271 + const generation = projectGeneration.current;
272 if (projectId === null || loadingProviders) return;
273 setLoadingProviders(true);
274 const result = await listProviders({
275 environmentId: props.environmentId,
276 input: { instanceId: props.instanceId, projectId },
277 });
278 + if (generation !== projectGeneration.current) return;
279 setLoadingProviders(false);
280 if (result._tag === "Success") {
281 setProviders(result.value.providers);
@@ -241,6 +299,7 @@ export function AcpSessionManagementSection(props: {
299 };
300
301 const saveProvider = async (provider: AcpRegistryConfigurableProvider) => {
302 + const generation = projectGeneration.current;
303 if (
304 !readEnvironmentScope(props.environmentId, AuthProvidersManageScope) ||
305 projectId === null ||
@@ -272,6 +331,7 @@ export function AcpSessionManagementSection(props: {
331 ...(headers === undefined ? {} : { headers }),
332 },
333 });
334 + if (generation !== projectGeneration.current) return;
335 setSavingProviderId(null);
336 if (result._tag === "Success") {
337 toastManager.add({ type: "success", title: "ACP provider configured" });
@@ -282,18 +342,25 @@ export function AcpSessionManagementSection(props: {
342 };
343
344 const disableConfiguredProvider = async (provider: AcpRegistryConfigurableProvider) => {
345 + const generation = projectGeneration.current;
346 if (projectId === null || savingProviderId !== null || loadingProviders || provider.required)
347 return;
348 const confirmed = await ensureLocalApi().dialogs.confirm(
349 `Disable ACP provider "${provider.providerId}"?`,
350 { variant: "destructive" },
351 );
291 - if (!confirmed || !readEnvironmentScope(props.environmentId, AuthProvidersManageScope)) return;
352 + if (
353 + generation !== projectGeneration.current ||
354 + !confirmed ||
355 + !readEnvironmentScope(props.environmentId, AuthProvidersManageScope)
356 + )
357 + return;
358 setSavingProviderId(provider.providerId);
359 const result = await disableProvider({
360 environmentId: props.environmentId,
361 input: { instanceId: props.instanceId, projectId, providerId: provider.providerId },
362 });
363 + if (generation !== projectGeneration.current) return;
364 setSavingProviderId(null);
365 if (result._tag === "Success") {
366 toastManager.add({ type: "success", title: "ACP provider disabled" });
@@ -350,11 +417,7 @@ export function AcpSessionManagementSection(props: {
417 disabled={!canRead || projectOperationPending}
418 onValueChange={(value) => {
419 if (value === null) return;
353 - setProjectId(value as ProjectId);
354 - setSessions([]);
355 - setNextCursor(null);
356 - setProviders([]);
357 - setProviderDrafts({});
420 + props.onProjectChange(value as ProjectId);
421 }}
422 >
423 <SelectTrigger aria-label="Project for ACP sessions" className="w-40" size="sm">
@@ -485,9 +548,7 @@ export function AcpSessionManagementSection(props: {
548 disabled={!canRead || projectOperationPending}
549 onValueChange={(value) => {
550 if (value === null) return;
488 - setProjectId(value as ProjectId);
489 - setProviders([]);
490 - setProviderDrafts({});
551 + props.onProjectChange(value as ProjectId);
552 }}
553 >
554 <SelectTrigger aria-label="Project for ACP providers" className="min-w-48" size="xs">