Files
openchamber/packages/vscode/src/bridge-git-runtime.ts
T
jwcrystalandBohdan Triapitsyn fccf4bad32 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>
2026-04-16 20:13:59 +03:00

439 lines
17 KiB
TypeScript

import * as gitService from './gitService';
import type { BridgeResponse } from './bridge';
type BridgeMessageInput = {
id: string;
type: string;
payload?: unknown;
};
const requireDirectory = (id: string, type: string, directory?: string): BridgeResponse | null => {
if (!directory) {
return { id, type, success: false, error: 'Directory is required' };
}
return null;
};
export async function handleStandardGitBridgeMessage(message: BridgeMessageInput): Promise<BridgeResponse | null> {
const { id, type, payload } = message;
switch (type) {
case 'api:git/check': {
const { directory } = (payload || {}) as { directory?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const isRepo = await gitService.checkIsGitRepository(directory!);
return { id, type, success: true, data: isRepo };
}
case 'api:git/worktree-type': {
const { directory } = (payload || {}) as { directory?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const isLinked = await gitService.isLinkedWorktree(directory!);
return { id, type, success: true, data: isLinked };
}
case 'api:git/status': {
const { directory } = (payload || {}) as { directory?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const status = await gitService.getGitStatus(directory!);
return { id, type, success: true, data: status };
}
case 'api:git/branches': {
const { directory, method, name, startPoint, force } = (payload || {}) as {
directory?: string;
method?: string;
name?: string;
startPoint?: string;
force?: boolean;
};
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const normalizedMethod = typeof method === 'string' ? method.toUpperCase() : 'GET';
if (normalizedMethod === 'GET') {
const branches = await gitService.getGitBranches(directory!);
return { id, type, success: true, data: branches };
}
if (normalizedMethod === 'POST') {
if (!name) {
return { id, type, success: false, error: 'Branch name is required' };
}
const result = await gitService.createBranch(directory!, name, startPoint);
return { id, type, success: true, data: result };
}
if (normalizedMethod === 'DELETE') {
if (!name) {
return { id, type, success: false, error: 'Branch name is required' };
}
const result = await gitService.deleteGitBranch(directory!, name, force);
return { id, type, success: true, data: result };
}
return { id, type, success: false, error: `Unsupported method: ${normalizedMethod}` };
}
case 'api:git/remote-branches': {
const { directory, branch, remote } = (payload || {}) as {
directory?: string;
branch?: string;
remote?: string;
};
if (!directory || !branch) {
return { id, type, success: false, error: 'Directory and branch are required' };
}
const result = await gitService.deleteRemoteBranch(directory, branch, remote);
return { id, type, success: true, data: result };
}
case 'api:git/checkout': {
const { directory, branch } = (payload || {}) as { directory?: string; branch?: string };
if (!directory || !branch) {
return { id, type, success: false, error: 'Directory and branch are required' };
}
const result = await gitService.checkoutBranch(directory, branch);
return { id, type, success: true, data: result };
}
case 'api:git/worktrees': {
const { directory, method } = (payload || {}) as {
directory?: string;
method?: string;
body?: unknown;
directoryPath?: string;
deleteLocalBranch?: boolean;
};
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const normalizedMethod = typeof method === 'string' ? method.toUpperCase() : 'GET';
if (normalizedMethod === 'GET') {
const worktrees = await gitService.listGitWorktrees(directory!);
return { id, type, success: true, data: worktrees };
}
if (normalizedMethod === 'POST') {
const created = await gitService.createWorktree(directory!, (payload || {}) as gitService.CreateGitWorktreePayload);
return { id, type, success: true, data: created };
}
if (normalizedMethod === 'DELETE') {
const removePayload = payload as {
body?: { directory?: string; deleteLocalBranch?: boolean };
directory?: string;
deleteLocalBranch?: boolean;
};
const bodyDirectory = typeof removePayload?.body?.directory === 'string'
? removePayload.body.directory
: '';
const legacyDirectory = typeof removePayload?.directory === 'string' ? removePayload.directory : '';
const worktreeDirectory = bodyDirectory || legacyDirectory || '';
if (!worktreeDirectory) {
return { id, type, success: false, error: 'Worktree directory is required' };
}
const removed = await gitService.removeWorktree(directory!, {
directory: worktreeDirectory,
deleteLocalBranch: removePayload?.body?.deleteLocalBranch === true || removePayload?.deleteLocalBranch === true,
});
return { id, type, success: true, data: { success: Boolean(removed) } };
}
return { id, type, success: false, error: `Unsupported method: ${normalizedMethod}` };
}
case 'api:git/worktrees/validate': {
const { directory } = (payload || {}) as { directory?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.validateWorktreeCreate(directory!, (payload || {}) as gitService.CreateGitWorktreePayload);
return { id, type, success: true, data: result };
}
case 'api:git/worktrees/bootstrap-status': {
const { directory } = (payload || {}) as { directory?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.getWorktreeBootstrapStatus(directory!);
return { id, type, success: true, data: result };
}
case 'api:git/worktrees/preview': {
const { directory } = (payload || {}) as { directory?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.previewWorktreeCreate(directory!, (payload || {}) as gitService.CreateGitWorktreePayload);
return { id, type, success: true, data: result };
}
case 'api:git/validate-directory': {
const { directory, worktreeRoot } = (payload || {}) as { directory?: string; worktreeRoot?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.validateWorktreeDirectory(directory!, worktreeRoot!);
return { id, type, success: true, data: result };
}
case 'api:git/canonicalize-worktree-state': {
const { directory } = (payload || {}) as { directory?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.canonicalizeWorktreeState(directory!);
return { id, type, success: true, data: result };
}
case 'api:git/diff': {
const { directory, path: filePath, staged, contextLines } = (payload || {}) as {
directory?: string;
path?: string;
staged?: boolean;
contextLines?: number;
};
if (!directory || !filePath) {
return { id, type, success: false, error: 'Directory and path are required' };
}
const result = await gitService.getGitDiff(directory, filePath, staged, contextLines);
return { id, type, success: true, data: result };
}
case 'api:git/file-diff': {
const { directory, path: filePath, staged } = (payload || {}) as {
directory?: string;
path?: string;
staged?: boolean;
};
if (!directory || !filePath) {
return { id, type, success: false, error: 'Directory and path are required' };
}
const result = await gitService.getGitFileDiff(directory, filePath, staged);
return { id, type, success: true, data: result };
}
case 'api:git/revert': {
const { directory, path: filePath } = (payload || {}) as { directory?: string; path?: string };
if (!directory || !filePath) {
return { id, type, success: false, error: 'Directory and path are required' };
}
await gitService.revertGitFile(directory, filePath);
return { id, type, success: true, data: { success: true } };
}
case 'api:git/commit': {
const { directory, message, addAll, files } = (payload || {}) as {
directory?: string;
message?: string;
addAll?: boolean;
files?: string[];
};
if (!directory || !message) {
return { id, type, success: false, error: 'Directory and message are required' };
}
const result = await gitService.createGitCommit(directory, message, { addAll, files });
return { id, type, success: true, data: result };
}
case 'api:git/push': {
const { directory, remote, branch, options } = (payload || {}) as {
directory?: string;
remote?: string;
branch?: string;
options?: string[] | Record<string, unknown>;
};
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.gitPush(directory!, { remote, branch, options });
return { id, type, success: true, data: result };
}
case 'api:git/pull': {
const { directory, remote, branch } = (payload || {}) as {
directory?: string;
remote?: string;
branch?: string;
};
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.gitPull(directory!, { remote, branch });
return { id, type, success: true, data: result };
}
case 'api:git/fetch': {
const { directory, remote, branch } = (payload || {}) as {
directory?: string;
remote?: string;
branch?: string;
};
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.gitFetch(directory!, { remote, branch });
return { id, type, success: true, data: result };
}
case 'api:git/remotes': {
const { directory, method, remote } = (payload || {}) as {
directory?: string;
method?: string;
remote?: string;
};
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const normalizedMethod = typeof method === 'string' ? method.toUpperCase() : 'GET';
if (normalizedMethod === 'GET') {
const result = await gitService.getRemotes(directory!);
return { id, type, success: true, data: result };
}
if (normalizedMethod === 'DELETE') {
if (!remote) {
return { id, type, success: false, error: 'Remote name is required' };
}
const result = await gitService.removeRemote(directory!, remote);
return { id, type, success: true, data: result };
}
return { id, type, success: false, error: `Unsupported method: ${normalizedMethod}` };
}
case 'api:git/rebase': {
const { directory, onto } = (payload || {}) as { directory?: string; onto?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
if (!onto) {
return { id, type, success: false, error: 'onto is required' };
}
const result = await gitService.rebase(directory!, { onto });
return { id, type, success: true, data: result };
}
case 'api:git/rebase/abort': {
const { directory } = (payload || {}) as { directory?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.abortRebase(directory!);
return { id, type, success: true, data: result };
}
case 'api:git/merge': {
const { directory, branch } = (payload || {}) as { directory?: string; branch?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
if (!branch) {
return { id, type, success: false, error: 'branch is required' };
}
const result = await gitService.merge(directory!, { branch });
return { id, type, success: true, data: result };
}
case 'api:git/merge/abort': {
const { directory } = (payload || {}) as { directory?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.abortMerge(directory!);
return { id, type, success: true, data: result };
}
case 'api:git/rebase/continue': {
const { directory } = (payload || {}) as { directory?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.continueRebase(directory!);
return { id, type, success: true, data: result };
}
case 'api:git/merge/continue': {
const { directory } = (payload || {}) as { directory?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.continueMerge(directory!);
return { id, type, success: true, data: result };
}
case 'api:git/stash': {
const { directory, message, includeUntracked } = (payload || {}) as {
directory?: string;
message?: string;
includeUntracked?: boolean;
};
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.stash(directory!, { message, includeUntracked });
return { id, type, success: true, data: result };
}
case 'api:git/stash/pop': {
const { directory } = (payload || {}) as { directory?: string };
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.stashPop(directory!);
return { id, type, success: true, data: result };
}
case 'api:git/log': {
const { directory, maxCount, from, to, file } = (payload || {}) as {
directory?: string;
maxCount?: number;
from?: string;
to?: string;
file?: string;
};
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const result = await gitService.getGitLog(directory!, { maxCount, from, to, file });
return { id, type, success: true, data: result };
}
case 'api:git/commit-files': {
const { directory, hash } = (payload || {}) as { directory?: string; hash?: string };
if (!directory || !hash) {
return { id, type, success: false, error: 'Directory and hash are required' };
}
const result = await gitService.getCommitFiles(directory, hash);
return { id, type, success: true, data: result };
}
case 'api:git/identity': {
const { directory, method, userName, userEmail, sshKey } = (payload || {}) as {
directory?: string;
method?: string;
userName?: string;
userEmail?: string;
sshKey?: string | null;
};
const dirError = requireDirectory(id, type, directory);
if (dirError) return dirError;
const normalizedMethod = typeof method === 'string' ? method.toUpperCase() : 'GET';
if (normalizedMethod === 'GET') {
const identity = await gitService.getCurrentGitIdentity(directory!);
return { id, type, success: true, data: identity };
}
if (normalizedMethod === 'POST') {
if (!userName || !userEmail) {
return { id, type, success: false, error: 'userName and userEmail are required' };
}
const result = await gitService.setGitIdentity(directory!, userName, userEmail, sshKey);
return { id, type, success: true, data: result };
}
return { id, type, success: false, error: `Unsupported method: ${normalizedMethod}` };
}
case 'api:git/ignore-openchamber': {
return { id, type, success: true, data: { success: true } };
}
default:
return null;
}
}