Implements the new-thread workspace model: every new thread starts from the
resolved default workspace mode instead of inheriting the previous thread's
choices, and worktree threads pin a fresh remote base with visible provenance.
Surface-derived defaults
- New `deriveThreadEnvModeFromSurface` setting (default on): attached
surfaces (desktop app, loopback browser on a host-managed environment)
default to the current checkout; detached surfaces (remote browser,
mobile, relay/SSH) default to a fresh worktree. Explicit
`defaultThreadEnvMode` still pins a mode globally when derivation is off,
keeping the wire value decodable by older clients.
- Sticky per-draft inheritance retired: sidebar/new-thread actions no longer
seed mode/branch/worktree from the active thread. `chat.newLocal` remains
the explicit current-checkout exception (draft-only).
- Per-project override (`projectThreadEnvModeOverrides` client setting) via
an explicit "Always … for this project" action in the workspace picker —
the only sanctioned way a composer choice retrains the default.
Fresh worktree bases without a blocking fetch
- `WorktreeBasePlanner`: fetch within the 30s freshness window counts as
fresh; concurrent fetches dedupe per repository; a failed fetch with a
successful fetch within the last hour proceeds on the last-known remote
commit (fail-visible, "stale" provenance); otherwise the bootstrap fails
closed and never silently falls back to a local ref.
- Composer prefetch: worktree-mode drafts fire `vcs.prefetchRemote` on open
so the send-time check almost always hits the fresh window.
- `newWorktreesStartFromOrigin` now defaults on.
Provenance and registry
- Bootstrap records a `worktree.base-pinned` thread activity (base ref, sha,
provenance, fetch time); the branch toolbar renders the pinned fact
("Worktree · a1b2c3f") with provenance on hover.
- `WorktreeRegistry` persists thread↔worktree records to
`stateDir/worktree-registry.json`, updated at bootstrap and on thread
deletion — groundwork for lifecycle/GC tooling.
- Deterministic branch naming: worktree branches derive from the thread id
(`t3code/<uuid-prefix>`), with collision suffixing server-side.
Composer UX
- Dirty-checkout disclosure both directions with one-click mode switch.
- Workspace picker labels choices as "this draft only".
Co-Authored-By: Claude Fable 5 <[email protected]>
259 lines
9.9 KiB
TypeScript
259 lines
9.9 KiB
TypeScript
import { useAtomValue } from "@effect/atom-react";
|
|
import {
|
|
scopedProjectKey,
|
|
scopeProjectRef,
|
|
scopeThreadRef,
|
|
} from "@t3tools/client-runtime/environment";
|
|
import {
|
|
DEFAULT_RUNTIME_MODE,
|
|
DEFAULT_SERVER_SETTINGS,
|
|
type ScopedProjectRef,
|
|
} from "@t3tools/contracts";
|
|
import { useParams, useRouter } from "@tanstack/react-router";
|
|
import { useCallback, useMemo } from "react";
|
|
|
|
import { environmentPresentations } from "../state/presentation";
|
|
import { resolveSurfaceThreadEnvMode } from "../lib/threadSurface";
|
|
import {
|
|
markPromotedDraftThreadByRef,
|
|
type DraftThreadEnvMode,
|
|
type DraftThreadState,
|
|
useComposerDraftStore,
|
|
} from "../composerDraftStore";
|
|
import { newDraftId, newThreadId } from "../lib/utils";
|
|
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
|
|
import {
|
|
deriveLogicalProjectKeyFromSettings,
|
|
getProjectOrderKey,
|
|
selectProjectGroupingSettings,
|
|
} from "../logicalProject";
|
|
import { readThreadShell, useProjects, useServerConfigs, useThread } from "../state/entities";
|
|
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
|
|
import { resolveThreadRouteTarget } from "../threadRoutes";
|
|
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
|
|
import { useClientSettings } from "./useSettings";
|
|
|
|
export function useNewThreadHandler() {
|
|
const projects = useProjects();
|
|
const serverConfigs = useServerConfigs();
|
|
const environmentPresentationById = useAtomValue(environmentPresentations.presentationsAtom);
|
|
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
|
const projectThreadEnvModeOverrides = useClientSettings(
|
|
(settings) => settings.projectThreadEnvModeOverrides,
|
|
);
|
|
const router = useRouter();
|
|
const getCurrentRouteTarget = useCallback(() => {
|
|
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
|
|
return resolveThreadRouteTarget(currentRouteParams);
|
|
}, [router]);
|
|
|
|
return useCallback(
|
|
(
|
|
projectRef: ScopedProjectRef,
|
|
options?: {
|
|
branch?: string | null;
|
|
worktreePath?: string | null;
|
|
envMode?: DraftThreadEnvMode;
|
|
startFromOrigin?: boolean;
|
|
},
|
|
): Promise<void> => {
|
|
const {
|
|
getDraftSessionByLogicalProjectKey,
|
|
getDraftSession,
|
|
getDraftThread,
|
|
applyStickyState,
|
|
setDraftThreadContext,
|
|
setLogicalProjectDraftThreadId,
|
|
} = useComposerDraftStore.getState();
|
|
const currentRouteTarget = getCurrentRouteTarget();
|
|
const project = projects.find(
|
|
(candidate) =>
|
|
candidate.id === projectRef.projectId &&
|
|
candidate.environmentId === projectRef.environmentId,
|
|
);
|
|
const environmentSettings =
|
|
serverConfigs.get(projectRef.environmentId)?.settings ?? DEFAULT_SERVER_SETTINGS;
|
|
const logicalProjectKey = project
|
|
? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings)
|
|
: scopedProjectKey(projectRef);
|
|
const hasBranchOption = options?.branch !== undefined;
|
|
const hasWorktreePathOption = options?.worktreePath !== undefined;
|
|
const hasEnvModeOption = options?.envMode !== undefined;
|
|
const hasStartFromOriginOption = options?.startFromOrigin !== undefined;
|
|
const storedDraftThread = getDraftSessionByLogicalProjectKey(logicalProjectKey);
|
|
const storedDraftThreadRef = storedDraftThread
|
|
? scopeThreadRef(storedDraftThread.environmentId, storedDraftThread.threadId)
|
|
: null;
|
|
const reusableStoredDraftThread =
|
|
storedDraftThreadRef && readThreadShell(storedDraftThreadRef) !== null
|
|
? null
|
|
: storedDraftThread;
|
|
if (storedDraftThreadRef && reusableStoredDraftThread === null) {
|
|
markPromotedDraftThreadByRef(storedDraftThreadRef);
|
|
}
|
|
const latestActiveDraftThread: DraftThreadState | null = currentRouteTarget
|
|
? currentRouteTarget.kind === "server"
|
|
? getDraftThread(currentRouteTarget.threadRef)
|
|
: getDraftSession(currentRouteTarget.draftId)
|
|
: null;
|
|
if (reusableStoredDraftThread) {
|
|
return (async () => {
|
|
if (
|
|
hasBranchOption ||
|
|
hasWorktreePathOption ||
|
|
hasEnvModeOption ||
|
|
hasStartFromOriginOption
|
|
) {
|
|
setDraftThreadContext(reusableStoredDraftThread.draftId, {
|
|
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
|
|
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
|
|
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
|
|
...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
|
|
});
|
|
}
|
|
setLogicalProjectDraftThreadId(
|
|
logicalProjectKey,
|
|
projectRef,
|
|
reusableStoredDraftThread.draftId,
|
|
{
|
|
threadId: reusableStoredDraftThread.threadId,
|
|
},
|
|
);
|
|
if (
|
|
currentRouteTarget?.kind === "draft" &&
|
|
currentRouteTarget.draftId === reusableStoredDraftThread.draftId
|
|
) {
|
|
return;
|
|
}
|
|
await router.navigate({
|
|
to: "/draft/$draftId",
|
|
params: { draftId: reusableStoredDraftThread.draftId },
|
|
});
|
|
})();
|
|
}
|
|
|
|
if (
|
|
latestActiveDraftThread &&
|
|
currentRouteTarget?.kind === "draft" &&
|
|
latestActiveDraftThread.logicalProjectKey === logicalProjectKey &&
|
|
latestActiveDraftThread.promotedTo == null
|
|
) {
|
|
if (
|
|
hasBranchOption ||
|
|
hasWorktreePathOption ||
|
|
hasEnvModeOption ||
|
|
hasStartFromOriginOption
|
|
) {
|
|
setDraftThreadContext(currentRouteTarget.draftId, {
|
|
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
|
|
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
|
|
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
|
|
...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
|
|
});
|
|
}
|
|
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 } : {}),
|
|
...(hasStartFromOriginOption ? { startFromOrigin: options?.startFromOrigin } : {}),
|
|
});
|
|
return Promise.resolve();
|
|
}
|
|
|
|
const draftId = newDraftId();
|
|
const threadId = newThreadId();
|
|
const createdAt = new Date().toISOString();
|
|
// The default mode derives from the surface (attached checkout →
|
|
// local, detached → worktree) unless a project override or an explicit
|
|
// setting pins a mode. Draft exceptions never retrain this default —
|
|
// only the project override ("Always for this project") does, and only
|
|
// through an explicit settings write.
|
|
const projectEnvModeOverride =
|
|
projectThreadEnvModeOverrides[scopedProjectKey(projectRef)] ?? null;
|
|
const initialEnvMode =
|
|
options?.envMode ??
|
|
projectEnvModeOverride ??
|
|
resolveSurfaceThreadEnvMode({
|
|
settings: environmentSettings,
|
|
target: environmentPresentationById.get(projectRef.environmentId)?.entry.target ?? null,
|
|
});
|
|
return (async () => {
|
|
setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
|
|
threadId,
|
|
createdAt,
|
|
branch: options?.branch ?? null,
|
|
worktreePath: options?.worktreePath ?? null,
|
|
envMode: initialEnvMode,
|
|
startFromOrigin:
|
|
options?.startFromOrigin ??
|
|
resolveNewDraftStartFromOrigin({
|
|
envMode: initialEnvMode,
|
|
newWorktreesStartFromOrigin: environmentSettings.newWorktreesStartFromOrigin,
|
|
}),
|
|
runtimeMode: DEFAULT_RUNTIME_MODE,
|
|
});
|
|
applyStickyState(draftId);
|
|
|
|
await router.navigate({
|
|
to: "/draft/$draftId",
|
|
params: { draftId },
|
|
});
|
|
})();
|
|
},
|
|
[
|
|
environmentPresentationById,
|
|
getCurrentRouteTarget,
|
|
projectGroupingSettings,
|
|
projects,
|
|
projectThreadEnvModeOverrides,
|
|
router,
|
|
serverConfigs,
|
|
],
|
|
);
|
|
}
|
|
|
|
export function useHandleNewThread() {
|
|
const projectOrder = useUiStateStore((store) => store.projectOrder);
|
|
const routeTarget = useParams({
|
|
strict: false,
|
|
select: (params) => resolveThreadRouteTarget(params),
|
|
});
|
|
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
|
|
const activeThread = useThread(routeThreadRef);
|
|
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
|
|
const activeDraftThread = useComposerDraftStore(() =>
|
|
routeTarget
|
|
? routeTarget.kind === "server"
|
|
? getDraftThread(routeTarget.threadRef)
|
|
: useComposerDraftStore.getState().getDraftSession(routeTarget.draftId)
|
|
: null,
|
|
);
|
|
const projects = useProjects();
|
|
const orderedProjects = useMemo(() => {
|
|
return orderItemsByPreferredIds({
|
|
items: projects,
|
|
preferredIds: projectOrder,
|
|
getId: getProjectOrderKey,
|
|
getPreferenceIds: (project) => [
|
|
getProjectOrderKey(project),
|
|
legacyProjectCwdPreferenceKey(project.workspaceRoot),
|
|
],
|
|
});
|
|
}, [projectOrder, projects]);
|
|
const handleNewThread = useNewThreadHandler();
|
|
|
|
return {
|
|
activeDraftThread,
|
|
activeThread,
|
|
defaultProjectRef: orderedProjects[0]
|
|
? scopeProjectRef(orderedProjects[0].environmentId, orderedProjects[0].id)
|
|
: null,
|
|
handleNewThread,
|
|
routeThreadRef,
|
|
};
|
|
}
|