Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions apps/web/src/components/HomeDraftLanding.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { createMemoryHistory } from "@tanstack/react-router";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
import type * as Context from "effect/Context";
import { Atom } from "effect/reactivity";
import { expect, it, vi } from "vite-plus/test";

import { AppRoot } from "~/AppRoot";
import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
import { __setClientSettingsForTests } from "~/hooks/useSettings";
import stylesheet from "~/index.css?inline";
import { getRouter } from "~/router";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import {
ENVIRONMENT_ID,
installFakeEnvironment,
threadWithHistory,
type FakeDriver,
} from "../../test/fakeEnvironment";
import { act, render } from "../../test/render";

const configVisible = Atom.make(false).pipe(Atom.keepAlive);

vi.mock(import("~/state/server"), async (original) => {
const actual = await original();
const { Atom } = await import("effect/reactivity");
return {
...actual,
environmentServerConfigsAtom: Atom.make((get) => {
if (!get(configVisible)) return new Map();
const config = get(actual.environmentServerConfigsAtom).get(ENVIRONMENT_ID);
if (config === undefined) return new Map();
return new Map([
[
ENVIRONMENT_ID,
{
...config,
settings: { ...config.settings, defaultThreadEnvMode: "worktree" as const },
},
],
]);
}),
};
});

vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (original) => {
const [actual, { fakeDriver }, Layer] = await Promise.all([
original<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
import("../../test/fakeEnvironment"),
import("effect/Layer"),
]);
return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
});

function setup() {
appAtomRegistry.set(configVisible, false);
__setClientSettingsForTests({
...DEFAULT_CLIENT_SETTINGS,
onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
});
return installFakeEnvironment([threadWithHistory("home-settings", 1)]);
}

