Prepare datamodel for multi-environment (#1765)

Co-authored-by: justsomelegs <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-04-09 02:05:20 +00:00
1 parent 72b7f90c50
commit b96308fc5a
121 files changed
+10195 -4958

No files matched your search

+81 -42
View File
@@ -1,5 +1,6 @@
import { DEFAULT_RUNTIME_MODE, type ProjectId, ThreadId } from "@t3tools/contracts";
import { useNavigate, useParams } from "@tanstack/react-router";
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime";
import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef } from "@t3tools/contracts";
import { useParams, useRouter } from "@tanstack/react-router";
import { useCallback, useMemo } from "react";
import { useShallow } from "zustand/react/shallow";
import {
@@ -7,37 +8,49 @@ import {
type DraftThreadState,
useComposerDraftStore,
} from "../composerDraftStore";
import { newThreadId } from "../lib/utils";
import { newDraftId, newThreadId } from "../lib/utils";
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
import { useStore } from "../store";
import { createThreadSelector } from "../storeSelectors";
import { deriveLogicalProjectKey } from "../logicalProject";
import { selectProjectsAcrossEnvironments, useStore } from "../store";
import { createThreadSelectorByRef } from "../storeSelectors";
import { resolveThreadRouteTarget } from "../threadRoutes";
import { useUiStateStore } from "../uiStateStore";
export function useHandleNewThread() {
const projectIds = useStore(useShallow((store) => store.projectIds));
const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
const projectOrder = useUiStateStore((store) => store.projectOrder);
const navigate = useNavigate();
const routeThreadId = useParams({
const router = useRouter();
const routeTarget = useParams({
strict: false,
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
select: (params) => resolveThreadRouteTarget(params),
});
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
const activeThread = useStore(
useMemo(() => createThreadSelector(routeThreadId), [routeThreadId]),
useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]),
);
const activeDraftThread = useComposerDraftStore((store) =>
routeThreadId ? (store.draftThreadsByThreadId[routeThreadId] ?? null) : null,
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
const activeDraftThread = useComposerDraftStore(() =>
routeTarget
? routeTarget.kind === "server"
? getDraftThread(routeTarget.threadRef)
: useComposerDraftStore.getState().getDraftSession(routeTarget.draftId)
: null,
);
const orderedProjects = useMemo(() => {
return orderItemsByPreferredIds({
items: projectIds,
items: projects,
preferredIds: projectOrder,
getId: (projectId) => projectId,
getId: (project) => scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
});
}, [projectIds, projectOrder]);
}, [projectOrder, projects]);
const getCurrentRouteTarget = useCallback(() => {
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
return resolveThreadRouteTarget(currentRouteParams);
}, [router]);
const handleNewThread = useCallback(
(
projectId: ProjectId,
projectRef: ScopedProjectRef,
options?: {
branch?: string | null;
worktreePath?: string | null;
@@ -45,84 +58,110 @@ export function useHandleNewThread() {
},
): Promise<void> => {
const {
clearProjectDraftThreadId,
getDraftSessionByLogicalProjectKey,
getDraftSession,
getDraftThread,
getDraftThreadByProjectId,
applyStickyState,
setDraftThreadContext,
setProjectDraftThreadId,
setLogicalProjectDraftThreadId,
} = useComposerDraftStore.getState();
const currentRouteTarget = getCurrentRouteTarget();
const project = projects.find(
(candidate) =>
candidate.id === projectRef.projectId &&
candidate.environmentId === projectRef.environmentId,
);
const logicalProjectKey = project
? deriveLogicalProjectKey(project)
: scopedProjectKey(projectRef);
const hasBranchOption = options?.branch !== undefined;
const hasWorktreePathOption = options?.worktreePath !== undefined;
const hasEnvModeOption = options?.envMode !== undefined;
const storedDraftThread = getDraftThreadByProjectId(projectId);
const latestActiveDraftThread: DraftThreadState | null = routeThreadId
? getDraftThread(routeThreadId)
const storedDraftThread = getDraftSessionByLogicalProjectKey(logicalProjectKey);
const latestActiveDraftThread: DraftThreadState | null = currentRouteTarget
? currentRouteTarget.kind === "server"
? getDraftThread(currentRouteTarget.threadRef)
: getDraftSession(currentRouteTarget.draftId)
: null;
if (storedDraftThread) {
return (async () => {
if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
setDraftThreadContext(storedDraftThread.threadId, {
setDraftThreadContext(storedDraftThread.draftId, {
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
});
}
setProjectDraftThreadId(projectId, storedDraftThread.threadId);
if (routeThreadId === storedDraftThread.threadId) {
setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, storedDraftThread.draftId, {
threadId: storedDraftThread.threadId,
});
if (
currentRouteTarget?.kind === "draft" &&
currentRouteTarget.draftId === storedDraftThread.draftId
) {
return;
}
await navigate({
to: "/$threadId",
params: { threadId: storedDraftThread.threadId },
await router.navigate({
to: "/draft/$draftId",
params: { draftId: storedDraftThread.draftId },
});
})();
}
clearProjectDraftThreadId(projectId);
if (
latestActiveDraftThread &&
routeThreadId &&
latestActiveDraftThread.projectId === projectId
currentRouteTarget?.kind === "draft" &&
latestActiveDraftThread.logicalProjectKey === logicalProjectKey
) {
if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
setDraftThreadContext(routeThreadId, {
setDraftThreadContext(currentRouteTarget.draftId, {
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
});
}
setProjectDraftThreadId(projectId, routeThreadId);
setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, currentRouteTarget.draftId, {
threadId: latestActiveDraftThread.threadId,
createdAt: latestActiveDraftThread.createdAt,
runtimeMode: latestActiveDraftThread.runtimeMode,
interactionMode: latestActiveDraftThread.interactionMode,
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
});
return Promise.resolve();
}
const draftId = newDraftId();
const threadId = newThreadId();
const createdAt = new Date().toISOString();
return (async () => {
setProjectDraftThreadId(projectId, threadId, {
setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
threadId,
createdAt,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
envMode: options?.envMode ?? "local",
runtimeMode: DEFAULT_RUNTIME_MODE,
});
applyStickyState(threadId);
applyStickyState(draftId);
await navigate({
to: "/$threadId",
params: { threadId },
await router.navigate({
to: "/draft/$draftId",
params: { draftId },
});
})();
},
[navigate, routeThreadId],
[getCurrentRouteTarget, router, projects],
);
return {
activeDraftThread,
activeThread,
defaultProjectId: orderedProjects[0] ?? null,
defaultProjectRef: orderedProjects[0]
? scopeProjectRef(orderedProjects[0].environmentId, orderedProjects[0].id)
: null,
handleNewThread,
routeThreadId,
routeThreadRef,
};
}
+4 -6
View File
@@ -26,7 +26,7 @@ import {
TimestampFormat,
UnifiedSettings,
} from "@t3tools/contracts/settings";
import { ensureNativeApi } from "~/nativeApi";
import { ensureLocalApi } from "~/localApi";
import { useLocalStorage } from "./useLocalStorage";
import { normalizeCustomModelSlugs } from "~/modelSelection";
import { Predicate, Schema, Struct } from "effect";
@@ -67,9 +67,7 @@ function splitPatch(patch: Partial<UnifiedSettings>): {
* only re-render when the slice they care about changes.
*/
export function useSettings<T extends UnifiedSettings = UnifiedSettings>(
selector?: (s: UnifiedSettings) => T,
): T {
export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings) => T): T {
const serverSettings = useServerSettings();
const [clientSettings] = useLocalStorage(
CLIENT_SETTINGS_STORAGE_KEY,
@@ -111,7 +109,7 @@ export function useUpdateSettings() {
applySettingsUpdated(deepMerge(currentServerConfig.settings, serverPatch));
}
// Fire-and-forget RPC — push will reconcile on success
void ensureNativeApi().server.updateSettings(serverPatch);
void ensureLocalApi().server.updateSettings(serverPatch);
}
if (Object.keys(clientPatch).length > 0) {
@@ -239,7 +237,7 @@ export function migrateLocalSettingsToServer(): void {
// Migrate server-relevant keys via RPC
const serverPatch = buildLegacyServerSettingsMigrationPatch(old);
if (Object.keys(serverPatch).length > 0) {
const api = ensureNativeApi();
const api = ensureLocalApi();
void api.server.updateSettings(serverPatch);
}
+128 -64
View File
@@ -1,42 +1,63 @@
import { ThreadId } from "@t3tools/contracts";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useParams } from "@tanstack/react-router";
import { parseScopedThreadKey, scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
import { type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter } from "@tanstack/react-router";
import { useCallback } from "react";
import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "./useHandleNewThread";
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { ensureEnvironmentApi, readEnvironmentApi } from "../environmentApi";
import { invalidateGitQueries } from "../lib/gitReactQuery";
import { newCommandId } from "../lib/utils";
import { readNativeApi } from "../nativeApi";
import { selectProjectById, selectThreadById, selectThreads, useStore } from "../store";
import { readLocalApi } from "../localApi";
import {
selectProjectByRef,
selectThreadByRef,
selectThreadsForEnvironment,
useStore,
} from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { toastManager } from "../components/ui/toast";
import { useSettings } from "./useSettings";
export function useThreadActions() {
const appSettings = useSettings();
const sidebarThreadSortOrder = useSettings((settings) => settings.sidebarThreadSortOrder);
const confirmThreadDelete = useSettings((settings) => settings.confirmThreadDelete);
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
const clearProjectDraftThreadById = useComposerDraftStore(
(store) => store.clearProjectDraftThreadById,
);
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
const routeThreadId = useParams({
strict: false,
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
});
const navigate = useNavigate();
const router = useRouter();
const { handleNewThread } = useHandleNewThread();
const queryClient = useQueryClient();
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
const resolveThreadTarget = useCallback((target: ScopedThreadRef) => {
const state = useStore.getState();
const thread = selectThreadByRef(state, target);
if (!thread) {
return null;
}
return {
thread,
threadRef: target,
};
}, []);
const getCurrentRouteThreadRef = useCallback(() => {
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
return resolveThreadRouteRef(currentRouteParams);
}, [router]);
const archiveThread = useCallback(
async (threadId: ThreadId) => {
const api = readNativeApi();
async (target: ScopedThreadRef) => {
const api = readEnvironmentApi(target.environmentId);
if (!api) return;
const thread = selectThreadById(threadId)(useStore.getState());
if (!thread) return;
const resolved = resolveThreadTarget(target);
if (!resolved) return;
const { thread, threadRef } = resolved;
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
throw new Error("Cannot archive a running thread.");
}
@@ -44,48 +65,69 @@ export function useThreadActions() {
await api.orchestration.dispatchCommand({
type: "thread.archive",
commandId: newCommandId(),
threadId,
threadId: threadRef.threadId,
});
const currentRouteThreadRef = getCurrentRouteThreadRef();
if (routeThreadId === threadId) {
await handleNewThread(thread.projectId);
if (
currentRouteThreadRef?.threadId === threadRef.threadId &&
currentRouteThreadRef.environmentId === threadRef.environmentId
) {
await handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId));
}
},
[handleNewThread, routeThreadId],
[getCurrentRouteThreadRef, handleNewThread, resolveThreadTarget],
);
const unarchiveThread = useCallback(async (threadId: ThreadId) => {
const api = readNativeApi();
const unarchiveThread = useCallback(async (target: ScopedThreadRef) => {
const api = readEnvironmentApi(target.environmentId);
if (!api) return;
await api.orchestration.dispatchCommand({
type: "thread.unarchive",
commandId: newCommandId(),
threadId,
threadId: target.threadId,
});
}, []);
const deleteThread = useCallback(
async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {}) => {
const api = readNativeApi();
async (target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet<string> } = {}) => {
const api = readEnvironmentApi(target.environmentId);
if (!api) return;
const resolved = resolveThreadTarget(target);
if (!resolved) return;
const { thread, threadRef } = resolved;
const state = useStore.getState();
const threads = selectThreads(state);
const thread = selectThreadById(threadId)(state);
if (!thread) return;
const threadProject = selectProjectById(thread.projectId)(state);
const deletedIds = opts.deletedThreadIds;
const threads = selectThreadsForEnvironment(state, threadRef.environmentId);
const threadProject = selectProjectByRef(state, {
environmentId: threadRef.environmentId,
projectId: thread.projectId,
});
const deletedIds =
opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
? new Set<ThreadId>(
[...opts.deletedThreadKeys].flatMap((threadKey) => {
const ref = parseScopedThreadKey(threadKey);
return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
}),
)
: undefined;
const survivingThreads =
deletedIds && deletedIds.size > 0
? threads.filter((entry) => entry.id === threadId || !deletedIds.has(entry.id))
? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
: threads;
const orphanedWorktreePath = getOrphanedWorktreePathForThread(survivingThreads, threadId);
const orphanedWorktreePath = getOrphanedWorktreePathForThread(
survivingThreads,
threadRef.threadId,
);
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
const localApi = readLocalApi();
const shouldDeleteWorktree =
canDeleteWorktree &&
(await api.dialogs.confirm(
localApi &&
(await localApi.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
@@ -99,44 +141,60 @@ export function useThreadActions() {
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId,
threadId: threadRef.threadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
}
try {
await api.terminal.close({ threadId, deleteHistory: true });
await api.terminal.close({ threadId: threadRef.threadId, deleteHistory: true });
} catch {
// Terminal may already be closed.
}
const deletedThreadIds = opts.deletedThreadIds ?? new Set<ThreadId>();
const shouldNavigateToFallback = routeThreadId === threadId;
const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
const currentRouteThreadRef = getCurrentRouteThreadRef();
const shouldNavigateToFallback =
currentRouteThreadRef?.threadId === threadRef.threadId &&
currentRouteThreadRef.environmentId === threadRef.environmentId;
const fallbackThreadId = getFallbackThreadIdAfterDelete({
threads,
deletedThreadId: threadId,
deletedThreadId: threadRef.threadId,
deletedThreadIds,
sortOrder: appSettings.sidebarThreadSortOrder,
sortOrder: sidebarThreadSortOrder,
});
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId,
threadId: threadRef.threadId,
});
clearComposerDraftForThread(threadId);
clearProjectDraftThreadById(thread.projectId, thread.id);
clearTerminalState(threadId);
clearComposerDraftForThread(threadRef);
clearProjectDraftThreadById(
scopeProjectRef(threadRef.environmentId, thread.projectId),
threadRef,
);
clearTerminalState(threadRef);
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
await navigate({
to: "/$threadId",
params: { threadId: fallbackThreadId },
replace: true,
});
const fallbackThread = selectThreadByRef(
useStore.getState(),
scopeThreadRef(threadRef.environmentId, fallbackThreadId),
);
if (fallbackThread) {
await router.navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(
scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
),
replace: true,
});
} else {
await router.navigate({ to: "/", replace: true });
}
} else {
await navigate({ to: "/", replace: true });
await router.navigate({ to: "/", replace: true });
}
}
@@ -145,15 +203,18 @@ export function useThreadActions() {
}
try {
await removeWorktreeMutation.mutateAsync({
await ensureEnvironmentApi(threadRef.environmentId).git.removeWorktree({
cwd: threadProject.cwd,
path: orphanedWorktreePath,
force: true,
});
await invalidateGitQueries(queryClient, {
environmentId: threadRef.environmentId,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
console.error("Failed to remove orphaned worktree after thread deletion", {
threadId,
threadId: threadRef.threadId,
projectCwd: threadProject.cwd,
worktreePath: orphanedWorktreePath,
error,
@@ -169,22 +230,25 @@ export function useThreadActions() {
clearComposerDraftForThread,
clearProjectDraftThreadById,
clearTerminalState,
appSettings.sidebarThreadSortOrder,
navigate,
removeWorktreeMutation,
routeThreadId,
getCurrentRouteThreadRef,
router,
queryClient,
resolveThreadTarget,
sidebarThreadSortOrder,
],
);
const confirmAndDeleteThread = useCallback(
async (threadId: ThreadId) => {
const api = readNativeApi();
async (target: ScopedThreadRef) => {
const api = readEnvironmentApi(target.environmentId);
if (!api) return;
const thread = selectThreadById(threadId)(useStore.getState());
if (!thread) return;
const localApi = readLocalApi();
const resolved = resolveThreadTarget(target);
if (!resolved) return;
const { thread } = resolved;
if (appSettings.confirmThreadDelete) {
const confirmed = await api.dialogs.confirm(
if (confirmThreadDelete && localApi) {
const confirmed = await localApi.dialogs.confirm(
[
`Delete thread "${thread.title}"?`,
"This permanently clears conversation history for this thread.",
@@ -195,9 +259,9 @@ export function useThreadActions() {
}
}
await deleteThread(threadId);
await deleteThread(target);
},
[appSettings.confirmThreadDelete, deleteThread],
[confirmThreadDelete, deleteThread, resolveThreadTarget],
);
return {