feat: session worktree isolation (#913)
* feat: add session-worktree contract types and canonicalizeWorktreeState API - Add SessionWorktreeAttachment type and worktree metadata fields (worktreeRoot, worktreeStatus, headState, worktreeSource) to session/worktree types - Add GitAPI.validateWorktreeDirectory() and canonicalizeWorktreeState() methods with full HTTP delegation chain (gitApiHttp → routes.js → service.js) - Add canonicalizeWorktreeState() implementation that resolves worktreeRoot, headState (branch/detached/unborn), attentionReason (merge/rebase/etc), and worktreeStatus (ready/missing/invalid/not-a-repo) for a given directory - Add validateWorktreeDirectory() to check whether a cwd is inside a worktreeRoot - Add session-worktree-contract.ts: pure functions for resolving session worktree state, formatting badges, and building repair actions - Add session-worktree-store.ts: authoritative Zustand store for session-to-worktree attachments, replacing session-ui-store as the source of truth for worktree binding - Add unit tests for contract functions and store operations * feat: canonicalize worktree metadata producers - worktreeManager.listProjectWorktrees: derive headState (branch/detached/unborn) from worktree list entry instead of relying on external state, and populate all Phase 1 canonical fields (worktreeRoot, worktreeStatus, worktreeSource) for each discovered worktree entry - worktreeManager.createWorktree: include all Phase 1 canonical fields (worktreeRoot, worktreeStatus, headState, worktreeSource) in returned metadata - useDetectedWorktreeRoot: populate fallback canonical fields so that sessions without store-based metadata still have worktreeRoot/worktreeStatus/ headState/worktreeSource when resolved through the fallback path * feat: route sessions through authoritative worktree attachments - session-ui-store: import session-worktree-store as the authoritative source for session↔worktree attachment state - setWorktreeMetadata: mirror all writes to session-worktree-store so that session-worktree-store.attachments is always the authoritative record; local worktreeMetadata map is kept for backward-compatible reads - Add session-ui-store.test.js with unit tests covering: valid cwd routing, degraded fallback, created-for-session attachments, legacy upgrade recovery, missing/not-a-repo status handling * feat: clarify session worktree targets - session-worktree-contract: extend buildSessionTargetOptions to accept pendingBootstrapDirectory and mark pending worktrees with pending=true; extend SessionTargetOption to include optional pending flag - ChatInput: replace manual worktree branch options construction with buildSessionTargetOptions; add ⏳ prefix for pending bootstrap worktrees - Add test for pending bootstrap worktree distinction * feat: show worktree-backed session state - Header: read worktree attachment from authoritative session-worktree-store and render needs-attention/degraded/missing badge with alert icon next to current session info when session has degraded/missing/invalid state - GitView: show 'Worktree features are unavailable' message when session has missing worktree status and open-without-worktree-features repair action * feat: enforce safe mutations for attached worktrees - session-worktree-contract: add getMutationBlockingReasons helper that returns blocking reasons (missing/invalid/attention state) for high-risk mutations - GitView: gate handleCheckoutBranch, handleCreateBranch, and handleRenameBranch with getMutationBlockingReasons; block with explicit toast message when worktree is missing, invalid, or has an in-progress git operation - session-worktree-contract.test: add 7 tests covering mutation blocking for missing/invalid/attention states (merge/rebase/cherry-pick) * feat: implement session worktree isolation This adds a shared session↔worktree contract that makes session switching worktree-backed. Sessions attached to different worktrees keep stable branch context without shared-directory auto-checkout. Commits: - feat: add session-worktree contract types and canonicalizeWorktreeState API - feat: canonicalize worktree metadata producers - feat: route sessions through authoritative worktree attachments - feat: clarify session worktree targets - feat: show worktree-backed session state - feat: enforce safe mutations for attached worktrees * feat: make authoritative attachment first-priority source for session directory resolution Phase A: resolveSessionDirectory, getDirectoryForSession, hooks read authoritative attachment before falling back to worktreeMetadata. Phase B: createSession canonicalizes and writes attachment on creation; setCurrentSession recovers legacy/missing attachments via async canonicalization. * feat: make authoritative attachment the primary branch source in Header/GitView Phase C: Header branch label and GitView project root now read from authoritative SessionWorktreeAttachment first, falling back to live git and legacy sources only when attachment is absent, degraded, or legacy. Adds getAttachmentBranchLabel() helper with 7 tests. * feat: add runtime parity for validateWorktreeDirectory and canonicalizeWorktreeState Phase D: Web runtime API, VS Code bridge, and VS Code gitService now expose validateWorktreeDirectory and canonicalizeWorktreeState, matching the server-side implementations. All three runtimes (web, desktop, VS Code) can now delegate worktree canonicalization without HTTP fallback. * feat: add dirty-tree blocking to mutation safety gates getMutationBlockingReasons now accepts an optional gitStatus param and blocks branch mutations when the tree has uncommitted changes. GitView passes live status to all three blocking call sites. 5 new tests covering dirty, clean, null, combined, and no-file-count cases. * refactor: revert branch label to live-git-first, remove getAttachmentBranchLabel Live git is the correct source for branch labels in all scenarios: dedicated worktree sessions have identical live/attachment branches, and shared-directory sessions must show the real current branch. Attachment remains authoritative for worktreeRoot, cwd, degraded/ missing/repair status, and mutation blocking. * chore: remove session worktree isolation plan doc * refactor: simplify session worktree isolation implementation --------- Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
This commit is contained in:
committed by
GitHub
co-authored by
Bohdan Triapitsyn
parent
f96ccc58c3
commit
fccf4bad32
@@ -66,6 +66,7 @@ import { PROJECT_COLOR_MAP, PROJECT_ICON_MAP, getProjectIconImageUrl } from '@/l
|
||||
import { useGitBranches, useGitStore } from '@/stores/useGitStore';
|
||||
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
||||
import { createWorktreeDraft } from '@/lib/worktreeSessionCreator';
|
||||
import { buildSessionTargetOptions } from '@/sync/session-worktree-contract';
|
||||
import { usePermissionStore } from '@/stores/permissionStore';
|
||||
|
||||
const MAX_VISIBLE_TEXTAREA_LINES = 8;
|
||||
@@ -2899,13 +2900,9 @@ const ChatInputComponent: React.FC<ChatInputProps> = ({ onOpenSettings, scrollTo
|
||||
|
||||
const worktreeBranchOptions = React.useMemo(() => {
|
||||
if (!selectedDraftProject) {
|
||||
return [] as Array<{ value: string; label: string }>;
|
||||
return [];
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
const options: Array<{ value: string; label: string }> = [];
|
||||
const rootValue = projectRootBranchOption?.value ?? null;
|
||||
|
||||
const worktrees = (() => {
|
||||
if (!selectedDraftProjectPath) {
|
||||
return [];
|
||||
@@ -2915,23 +2912,13 @@ const ChatInputComponent: React.FC<ChatInputProps> = ({ onOpenSettings, scrollTo
|
||||
?? [];
|
||||
})();
|
||||
|
||||
worktrees
|
||||
.slice()
|
||||
.sort((a, b) => a.branch.localeCompare(b.branch))
|
||||
.forEach((worktree) => {
|
||||
const normalizedValue = normalizePath(worktree.path);
|
||||
if (!normalizedValue || normalizedValue === rootValue || seen.has(normalizedValue)) {
|
||||
return;
|
||||
}
|
||||
seen.add(normalizedValue);
|
||||
options.push({
|
||||
value: normalizedValue,
|
||||
label: worktree.branch?.trim() || formatDirectoryName(worktree.path),
|
||||
});
|
||||
});
|
||||
|
||||
return options;
|
||||
}, [availableWorktreesByProject, projectRootBranchOption?.value, selectedDraftProject, selectedDraftProjectPath]);
|
||||
return buildSessionTargetOptions({
|
||||
projectRoot: normalizePath(selectedDraftProject.path) ?? '',
|
||||
rootBranch: selectedDraftProjectBranches?.current?.trim() ?? '',
|
||||
worktrees,
|
||||
pendingBootstrapDirectory: newSessionDraft?.bootstrapPendingDirectory ?? null,
|
||||
});
|
||||
}, [availableWorktreesByProject, newSessionDraft?.bootstrapPendingDirectory, selectedDraftProject, selectedDraftProjectBranches?.current, selectedDraftProjectPath]);
|
||||
|
||||
const selectedDraftDirectory = React.useMemo(
|
||||
() => normalizePath(newSessionDraft?.bootstrapPendingDirectory ?? null)
|
||||
@@ -3350,7 +3337,7 @@ const ChatInputComponent: React.FC<ChatInputProps> = ({ onOpenSettings, scrollTo
|
||||
</div>
|
||||
{worktreeBranchOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value} className="max-w-[24rem] truncate">
|
||||
{option.label}
|
||||
{option.pending ? '⏳ ' : ''}{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
|
||||
@@ -16,11 +16,13 @@ import {
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { SortableTabsStrip, type SortableTabsStripItem } from '@/components/ui/sortable-tabs-strip';
|
||||
|
||||
import { RiArrowLeftSLine, RiChat4Line, RiChatNewLine, RiCheckLine, RiCloseLine, RiCommandLine, RiFileTextLine, RiFolder6Line, RiGitBranchLine, RiGithubFill, RiLayoutLeftLine, RiLayoutRightLine, RiPlayListAddLine, RiRefreshLine, RiServerLine, RiStackLine, RiTerminalBoxLine, RiTimerLine, type RemixiconComponentType } from '@remixicon/react';
|
||||
import { RiArrowLeftSLine, RiChat4Line, RiChatNewLine, RiCheckLine, RiCloseLine, RiCommandLine, RiFileTextLine, RiFolder6Line, RiGitBranchLine, RiGithubFill, RiLayoutLeftLine, RiLayoutRightLine, RiPlayListAddLine, RiRefreshLine, RiServerLine, RiStackLine, RiTerminalBoxLine, RiTimerLine, RiAlertLine, type RemixiconComponentType } from '@remixicon/react';
|
||||
import { DiffIcon } from '@/components/icons/DiffIcon';
|
||||
import { useUIStore, type MainTab } from '@/stores/useUIStore';
|
||||
import { useConfigStore } from '@/stores/useConfigStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useSessionWorktreeStore } from '@/sync/session-worktree-store';
|
||||
import { formatSessionWorktreeBadge } from '@/sync/session-worktree-contract';
|
||||
import { useAllLiveSessions, useSession, useSessionMessagesResolved } from '@/sync/sync-context';
|
||||
import { getAllSyncSessions } from '@/sync/sync-refs';
|
||||
import { useProjectsStore } from '@/stores/useProjectsStore';
|
||||
@@ -1023,6 +1025,26 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
if (!currentSessionId) return null;
|
||||
return state.worktreeMetadata.get(currentSessionId)?.branch?.trim() ?? null;
|
||||
});
|
||||
|
||||
// Authoritative session↔worktree attachment from session-worktree-store
|
||||
const worktreeAttachment = useSessionWorktreeStore((state) =>
|
||||
currentSessionId ? state.getAttachment(currentSessionId) : undefined
|
||||
);
|
||||
|
||||
const worktreeBadge = React.useMemo(() => {
|
||||
if (!worktreeAttachment) return null;
|
||||
return formatSessionWorktreeBadge(worktreeAttachment);
|
||||
}, [worktreeAttachment]);
|
||||
|
||||
const worktreeBadgeKind = React.useMemo(() => {
|
||||
if (!worktreeAttachment) return null;
|
||||
if (worktreeAttachment.legacy) return 'legacy';
|
||||
if (worktreeAttachment.degraded) return 'degraded';
|
||||
if (worktreeAttachment.worktreeStatus === 'missing') return 'missing';
|
||||
if (worktreeAttachment.worktreeStatus === 'invalid') return 'invalid';
|
||||
if (worktreeAttachment.attentionReason) return 'attention';
|
||||
return null;
|
||||
}, [worktreeAttachment]);
|
||||
const worktreeDirectory = React.useMemo(() => {
|
||||
return normalize(worktreePath || '');
|
||||
}, [worktreePath]);
|
||||
@@ -1739,6 +1761,15 @@ export const Header: React.FC<HeaderProps> = ({
|
||||
<span className="text-status-error/65">-{currentSessionChanges.deletions}</span>
|
||||
</span>
|
||||
) : null}
|
||||
{worktreeBadgeKind ? (
|
||||
<span className={cn(
|
||||
"inline-flex min-w-0 items-center gap-0.5",
|
||||
worktreeBadgeKind === 'attention' || worktreeBadgeKind === 'invalid' || worktreeBadgeKind === 'missing' ? 'text-status-warning' : 'text-muted-foreground/60'
|
||||
)}>
|
||||
<RiAlertLine className="h-3 w-3 flex-shrink-0" />
|
||||
<span className="truncate">{worktreeBadge}</span>
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -48,6 +48,8 @@ import {
|
||||
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { useDetectedWorktreeMetadata } from '@/hooks/useDetectedWorktreeRoot';
|
||||
import { useSessionWorktreeStore } from '@/sync/session-worktree-store';
|
||||
import { getSessionWorktreeRepairActions, getMutationBlockingReasons } from '@/sync/session-worktree-contract';
|
||||
import { IntegrateCommitsSection } from './git/IntegrateCommitsSection';
|
||||
|
||||
import { GitHeader } from './git/GitHeader';
|
||||
@@ -273,6 +275,18 @@ export const GitView: React.FC = () => {
|
||||
const isGitRepo = useIsGitRepo(currentDirectory ?? null);
|
||||
const status = useGitStatus(currentDirectory ?? null);
|
||||
|
||||
// Authoritative session↔worktree attachment for repair action display
|
||||
const worktreeAttachment = useSessionWorktreeStore((s) =>
|
||||
currentSessionId ? s.getAttachment(currentSessionId) : undefined
|
||||
);
|
||||
const repairActions = worktreeAttachment ? getSessionWorktreeRepairActions(worktreeAttachment) : [];
|
||||
|
||||
// When an authoritative attachment exists, derive worktree-related fields from it
|
||||
// rather than from the live detected worktree metadata.
|
||||
const authoritativeProjectRoot = worktreeAttachment && !worktreeAttachment.degraded && !worktreeAttachment.legacy
|
||||
? worktreeAttachment.worktreeRoot ?? undefined
|
||||
: undefined;
|
||||
|
||||
const worktreeMetadata = useDetectedWorktreeMetadata(currentDirectory, storeWorktreeMetadata, status?.current ?? undefined);
|
||||
const branches = useGitBranches(currentDirectory ?? null);
|
||||
const log = useGitLog(currentDirectory ?? null);
|
||||
@@ -374,7 +388,7 @@ export const GitView: React.FC = () => {
|
||||
const [rootBranchHint, setRootBranchHint] = React.useState<string | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
const projectRoot = worktreeMetadata?.projectDirectory;
|
||||
const projectRoot = authoritativeProjectRoot || worktreeMetadata?.projectDirectory;
|
||||
if (!projectRoot) {
|
||||
setRootBranchHint(null);
|
||||
return;
|
||||
@@ -396,7 +410,7 @@ export const GitView: React.FC = () => {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [worktreeMetadata?.projectDirectory]);
|
||||
}, [authoritativeProjectRoot, worktreeMetadata?.projectDirectory]);
|
||||
|
||||
const [commitMessage, setCommitMessage] = React.useState(
|
||||
initialSnapshot?.commitMessage ?? ''
|
||||
@@ -448,7 +462,7 @@ export const GitView: React.FC = () => {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const repoRootForIntegrate = worktreeMetadata?.projectDirectory || null;
|
||||
const repoRootForIntegrate = authoritativeProjectRoot || worktreeMetadata?.projectDirectory || null;
|
||||
const sourceBranchForIntegrate = status?.current || null;
|
||||
const shouldShowIntegrateCommits = React.useMemo(() => {
|
||||
// For PR worktrees from forks we set upstream to a non-origin remote (e.g. pr-<owner>-<repo>).
|
||||
@@ -1042,8 +1056,29 @@ export const GitView: React.FC = () => {
|
||||
}
|
||||
}, [currentDirectory, selectedPaths, settingsGitmojiEnabled, gitmojiEmojis, scrollActionPanelToBottom]);
|
||||
|
||||
const formatBlockingReason = (reason: ReturnType<typeof getMutationBlockingReasons>[number]): string => {
|
||||
if (reason.reason === 'dirty') {
|
||||
const count = typeof reason.dirtyFiles === 'number' ? reason.dirtyFiles : null;
|
||||
return count != null ? `${count} uncommitted file${count === 1 ? '' : 's'}` : 'uncommitted changes';
|
||||
}
|
||||
if (reason.reason === 'attention') {
|
||||
return `${reason.attentionReason} in progress`;
|
||||
}
|
||||
if (reason.reason === 'missing') {
|
||||
return 'worktree is missing';
|
||||
}
|
||||
return 'worktree is invalid';
|
||||
};
|
||||
|
||||
const handleCreateBranch = async (branchName: string, remote?: GitRemote) => {
|
||||
if (!currentDirectory || !status) return;
|
||||
|
||||
const blockingReasons = getMutationBlockingReasons(worktreeAttachment ?? null, status);
|
||||
if (blockingReasons.length > 0) {
|
||||
toast.error(`Cannot create branch: ${formatBlockingReason(blockingReasons[0])}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const checkoutBase = status.current ?? null;
|
||||
const remoteName = remote?.name ?? 'origin';
|
||||
|
||||
@@ -1092,6 +1127,12 @@ export const GitView: React.FC = () => {
|
||||
const handleRenameBranch = async (oldName: string, newName: string) => {
|
||||
if (!currentDirectory) return;
|
||||
|
||||
const blockingReasons = getMutationBlockingReasons(worktreeAttachment ?? null, status);
|
||||
if (blockingReasons.length > 0) {
|
||||
toast.error(`Cannot rename branch: ${formatBlockingReason(blockingReasons[0])}`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await git.renameBranch(currentDirectory, oldName, newName);
|
||||
toast.success(`Renamed branch ${oldName} to ${newName}`);
|
||||
@@ -1106,6 +1147,14 @@ export const GitView: React.FC = () => {
|
||||
|
||||
const handleCheckoutBranch = async (branch: string) => {
|
||||
if (!currentDirectory) return;
|
||||
|
||||
// Block mutation if worktree is in an attention-required state
|
||||
const blockingReasons = getMutationBlockingReasons(worktreeAttachment ?? null, status);
|
||||
if (blockingReasons.length > 0) {
|
||||
toast.error(`Cannot checkout: ${formatBlockingReason(blockingReasons[0])}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const normalized = branch.replace(/^remotes\//, '');
|
||||
|
||||
if (status?.current === normalized) {
|
||||
@@ -1936,6 +1985,11 @@ export const GitView: React.FC = () => {
|
||||
<p className="typography-meta mt-1 text-muted-foreground">
|
||||
Choose a different directory or initialize Git to use this workspace.
|
||||
</p>
|
||||
{repairActions.includes('open-without-worktree-features') ? (
|
||||
<p className="typography-meta mt-2 text-muted-foreground">
|
||||
Worktree features are unavailable for this session.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user