it("stays recoverable while the most recent project's settings are unavailable", async () => {
using _environment = setup();
const router = getRouter(createMemoryHistory({ initialEntries: ["/"] }));
await router.load();
await using screen = await render(
<>
<style>{stylesheet}</style>
<AppRoot router={router} />
</>,
{ router: false },
);

const retry = screen.getByRole("button", { name: "Try again", exact: true });
await expect.element(retry).toBeVisible();
await expect.element(screen.getByText("Environment settings are still loading")).toBeVisible();
expect(router.state.location.pathname).toBe("/");

await retry.click();
await expect.element(retry).toBeVisible();
expect(router.state.location.pathname).toBe("/");

await act(() => appAtomRegistry.set(configVisible, true));
await vi.waitFor(() => expect(router.state.location.pathname).toMatch(/^\/draft\//));
const draftId = DraftId.make(
decodeURIComponent(router.state.location.pathname.split("/").at(-1)!),
);
expect(useComposerDraftStore.getState().getDraftSession(draftId)?.envMode).toBe("worktree");
});
62 changes: 61 additions & 1 deletion apps/web/src/hooks/useHandleNewThread.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const testState = vi.hoisted(() => {
let completeProjectFileRead: (value: null) => void = () => undefined;
let projectFileRead = Promise.resolve<null>(null);
let projectRemoved = false;
let configMissing = false;
let connectedEnvironmentIds = ["environment-primary", "environment-ssh"];
let targetSettings = {
defaultThreadEnvMode: "local" as "local" | "worktree" | null,
Expand Down Expand Up @@ -56,6 +57,13 @@ const testState = vi.hoisted(() => {
};

return {
toast: vi.fn(),
get configMissing() {
return configMissing;
},
setConfigMissing(value: boolean) {
configMissing = value;
},
completeProjectFileRead: (value: null) => completeProjectFileRead(value),
draftStore,
get projectFileRead() {
Expand Down Expand Up @@ -101,6 +109,7 @@ const testState = vi.hoisted(() => {
openDraftRoute = null;
draftsWithUserText = new Set();
projectRemoved = false;
configMissing = false;
connectedEnvironmentIds = ["environment-primary", "environment-ssh"];
targetSettings = {
defaultThreadEnvMode: workspaceDefaults.envMode,
Expand Down Expand Up @@ -132,9 +141,15 @@ const testServerConfigs = () =>
},
},
],
["environment-ssh", { settings: testState.targetSettings }],
...(!testState.configMissing
? [["environment-ssh", { settings: testState.targetSettings }] as const]
: []),
]);

vi.mock("../components/ui/toast", () => ({
toastManager: { add: testState.toast },
}));

vi.mock("../rpc/atomRegistry", () => ({
appAtomRegistry: {
get: (atom: unknown) =>
Expand Down Expand Up @@ -271,6 +286,34 @@ describe.each([
},
],
])("useNewThreadHandler with a %s draft", (_, draft) => {
it("does not guess before settings load and uses them on retry", async () => {
testState.reset(draft, { envMode: "worktree", startFromOrigin: true });
testState.toast.mockClear();
testState.setConfigMissing(true);
const openThread = useNewThreadHandler();
const projectRef = {
environmentId: "environment-ssh",
projectId: "project-remote",
} as never;

await expect(openThread(projectRef)).resolves.toBeNull();
expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled();
expect(testState.draftStore.setDraftThreadContext).not.toHaveBeenCalled();
expect(testState.router.navigate).not.toHaveBeenCalled();
expect(testState.toast).toHaveBeenCalledWith(
expect.objectContaining({ title: "Environment settings are still loading" }),
);

testState.setConfigMissing(false);
await expect(openThread(projectRef)).resolves.not.toBeNull();
expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith(
"remote-project",
projectRef,
draft?.draftId ?? "draft-delayed",
expect.objectContaining({ envMode: "worktree", startFromOrigin: true }),
);
});

it("abandons a delayed draft open when the user navigates elsewhere", async () => {
testState.reset(draft);
const openThread = useNewThreadHandler();
Expand Down Expand Up @@ -349,6 +392,23 @@ describe.each([
});

describe("useNewThreadHandler", () => {
it("keeps an explicit choice while the target settings are unavailable", async () => {
testState.reset(null);
testState.setConfigMissing(true);
await expect(
useNewThreadHandler()(
{ environmentId: "environment-ssh", projectId: "project-remote" } as never,
{ envMode: "worktree" },
),
).resolves.not.toBeNull();
expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith(
"remote-project",
expect.anything(),
"draft-delayed",
expect.objectContaining({ envMode: "worktree" }),
);
});

it("keeps the text of a draft that gained some while it waited", async () => {
testState.reset(null);
const raced = {
Expand Down
23 changes: 20 additions & 3 deletions apps/web/src/hooks/useHandleNewThread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
} from "@t3tools/client-runtime/environment";
import { DEFAULT_SERVER_SETTINGS, type ScopedProjectRef, type ThreadId } from "@t3tools/contracts";
import { type AnyRouter, useRouter } from "@tanstack/react-router";
import { msg } from "gt-react";
import { m } from "~/i18n/messages";
import {
composerDraftHasUserContent,
markPromotedDraftThreadByRef,
Expand All @@ -15,6 +17,7 @@ import {
} from "../composerDraftStore";
import { newDraftId, newThreadId } from "../lib/utils";
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
import { toastManager } from "../components/ui/toast";
import {
deriveLogicalProjectKeyFromSettings,
getProjectOrderKey,
Expand Down Expand Up @@ -108,8 +111,8 @@ export function createNewThreadHandler(router: AnyRouter) {
const projectGroupingSettings = selectProjectGroupingSettings(getClientSettings());
// Read at call time; status pushes replace the config map and would recreate every sidebar handler.
const environmentServerConfigs = appAtomRegistry.get(environmentServerConfigsAtom);
const targetServerSettings =
environmentServerConfigs.get(projectRef.environmentId)?.settings ?? DEFAULT_SERVER_SETTINGS;
const targetServerConfig = environmentServerConfigs.get(projectRef.environmentId);
const targetServerSettings = targetServerConfig?.settings ?? DEFAULT_SERVER_SETTINGS;
const {
getComposerDraft,
getDraftSessionByLogicalProjectKey,
Expand Down Expand Up @@ -197,7 +200,15 @@ export function createNewThreadHandler(router: AnyRouter) {
currentRouteTarget?.kind === "draft" ? currentRouteTarget.draftId : null,
destinationDraftId,
});
const resolveDefaultEnvMode = async (): Promise<DraftThreadEnvMode> => {
const resolveDefaultEnvMode = async (): Promise<DraftThreadEnvMode | null> => {
if (targetServerConfig === undefined) {
toastManager.add({
type: "warning",
title: m(msg("Environment settings are still loading")),
description: m(msg("Wait for this environment to finish connecting, then try again.")),
});
return null;
Comment thread
nateEc marked this conversation as resolved.
Resolved
}
// Environment queries wait for a connection, so reading the project file on an
// offline machine would never settle and the draft would never open.
const consultProjectFile =
Expand Down Expand Up @@ -291,6 +302,9 @@ export function createNewThreadHandler(router: AnyRouter) {
if (abandonedSinceRequest()) {
return resultIfAbandoned();
}
if (defaultEnvMode === null) {
return null;
}
// Concurrent calls may change the draft; stale resets, remaps, or navigation could clobber it.
const routeTargetNow = getCurrentRouteTarget();
const openedMeanwhile =
Expand Down Expand Up @@ -407,6 +421,9 @@ export function createNewThreadHandler(router: AnyRouter) {
if (abandonedSinceRequest()) {
return resultIfAbandoned();
}
if (initialEnvMode === null) {
return null;
}
// Reuse drafts registered while awaiting so their pending navigation cannot lose them.
const racedDraft = getDraftSessionByLogicalProjectKey(logicalProjectKey);
if (
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/i18n/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -2731,6 +2731,8 @@
"8f109e64ea66ebaf": "Der Text konnte nicht in die Zwischenablage kopiert werden.",
"3444fc0e046baae6": "Die Zwischenablage-API ist beim Lesen des Textes nicht verfügbar.",
"ec2160de6dd9c8d3": "Der Text konnte nicht aus der Zwischenablage gelesen werden.",
"d0d666e8667322ca": "Umgebungseinstellungen werden noch geladen",
"aa985f3cefd7c4d2": "Warte, bis die Verbindung zu dieser Umgebung hergestellt ist, und versuche es dann erneut.",
"433bd7a75c28a858": "Das {label}-Repository konnte nicht erstellt werden",
"181a251357eeca66": "{error} Verwende „Repository veröffentlichen“ im Git-Menü, um es erneut zu versuchen.",
"fc6379bdbd00c0a3": "Auf {label} veröffentlicht",
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/i18n/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -2730,6 +2730,8 @@
"8f109e64ea66ebaf": "Failed to copy text to the clipboard.",
"3444fc0e046baae6": "Clipboard API is unavailable while reading text.",
"ec2160de6dd9c8d3": "Failed to read text from the clipboard.",
"d0d666e8667322ca": "Environment settings are still loading",
"aa985f3cefd7c4d2": "Wait for this environment to finish connecting, then try again.",
"433bd7a75c28a858": "Could not create the {label} repository",
"181a251357eeca66": "{error} Use Publish Repository in the Git menu to try again.",
"fc6379bdbd00c0a3": "Published to {label}",
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/i18n/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -2730,6 +2730,8 @@
"8f109e64ea66ebaf": "No se pudo copiar el texto al portapapeles.",
"3444fc0e046baae6": "La API del portapapeles no está disponible al leer texto.",
"ec2160de6dd9c8d3": "No se pudo leer el texto del portapapeles.",
"d0d666e8667322ca": "La configuración del entorno aún se está cargando",
"aa985f3cefd7c4d2": "Espera a que se conecte este entorno y vuelve a intentarlo.",
"433bd7a75c28a858": "No se pudo crear el repositorio de {label}",
"181a251357eeca66": "{error} Usa Publicar repositorio en el menú de Git para volver a intentarlo.",
"fc6379bdbd00c0a3": "Publicado en {label}",
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/i18n/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -2730,6 +2730,8 @@
"8f109e64ea66ebaf": "Impossible de copier le texte dans le presse-papiers.",
"3444fc0e046baae6": "L’API Presse-papiers n’est pas disponible pour lire le texte.",
"ec2160de6dd9c8d3": "Impossible de lire le texte depuis le presse-papiers.",
"d0d666e8667322ca": "Les paramètres de l’environnement sont en cours de chargement",
"aa985f3cefd7c4d2": "Attendez que la connexion à cet environnement soit établie, puis réessayez.",
"433bd7a75c28a858": "Impossible de créer le dépôt {label}",
"181a251357eeca66": "{error} Utilisez Publier le dépôt dans le menu Git pour réessayer.",
"fc6379bdbd00c0a3": "Publié sur {label}",
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/i18n/translations/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -2728,6 +2728,8 @@
"8f109e64ea66ebaf": "テキストをクリップボードにコピーできませんでした。",
"3444fc0e046baae6": "テキストを読み取る際にクリップボード API を利用できませんでした。",
"ec2160de6dd9c8d3": "クリップボードからテキストを読み取れませんでした。",
"d0d666e8667322ca": "環境設定を読み込み中です",
"aa985f3cefd7c4d2": "この環境に接続されたら、もう一度お試しください。",
"433bd7a75c28a858": "{label} のリポジトリを作成できませんでした",
"181a251357eeca66": "{error} Git メニューの [リポジトリを公開] から再試行してください。",
"fc6379bdbd00c0a3": "{label} に公開しました",
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/i18n/translations/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -2729,6 +2729,8 @@
"8f109e64ea66ebaf": "텍스트를 클립보드에 복사하지 못했습니다.",
"3444fc0e046baae6": "텍스트를 읽는 중 클립보드 API를 사용할 수 없습니다.",
"ec2160de6dd9c8d3": "클립보드에서 텍스트를 읽지 못했습니다.",
"d0d666e8667322ca": "환경 설정을 불러오는 중입니다",
"aa985f3cefd7c4d2": "이 환경에 연결되면 다시 시도하세요.",
"433bd7a75c28a858": "{label} 저장소를 만들 수 없습니다",
"181a251357eeca66": "{error} 다시 시도하려면 Git 메뉴에서 저장소 게시를 사용하세요.",
"fc6379bdbd00c0a3": "{label}에 게시됨",
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/i18n/translations/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -2730,6 +2730,8 @@
"8f109e64ea66ebaf": "Falha ao copiar o texto para a área de transferência.",
"3444fc0e046baae6": "A API da área de transferência não está disponível ao ler o texto.",
"ec2160de6dd9c8d3": "Falha ao ler o texto da área de transferência.",
"d0d666e8667322ca": "As configurações do ambiente ainda estão carregando",
"aa985f3cefd7c4d2": "Aguarde até que este ambiente esteja conectado e tente novamente.",
"433bd7a75c28a858": "Não foi possível criar o repositório no {label}",
"181a251357eeca66": "{error} Use Publicar repositório no menu do Git para tentar novamente.",
"fc6379bdbd00c0a3": "Publicado no {label}",
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/i18n/translations/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -2730,6 +2730,8 @@
"8f109e64ea66ebaf": "Не удалось скопировать текст в буфер обмена.",
"3444fc0e046baae6": "API буфера обмена недоступен при чтении текста.",
"ec2160de6dd9c8d3": "Не удалось прочитать текст из буфера обмена.",
"d0d666e8667322ca": "Настройки окружения ещё загружаются",
"aa985f3cefd7c4d2": "Дождитесь подключения к этому окружению и повторите попытку.",
"433bd7a75c28a858": "Не удалось создать репозиторий {label}",
"181a251357eeca66": "{error} Повторите через «Опубликовать репозиторий» в меню Git.",
"fc6379bdbd00c0a3": "Опубликовано на {label}",
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/i18n/translations/sv.json
Original file line number Diff line number Diff line change
Expand Up @@ -2730,6 +2730,8 @@
"8f109e64ea66ebaf": "Kunde inte kopiera text till urklipp.",
"3444fc0e046baae6": "Urklipps-API:t är inte tillgängligt vid läsning av text.",
"ec2160de6dd9c8d3": "Kunde inte läsa text från urklipp.",
"d0d666e8667322ca": "Miljöinställningarna läses fortfarande in",
"aa985f3cefd7c4d2": "Vänta tills den här miljön är ansluten och försök sedan igen.",
"433bd7a75c28a858": "Kunde inte skapa {label}-repot",
"181a251357eeca66": "{error} Använd Publicera repo i Git-menyn för att försöka igen.",
"fc6379bdbd00c0a3": "Publicerat till {label}",
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/i18n/translations/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -2734,6 +2734,8 @@
"8f109e64ea66ebaf": "无法将文本复制到剪贴板。",
"3444fc0e046baae6": "读取文本时剪贴板 API 不可用。",
"ec2160de6dd9c8d3": "无法从剪贴板读取文本。",
"d0d666e8667322ca": "环境设置仍在加载",
"aa985f3cefd7c4d2": "请等待此环境连接成功后重试。",
"433bd7a75c28a858": "无法创建 {label} 仓库",
"181a251357eeca66": "{error} 请使用 Git 菜单中的“发布仓库”重试。",
"fc6379bdbd00c0a3": "已发布到 {label}",
Expand Down
Loading
Loading