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
@@ -0,0 +1,191 @@
|
||||
import { beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { useSessionWorktreeStore } from './session-worktree-store';
|
||||
import { useSessionUIStore } from './session-ui-store';
|
||||
|
||||
/**
|
||||
* Unit tests for session worktree routing through the authoritative store.
|
||||
*
|
||||
* These tests verify that session-worktree-store is properly integrated as the
|
||||
* authoritative holder of session↔worktree attachments, and that session-ui-store
|
||||
* routes through it for switching and creation flows.
|
||||
*
|
||||
* Note: Full integration tests for setCurrentSession require runtime mocking.
|
||||
* These tests focus on the contract layer: that setAttachment/getAttachment work
|
||||
* correctly and that the contract helpers produce correct results.
|
||||
*/
|
||||
|
||||
describe('session-worktree-store worktree routing', () => {
|
||||
beforeEach(() => {
|
||||
// Clear all attachments before each test
|
||||
const store = useSessionWorktreeStore.getState();
|
||||
const attachments = store.attachments;
|
||||
for (const sessionId of attachments.keys()) {
|
||||
store.clearAttachment(sessionId);
|
||||
}
|
||||
useSessionUIStore.setState({ currentSessionId: null, worktreeMetadata: new Map() });
|
||||
});
|
||||
|
||||
test('getDirectoryForSession prefers authoritative attachment cwd over sync fallback', () => {
|
||||
useSessionWorktreeStore.getState().setAttachment('session-dir', {
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/repo/worktrees/feat-a/src',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
});
|
||||
|
||||
expect(useSessionUIStore.getState().getDirectoryForSession('session-dir')).toBe('/repo/worktrees/feat-a/src');
|
||||
});
|
||||
|
||||
test('getDirectoryForSession falls back to authoritative worktreeRoot when attachment is degraded', () => {
|
||||
useSessionWorktreeStore.getState().setAttachment('session-dir', {
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/tmp/outside',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'invalid',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: true,
|
||||
});
|
||||
|
||||
expect(useSessionUIStore.getState().getDirectoryForSession('session-dir')).toBe('/repo/worktrees/feat-a');
|
||||
});
|
||||
|
||||
test('setCurrentSession uses canonical cwd when valid', () => {
|
||||
const store = useSessionWorktreeStore.getState();
|
||||
|
||||
// Simulate: session has valid worktree metadata with cwd inside worktreeRoot
|
||||
store.setAttachment('session-1', {
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/repo/worktrees/feat-a/src',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
});
|
||||
|
||||
const attachment = store.getAttachment('session-1');
|
||||
expect(attachment).toBeDefined();
|
||||
expect(attachment.cwd).toBe('/repo/worktrees/feat-a/src');
|
||||
expect(attachment.worktreeRoot).toBe('/repo/worktrees/feat-a');
|
||||
expect(attachment.degraded).toBe(false);
|
||||
expect(attachment.worktreeStatus).toBe('ready');
|
||||
});
|
||||
|
||||
test('setCurrentSession falls back to worktreeRoot when cwd is degraded', () => {
|
||||
const store = useSessionWorktreeStore.getState();
|
||||
|
||||
// Simulate: cwd is outside worktreeRoot (degraded)
|
||||
store.setAttachment('session-2', {
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/repo/worktrees/feat-a', // same as worktreeRoot means not degraded for this case
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: true, // marked degraded because cwd was resolved from invalid state
|
||||
});
|
||||
|
||||
const attachment = store.getAttachment('session-2');
|
||||
expect(attachment).toBeDefined();
|
||||
expect(attachment.degraded).toBe(true);
|
||||
// cwd should equal worktreeRoot when degraded (fallback)
|
||||
expect(attachment.cwd).toBe(attachment.worktreeRoot);
|
||||
});
|
||||
|
||||
test('isolated session initializes created-for-session attachment', () => {
|
||||
const store = useSessionWorktreeStore.getState();
|
||||
|
||||
// Simulate: isolated worktree session created for a specific branch
|
||||
store.setAttachment('session-isolated', {
|
||||
worktreeRoot: '/repo/worktrees/feature-xyz',
|
||||
cwd: '/repo/worktrees/feature-xyz',
|
||||
branch: 'feature-xyz',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'created-for-session',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
});
|
||||
|
||||
const attachment = store.getAttachment('session-isolated');
|
||||
expect(attachment).toBeDefined();
|
||||
expect(attachment.worktreeSource).toBe('created-for-session');
|
||||
expect(attachment.worktreeStatus).toBe('ready');
|
||||
expect(attachment.legacy).toBe(false);
|
||||
});
|
||||
|
||||
test('legacy session upgrades when runtime canonicalization recovers a worktree', () => {
|
||||
const store = useSessionWorktreeStore.getState();
|
||||
|
||||
// Simulate: session without metadata (legacy) gets upgraded via runtime resolution
|
||||
// Initially no attachment
|
||||
let attachment = store.getAttachment('session-legacy');
|
||||
expect(attachment).toBeUndefined();
|
||||
|
||||
// Runtime canonicalization resolves it to a worktree
|
||||
store.setAttachment('session-legacy', {
|
||||
worktreeRoot: '/repo/worktrees/recovered',
|
||||
cwd: '/repo/worktrees/recovered',
|
||||
branch: 'recovered',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false, // upgraded from legacy=true to false
|
||||
degraded: false,
|
||||
});
|
||||
|
||||
attachment = store.getAttachment('session-legacy');
|
||||
expect(attachment).toBeDefined();
|
||||
expect(attachment.legacy).toBe(false);
|
||||
expect(attachment.worktreeRoot).toBe('/repo/worktrees/recovered');
|
||||
});
|
||||
|
||||
test('missing worktree session has missing status', () => {
|
||||
const store = useSessionWorktreeStore.getState();
|
||||
|
||||
// Simulate: session whose worktree was deleted
|
||||
store.setAttachment('session-missing', {
|
||||
worktreeRoot: null,
|
||||
cwd: null,
|
||||
branch: null,
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'missing',
|
||||
worktreeSource: null,
|
||||
legacy: false,
|
||||
degraded: true,
|
||||
});
|
||||
|
||||
const attachment = store.getAttachment('session-missing');
|
||||
expect(attachment).toBeDefined();
|
||||
expect(attachment.worktreeStatus).toBe('missing');
|
||||
expect(attachment.degraded).toBe(true);
|
||||
});
|
||||
|
||||
test('not-a-repo session has correct status', () => {
|
||||
const store = useSessionWorktreeStore.getState();
|
||||
|
||||
// Simulate: session opened in a directory that is not a git repo
|
||||
store.setAttachment('session-not-repo', {
|
||||
worktreeRoot: null,
|
||||
cwd: '/tmp/not-a-repo',
|
||||
branch: null,
|
||||
headState: 'detached',
|
||||
worktreeStatus: 'not-a-repo',
|
||||
worktreeSource: null,
|
||||
legacy: false,
|
||||
degraded: true,
|
||||
});
|
||||
|
||||
const attachment = store.getAttachment('session-not-repo');
|
||||
expect(attachment).toBeDefined();
|
||||
expect(attachment.worktreeStatus).toBe('not-a-repo');
|
||||
});
|
||||
});
|
||||
@@ -6,12 +6,15 @@
|
||||
* current selection, draft state, viewport anchors, model/agent preferences,
|
||||
* voice state, abort prompts, attached files, worktree metadata.
|
||||
*
|
||||
* Session↔worktree attachments are the authoritative exception: they live in
|
||||
* session-worktree-store (shared sync), and session-ui-store routes through it.
|
||||
*
|
||||
* SDK-calling actions that need domain data read it from sync-refs.
|
||||
*/
|
||||
|
||||
import { create } from "zustand"
|
||||
import type { Session, Part, Message, TextPart } from "@opencode-ai/sdk/v2/client"
|
||||
import type { AttachedFile, SessionContextUsage } from "@/stores/types/sessionTypes"
|
||||
import type { AttachedFile, SessionContextUsage, SessionWorktreeAttachment } from "@/stores/types/sessionTypes"
|
||||
import type { WorktreeMetadata } from "@/types/worktree"
|
||||
import { opencodeClient } from "@/lib/opencode/client"
|
||||
import { useConfigStore } from "@/stores/useConfigStore"
|
||||
@@ -25,6 +28,7 @@ import { flattenAssistantTextParts } from "@/lib/messages/messageText"
|
||||
import { EXECUTION_FORK_META_TEXT } from "@/lib/messages/executionMeta"
|
||||
import { waitForWorktreeBootstrap } from "@/lib/worktrees/worktreeBootstrap"
|
||||
import { waitForPendingDraftWorktreeRequest } from "@/lib/worktrees/pendingDraftWorktree"
|
||||
import { canonicalizeWorktreeState } from "@/lib/gitApi"
|
||||
import type { ProjectEntry } from "@/lib/api/types"
|
||||
import {
|
||||
getSyncSessions,
|
||||
@@ -47,6 +51,8 @@ import {
|
||||
import { useInputStore, type SyntheticContextPart } from "./input-store"
|
||||
import { useSelectionStore } from "./selection-store"
|
||||
import { useViewportStore } from "./viewport-store"
|
||||
import { useSessionWorktreeStore } from "./session-worktree-store"
|
||||
import { buildAttachmentFromCanonicalization, getAttachedSessionDirectory } from "./session-worktree-contract"
|
||||
|
||||
export type { AttachedFile }
|
||||
|
||||
@@ -341,11 +347,37 @@ const resolveDraftProjectForDirectory = (
|
||||
resolveProjectFromWorktreeDirectory(projects, availableWorktreesByProject, directory) ??
|
||||
resolveProjectForDirectory(projects, directory)
|
||||
|
||||
const getAttachmentForSession = (sessionId: string | null | undefined): SessionWorktreeAttachment | undefined => {
|
||||
if (!sessionId) return undefined
|
||||
return useSessionWorktreeStore.getState().getAttachment(sessionId)
|
||||
}
|
||||
|
||||
const recoverSessionAttachment = async (
|
||||
sessionId: string,
|
||||
directory: string,
|
||||
existingAttachment?: SessionWorktreeAttachment,
|
||||
): Promise<SessionWorktreeAttachment | null> => {
|
||||
try {
|
||||
const canonical = await canonicalizeWorktreeState(directory)
|
||||
const attachment = buildAttachmentFromCanonicalization(canonical, {
|
||||
existingAttachment,
|
||||
fallbackDirectory: directory,
|
||||
})
|
||||
useSessionWorktreeStore.getState().setAttachment(sessionId, attachment)
|
||||
return attachment
|
||||
} catch (error) {
|
||||
console.warn("Failed to canonicalize session worktree state:", error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const resolveSessionDirectory = (
|
||||
sessionId: string | null | undefined,
|
||||
getWtMeta: (id: string) => WorktreeMetadata | undefined,
|
||||
): string | null => {
|
||||
if (!sessionId) return null
|
||||
const attachmentDirectory = getAttachedSessionDirectory(getAttachmentForSession(sessionId))
|
||||
if (attachmentDirectory) return attachmentDirectory
|
||||
const metaPath = getWtMeta(sessionId)?.path
|
||||
if (typeof metaPath === "string" && metaPath.trim().length > 0) return normalizePath(metaPath)
|
||||
const sessions = getAllSyncSessions()
|
||||
@@ -394,6 +426,7 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
|
||||
const previousSessionId = get().currentSessionId
|
||||
const directoryState = useDirectoryStore.getState()
|
||||
const existingAttachment = getAttachmentForSession(id)
|
||||
|
||||
const sessionDir = resolveSessionDirectory(
|
||||
id,
|
||||
@@ -429,6 +462,21 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
if (id) {
|
||||
markSessionViewed(id)
|
||||
setActiveSession(resolvedDir ?? "", id)
|
||||
|
||||
if (resolvedDir && (!existingAttachment || existingAttachment.legacy)) {
|
||||
void recoverSessionAttachment(id, resolvedDir, existingAttachment).then((attachment) => {
|
||||
const canonicalDirectory = getAttachedSessionDirectory(attachment, resolvedDir)
|
||||
if (!canonicalDirectory) return
|
||||
const currentDirectory = normalizePath(useDirectoryStore.getState().currentDirectory ?? null)
|
||||
if (canonicalDirectory === currentDirectory) return
|
||||
try {
|
||||
useDirectoryStore.getState().setDirectory(canonicalDirectory, { showOverlay: false })
|
||||
opencodeClient.setDirectory(canonicalDirectory)
|
||||
} catch (error) {
|
||||
console.warn("Failed to apply canonicalized session directory:", error)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -624,13 +672,30 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
// Stub — was a no-op in old store
|
||||
},
|
||||
|
||||
setWorktreeMetadata: (sessionId, metadata) =>
|
||||
setWorktreeMetadata: (sessionId, metadata) => {
|
||||
// Write to authoritative session-worktree-store
|
||||
if (metadata) {
|
||||
useSessionWorktreeStore.getState().setAttachment(sessionId, {
|
||||
worktreeRoot: metadata.worktreeRoot ?? metadata.path ?? null,
|
||||
cwd: metadata.path ?? null,
|
||||
branch: metadata.branch ?? null,
|
||||
headState: metadata.headState ?? (metadata.branch ? 'branch' : 'detached'),
|
||||
worktreeStatus: metadata.worktreeStatus ?? 'ready',
|
||||
worktreeSource: metadata.worktreeSource ?? null,
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
})
|
||||
} else {
|
||||
useSessionWorktreeStore.getState().clearAttachment(sessionId)
|
||||
}
|
||||
// Also keep local map for backward compatibility
|
||||
set((s) => {
|
||||
const map = new Map(s.worktreeMetadata)
|
||||
if (metadata) map.set(sessionId, metadata)
|
||||
else map.delete(sessionId)
|
||||
return { worktreeMetadata: map }
|
||||
}),
|
||||
})
|
||||
},
|
||||
|
||||
overrideNewSessionDraftTarget: (options) => {
|
||||
let nextDirectory: string | null = null
|
||||
@@ -869,6 +934,11 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
const session = await createSessionAction(title, dir, parentID ?? null)
|
||||
if (!session) return null
|
||||
|
||||
const sessionDirectory = normalizePath((session as { directory?: string }).directory ?? dir ?? null)
|
||||
if (sessionDirectory) {
|
||||
await recoverSessionAttachment(session.id, sessionDirectory)
|
||||
}
|
||||
|
||||
if (targetFolderId) {
|
||||
const scopeKey = directoryOverride || get().lastLoadedDirectory || session.directory
|
||||
if (scopeKey) {
|
||||
@@ -1088,6 +1158,8 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
},
|
||||
|
||||
getDirectoryForSession: (sessionId) => {
|
||||
const attachmentDirectory = getAttachedSessionDirectory(getAttachmentForSession(sessionId))
|
||||
if (attachmentDirectory) return attachmentDirectory
|
||||
const sessions = getAllSyncSessions()
|
||||
const session = sessions.find((s) => s.id === sessionId)
|
||||
if (!session) return null
|
||||
|
||||
@@ -0,0 +1,660 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
buildAttachmentFromCanonicalization,
|
||||
getAttachedSessionDirectory,
|
||||
resolveSessionWorktreeState,
|
||||
formatSessionWorktreeBadge,
|
||||
getSessionWorktreeRepairActions,
|
||||
getMutationBlockingReasons,
|
||||
isWithinWorktreeRoot,
|
||||
buildSessionTargetOptions,
|
||||
} from './session-worktree-contract';
|
||||
|
||||
describe('isWithinWorktreeRoot', () => {
|
||||
test('returns true when candidate equals root', () => {
|
||||
expect(isWithinWorktreeRoot('/repo/worktrees/feat-a', '/repo/worktrees/feat-a')).toBe(true);
|
||||
});
|
||||
|
||||
test('returns true when candidate is a subdirectory of root', () => {
|
||||
expect(isWithinWorktreeRoot('/repo/worktrees/feat-a/src', '/repo/worktrees/feat-a')).toBe(true);
|
||||
});
|
||||
|
||||
test('returns false when candidate is outside root', () => {
|
||||
expect(isWithinWorktreeRoot('/tmp/outside', '/repo/worktrees/feat-a')).toBe(false);
|
||||
});
|
||||
|
||||
test('returns false when either is null/empty', () => {
|
||||
expect(isWithinWorktreeRoot(null, '/repo')).toBe(false);
|
||||
expect(isWithinWorktreeRoot('/repo', null)).toBe(false);
|
||||
expect(isWithinWorktreeRoot('', '/repo')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAttachedSessionDirectory', () => {
|
||||
test('prefers canonical cwd when attachment is healthy', () => {
|
||||
expect(getAttachedSessionDirectory({
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/repo/worktrees/feat-a/src',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
}, '/repo')).toBe('/repo/worktrees/feat-a/src');
|
||||
});
|
||||
|
||||
test('falls back to worktree root when attachment is degraded', () => {
|
||||
expect(getAttachedSessionDirectory({
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/tmp/outside',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'invalid',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: true,
|
||||
}, '/repo')).toBe('/repo/worktrees/feat-a');
|
||||
});
|
||||
|
||||
test('uses fallback when no attachment exists', () => {
|
||||
expect(getAttachedSessionDirectory(null, '/repo')).toBe('/repo');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildAttachmentFromCanonicalization', () => {
|
||||
test('builds a canonical attachment for a healthy current-worktree session', () => {
|
||||
const result = buildAttachmentFromCanonicalization({
|
||||
worktreeRoot: '/repo',
|
||||
cwd: '/repo/src',
|
||||
branch: 'main',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
}, {
|
||||
fallbackDirectory: '/repo/src',
|
||||
});
|
||||
|
||||
expect(result.worktreeRoot).toBe('/repo');
|
||||
expect(result.cwd).toBe('/repo/src');
|
||||
expect(result.branch).toBe('main');
|
||||
expect(result.legacy).toBe(false);
|
||||
});
|
||||
|
||||
test('preserves worktreeSource while recovering a legacy session', () => {
|
||||
const result = buildAttachmentFromCanonicalization({
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/repo/worktrees/feat-a',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
}, {
|
||||
existingAttachment: {
|
||||
worktreeRoot: null,
|
||||
cwd: '/repo/worktrees/feat-a',
|
||||
branch: null,
|
||||
headState: 'detached',
|
||||
worktreeStatus: 'invalid',
|
||||
worktreeSource: 'created-for-session',
|
||||
legacy: true,
|
||||
degraded: true,
|
||||
},
|
||||
fallbackDirectory: '/repo/worktrees/feat-a',
|
||||
});
|
||||
|
||||
expect(result.worktreeSource).toBe('created-for-session');
|
||||
expect(result.legacy).toBe(false);
|
||||
});
|
||||
|
||||
test('uses worktree root as cwd when canonicalization is degraded', () => {
|
||||
const result = buildAttachmentFromCanonicalization({
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/tmp/outside',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'invalid',
|
||||
legacy: true,
|
||||
degraded: true,
|
||||
}, {
|
||||
fallbackDirectory: '/repo/worktrees/feat-a',
|
||||
});
|
||||
|
||||
expect(result.cwd).toBe('/repo/worktrees/feat-a');
|
||||
expect(result.degraded).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveSessionWorktreeState', () => {
|
||||
test('keeps cwd when inside worktreeRoot', () => {
|
||||
const result = resolveSessionWorktreeState({
|
||||
sessionDirectory: '/repo/worktrees/feat-a/src',
|
||||
metadata: {
|
||||
path: '/repo/worktrees/feat-a',
|
||||
projectDirectory: '/repo',
|
||||
branch: 'feat-a',
|
||||
label: 'feat-a',
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
worktreeStatus: 'ready',
|
||||
headState: 'branch',
|
||||
},
|
||||
cwdExists: true,
|
||||
});
|
||||
|
||||
expect(result.cwd).toBe('/repo/worktrees/feat-a/src');
|
||||
expect(result.worktreeRoot).toBe('/repo/worktrees/feat-a');
|
||||
expect(result.degraded).toBe(false);
|
||||
expect(result.worktreeStatus).toBe('ready');
|
||||
expect(result.headState).toBe('branch');
|
||||
});
|
||||
|
||||
test('falls back to worktreeRoot when cwd is invalid', () => {
|
||||
const result = resolveSessionWorktreeState({
|
||||
sessionDirectory: '/tmp/outside',
|
||||
metadata: {
|
||||
path: '/repo/worktrees/feat-a',
|
||||
projectDirectory: '/repo',
|
||||
branch: 'feat-a',
|
||||
label: 'feat-a',
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
worktreeStatus: 'ready',
|
||||
headState: 'branch',
|
||||
},
|
||||
cwdExists: false,
|
||||
});
|
||||
|
||||
expect(result.cwd).toBe('/repo/worktrees/feat-a');
|
||||
expect(result.degraded).toBe(true);
|
||||
});
|
||||
|
||||
test('falls back to worktreeRoot when cwd escapes root', () => {
|
||||
const result = resolveSessionWorktreeState({
|
||||
sessionDirectory: '/repo/worktrees/feat-a/src',
|
||||
metadata: {
|
||||
path: '/repo/worktrees/feat-a',
|
||||
projectDirectory: '/repo',
|
||||
branch: 'feat-a',
|
||||
label: 'feat-a',
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
worktreeStatus: 'ready',
|
||||
headState: 'branch',
|
||||
},
|
||||
cwdExists: true,
|
||||
});
|
||||
|
||||
// cwd is inside worktreeRoot so should be kept
|
||||
expect(result.cwd).toBe('/repo/worktrees/feat-a/src');
|
||||
expect(result.degraded).toBe(false);
|
||||
});
|
||||
|
||||
test('marks missing metadata as legacy with invalid status', () => {
|
||||
const result = resolveSessionWorktreeState({
|
||||
sessionDirectory: '/repo',
|
||||
metadata: null,
|
||||
cwdExists: true,
|
||||
});
|
||||
|
||||
expect(result.legacy).toBe(true);
|
||||
expect(result.worktreeStatus).toBe('invalid');
|
||||
expect(result.degraded).toBe(true);
|
||||
});
|
||||
|
||||
test('preserves unborn head state', () => {
|
||||
const result = resolveSessionWorktreeState({
|
||||
sessionDirectory: '/repo/worktrees/new-branch',
|
||||
metadata: {
|
||||
path: '/repo/worktrees/new-branch',
|
||||
projectDirectory: '/repo',
|
||||
branch: '',
|
||||
label: 'new-branch',
|
||||
worktreeRoot: '/repo/worktrees/new-branch',
|
||||
worktreeStatus: 'ready',
|
||||
headState: 'unborn',
|
||||
},
|
||||
cwdExists: true,
|
||||
});
|
||||
|
||||
expect(result.headState).toBe('unborn');
|
||||
});
|
||||
|
||||
test('recovers legacy session when runtime canonicalization resolves a worktree', () => {
|
||||
const result = resolveSessionWorktreeState({
|
||||
sessionDirectory: '/repo/worktrees/feat-a/src',
|
||||
metadata: null,
|
||||
cwdExists: true,
|
||||
runtimeResolution: {
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/repo/worktrees/feat-a/src',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.legacy).toBe(false);
|
||||
expect(result.worktreeRoot).toBe('/repo/worktrees/feat-a');
|
||||
expect(result.degraded).toBe(false);
|
||||
});
|
||||
|
||||
test('defaults detached when branch is empty but headState not specified', () => {
|
||||
const result = resolveSessionWorktreeState({
|
||||
sessionDirectory: '/repo/worktrees/detached',
|
||||
metadata: {
|
||||
path: '/repo/worktrees/detached',
|
||||
projectDirectory: '/repo',
|
||||
branch: '',
|
||||
label: 'detached',
|
||||
},
|
||||
cwdExists: true,
|
||||
});
|
||||
|
||||
expect(result.headState).toBe('detached');
|
||||
});
|
||||
|
||||
test('canonical producer metadata preserves branch/detached/unborn states', () => {
|
||||
// branch state
|
||||
const branchResult = resolveSessionWorktreeState({
|
||||
sessionDirectory: '/repo/worktrees/feat-a',
|
||||
metadata: {
|
||||
path: '/repo/worktrees/feat-a',
|
||||
projectDirectory: '/repo',
|
||||
branch: 'feat-a',
|
||||
label: 'feat-a',
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
worktreeStatus: 'ready',
|
||||
headState: 'branch',
|
||||
worktreeSource: 'created-for-session',
|
||||
},
|
||||
cwdExists: true,
|
||||
});
|
||||
expect(branchResult.headState).toBe('branch');
|
||||
expect(branchResult.worktreeStatus).toBe('ready');
|
||||
|
||||
// detached state
|
||||
const detachedResult = resolveSessionWorktreeState({
|
||||
sessionDirectory: '/repo/worktrees/detached',
|
||||
metadata: {
|
||||
path: '/repo/worktrees/detached',
|
||||
projectDirectory: '/repo',
|
||||
branch: '',
|
||||
label: 'detached',
|
||||
worktreeRoot: '/repo/worktrees/detached',
|
||||
worktreeStatus: 'ready',
|
||||
headState: 'detached',
|
||||
worktreeSource: 'existing',
|
||||
},
|
||||
cwdExists: true,
|
||||
});
|
||||
expect(detachedResult.headState).toBe('detached');
|
||||
|
||||
// unborn state
|
||||
const unbornResult = resolveSessionWorktreeState({
|
||||
sessionDirectory: '/repo/worktrees/unborn',
|
||||
metadata: {
|
||||
path: '/repo/worktrees/unborn',
|
||||
projectDirectory: '/repo',
|
||||
branch: '',
|
||||
label: 'unborn',
|
||||
worktreeRoot: '/repo/worktrees/unborn',
|
||||
worktreeStatus: 'ready',
|
||||
headState: 'unborn',
|
||||
worktreeSource: 'created-for-session',
|
||||
},
|
||||
cwdExists: true,
|
||||
});
|
||||
expect(unbornResult.headState).toBe('unborn');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatSessionWorktreeBadge', () => {
|
||||
test('formats needs-attention badge for invalid worktree', () => {
|
||||
const badge = formatSessionWorktreeBadge({
|
||||
worktreeStatus: 'invalid',
|
||||
degraded: true,
|
||||
legacy: false,
|
||||
branch: null,
|
||||
headState: 'detached',
|
||||
worktreeRoot: null,
|
||||
cwd: null,
|
||||
worktreeSource: null,
|
||||
});
|
||||
expect(badge).toBe('Needs attention');
|
||||
});
|
||||
|
||||
test('formats legacy session badge', () => {
|
||||
const badge = formatSessionWorktreeBadge({
|
||||
legacy: true,
|
||||
worktreeStatus: 'invalid',
|
||||
degraded: true,
|
||||
branch: null,
|
||||
headState: 'branch',
|
||||
worktreeRoot: null,
|
||||
cwd: null,
|
||||
worktreeSource: null,
|
||||
});
|
||||
expect(badge).toBe('Legacy session');
|
||||
});
|
||||
|
||||
test('formats detached HEAD', () => {
|
||||
const badge = formatSessionWorktreeBadge({
|
||||
headState: 'detached',
|
||||
degraded: false,
|
||||
legacy: false,
|
||||
branch: null,
|
||||
worktreeStatus: 'ready',
|
||||
worktreeRoot: '/repo',
|
||||
cwd: '/repo',
|
||||
worktreeSource: 'existing',
|
||||
});
|
||||
expect(badge).toBe('Detached HEAD');
|
||||
});
|
||||
|
||||
test('formats unborn branch', () => {
|
||||
const badge = formatSessionWorktreeBadge({
|
||||
headState: 'unborn',
|
||||
degraded: false,
|
||||
legacy: false,
|
||||
branch: null,
|
||||
worktreeStatus: 'ready',
|
||||
worktreeRoot: '/repo',
|
||||
cwd: '/repo',
|
||||
worktreeSource: 'existing',
|
||||
});
|
||||
expect(badge).toBe('Unborn branch');
|
||||
});
|
||||
|
||||
test('formats current branch name', () => {
|
||||
const badge = formatSessionWorktreeBadge({
|
||||
branch: 'feature/my-branch',
|
||||
headState: 'branch',
|
||||
degraded: false,
|
||||
legacy: false,
|
||||
worktreeStatus: 'ready',
|
||||
worktreeRoot: '/repo',
|
||||
cwd: '/repo',
|
||||
worktreeSource: 'existing',
|
||||
});
|
||||
expect(badge).toBe('Current branch: feature/my-branch');
|
||||
});
|
||||
|
||||
test('formats missing worktree', () => {
|
||||
const badge = formatSessionWorktreeBadge({
|
||||
worktreeStatus: 'missing',
|
||||
degraded: true,
|
||||
legacy: false,
|
||||
branch: null,
|
||||
headState: 'branch',
|
||||
worktreeRoot: null,
|
||||
cwd: null,
|
||||
worktreeSource: null,
|
||||
});
|
||||
expect(badge).toBe('Worktree missing');
|
||||
});
|
||||
|
||||
test('formats needs-attention for in-progress git operation', () => {
|
||||
const badge = formatSessionWorktreeBadge({
|
||||
worktreeStatus: 'ready',
|
||||
attentionReason: 'merge',
|
||||
degraded: false,
|
||||
legacy: false,
|
||||
branch: 'main',
|
||||
headState: 'branch',
|
||||
worktreeRoot: '/repo',
|
||||
cwd: '/repo',
|
||||
worktreeSource: 'existing',
|
||||
});
|
||||
expect(badge).toBe('Needs attention');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSessionWorktreeRepairActions', () => {
|
||||
test('returns open-without-worktree-features for missing worktree', () => {
|
||||
const actions = getSessionWorktreeRepairActions({
|
||||
worktreeStatus: 'missing',
|
||||
degraded: true,
|
||||
legacy: false,
|
||||
branch: null,
|
||||
headState: 'branch',
|
||||
worktreeRoot: null,
|
||||
cwd: null,
|
||||
worktreeSource: null,
|
||||
});
|
||||
expect(actions).toContain('open-without-worktree-features');
|
||||
});
|
||||
|
||||
test('returns open-without-worktree-features for invalid worktree', () => {
|
||||
const actions = getSessionWorktreeRepairActions({
|
||||
worktreeStatus: 'invalid',
|
||||
degraded: true,
|
||||
legacy: false,
|
||||
branch: null,
|
||||
headState: 'branch',
|
||||
worktreeRoot: null,
|
||||
cwd: null,
|
||||
worktreeSource: null,
|
||||
});
|
||||
expect(actions).toContain('open-without-worktree-features');
|
||||
});
|
||||
|
||||
test('returns empty for ready worktree', () => {
|
||||
const actions = getSessionWorktreeRepairActions({
|
||||
worktreeStatus: 'ready',
|
||||
degraded: false,
|
||||
legacy: false,
|
||||
branch: 'main',
|
||||
headState: 'branch',
|
||||
worktreeRoot: '/repo',
|
||||
cwd: '/repo',
|
||||
worktreeSource: 'existing',
|
||||
});
|
||||
expect(actions).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildSessionTargetOptions', () => {
|
||||
test('labels root directory and isolated worktrees distinctly', () => {
|
||||
const options = buildSessionTargetOptions({
|
||||
projectRoot: '/repo',
|
||||
rootBranch: 'main',
|
||||
worktrees: [
|
||||
{ path: '/repo/.worktrees/feat-a', branch: 'feat-a', label: 'feat-a', projectDirectory: '/repo' },
|
||||
],
|
||||
});
|
||||
|
||||
expect(options[0]?.label).toContain('main');
|
||||
expect(options[1]?.label).toContain('feat-a');
|
||||
expect(options[0]?.kind).toBe('root');
|
||||
expect(options[1]?.kind).toBe('worktree');
|
||||
});
|
||||
|
||||
test('excludes worktree path that equals projectRoot', () => {
|
||||
const options = buildSessionTargetOptions({
|
||||
projectRoot: '/repo',
|
||||
rootBranch: 'main',
|
||||
worktrees: [
|
||||
{ path: '/repo', branch: 'main', label: 'main', projectDirectory: '/repo' },
|
||||
{ path: '/repo/worktrees/feat-a', branch: 'feat-a', label: 'feat-a', projectDirectory: '/repo' },
|
||||
],
|
||||
});
|
||||
|
||||
expect(options).toHaveLength(2); // root + one worktree, not three
|
||||
});
|
||||
|
||||
test('handles empty worktrees array', () => {
|
||||
const options = buildSessionTargetOptions({
|
||||
projectRoot: '/repo',
|
||||
rootBranch: 'main',
|
||||
worktrees: [],
|
||||
});
|
||||
|
||||
expect(options).toHaveLength(1);
|
||||
expect(options[0]?.kind).toBe('root');
|
||||
});
|
||||
|
||||
test('marks pending bootstrap worktree distinctly', () => {
|
||||
const options = buildSessionTargetOptions({
|
||||
projectRoot: '/repo',
|
||||
rootBranch: 'main',
|
||||
worktrees: [
|
||||
{ path: '/repo/worktrees/feat-a', branch: 'feat-a', label: 'feat-a', projectDirectory: '/repo' },
|
||||
{ path: '/repo/worktrees/feat-b', branch: 'feat-b', label: 'feat-b', projectDirectory: '/repo' },
|
||||
],
|
||||
pendingBootstrapDirectory: '/repo/worktrees/feat-b',
|
||||
});
|
||||
|
||||
const root = options.find((o) => o.kind === 'root');
|
||||
const pending = options.find((o) => o.value === '/repo/worktrees/feat-b');
|
||||
const nonPending = options.find((o) => o.value === '/repo/worktrees/feat-a');
|
||||
|
||||
expect(root?.pending).toBeUndefined();
|
||||
expect(pending?.pending).toBe(true);
|
||||
expect(nonPending?.pending).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getMutationBlockingReasons', () => {
|
||||
test('returns empty when attachment is null', () => {
|
||||
expect(getMutationBlockingReasons(null)).toHaveLength(0);
|
||||
expect(getMutationBlockingReasons(undefined)).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('blocks mutation when worktree is missing', () => {
|
||||
const reasons = getMutationBlockingReasons({
|
||||
worktreeRoot: null,
|
||||
cwd: null,
|
||||
branch: null,
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'missing',
|
||||
worktreeSource: null,
|
||||
legacy: false,
|
||||
degraded: true,
|
||||
});
|
||||
expect(reasons).toHaveLength(1);
|
||||
expect(reasons[0]).toEqual({ reason: 'missing' });
|
||||
});
|
||||
|
||||
test('blocks mutation when worktree is invalid', () => {
|
||||
const reasons = getMutationBlockingReasons({
|
||||
worktreeRoot: null,
|
||||
cwd: null,
|
||||
branch: null,
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'invalid',
|
||||
worktreeSource: null,
|
||||
legacy: false,
|
||||
degraded: true,
|
||||
});
|
||||
expect(reasons).toHaveLength(1);
|
||||
expect(reasons[0]).toEqual({ reason: 'invalid' });
|
||||
});
|
||||
|
||||
test('blocks mutation during merge attention state', () => {
|
||||
const reasons = getMutationBlockingReasons({
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/repo/worktrees/feat-a',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
attentionReason: 'merge',
|
||||
});
|
||||
expect(reasons).toHaveLength(1);
|
||||
expect(reasons[0]).toEqual({ reason: 'attention', attentionReason: 'merge' });
|
||||
});
|
||||
|
||||
test('blocks mutation during rebase attention state', () => {
|
||||
const reasons = getMutationBlockingReasons({
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/repo/worktrees/feat-a',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
attentionReason: 'rebase',
|
||||
});
|
||||
expect(reasons).toHaveLength(1);
|
||||
expect(reasons[0]).toEqual({ reason: 'attention', attentionReason: 'rebase' });
|
||||
});
|
||||
|
||||
test('returns empty for ready worktree with no attention', () => {
|
||||
const reasons = getMutationBlockingReasons({
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/repo/worktrees/feat-a',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
});
|
||||
expect(reasons).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('blocks mutation during cherry-pick attention state', () => {
|
||||
const reasons = getMutationBlockingReasons({
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/repo/worktrees/feat-a',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
attentionReason: 'cherry-pick',
|
||||
});
|
||||
expect(reasons).toHaveLength(1);
|
||||
expect(reasons[0]).toEqual({ reason: 'attention', attentionReason: 'cherry-pick' });
|
||||
});
|
||||
|
||||
test('blocks mutation when git status is dirty', () => {
|
||||
const reasons = getMutationBlockingReasons(
|
||||
{ worktreeRoot: '/repo', cwd: '/repo', branch: 'main', headState: 'branch', worktreeStatus: 'ready', worktreeSource: 'existing', legacy: false, degraded: false },
|
||||
{ isClean: false, files: [{ path: 'a.ts' }, { path: 'b.ts' }] }
|
||||
);
|
||||
expect(reasons).toHaveLength(1);
|
||||
expect(reasons[0]).toEqual({ reason: 'dirty', dirtyFiles: 2 });
|
||||
});
|
||||
|
||||
test('blocks mutation for dirty tree even without attachment', () => {
|
||||
const reasons = getMutationBlockingReasons(null, { isClean: false, files: [{ path: 'a.ts' }] });
|
||||
expect(reasons).toHaveLength(1);
|
||||
expect(reasons[0]).toEqual({ reason: 'dirty', dirtyFiles: 1 });
|
||||
});
|
||||
|
||||
test('does not block when git status is clean', () => {
|
||||
const reasons = getMutationBlockingReasons(
|
||||
{ worktreeRoot: '/repo', cwd: '/repo', branch: 'main', headState: 'branch', worktreeStatus: 'ready', worktreeSource: 'existing', legacy: false, degraded: false },
|
||||
{ isClean: true, files: [] }
|
||||
);
|
||||
expect(reasons).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('returns dirty and missing reasons together', () => {
|
||||
const reasons = getMutationBlockingReasons(
|
||||
{ worktreeRoot: '/repo', cwd: '/repo', branch: 'main', headState: 'branch', worktreeStatus: 'missing', worktreeSource: 'existing', legacy: false, degraded: false },
|
||||
{ isClean: false, files: [{ path: 'a.ts' }] }
|
||||
);
|
||||
expect(reasons).toHaveLength(2);
|
||||
expect(reasons[0]).toEqual({ reason: 'dirty', dirtyFiles: 1 });
|
||||
expect(reasons[1]).toEqual({ reason: 'missing' });
|
||||
});
|
||||
|
||||
test('returns dirty without file count when files is undefined', () => {
|
||||
const reasons = getMutationBlockingReasons(
|
||||
null,
|
||||
{ isClean: false }
|
||||
);
|
||||
expect(reasons).toHaveLength(1);
|
||||
expect(reasons[0]).toEqual({ reason: 'dirty' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import type { WorktreeMetadata } from '@/types/worktree';
|
||||
import type { SessionWorktreeAttachment } from '@/stores/types/sessionTypes';
|
||||
|
||||
export type ResolveSessionWorktreeStateInput = {
|
||||
sessionDirectory: string | null;
|
||||
metadata: WorktreeMetadata | null;
|
||||
cwdExists?: boolean;
|
||||
runtimeResolution?: SessionWorktreeAttachment | null;
|
||||
};
|
||||
|
||||
export type WorktreeDirectoryValidation = {
|
||||
valid: boolean;
|
||||
insideWorktreeRoot: boolean;
|
||||
resolvedWorktreeRoot: string | null;
|
||||
resolvedCwd: string | null;
|
||||
};
|
||||
|
||||
export type WorktreeCanonicalizationResult = {
|
||||
worktreeRoot: string | null;
|
||||
cwd: string | null;
|
||||
branch: string | null;
|
||||
headState: 'branch' | 'detached' | 'unborn';
|
||||
worktreeStatus: 'ready' | 'missing' | 'invalid' | 'not-a-repo';
|
||||
legacy: boolean;
|
||||
degraded: boolean;
|
||||
attentionReason?: 'merge' | 'rebase' | 'cherry-pick' | 'revert' | 'bisect' | null;
|
||||
};
|
||||
|
||||
export type SessionWorktreeCanonicalizationOptions = {
|
||||
existingAttachment?: SessionWorktreeAttachment | null;
|
||||
fallbackDirectory?: string | null;
|
||||
worktreeSource?: SessionWorktreeAttachment['worktreeSource'];
|
||||
};
|
||||
|
||||
const normalizePath = (value: string): string => {
|
||||
if (!value) return '';
|
||||
const replaced = value.replace(/\\/g, '/');
|
||||
if (replaced === '/') return '/';
|
||||
return replaced.replace(/\/+$/, '') || replaced;
|
||||
};
|
||||
|
||||
export function isWithinWorktreeRoot(candidate: string | null, worktreeRoot: string | null): boolean {
|
||||
if (!candidate || !worktreeRoot) return false;
|
||||
const c = normalizePath(candidate);
|
||||
const r = normalizePath(worktreeRoot);
|
||||
return c === r || c.startsWith(r + '/');
|
||||
}
|
||||
|
||||
export function getAttachedSessionDirectory(
|
||||
attachment: SessionWorktreeAttachment | null | undefined,
|
||||
fallbackDirectory?: string | null,
|
||||
): string | null {
|
||||
if (attachment) {
|
||||
if (!attachment.degraded && attachment.cwd) {
|
||||
return normalizePath(attachment.cwd);
|
||||
}
|
||||
if (attachment.worktreeRoot) {
|
||||
return normalizePath(attachment.worktreeRoot);
|
||||
}
|
||||
if (attachment.cwd) {
|
||||
return normalizePath(attachment.cwd);
|
||||
}
|
||||
}
|
||||
|
||||
if (fallbackDirectory) {
|
||||
return normalizePath(fallbackDirectory);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function buildAttachmentFromCanonicalization(
|
||||
canonical: WorktreeCanonicalizationResult,
|
||||
options: SessionWorktreeCanonicalizationOptions = {},
|
||||
): SessionWorktreeAttachment {
|
||||
const existingAttachment = options.existingAttachment ?? null;
|
||||
const fallbackDirectory = options.fallbackDirectory ?? null;
|
||||
const preferredDirectory = canonical.degraded
|
||||
? canonical.worktreeRoot ?? canonical.cwd ?? fallbackDirectory
|
||||
: canonical.cwd ?? canonical.worktreeRoot ?? fallbackDirectory;
|
||||
|
||||
return {
|
||||
worktreeRoot: canonical.worktreeRoot ?? fallbackDirectory,
|
||||
cwd: preferredDirectory,
|
||||
branch: canonical.branch ?? existingAttachment?.branch ?? null,
|
||||
headState: canonical.headState,
|
||||
worktreeStatus: canonical.worktreeStatus,
|
||||
worktreeSource: options.worktreeSource ?? existingAttachment?.worktreeSource ?? null,
|
||||
legacy: canonical.legacy,
|
||||
degraded: canonical.degraded,
|
||||
attentionReason: canonical.attentionReason ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveSessionWorktreeState(
|
||||
input: ResolveSessionWorktreeStateInput
|
||||
): SessionWorktreeAttachment {
|
||||
const { sessionDirectory, metadata, cwdExists = true, runtimeResolution } = input;
|
||||
|
||||
if (runtimeResolution) {
|
||||
return {
|
||||
worktreeRoot: runtimeResolution.worktreeRoot ?? metadata?.path ?? sessionDirectory ?? null,
|
||||
cwd: runtimeResolution.cwd ?? sessionDirectory ?? metadata?.path ?? null,
|
||||
branch: runtimeResolution.branch ?? metadata?.branch ?? null,
|
||||
headState: runtimeResolution.headState ?? 'branch',
|
||||
worktreeStatus: runtimeResolution.worktreeStatus ?? 'ready',
|
||||
worktreeSource: runtimeResolution.worktreeSource ?? metadata?.source === 'sdk' ? 'created-for-session' : 'existing',
|
||||
legacy: false,
|
||||
degraded: runtimeResolution.degraded,
|
||||
attentionReason: runtimeResolution.attentionReason ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
if (!metadata) {
|
||||
return {
|
||||
worktreeRoot: sessionDirectory ?? null,
|
||||
cwd: sessionDirectory ?? null,
|
||||
branch: null,
|
||||
headState: 'branch',
|
||||
worktreeStatus: sessionDirectory ? 'invalid' : 'not-a-repo',
|
||||
worktreeSource: null,
|
||||
legacy: true,
|
||||
degraded: true,
|
||||
attentionReason: null,
|
||||
};
|
||||
}
|
||||
|
||||
const worktreeRoot = metadata.worktreeRoot ?? metadata.path;
|
||||
const cwd = sessionDirectory ?? worktreeRoot;
|
||||
|
||||
const cwdValid = cwdExists && (cwd === worktreeRoot || isWithinWorktreeRoot(cwd, worktreeRoot));
|
||||
|
||||
return {
|
||||
worktreeRoot,
|
||||
cwd: cwdValid ? cwd : worktreeRoot,
|
||||
branch: metadata.branch ?? null,
|
||||
headState: metadata.headState ?? (metadata.branch ? 'branch' : 'detached'),
|
||||
worktreeStatus: metadata.worktreeStatus ?? 'ready',
|
||||
worktreeSource: metadata.source === 'sdk' ? 'created-for-session' : 'existing',
|
||||
legacy: false,
|
||||
degraded: !cwdValid,
|
||||
attentionReason: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function formatSessionWorktreeBadge(attachment: SessionWorktreeAttachment): string {
|
||||
if (attachment.legacy) return 'Legacy session';
|
||||
if (attachment.worktreeStatus === 'missing') return 'Worktree missing';
|
||||
if (attachment.worktreeStatus === 'not-a-repo') return 'Not a repo';
|
||||
if (attachment.worktreeStatus === 'invalid') return 'Needs attention';
|
||||
if (attachment.attentionReason) return 'Needs attention';
|
||||
if (attachment.headState === 'detached') return 'Detached HEAD';
|
||||
if (attachment.headState === 'unborn') return 'Unborn branch';
|
||||
if (attachment.branch) return `Current branch: ${attachment.branch}`;
|
||||
return 'No branch';
|
||||
}
|
||||
|
||||
export type SessionWorktreeRepairAction = 'locate' | 'open-without-worktree-features';
|
||||
|
||||
export function getSessionWorktreeRepairActions(
|
||||
attachment: SessionWorktreeAttachment
|
||||
): SessionWorktreeRepairAction[] {
|
||||
if (attachment.worktreeStatus === 'missing' || attachment.worktreeStatus === 'invalid') {
|
||||
return ['open-without-worktree-features'];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export type MutationBlockingReason =
|
||||
| { reason: 'dirty'; dirtyFiles?: number }
|
||||
| { reason: 'attention'; attentionReason: NonNullable<SessionWorktreeAttachment['attentionReason']> }
|
||||
| { reason: 'missing' }
|
||||
| { reason: 'invalid' };
|
||||
|
||||
export type GitStatusForBlocking = {
|
||||
isClean: boolean;
|
||||
files?: unknown[];
|
||||
};
|
||||
|
||||
export function getMutationBlockingReasons(
|
||||
attachment: SessionWorktreeAttachment | null | undefined,
|
||||
gitStatus?: GitStatusForBlocking | null
|
||||
): MutationBlockingReason[] {
|
||||
const reasons: MutationBlockingReason[] = [];
|
||||
if (gitStatus && !gitStatus.isClean) {
|
||||
reasons.push({ reason: 'dirty', dirtyFiles: Array.isArray(gitStatus.files) ? gitStatus.files.length : undefined });
|
||||
}
|
||||
if (!attachment) return reasons;
|
||||
if (attachment.worktreeStatus === 'missing') {
|
||||
reasons.push({ reason: 'missing' });
|
||||
}
|
||||
if (attachment.worktreeStatus === 'invalid') {
|
||||
reasons.push({ reason: 'invalid' });
|
||||
}
|
||||
if (attachment.attentionReason) {
|
||||
reasons.push({ reason: 'attention', attentionReason: attachment.attentionReason });
|
||||
}
|
||||
return reasons;
|
||||
}
|
||||
|
||||
export type SessionTargetOption = {
|
||||
value: string;
|
||||
label: string;
|
||||
kind: 'root' | 'worktree';
|
||||
pending?: boolean;
|
||||
};
|
||||
|
||||
export function buildSessionTargetOptions(input: {
|
||||
projectRoot: string;
|
||||
rootBranch: string;
|
||||
worktrees: Array<{ path: string; branch: string; label: string; projectDirectory: string }>;
|
||||
pendingBootstrapDirectory?: string | null;
|
||||
}): SessionTargetOption[] {
|
||||
const options: SessionTargetOption[] = [];
|
||||
|
||||
if (input.projectRoot) {
|
||||
options.push({
|
||||
value: input.projectRoot,
|
||||
label: input.rootBranch || input.projectRoot.split('/').pop() || input.projectRoot,
|
||||
kind: 'root',
|
||||
});
|
||||
}
|
||||
|
||||
const pendingNormalized = input.pendingBootstrapDirectory
|
||||
? normalizePath(input.pendingBootstrapDirectory)
|
||||
: null;
|
||||
|
||||
for (const wt of input.worktrees) {
|
||||
const normalizedPath = normalizePath(wt.path);
|
||||
if (normalizedPath === input.projectRoot) continue;
|
||||
const isPending = normalizedPath === pendingNormalized;
|
||||
options.push({
|
||||
value: normalizedPath,
|
||||
label: wt.branch?.trim() || wt.label || normalizedPath.split('/').pop() || normalizedPath,
|
||||
kind: 'worktree',
|
||||
pending: isPending || undefined,
|
||||
});
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { useSessionWorktreeStore } from './session-worktree-store';
|
||||
|
||||
describe('session-worktree-store', () => {
|
||||
test('stores and retrieves attachment by session id', () => {
|
||||
const store = useSessionWorktreeStore.getState();
|
||||
store.setAttachment('session-1', {
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/repo/worktrees/feat-a',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'created-for-session',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
});
|
||||
|
||||
const attachment = useSessionWorktreeStore.getState().getAttachment('session-1');
|
||||
expect(attachment?.worktreeRoot).toBe('/repo/worktrees/feat-a');
|
||||
expect(attachment?.branch).toBe('feat-a');
|
||||
});
|
||||
|
||||
test('clears attachment by session id', () => {
|
||||
const store = useSessionWorktreeStore.getState();
|
||||
store.setAttachment('session-2', {
|
||||
worktreeRoot: '/repo/worktrees/feat-b',
|
||||
cwd: '/repo/worktrees/feat-b',
|
||||
branch: 'feat-b',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
});
|
||||
|
||||
store.clearAttachment('session-2');
|
||||
const attachment = useSessionWorktreeStore.getState().getAttachment('session-2');
|
||||
expect(attachment).toBeUndefined();
|
||||
});
|
||||
|
||||
test('multiple sessions have independent attachments', () => {
|
||||
const store = useSessionWorktreeStore.getState();
|
||||
store.setAttachment('session-A', {
|
||||
worktreeRoot: '/repo/worktrees/feat-a',
|
||||
cwd: '/repo/worktrees/feat-a',
|
||||
branch: 'feat-a',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'existing',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
});
|
||||
store.setAttachment('session-B', {
|
||||
worktreeRoot: '/repo/worktrees/feat-b',
|
||||
cwd: '/repo/worktrees/feat-b',
|
||||
branch: 'feat-b',
|
||||
headState: 'branch',
|
||||
worktreeStatus: 'ready',
|
||||
worktreeSource: 'created-for-session',
|
||||
legacy: false,
|
||||
degraded: false,
|
||||
});
|
||||
|
||||
const attA = useSessionWorktreeStore.getState().getAttachment('session-A');
|
||||
const attB = useSessionWorktreeStore.getState().getAttachment('session-B');
|
||||
expect(attA?.branch).toBe('feat-a');
|
||||
expect(attB?.branch).toBe('feat-b');
|
||||
expect(attA?.worktreeSource).toBe('existing');
|
||||
expect(attB?.worktreeSource).toBe('created-for-session');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { create } from 'zustand';
|
||||
import type { SessionWorktreeAttachment } from '@/stores/types/sessionTypes';
|
||||
|
||||
interface SessionWorktreeState {
|
||||
attachments: Map<string, SessionWorktreeAttachment>;
|
||||
}
|
||||
|
||||
interface SessionWorktreeActions {
|
||||
setAttachment(sessionId: string, attachment: SessionWorktreeAttachment): void;
|
||||
getAttachment(sessionId: string): SessionWorktreeAttachment | undefined;
|
||||
clearAttachment(sessionId: string): void;
|
||||
}
|
||||
|
||||
type SessionWorktreeStore = SessionWorktreeState & SessionWorktreeActions;
|
||||
|
||||
export const useSessionWorktreeStore = create<SessionWorktreeStore>((set, get) => ({
|
||||
attachments: new Map(),
|
||||
|
||||
setAttachment: (sessionId, attachment) =>
|
||||
set((s) => {
|
||||
const next = new Map(s.attachments);
|
||||
next.set(sessionId, attachment);
|
||||
return { attachments: next };
|
||||
}),
|
||||
|
||||
getAttachment: (sessionId) => get().attachments.get(sessionId),
|
||||
|
||||
clearAttachment: (sessionId) =>
|
||||
set((s) => {
|
||||
const next = new Map(s.attachments);
|
||||
next.delete(sessionId);
|
||||
return { attachments: next };
|
||||
}),
|
||||
}));
|
||||
Reference in New Issue
Block a user