Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
de7f96038b |
No files matched your search
@@ -0,0 +1,175 @@
|
||||
# Worktree Management v1
|
||||
|
||||
## Problem
|
||||
|
||||
t3code creates a worktree per thread (`~/.t3/worktrees/<project>/t3code-<hash>`, branch
|
||||
`t3code/<8hex>`) but has almost no lifecycle management. With the settled system, threads
|
||||
are rarely deleted anymore, so worktrees accumulate unboundedly (real case: 186 worktrees).
|
||||
|
||||
Current state:
|
||||
|
||||
- No worktree registry. A worktree exists only as the denormalized `worktree_path` column on
|
||||
`projection_threads` (`apps/server/src/persistence/Layers/ProjectionThreads.ts:41`). Nothing
|
||||
records creation time, last use, or dirty state.
|
||||
- The only cleanup path is the interactive "delete worktree too?" dialog when deleting the
|
||||
last thread that uses one (`apps/web/src/hooks/useThreadActions.ts:253-397`). It is
|
||||
desktop-only (requires `localApi`), so web users always leak worktrees. `thread.delete`
|
||||
on the server never touches the worktree (`apps/server/src/orchestration/decider.ts:381-401`).
|
||||
- `git worktree prune` is never invoked anywhere.
|
||||
- Settling (`settled_override`/`settled_at`) is a projection-level soft-hide; it has no effect
|
||||
on the worktree, so settled threads pin their worktrees forever.
|
||||
- Checkpoint refs (`refs/t3/checkpoints/...`) live in the shared ref store, not in the
|
||||
worktree's private git dir, so removing a worktree does not lose checkpoints. Branches are
|
||||
likewise repo-level. This is what makes lossless revival possible.
|
||||
|
||||
## Decisions (locked)
|
||||
|
||||
1. **Worktrees only in v1.** No branch deletion, no checkpoint-ref GC. Branches are cheap and
|
||||
keeping them makes revival trivial. Merged-branch cleanup can be a later tier.
|
||||
2. **No safety-snapshot-before-delete.** Auto-prune only ever touches *safe* worktrees. Users
|
||||
may force-delete a dirty worktree, but the UI must make clear that this is destructive and
|
||||
the uncommitted state cannot be restored later — that's on them.
|
||||
3. **Never auto-prune dirty worktrees.** Instead, surface them in the Worktrees settings page
|
||||
as "needs attention": e.g. *"This worktree has had no activity for N days, but has
|
||||
uncommitted changes so it won't be deleted automatically."*
|
||||
4. **Global policy settings only.** Per-project overrides are an application-wide capability
|
||||
we don't have yet; out of scope.
|
||||
5. **Orphan handling is configurable.** A setting chooses whether orphaned worktrees (no
|
||||
thread references them) are deleted immediately when they become orphaned, or just fall
|
||||
under the normal inactivity schedule.
|
||||
6. **CLI is a stretch goal and must be super minimal** (`t3 worktrees list` / `prune`), or
|
||||
dropped from v1 entirely.
|
||||
|
||||
## Definitions
|
||||
|
||||
**Worktree record** (derived, not persisted): for each entry in `git worktree list --porcelain`
|
||||
under the project's worktrees dir, joined against thread rows sharing that normalized path:
|
||||
|
||||
- `path`, `branch`
|
||||
- linked threads: id, title, effective settled state, deleted state
|
||||
- `dirty` (working-tree changes, via existing `localStatus` — `GitManager.ts:856-864`)
|
||||
- `unpushed` (`aheadCount` / `aheadOfDefaultCount` / `hasUpstream` via `remoteStatus`)
|
||||
- `prState` (merged / open / none, already available on the remote status result)
|
||||
- `lastActivity`: max of linked threads' last activity / `settled_at`; fallback to worktree
|
||||
dir mtime for orphans
|
||||
- `orphaned`: no non-deleted thread references the path
|
||||
- `safeToPrune`: see below
|
||||
|
||||
**Safe to prune** = ALL of:
|
||||
|
||||
- no *active* (unsettled, undeleted) thread references the worktree
|
||||
- working tree clean
|
||||
- branch merged, or fully pushed (`hasUpstream && aheadCount == 0`), or contains no commits
|
||||
beyond its recorded merge-base (`aheadOfDefaultCount == 0`)
|
||||
- path is inside the managed worktrees dir and is not the project `workspaceRoot`
|
||||
|
||||
**Auto-prunable** = safeToPrune AND (orphaned with "delete orphans immediately" enabled, OR
|
||||
`lastActivity` older than the configured inactivity window).
|
||||
|
||||
## Components
|
||||
|
||||
### 1. Worktree inventory service (server)
|
||||
|
||||
New Effect service (e.g. `apps/server/src/vcs/WorktreeInventory.ts`) that produces the derived
|
||||
records above per project. Scan via `git worktree list --porcelain` (driver already parses
|
||||
this at `GitVcsDriverCore.ts:2121-2164` for branch annotation — extract/reuse). Status via
|
||||
existing `GitManager.localStatus`/`remoteStatus` (already ~1s cached). Short TTL cache on the
|
||||
assembled inventory; a full status sweep across 186 worktrees is not free, so statuses should
|
||||
be fetched lazily/batched and the settings page should render the list first and stream
|
||||
status in.
|
||||
|
||||
Exposed over WS RPC alongside the existing `vcsCreateWorktree`/`vcsRemoveWorktree`
|
||||
(`apps/server/src/ws.ts:1838-1849`): `vcsListWorktrees` (inventory) and
|
||||
`vcsPruneWorktrees` (bulk delete of a provided safe set, server re-validates safety before
|
||||
each removal — never trust the client's classification).
|
||||
|
||||
### 2. Worktrees settings page (web)
|
||||
|
||||
Follow the appearance-settings pattern:
|
||||
|
||||
- route `apps/web/src/routes/settings.worktrees.tsx`
|
||||
- `WorktreesSettingsPanel` in `apps/web/src/components/settings/SettingsPanels.tsx`
|
||||
- nav entry + path union in `apps/web/src/components/settings/SettingsSidebarNav.tsx:26-49`
|
||||
|
||||
Content:
|
||||
|
||||
- List of managed worktrees with badges: dirty, unpushed, merged, orphaned, settled-only,
|
||||
linked-thread count. Sort: needs-attention first, then by lastActivity ascending.
|
||||
- "Needs attention" grouping for dirty-but-inactive worktrees with the explanatory copy from
|
||||
decision 3.
|
||||
- Filtering (client-side over the loaded inventory — no new RPC surface):
|
||||
- free-text search matching branch name, directory name, and linked thread titles
|
||||
- project filter (the page is global; with several projects the list interleaves otherwise)
|
||||
- status filter chips, multi-select: needs attention / safe to prune / dirty / unpushed /
|
||||
orphaned / settled-only
|
||||
- the bulk "Prune N safe worktrees" action operates on the *filtered* set when filters are
|
||||
active, and the button label must reflect that (e.g. "Prune 12 safe worktrees (filtered)")
|
||||
- filter state is ephemeral (not persisted) in v1
|
||||
- Row actions: delete (safe rows: plain confirm; dirty/unpushed rows: destructive-styled
|
||||
confirm spelling out that uncommitted changes / unpushed commits are permanently lost).
|
||||
- Bulk action: "Prune N safe worktrees".
|
||||
- Policy controls (global):
|
||||
- auto-prune enabled on/off
|
||||
- inactivity window: 7 / 14 (default) / 30 days
|
||||
- "delete orphaned worktrees immediately" toggle
|
||||
- Deleting never deletes threads; threads keep their `branch`/`worktreePath` metadata for
|
||||
revival.
|
||||
|
||||
Open implementation question: where the policy settings persist. The sweep runs server-side,
|
||||
so the policy must be server-readable — unlike e.g. `sidebarAutoSettleAfterDays`, which is a
|
||||
client-side setting (`BetaSettingsPanel.tsx:12-14`). Resolve during implementation: either an
|
||||
existing server-persisted settings mechanism if one exists, or a small server settings
|
||||
store + RPC.
|
||||
|
||||
### 3. Auto-prune sweep (server)
|
||||
|
||||
Periodic loop on the `ProviderSessionReaper` pattern
|
||||
(`apps/server/src/provider/Layers/ProviderSessionReaper.ts:106-131` — `Effect.forkScoped` +
|
||||
`Schedule.spaced`), started from `serverRuntimeStartup.ts` like the reaper (`:345`). Cadence:
|
||||
hourly-ish; exact interval is uninteresting as long as it also runs once shortly after startup.
|
||||
|
||||
Each sweep, per project: build inventory → remove auto-prunable worktrees via existing
|
||||
`removeWorktree` (`GitVcsDriverCore.ts:2393-2405`, without `--force` — a non-forced
|
||||
`git worktree remove` refusing due to unexpected dirt is a desirable last-line safety net) →
|
||||
finish with `git worktree prune` (new driver op) to clear stale admin entries. Log a concise
|
||||
summary event/line of what was removed and what was skipped-with-reason (feeds the
|
||||
"needs attention" UI).
|
||||
|
||||
Also handle decision 5's immediate mode: when `thread.delete` orphans a worktree and the
|
||||
"delete orphans immediately" setting is on, the server removes it (if safe) without any
|
||||
client dialog — this replaces the desktop-only prompt path as the mechanism; the web/desktop
|
||||
delete flow keeps its dialog purely as UX when the setting is off.
|
||||
|
||||
### 4. Revival on unsettle
|
||||
|
||||
When a thread becomes active again (explicit unsettle, or the existing auto-unsettle-on-
|
||||
activity in `decider.ts:785-799` etc.) — or when a turn starts — and its `worktreePath` no
|
||||
longer exists on disk: recreate it in `bootstrap.prepareWorktree` (`ws.ts:1011-1041`) via
|
||||
`git worktree add <path> <branch>` on the thread's existing branch (branch always survives
|
||||
v1 pruning). If the branch is somehow gone (user deleted it manually), fail with a clear
|
||||
error offering to recreate from the base branch. Checkpoint refs survive pruning, so
|
||||
diff/revert history remains intact after revival.
|
||||
|
||||
### 5. Minimal CLI (stretch)
|
||||
|
||||
`t3 worktrees list` (table from the inventory) and `t3 worktrees prune [--dry-run]`
|
||||
(safe set only; no force flag in v1). New file in `apps/server/src/cli/`, patterned on
|
||||
`project.ts`. Cut first if v1 needs trimming — the settings page's bulk prune covers the
|
||||
acute 186-worktree cleanup.
|
||||
|
||||
## Build order
|
||||
|
||||
1. Inventory service + `vcsListWorktrees`/`vcsPruneWorktrees` RPC
|
||||
2. Worktrees settings page (observability + manual/bulk delete) — solves the acute pain
|
||||
3. Policy settings + auto-prune sweep + orphan-immediate handling + server-side removal on
|
||||
thread delete
|
||||
4. Revival on missing worktree
|
||||
5. CLI (stretch)
|
||||
|
||||
## Out of scope for v1
|
||||
|
||||
- Branch deletion / checkpoint-ref GC
|
||||
- Safety snapshots of dirty state before deletion
|
||||
- Per-project policy overrides
|
||||
- Any migration/backfill beyond what the inventory naturally surfaces (existing orphans just
|
||||
show up as prunable)
|
||||
@@ -76,6 +76,7 @@ import * as WorkspacePaths from "../src/workspace/WorkspacePaths.ts";
|
||||
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
|
||||
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
|
||||
import { WorktreeService } from "../src/vcs/WorktreeService.ts";
|
||||
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
|
||||
import * as AgentAwarenessRelay from "../src/relay/AgentAwarenessRelay.ts";
|
||||
|
||||
@@ -379,6 +380,11 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(providerRegistryLayer),
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(RepositoryIdentityResolver.layer),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(WorktreeService, {
|
||||
reviveWorktree: () => Effect.succeed({ revived: false }),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
|
||||
@@ -60,6 +60,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Clock from "effect/Clock";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
import { WorktreeService } from "../../vcs/WorktreeService.ts";
|
||||
import * as GitWorkflowService from "../../git/GitWorkflowService.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
@@ -378,6 +379,11 @@ describe("ProviderCommandReactor", () => {
|
||||
generateThreadTitle,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(WorktreeService, {
|
||||
reviveWorktree: () => Effect.succeed({ revived: false }),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
} from "../../serverSettings.ts";
|
||||
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
|
||||
import { WorktreeService } from "../../vcs/WorktreeService.ts";
|
||||
const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);
|
||||
const isProviderDriverKind = Schema.is(ProviderDriverKind);
|
||||
|
||||
@@ -196,6 +197,7 @@ const make = Effect.gen(function* () {
|
||||
const providerService = yield* ProviderService;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const worktreeService = yield* WorktreeService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
@@ -495,6 +497,26 @@ const make = Effect.gen(function* () {
|
||||
thread,
|
||||
projects: project ? [project] : [],
|
||||
});
|
||||
// A pruned (or manually deleted) worktree is recreated from the thread's
|
||||
// branch before the provider session starts in it.
|
||||
if (thread.worktreePath !== null && thread.branch !== null && project) {
|
||||
yield* worktreeService
|
||||
.reviveWorktree({
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
worktreePath: thread.worktreePath,
|
||||
branch: thread.branch,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: providerErrorLabel(preferredProvider),
|
||||
method: "thread.turn.start",
|
||||
detail: `Could not restore the thread's worktree: ${error.message}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const startProviderSession = (input?: {
|
||||
readonly resumeCursor?: unknown;
|
||||
|
||||
@@ -3,10 +3,15 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ProjectionThreadRepository } from "../../persistence/Services/ProjectionThreads.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import * as TerminalManager from "../../terminal/Manager.ts";
|
||||
import { WorktreeService } from "../../vcs/WorktreeService.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
ThreadDeletionReactor,
|
||||
@@ -40,6 +45,10 @@ const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const terminalManager = yield* TerminalManager.TerminalManager;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const worktreeService = yield* WorktreeService;
|
||||
const threadRepository = yield* ProjectionThreadRepository;
|
||||
const pathService = yield* Path.Path;
|
||||
|
||||
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
@@ -55,12 +64,47 @@ const make = Effect.gen(function* () {
|
||||
threadId,
|
||||
});
|
||||
|
||||
const pruneOrphanedWorktree = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: Effect.gen(function* () {
|
||||
const settings = yield* serverSettings.getSettings;
|
||||
if (!settings.worktrees.deleteOrphanedImmediately) {
|
||||
return;
|
||||
}
|
||||
const thread = Option.getOrNull(yield* threadRepository.getById({ threadId }));
|
||||
if (thread === null || thread.worktreePath === null) {
|
||||
return;
|
||||
}
|
||||
const worktreePath = pathService.resolve(thread.worktreePath);
|
||||
const { worktrees } = yield* worktreeService.listWorktrees({
|
||||
projectId: thread.projectId,
|
||||
});
|
||||
const record = worktrees.find((worktree) => worktree.path === worktreePath);
|
||||
// Only orphans qualify here; worktrees still referenced by settled
|
||||
// threads stay on the inactivity schedule. pruneWorktrees re-checks
|
||||
// full safety (clean, pushed, no active thread) before removal.
|
||||
if (record === undefined || !record.orphaned || !record.safeToPrune) {
|
||||
return;
|
||||
}
|
||||
const result = yield* worktreeService.pruneWorktrees({ paths: [record.path] });
|
||||
if (result.removed.length > 0) {
|
||||
yield* Effect.logInfo("thread deletion pruned orphaned worktree", {
|
||||
threadId,
|
||||
worktreePath: record.path,
|
||||
});
|
||||
}
|
||||
}),
|
||||
message: "thread deletion cleanup skipped orphaned worktree prune",
|
||||
threadId,
|
||||
});
|
||||
|
||||
const processThreadDeleted = Effect.fn("processThreadDeleted")(function* (
|
||||
event: ThreadDeletedEvent,
|
||||
) {
|
||||
const { threadId } = event.payload;
|
||||
yield* stopProviderSession(threadId);
|
||||
yield* closeThreadTerminals(threadId);
|
||||
yield* pruneOrphanedWorktree(threadId);
|
||||
});
|
||||
|
||||
const processThreadDeletedSafely = (event: ThreadDeletedEvent) =>
|
||||
|
||||
@@ -103,6 +103,7 @@ import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
|
||||
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriver from "./vcs/VcsDriver.ts";
|
||||
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as WorktreeService from "./vcs/WorktreeService.ts";
|
||||
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
@@ -335,6 +336,7 @@ const buildAppUnderTest = (options?: {
|
||||
>;
|
||||
reviewService?: Partial<ReviewService.ReviewService["Service"]>;
|
||||
vcsStatusBroadcaster?: Partial<VcsStatusBroadcaster.VcsStatusBroadcaster["Service"]>;
|
||||
worktreeService?: Partial<WorktreeService.WorktreeService["Service"]>;
|
||||
projectSetupScriptRunner?: Partial<
|
||||
ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]
|
||||
>;
|
||||
@@ -517,6 +519,9 @@ const buildAppUnderTest = (options?: {
|
||||
const vcsProvisioningLayer = VcsProvisioningService.layer.pipe(
|
||||
Layer.provide(vcsDriverRegistryLayer),
|
||||
);
|
||||
const worktreeServiceLayer = Layer.mock(WorktreeService.WorktreeService)({
|
||||
...options?.layers?.worktreeService,
|
||||
});
|
||||
const reviewLayer = options?.layers?.reviewService
|
||||
? Layer.mock(ReviewService.ReviewService)({
|
||||
...options.layers.reviewService,
|
||||
@@ -641,7 +646,7 @@ const buildAppUnderTest = (options?: {
|
||||
Layer.provide(gitVcsDriverLayer),
|
||||
Layer.provide(gitWorkflowLayer),
|
||||
Layer.provide(reviewLayer),
|
||||
Layer.provide(vcsProvisioningLayer),
|
||||
Layer.provide(Layer.mergeAll(vcsProvisioningLayer, worktreeServiceLayer)),
|
||||
Layer.provide(
|
||||
Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
|
||||
...options?.layers?.sourceControlRepositoryService,
|
||||
|
||||
@@ -65,6 +65,8 @@ import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
|
||||
import * as VcsProcess from "./vcs/VcsProcess.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as WorktreeReaper from "./vcs/WorktreeReaper.ts";
|
||||
import * as WorktreeService from "./vcs/WorktreeService.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as ReviewService from "./review/ReviewService.ts";
|
||||
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
|
||||
@@ -229,6 +231,12 @@ const ReviewLayerLive = ReviewService.layer.pipe(
|
||||
);
|
||||
|
||||
const VcsLayerLive = Layer.empty.pipe(
|
||||
// Listed first so the later provideMerge entries (GitWorkflowLayerLive and
|
||||
// friends) feed its requirements; projection repositories and server
|
||||
// settings arrive from layers merged after VcsLayerLive in the runtime
|
||||
// chain.
|
||||
Layer.provideMerge(WorktreeReaper.layer),
|
||||
Layer.provideMerge(WorktreeService.layer),
|
||||
Layer.provideMerge(VcsProjectConfig.layer),
|
||||
Layer.provideMerge(VcsDriverRegistryLayerLive),
|
||||
Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
|
||||
|
||||
@@ -34,6 +34,7 @@ import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
|
||||
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
|
||||
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
|
||||
import * as ProviderSessionReaper from "./provider/Services/ProviderSessionReaper.ts";
|
||||
import * as WorktreeReaper from "./vcs/WorktreeReaper.ts";
|
||||
import {
|
||||
formatHeadlessServeOutput,
|
||||
formatHostForUrl,
|
||||
@@ -293,6 +294,7 @@ export const make = Effect.gen(function* () {
|
||||
const keybindings = yield* Keybindings.Keybindings;
|
||||
const orchestrationReactor = yield* OrchestrationReactor.OrchestrationReactor;
|
||||
const providerSessionReaper = yield* ProviderSessionReaper.ProviderSessionReaper;
|
||||
const worktreeReaper = yield* WorktreeReaper.WorktreeReaper;
|
||||
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
@@ -343,6 +345,7 @@ export const make = Effect.gen(function* () {
|
||||
Effect.gen(function* () {
|
||||
yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));
|
||||
yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));
|
||||
yield* worktreeReaper.start().pipe(Scope.provide(reactorScope));
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* WorktreeReaper - Periodic auto-prune sweep for managed worktrees.
|
||||
*
|
||||
* Applies the `worktrees` server-settings policy: removes safe-to-prune
|
||||
* worktrees whose last activity is older than the configured inactivity
|
||||
* window, plus orphaned ones when "delete orphaned immediately" is enabled.
|
||||
* Safety is re-validated by WorktreeService.pruneWorktrees on every removal,
|
||||
* and dirty worktrees are never touched.
|
||||
*
|
||||
* @module WorktreeReaper
|
||||
*/
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { WorktreeService } from "./WorktreeService.ts";
|
||||
|
||||
const DEFAULT_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
|
||||
const DEFAULT_INITIAL_DELAY_MS = 2 * 60 * 1000;
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export interface WorktreeReaperOptions {
|
||||
readonly sweepIntervalMs?: number;
|
||||
readonly initialDelayMs?: number;
|
||||
}
|
||||
|
||||
export class WorktreeReaper extends Context.Service<
|
||||
WorktreeReaper,
|
||||
{
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
/** One sweep pass; exposed for tests and the reactor-triggered path. */
|
||||
readonly sweep: Effect.Effect<void>;
|
||||
}
|
||||
>()("t3/vcs/WorktreeReaper") {}
|
||||
|
||||
export const makeWorktreeReaper = (options?: WorktreeReaperOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const worktreeService = yield* WorktreeService;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
|
||||
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
|
||||
const initialDelayMs = Math.max(0, options?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS);
|
||||
|
||||
const runSweep = Effect.gen(function* () {
|
||||
const settings = yield* serverSettings.getSettings;
|
||||
const policy = settings.worktrees;
|
||||
if (policy.autoPruneAfterDays === null && !policy.deleteOrphanedImmediately) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { worktrees } = yield* worktreeService.listWorktrees({});
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const cutoffMs =
|
||||
policy.autoPruneAfterDays === null ? null : now - policy.autoPruneAfterDays * DAY_MS;
|
||||
|
||||
const candidates = worktrees.filter((worktree) => {
|
||||
if (!worktree.safeToPrune) return false;
|
||||
if (policy.deleteOrphanedImmediately && worktree.orphaned) return true;
|
||||
if (cutoffMs === null || worktree.lastActivityAt === null) return false;
|
||||
const lastActivityMs = Date.parse(worktree.lastActivityAt);
|
||||
return !Number.isNaN(lastActivityMs) && lastActivityMs < cutoffMs;
|
||||
});
|
||||
if (candidates.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = yield* worktreeService.pruneWorktrees({
|
||||
paths: candidates.map((worktree) => worktree.path),
|
||||
});
|
||||
yield* Effect.logInfo("worktree.reaper.sweep-complete", {
|
||||
candidateCount: candidates.length,
|
||||
removedCount: result.removed.length,
|
||||
skippedCount: result.skipped.length,
|
||||
autoPruneAfterDays: policy.autoPruneAfterDays,
|
||||
deleteOrphanedImmediately: policy.deleteOrphanedImmediately,
|
||||
});
|
||||
});
|
||||
|
||||
const sweep = runSweep.pipe(
|
||||
Effect.catch((error: unknown) =>
|
||||
Effect.logWarning("worktree.reaper.sweep-failed", { error }),
|
||||
),
|
||||
Effect.catchDefect((defect: unknown) =>
|
||||
Effect.logWarning("worktree.reaper.sweep-defect", { defect }),
|
||||
),
|
||||
);
|
||||
|
||||
const start = () =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.forkScoped(
|
||||
Effect.sleep(Duration.millis(initialDelayMs)).pipe(
|
||||
Effect.andThen(
|
||||
sweep.pipe(Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs)))),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* Effect.logInfo("worktree.reaper.started", {
|
||||
sweepIntervalMs,
|
||||
initialDelayMs,
|
||||
});
|
||||
});
|
||||
|
||||
return WorktreeReaper.of({ start, sweep });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(WorktreeReaper, makeWorktreeReaper());
|
||||
|
||||
export const layerWith = (options: WorktreeReaperOptions) =>
|
||||
Layer.effect(WorktreeReaper, makeWorktreeReaper(options));
|
||||
@@ -0,0 +1,275 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type VcsStatusLocalResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { GitWorkflowService } from "../git/GitWorkflowService.ts";
|
||||
import {
|
||||
type ProjectionProject,
|
||||
ProjectionProjectRepository,
|
||||
} from "../persistence/Services/ProjectionProjects.ts";
|
||||
import {
|
||||
type ProjectionThread,
|
||||
ProjectionThreadRepository,
|
||||
} from "../persistence/Services/ProjectionThreads.ts";
|
||||
import * as GitVcsDriver from "./GitVcsDriver.ts";
|
||||
import * as VcsProcess from "./VcsProcess.ts";
|
||||
import { layer as worktreeServiceLayer, WorktreeService } from "./WorktreeService.ts";
|
||||
|
||||
const PROJECT_ID = ProjectId.make("project-worktrees-test");
|
||||
|
||||
let projectRows: ProjectionProject[] = [];
|
||||
let threadRows: ProjectionThread[] = [];
|
||||
|
||||
const projectRepositoryMock = Layer.mock(ProjectionProjectRepository, {
|
||||
listAll: () => Effect.succeed(projectRows),
|
||||
});
|
||||
|
||||
const threadRepositoryMock = Layer.mock(ProjectionThreadRepository, {
|
||||
listByProjectId: ({ projectId }) =>
|
||||
Effect.succeed(threadRows.filter((thread) => thread.projectId === projectId)),
|
||||
});
|
||||
|
||||
// WorktreeService only touches localStatus/createWorktree/removeWorktree on
|
||||
// the workflow service; back those with the real git driver so the test
|
||||
// exercises real git behavior without GitManager's heavy dependency set.
|
||||
const gitWorkflowMock = Layer.effect(
|
||||
GitWorkflowService,
|
||||
Effect.gen(function* () {
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
const localStatus = (input: { readonly cwd: string }) =>
|
||||
driver
|
||||
.execute({
|
||||
operation: "WorktreeServiceTest.localStatus",
|
||||
cwd: input.cwd,
|
||||
args: ["status", "--porcelain"],
|
||||
timeoutMs: 10_000,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(result): VcsStatusLocalResult => ({
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: result.stdout.trim().length > 0,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
),
|
||||
);
|
||||
const mocked = Layer.mock(GitWorkflowService, {
|
||||
localStatus,
|
||||
createWorktree: driver.createWorktree,
|
||||
removeWorktree: driver.removeWorktree,
|
||||
});
|
||||
return yield* Effect.provide(Effect.service(GitWorkflowService), mocked);
|
||||
}),
|
||||
);
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-worktree-service-test-",
|
||||
});
|
||||
|
||||
const TestLayer = worktreeServiceLayer.pipe(
|
||||
Layer.provide(gitWorkflowMock),
|
||||
Layer.provide(projectRepositoryMock),
|
||||
Layer.provide(threadRepositoryMock),
|
||||
Layer.provideMerge(GitVcsDriver.layer),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runGit = (cwd: string, args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
yield* driver.execute({
|
||||
operation: "WorktreeServiceTest.git",
|
||||
cwd,
|
||||
args,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
});
|
||||
|
||||
function makeThread(
|
||||
overrides: Partial<ProjectionThread> & Pick<ProjectionThread, "threadId">,
|
||||
): ProjectionThread {
|
||||
return {
|
||||
projectId: PROJECT_ID,
|
||||
title: "Test thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurnId: null,
|
||||
createdAt: "2026-07-01T00:00:00.000Z",
|
||||
updatedAt: "2026-07-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
hasActionableProposedPlan: 0,
|
||||
deletedAt: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const setupRepoWithWorktrees = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
|
||||
const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-worktree-repo-",
|
||||
});
|
||||
yield* runGit(workspaceRoot, ["init", "-b", "main"]);
|
||||
yield* runGit(workspaceRoot, ["config", "user.email", "[email protected]"]);
|
||||
yield* runGit(workspaceRoot, ["config", "user.name", "Test"]);
|
||||
yield* fileSystem.writeFileString(path.join(workspaceRoot, "README.md"), "hello\n");
|
||||
yield* runGit(workspaceRoot, ["add", "README.md"]);
|
||||
yield* runGit(workspaceRoot, ["commit", "-m", "initial"]);
|
||||
|
||||
const activeWorktree = yield* driver.createWorktree({
|
||||
cwd: workspaceRoot,
|
||||
refName: "main",
|
||||
newRefName: "t3code/aaaa1111",
|
||||
path: null,
|
||||
});
|
||||
const settledWorktree = yield* driver.createWorktree({
|
||||
cwd: workspaceRoot,
|
||||
refName: "main",
|
||||
newRefName: "t3code/bbbb2222",
|
||||
path: null,
|
||||
});
|
||||
|
||||
projectRows = [
|
||||
{
|
||||
projectId: PROJECT_ID,
|
||||
title: "Worktrees Test",
|
||||
workspaceRoot,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-07-01T00:00:00.000Z",
|
||||
updatedAt: "2026-07-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
},
|
||||
];
|
||||
threadRows = [
|
||||
makeThread({
|
||||
threadId: ThreadId.make("thread-active"),
|
||||
branch: "t3code/aaaa1111",
|
||||
worktreePath: activeWorktree.worktree.path,
|
||||
updatedAt: "2026-07-20T00:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
threadId: ThreadId.make("thread-settled"),
|
||||
branch: "t3code/bbbb2222",
|
||||
worktreePath: settledWorktree.worktree.path,
|
||||
settledOverride: "settled",
|
||||
settledAt: "2026-07-10T00:00:00.000Z",
|
||||
updatedAt: "2026-07-10T00:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
return {
|
||||
workspaceRoot,
|
||||
activeWorktreePath: activeWorktree.worktree.path,
|
||||
settledWorktreePath: settledWorktree.worktree.path,
|
||||
};
|
||||
});
|
||||
|
||||
it.layer(TestLayer)("WorktreeService", (it) => {
|
||||
it.effect("classifies, prunes safely, and revives worktrees", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const service = yield* WorktreeService;
|
||||
const repo = yield* setupRepoWithWorktrees;
|
||||
|
||||
// Inventory: the active thread blocks its worktree, the settled one is
|
||||
// safe (clean, no upstream, no commits beyond the default branch).
|
||||
const inventory = yield* service.listWorktrees({});
|
||||
assert.equal(inventory.worktrees.length, 2);
|
||||
const activeRecord = inventory.worktrees.find(
|
||||
(worktree) => worktree.branch === "t3code/aaaa1111",
|
||||
);
|
||||
const settledRecord = inventory.worktrees.find(
|
||||
(worktree) => worktree.branch === "t3code/bbbb2222",
|
||||
);
|
||||
assert.isDefined(activeRecord);
|
||||
assert.isDefined(settledRecord);
|
||||
assert.isFalse(activeRecord?.safeToPrune);
|
||||
assert.deepEqual(activeRecord?.pruneBlockers, ["active_thread"]);
|
||||
assert.isFalse(activeRecord?.orphaned);
|
||||
assert.isTrue(settledRecord?.safeToPrune);
|
||||
assert.equal(settledRecord?.dirty, false);
|
||||
assert.equal(settledRecord?.threads[0]?.status, "settled");
|
||||
assert.equal(settledRecord?.lastActivityAt, "2026-07-10T00:00:00.000Z");
|
||||
|
||||
// A dirty settled worktree loses its safety and reports the blocker.
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(repo.settledWorktreePath, "scratch.txt"),
|
||||
"uncommitted\n",
|
||||
);
|
||||
const dirtyInventory = yield* service.listWorktrees({});
|
||||
const dirtyRecord = dirtyInventory.worktrees.find(
|
||||
(worktree) => worktree.branch === "t3code/bbbb2222",
|
||||
);
|
||||
assert.isFalse(dirtyRecord?.safeToPrune);
|
||||
assert.deepEqual(dirtyRecord?.pruneBlockers, ["dirty"]);
|
||||
yield* fileSystem.remove(path.join(repo.settledWorktreePath, "scratch.txt"));
|
||||
|
||||
// Prune re-validates: the active-thread worktree is skipped, the safe
|
||||
// one is removed from disk, and the branch survives.
|
||||
const canonicalSettledPath = yield* fileSystem.realPath(repo.settledWorktreePath);
|
||||
const pruneResult = yield* service.pruneWorktrees({
|
||||
paths: [repo.activeWorktreePath, repo.settledWorktreePath],
|
||||
});
|
||||
assert.equal(pruneResult.removed.length, 1);
|
||||
assert.equal(pruneResult.removed[0]?.path, canonicalSettledPath);
|
||||
assert.equal(pruneResult.skipped.length, 1);
|
||||
assert.equal(pruneResult.skipped[0]?.reason, "active_thread");
|
||||
assert.isFalse(yield* fileSystem.exists(repo.settledWorktreePath));
|
||||
const branchList = yield* Effect.gen(function* () {
|
||||
const driver = yield* GitVcsDriver.GitVcsDriver;
|
||||
return yield* driver.execute({
|
||||
operation: "WorktreeServiceTest.branchList",
|
||||
cwd: repo.workspaceRoot,
|
||||
args: ["branch", "--list", "t3code/bbbb2222"],
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
});
|
||||
assert.include(branchList.stdout, "t3code/bbbb2222");
|
||||
|
||||
// Revival recreates the pruned worktree from the surviving branch.
|
||||
const revived = yield* service.reviveWorktree({
|
||||
workspaceRoot: repo.workspaceRoot,
|
||||
worktreePath: repo.settledWorktreePath,
|
||||
branch: "t3code/bbbb2222",
|
||||
});
|
||||
assert.isTrue(revived.revived);
|
||||
assert.isTrue(yield* fileSystem.exists(repo.settledWorktreePath));
|
||||
const revivedAgain = yield* service.reviveWorktree({
|
||||
workspaceRoot: repo.workspaceRoot,
|
||||
worktreePath: repo.settledWorktreePath,
|
||||
branch: "t3code/bbbb2222",
|
||||
});
|
||||
assert.isFalse(revivedAgain.revived);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,574 @@
|
||||
/**
|
||||
* WorktreeService - Managed worktree inventory and safe pruning.
|
||||
*
|
||||
* Derives per-project worktree records by joining `git worktree list` output
|
||||
* against projected thread rows, classifies each worktree's prune safety from
|
||||
* purely local git state (no forge API calls), and removes safe worktrees.
|
||||
*
|
||||
* Worktree removal never deletes branches or checkpoint refs, so pruning a
|
||||
* safe worktree is lossless: the thread keeps its `branch`/`worktreePath`
|
||||
* metadata and the worktree can be recreated from the branch later.
|
||||
*
|
||||
* @module WorktreeService
|
||||
*/
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import {
|
||||
GitManagerError,
|
||||
type GitManagerServiceError,
|
||||
type ProjectId,
|
||||
type VcsListWorktreesInput,
|
||||
type VcsListWorktreesResult,
|
||||
type VcsPruneWorktreesInput,
|
||||
type VcsPruneWorktreesResult,
|
||||
type WorktreeInfo,
|
||||
type WorktreePruneBlocker,
|
||||
type WorktreePruneSkipReason,
|
||||
type WorktreeThreadRef,
|
||||
type WorktreeThreadStatus,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { GitWorkflowService } from "../git/GitWorkflowService.ts";
|
||||
import { ProjectionProjectRepository } from "../persistence/Services/ProjectionProjects.ts";
|
||||
import {
|
||||
type ProjectionThread,
|
||||
ProjectionThreadRepository,
|
||||
} from "../persistence/Services/ProjectionThreads.ts";
|
||||
import * as GitVcsDriver from "./GitVcsDriver.ts";
|
||||
|
||||
const WORKTREE_STATUS_CONCURRENCY = 8;
|
||||
const PROJECT_SCAN_CONCURRENCY = 4;
|
||||
|
||||
export class WorktreeService extends Context.Service<
|
||||
WorktreeService,
|
||||
{
|
||||
/** Inventory of managed worktrees across all (or one) projects. */
|
||||
readonly listWorktrees: (
|
||||
input: VcsListWorktreesInput,
|
||||
) => Effect.Effect<VcsListWorktreesResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Remove the requested worktrees after re-validating each one is still
|
||||
* safe to prune. Never forces: git itself refuses dirty removals as a
|
||||
* last line of defense. Finishes with `git worktree prune` on every
|
||||
* touched repository.
|
||||
*/
|
||||
readonly pruneWorktrees: (
|
||||
input: VcsPruneWorktreesInput,
|
||||
) => Effect.Effect<VcsPruneWorktreesResult, GitManagerServiceError>;
|
||||
|
||||
/**
|
||||
* Recreate a previously pruned worktree from its still-existing branch.
|
||||
* No-op when the directory already exists. Fails with a clear error when
|
||||
* the branch is gone (e.g. deleted manually).
|
||||
*/
|
||||
readonly reviveWorktree: (input: {
|
||||
readonly workspaceRoot: string;
|
||||
readonly worktreePath: string;
|
||||
readonly branch: string;
|
||||
}) => Effect.Effect<{ readonly revived: boolean }, GitManagerServiceError>;
|
||||
}
|
||||
>()("t3/vcs/WorktreeService") {}
|
||||
|
||||
interface ParsedWorktreeEntry {
|
||||
readonly path: string;
|
||||
readonly branch: string | null;
|
||||
}
|
||||
|
||||
function parseWorktreeListPorcelain(stdout: string): ParsedWorktreeEntry[] {
|
||||
const entries: ParsedWorktreeEntry[] = [];
|
||||
let currentPath: string | null = null;
|
||||
let currentBranch: string | null = null;
|
||||
const flush = () => {
|
||||
if (currentPath !== null) {
|
||||
entries.push({ path: currentPath, branch: currentBranch });
|
||||
}
|
||||
currentPath = null;
|
||||
currentBranch = null;
|
||||
};
|
||||
for (const line of stdout.split("\n")) {
|
||||
if (line.startsWith("worktree ")) {
|
||||
flush();
|
||||
currentPath = line.slice("worktree ".length);
|
||||
} else if (line.startsWith("branch refs/heads/")) {
|
||||
currentBranch = line.slice("branch refs/heads/".length);
|
||||
} else if (line === "") {
|
||||
flush();
|
||||
}
|
||||
}
|
||||
flush();
|
||||
return entries;
|
||||
}
|
||||
|
||||
interface BranchSyncInfo {
|
||||
readonly upstream: string | null;
|
||||
/** Upstream configured but its remote ref no longer exists (deleted after merge). */
|
||||
readonly upstreamGone: boolean;
|
||||
readonly aheadOfUpstreamCount: number | null;
|
||||
readonly behindUpstreamCount: number | null;
|
||||
}
|
||||
|
||||
function parseBranchSyncInfo(stdout: string): Map<string, BranchSyncInfo> {
|
||||
const result = new Map<string, BranchSyncInfo>();
|
||||
for (const line of stdout.split("\n")) {
|
||||
if (line.length === 0) continue;
|
||||
const [name, upstream = "", track = ""] = line.split("\t");
|
||||
if (!name) continue;
|
||||
if (upstream.length === 0) {
|
||||
result.set(name, {
|
||||
upstream: null,
|
||||
upstreamGone: false,
|
||||
aheadOfUpstreamCount: null,
|
||||
behindUpstreamCount: null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (track === "gone") {
|
||||
result.set(name, {
|
||||
upstream,
|
||||
upstreamGone: true,
|
||||
aheadOfUpstreamCount: null,
|
||||
behindUpstreamCount: null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const aheadMatch = /(?:^|, )ahead (\d+)/.exec(track);
|
||||
const behindMatch = /(?:^|, )behind (\d+)/.exec(track);
|
||||
result.set(name, {
|
||||
upstream,
|
||||
upstreamGone: false,
|
||||
aheadOfUpstreamCount: aheadMatch ? Number(aheadMatch[1]) : 0,
|
||||
behindUpstreamCount: behindMatch ? Number(behindMatch[1]) : 0,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function threadStatus(thread: ProjectionThread): WorktreeThreadStatus {
|
||||
if (thread.deletedAt !== null) return "deleted";
|
||||
if (thread.archivedAt !== null) return "archived";
|
||||
if (thread.settledOverride === "settled") return "settled";
|
||||
return "active";
|
||||
}
|
||||
|
||||
function latestIsoTimestamp(values: ReadonlyArray<string>): string | null {
|
||||
let latest: string | null = null;
|
||||
let latestMs = Number.NEGATIVE_INFINITY;
|
||||
for (const value of values) {
|
||||
const ms = Date.parse(value);
|
||||
if (!Number.isNaN(ms) && ms > latestMs) {
|
||||
latestMs = ms;
|
||||
latest = value;
|
||||
}
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const { worktreesDir } = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
const gitWorkflow = yield* GitWorkflowService;
|
||||
const projectRepository = yield* ProjectionProjectRepository;
|
||||
const threadRepository = yield* ProjectionThreadRepository;
|
||||
|
||||
// Canonicalize through symlinks (macOS /var → /private/var) so paths from
|
||||
// `git worktree list` compare equal to configured and stored paths.
|
||||
const canonicalizePath = (value: string) =>
|
||||
fs.realPath(value).pipe(Effect.orElseSucceed(() => pathService.resolve(value)));
|
||||
|
||||
const managedWorktreesRoot = yield* canonicalizePath(worktreesDir);
|
||||
|
||||
const isManagedWorktreePath = (worktreePath: string): boolean => {
|
||||
const relative = pathService.relative(managedWorktreesRoot, worktreePath);
|
||||
return relative.length > 0 && !relative.startsWith("..") && !pathService.isAbsolute(relative);
|
||||
};
|
||||
|
||||
const toGitManagerError = (operation: string, cwd: string, detail: string) => (cause: unknown) =>
|
||||
new GitManagerError({ operation, cwd, detail, cause });
|
||||
|
||||
const executeGitLenient = (operation: string, cwd: string, args: ReadonlyArray<string>) =>
|
||||
git
|
||||
.execute({ operation, cwd, args, allowNonZeroExit: true, timeoutMs: 15_000 })
|
||||
.pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout : null)));
|
||||
|
||||
const resolveDefaultRef = Effect.fn("WorktreeService.resolveDefaultRef")(function* (cwd: string) {
|
||||
const originHead = yield* executeGitLenient("WorktreeService.resolveDefaultRef", cwd, [
|
||||
"symbolic-ref",
|
||||
"refs/remotes/origin/HEAD",
|
||||
]);
|
||||
if (originHead !== null && originHead.trim().length > 0) {
|
||||
return originHead.trim();
|
||||
}
|
||||
for (const candidate of ["refs/heads/main", "refs/heads/master"]) {
|
||||
const exists = yield* git
|
||||
.execute({
|
||||
operation: "WorktreeService.resolveDefaultRef.localFallback",
|
||||
cwd,
|
||||
args: ["show-ref", "--verify", "--quiet", candidate],
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
})
|
||||
.pipe(Effect.map((result) => result.exitCode === 0));
|
||||
if (exists) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const countAheadOfDefault = Effect.fn("WorktreeService.countAheadOfDefault")(function* (
|
||||
cwd: string,
|
||||
branch: string,
|
||||
defaultRef: string,
|
||||
) {
|
||||
const stdout = yield* executeGitLenient("WorktreeService.countAheadOfDefault", cwd, [
|
||||
"rev-list",
|
||||
"--count",
|
||||
`refs/heads/${branch}`,
|
||||
"--not",
|
||||
defaultRef,
|
||||
]);
|
||||
if (stdout === null) return null;
|
||||
const count = Number(stdout.trim());
|
||||
return Number.isNaN(count) ? null : count;
|
||||
});
|
||||
|
||||
const worktreeDirMtime = (worktreePath: string) =>
|
||||
fs.stat(worktreePath).pipe(
|
||||
Effect.map((info) =>
|
||||
Option.match(info.mtime, {
|
||||
onNone: () => null,
|
||||
onSome: (mtime) => mtime.toISOString(),
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
|
||||
const listProjectWorktrees = Effect.fn("WorktreeService.listProjectWorktrees")(
|
||||
function* (project: {
|
||||
readonly projectId: ProjectId;
|
||||
readonly title: string;
|
||||
readonly workspaceRoot: string;
|
||||
}) {
|
||||
const worktreeListStdout = yield* executeGitLenient(
|
||||
"WorktreeService.listProjectWorktrees.worktreeList",
|
||||
project.workspaceRoot,
|
||||
["worktree", "list", "--porcelain"],
|
||||
).pipe(
|
||||
// A missing or non-git workspace root contributes no worktrees rather
|
||||
// than failing the whole inventory.
|
||||
Effect.catchCause(() => Effect.succeed(null)),
|
||||
);
|
||||
if (worktreeListStdout === null) {
|
||||
return [] as WorktreeInfo[];
|
||||
}
|
||||
|
||||
const rawEntries = parseWorktreeListPorcelain(worktreeListStdout);
|
||||
const entries = (yield* Effect.forEach(rawEntries, (entry) =>
|
||||
canonicalizePath(entry.path).pipe(
|
||||
Effect.map((canonical) => ({ ...entry, path: canonical })),
|
||||
),
|
||||
)).filter((entry) => isManagedWorktreePath(entry.path));
|
||||
if (entries.length === 0) {
|
||||
return [] as WorktreeInfo[];
|
||||
}
|
||||
|
||||
const [threads, branchSyncStdout, defaultRef] = yield* Effect.all(
|
||||
[
|
||||
threadRepository
|
||||
.listByProjectId({ projectId: project.projectId })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
toGitManagerError(
|
||||
"WorktreeService.listProjectWorktrees.threads",
|
||||
project.workspaceRoot,
|
||||
"Failed to load projected threads for the worktree inventory.",
|
||||
),
|
||||
),
|
||||
),
|
||||
executeGitLenient(
|
||||
"WorktreeService.listProjectWorktrees.branchSync",
|
||||
project.workspaceRoot,
|
||||
[
|
||||
"for-each-ref",
|
||||
"refs/heads",
|
||||
"--format=%(refname:short)%09%(upstream:short)%09%(upstream:track,nobracket)",
|
||||
],
|
||||
),
|
||||
resolveDefaultRef(project.workspaceRoot),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const branchSync = parseBranchSyncInfo(branchSyncStdout ?? "");
|
||||
const threadsByWorktreePath = new Map<string, ProjectionThread[]>();
|
||||
for (const thread of threads) {
|
||||
if (thread.worktreePath === null) continue;
|
||||
const resolved = yield* canonicalizePath(thread.worktreePath);
|
||||
const bucket = threadsByWorktreePath.get(resolved);
|
||||
if (bucket) {
|
||||
bucket.push(thread);
|
||||
} else {
|
||||
threadsByWorktreePath.set(resolved, [thread]);
|
||||
}
|
||||
}
|
||||
|
||||
return yield* Effect.forEach(
|
||||
entries,
|
||||
(entry) =>
|
||||
Effect.gen(function* () {
|
||||
const resolvedPath = entry.path;
|
||||
const branchName = entry.branch;
|
||||
const linkedThreads = threadsByWorktreePath.get(resolvedPath) ?? [];
|
||||
const threadRefs: WorktreeThreadRef[] = linkedThreads.map((thread) => ({
|
||||
threadId: thread.threadId,
|
||||
title: thread.title,
|
||||
status: threadStatus(thread),
|
||||
}));
|
||||
const orphaned = threadRefs.every((thread) => thread.status === "deleted");
|
||||
|
||||
const workingTree = yield* gitWorkflow.localStatus({ cwd: entry.path }).pipe(
|
||||
Effect.map((status) => ({
|
||||
dirty: status.hasWorkingTreeChanges as boolean | null,
|
||||
dirtyFileCount: status.workingTree.files.length as number | null,
|
||||
})),
|
||||
Effect.catchCause(() => Effect.succeed({ dirty: null, dirtyFileCount: null })),
|
||||
);
|
||||
const dirty = workingTree.dirty;
|
||||
|
||||
const sync = branchName === null ? undefined : branchSync.get(branchName);
|
||||
const hasUpstream = sync === undefined ? null : sync.upstream !== null;
|
||||
const upstreamGone = sync?.upstreamGone ?? false;
|
||||
const aheadOfUpstreamCount = sync?.aheadOfUpstreamCount ?? null;
|
||||
const behindUpstreamCount = sync?.behindUpstreamCount ?? null;
|
||||
// Only spend a rev-list on branches that cannot prove safety via
|
||||
// their upstream tracking state.
|
||||
const needsDefaultComparison =
|
||||
sync === undefined || sync.upstream === null || sync.upstreamGone;
|
||||
const aheadOfDefaultCount =
|
||||
branchName !== null && defaultRef !== null && needsDefaultComparison
|
||||
? yield* countAheadOfDefault(project.workspaceRoot, branchName, defaultRef)
|
||||
: null;
|
||||
|
||||
const nonDeletedActivity = latestIsoTimestamp(
|
||||
linkedThreads.filter((thread) => thread.deletedAt === null).map((t) => t.updatedAt),
|
||||
);
|
||||
const anyThreadActivity =
|
||||
nonDeletedActivity ?? latestIsoTimestamp(linkedThreads.map((t) => t.updatedAt));
|
||||
const lastActivityAt = anyThreadActivity ?? (yield* worktreeDirMtime(entry.path));
|
||||
|
||||
const blockers: WorktreePruneBlocker[] = [];
|
||||
if (threadRefs.some((thread) => thread.status === "active")) {
|
||||
blockers.push("active_thread");
|
||||
}
|
||||
if (dirty === true) {
|
||||
blockers.push("dirty");
|
||||
} else if (dirty === null) {
|
||||
blockers.push("status_unavailable");
|
||||
}
|
||||
if (branchName === null) {
|
||||
// Detached HEAD: no branch retains this worktree's commits.
|
||||
blockers.push("status_unavailable");
|
||||
} else if (sync !== undefined && sync.upstream !== null && !sync.upstreamGone) {
|
||||
if (aheadOfUpstreamCount === null) {
|
||||
blockers.push("status_unavailable");
|
||||
} else if (aheadOfUpstreamCount > 0) {
|
||||
blockers.push("unpushed");
|
||||
}
|
||||
} else if (sync !== undefined && sync.upstreamGone) {
|
||||
// The branch was pushed and its remote ref was deleted — the usual
|
||||
// post-merge state. The local branch keeps the commits, so this is
|
||||
// not "unpushed".
|
||||
} else if (aheadOfDefaultCount === null) {
|
||||
blockers.push("status_unavailable");
|
||||
} else if (aheadOfDefaultCount > 0) {
|
||||
blockers.push("unpushed");
|
||||
}
|
||||
|
||||
return {
|
||||
projectId: project.projectId,
|
||||
projectTitle: project.title,
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
path: resolvedPath,
|
||||
branch: branchName,
|
||||
threads: threadRefs,
|
||||
orphaned,
|
||||
dirty,
|
||||
dirtyFileCount: workingTree.dirtyFileCount,
|
||||
hasUpstream,
|
||||
upstreamGone,
|
||||
aheadOfUpstreamCount,
|
||||
behindUpstreamCount,
|
||||
aheadOfDefaultCount,
|
||||
lastActivityAt,
|
||||
safeToPrune: blockers.length === 0,
|
||||
pruneBlockers: blockers,
|
||||
} satisfies WorktreeInfo;
|
||||
}),
|
||||
{ concurrency: WORKTREE_STATUS_CONCURRENCY },
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const listWorktrees: WorktreeService["Service"]["listWorktrees"] = Effect.fn(
|
||||
"WorktreeService.listWorktrees",
|
||||
)(function* (input) {
|
||||
const projects = yield* projectRepository
|
||||
.listAll()
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
toGitManagerError(
|
||||
"WorktreeService.listWorktrees.projects",
|
||||
managedWorktreesRoot,
|
||||
"Failed to load projects for the worktree inventory.",
|
||||
),
|
||||
),
|
||||
);
|
||||
const selectedProjects = projects.filter(
|
||||
(project) =>
|
||||
project.deletedAt === null &&
|
||||
(input.projectId === undefined || project.projectId === input.projectId),
|
||||
);
|
||||
|
||||
const perProject = yield* Effect.forEach(
|
||||
selectedProjects,
|
||||
(project) => listProjectWorktrees(project),
|
||||
{ concurrency: PROJECT_SCAN_CONCURRENCY },
|
||||
);
|
||||
|
||||
// Two projects can point at the same repository; keep the first record
|
||||
// per worktree path.
|
||||
const seen = new Set<string>();
|
||||
const worktrees: WorktreeInfo[] = [];
|
||||
for (const record of perProject.flat()) {
|
||||
if (seen.has(record.path)) continue;
|
||||
seen.add(record.path);
|
||||
worktrees.push(record);
|
||||
}
|
||||
worktrees.sort((a, b) => {
|
||||
const aMs = a.lastActivityAt === null ? 0 : Date.parse(a.lastActivityAt);
|
||||
const bMs = b.lastActivityAt === null ? 0 : Date.parse(b.lastActivityAt);
|
||||
return aMs - bMs;
|
||||
});
|
||||
return { worktrees };
|
||||
});
|
||||
|
||||
const pruneWorktrees: WorktreeService["Service"]["pruneWorktrees"] = Effect.fn(
|
||||
"WorktreeService.pruneWorktrees",
|
||||
)(function* (input) {
|
||||
// Re-derive the inventory so safety reflects the current state, never a
|
||||
// stale client view.
|
||||
const { worktrees } = yield* listWorktrees({});
|
||||
const byPath = new Map(worktrees.map((worktree) => [worktree.path, worktree]));
|
||||
|
||||
const removed: Array<{ path: string; workspaceRoot: string }> = [];
|
||||
const skipped: Array<{ path: string; reason: WorktreePruneSkipReason; detail?: string }> = [];
|
||||
const touchedRoots = new Set<string>();
|
||||
|
||||
for (const requestedPath of input.paths) {
|
||||
const worktree = byPath.get(yield* canonicalizePath(requestedPath));
|
||||
if (worktree === undefined) {
|
||||
skipped.push({ path: requestedPath, reason: "unknown_worktree" });
|
||||
continue;
|
||||
}
|
||||
if (!worktree.safeToPrune) {
|
||||
skipped.push({
|
||||
path: worktree.path,
|
||||
reason: worktree.pruneBlockers[0] ?? "status_unavailable",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const removalError = yield* gitWorkflow
|
||||
.removeWorktree({ cwd: worktree.workspaceRoot, path: worktree.path })
|
||||
.pipe(
|
||||
Effect.as(null),
|
||||
Effect.catch((error) => Effect.succeed(error)),
|
||||
);
|
||||
if (removalError !== null) {
|
||||
skipped.push({
|
||||
path: worktree.path,
|
||||
reason: "remove_failed",
|
||||
detail: removalError.message,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
removed.push({ path: worktree.path, workspaceRoot: worktree.workspaceRoot });
|
||||
touchedRoots.add(worktree.workspaceRoot);
|
||||
}
|
||||
|
||||
yield* Effect.forEach(
|
||||
[...touchedRoots],
|
||||
(workspaceRoot) =>
|
||||
executeGitLenient("WorktreeService.pruneWorktrees.gitPrune", workspaceRoot, [
|
||||
"worktree",
|
||||
"prune",
|
||||
]).pipe(Effect.ignore({ log: true })),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
if (removed.length > 0) {
|
||||
yield* Effect.logInfo("worktrees.pruned", {
|
||||
removedCount: removed.length,
|
||||
skippedCount: skipped.length,
|
||||
removedPaths: removed.map((entry) => entry.path),
|
||||
});
|
||||
}
|
||||
|
||||
return { removed, skipped };
|
||||
});
|
||||
|
||||
const reviveWorktree: WorktreeService["Service"]["reviveWorktree"] = Effect.fn(
|
||||
"WorktreeService.reviveWorktree",
|
||||
)(function* (input) {
|
||||
const exists = yield* fs.exists(input.worktreePath).pipe(Effect.orElseSucceed(() => false));
|
||||
if (exists) {
|
||||
return { revived: false };
|
||||
}
|
||||
|
||||
const branchExists = yield* git
|
||||
.execute({
|
||||
operation: "WorktreeService.reviveWorktree.branchExists",
|
||||
cwd: input.workspaceRoot,
|
||||
args: ["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`],
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 5_000,
|
||||
})
|
||||
.pipe(Effect.map((result) => result.exitCode === 0));
|
||||
if (!branchExists) {
|
||||
return yield* new GitManagerError({
|
||||
operation: "WorktreeService.reviveWorktree",
|
||||
cwd: input.workspaceRoot,
|
||||
detail: `Cannot recreate the worktree at ${input.worktreePath}: branch '${input.branch}' no longer exists.`,
|
||||
});
|
||||
}
|
||||
|
||||
// A manually deleted worktree directory leaves a stale registration that
|
||||
// blocks `git worktree add` at the same path.
|
||||
yield* executeGitLenient("WorktreeService.reviveWorktree.prune", input.workspaceRoot, [
|
||||
"worktree",
|
||||
"prune",
|
||||
]);
|
||||
yield* gitWorkflow.createWorktree({
|
||||
cwd: input.workspaceRoot,
|
||||
refName: input.branch,
|
||||
path: input.worktreePath,
|
||||
});
|
||||
yield* Effect.logInfo("worktree.revived", {
|
||||
worktreePath: input.worktreePath,
|
||||
branch: input.branch,
|
||||
});
|
||||
return { revived: true };
|
||||
});
|
||||
|
||||
return WorktreeService.of({ listWorktrees, pruneWorktrees, reviveWorktree });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(WorktreeService, make);
|
||||
@@ -96,6 +96,7 @@ import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
|
||||
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
|
||||
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
|
||||
import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as WorktreeService from "./vcs/WorktreeService.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as ReviewService from "./review/ReviewService.ts";
|
||||
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
|
||||
@@ -341,6 +342,8 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.vcsListRefs, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsCreateWorktree, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.vcsRemoveWorktree, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.vcsListWorktrees, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsPruneWorktrees, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.vcsCreateRef, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.vcsSwitchRef, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.vcsInit, AuthOrchestrationOperateScope],
|
||||
@@ -427,6 +430,7 @@ const makeWsRpcLayer = (
|
||||
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
const review = yield* ReviewService.ReviewService;
|
||||
const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService;
|
||||
const worktreeService = yield* WorktreeService.WorktreeService;
|
||||
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
const terminalManager = yield* TerminalManager.TerminalManager;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
@@ -1847,6 +1851,26 @@ const makeWsRpcLayer = (
|
||||
gitWorkflow.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
),
|
||||
[WS_METHODS.vcsListWorktrees]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.vcsListWorktrees, worktreeService.listWorktrees(input), {
|
||||
"rpc.aggregate": "vcs",
|
||||
}),
|
||||
[WS_METHODS.vcsPruneWorktrees]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsPruneWorktrees,
|
||||
worktreeService
|
||||
.pruneWorktrees(input)
|
||||
.pipe(
|
||||
Effect.tap((result) =>
|
||||
Effect.forEach(
|
||||
[...new Set(result.removed.map((entry) => entry.workspaceRoot))],
|
||||
(workspaceRoot) => refreshGitStatus(workspaceRoot),
|
||||
{ discard: true },
|
||||
).pipe(Effect.ignore({ log: true })),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "vcs" },
|
||||
),
|
||||
[WS_METHODS.vcsCreateRef]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.vcsCreateRef,
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
ArrowLeftIcon,
|
||||
BotIcon,
|
||||
FlaskConicalIcon,
|
||||
FolderGit2Icon,
|
||||
GitBranchIcon,
|
||||
KeyboardIcon,
|
||||
Link2Icon,
|
||||
@@ -29,6 +30,7 @@ export type SettingsSectionPath =
|
||||
| "/settings/keybindings"
|
||||
| "/settings/providers"
|
||||
| "/settings/source-control"
|
||||
| "/settings/worktrees"
|
||||
| "/settings/connections"
|
||||
| "/settings/beta"
|
||||
| "/settings/archived";
|
||||
@@ -43,6 +45,7 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
|
||||
{ label: "Keybindings", to: "/settings/keybindings", icon: KeyboardIcon },
|
||||
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
|
||||
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
|
||||
{ label: "Worktrees", to: "/settings/worktrees", icon: FolderGit2Icon },
|
||||
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
|
||||
{ label: "Beta", to: "/settings/beta", icon: FlaskConicalIcon },
|
||||
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
|
||||
|
||||
@@ -0,0 +1,709 @@
|
||||
import { FolderGit2Icon, LoaderIcon, RefreshCwIcon, Trash2Icon } from "lucide-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import type { WorktreeInfo, WorktreePruneSkipReason } from "@t3tools/contracts";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
import { usePrimaryEnvironment } from "../../state/environments";
|
||||
import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { vcsEnvironment } from "../../state/vcs";
|
||||
import { formatRelativeTimeLabel } from "../../timestampFormat";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import { Input } from "../ui/input";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
|
||||
import { stackedThreadToast, toastManager } from "../ui/toast";
|
||||
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
|
||||
|
||||
const ALL_PROJECTS = "all";
|
||||
|
||||
const AUTO_PRUNE_OPTIONS: ReadonlyArray<{ value: string; label: string }> = [
|
||||
{ value: "off", label: "Never" },
|
||||
{ value: "7", label: "After 7 days" },
|
||||
{ value: "14", label: "After 14 days" },
|
||||
{ value: "30", label: "After 30 days" },
|
||||
];
|
||||
|
||||
type StatusFilter = "attention" | "safe" | "dirty" | "unpushed" | "orphaned" | "settled";
|
||||
|
||||
const STATUS_FILTERS: ReadonlyArray<{ key: StatusFilter; label: string }> = [
|
||||
{ key: "attention", label: "Needs attention" },
|
||||
{ key: "safe", label: "Safe to prune" },
|
||||
{ key: "dirty", label: "Dirty" },
|
||||
{ key: "unpushed", label: "Unpushed" },
|
||||
{ key: "orphaned", label: "Orphaned" },
|
||||
{ key: "settled", label: "Settled" },
|
||||
];
|
||||
|
||||
const SKIP_REASON_LABEL: Record<WorktreePruneSkipReason, string> = {
|
||||
active_thread: "in use by an active thread",
|
||||
dirty: "has uncommitted changes",
|
||||
unpushed: "has unpushed commits",
|
||||
status_unavailable: "its state could not be determined",
|
||||
unknown_worktree: "it is not a managed worktree",
|
||||
remove_failed: "git failed to remove it",
|
||||
};
|
||||
|
||||
function worktreeDisplayName(worktree: WorktreeInfo): string {
|
||||
return worktree.branch ?? (worktree.path.split("/").pop() || worktree.path);
|
||||
}
|
||||
|
||||
function hasActiveThread(worktree: WorktreeInfo): boolean {
|
||||
return worktree.threads.some((thread) => thread.status === "active");
|
||||
}
|
||||
|
||||
function isSettledOnly(worktree: WorktreeInfo): boolean {
|
||||
const nonDeleted = worktree.threads.filter((thread) => thread.status !== "deleted");
|
||||
return nonDeleted.length > 0 && nonDeleted.every((thread) => thread.status !== "active");
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocked from pruning by something the user can resolve (uncommitted or
|
||||
* unpushed work), as opposed to simply being in use by an active thread.
|
||||
*/
|
||||
function needsAttention(worktree: WorktreeInfo): boolean {
|
||||
return (
|
||||
!worktree.safeToPrune &&
|
||||
!hasActiveThread(worktree) &&
|
||||
worktree.pruneBlockers.some((blocker) => blocker === "dirty" || blocker === "unpushed")
|
||||
);
|
||||
}
|
||||
|
||||
function matchesSearch(worktree: WorktreeInfo, query: string): boolean {
|
||||
if (query.length === 0) return true;
|
||||
const haystacks = [
|
||||
worktree.branch ?? "",
|
||||
worktree.path.split("/").pop() ?? "",
|
||||
worktree.projectTitle,
|
||||
...worktree.threads.map((thread) => thread.title),
|
||||
];
|
||||
return haystacks.some((value) => value.toLowerCase().includes(query));
|
||||
}
|
||||
|
||||
function matchesStatusFilters(worktree: WorktreeInfo, filters: ReadonlySet<StatusFilter>): boolean {
|
||||
if (filters.size === 0) return true;
|
||||
for (const filter of filters) {
|
||||
switch (filter) {
|
||||
case "attention":
|
||||
if (needsAttention(worktree)) return true;
|
||||
break;
|
||||
case "safe":
|
||||
if (worktree.safeToPrune) return true;
|
||||
break;
|
||||
case "dirty":
|
||||
if (worktree.dirty === true) return true;
|
||||
break;
|
||||
case "unpushed":
|
||||
if (worktree.pruneBlockers.includes("unpushed")) return true;
|
||||
break;
|
||||
case "orphaned":
|
||||
if (worktree.orphaned) return true;
|
||||
break;
|
||||
case "settled":
|
||||
if (isSettledOnly(worktree)) return true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function ThreadsCell({ worktree }: { worktree: WorktreeInfo }) {
|
||||
const nonDeleted = worktree.threads.filter((thread) => thread.status !== "deleted");
|
||||
if (nonDeleted.length === 0) {
|
||||
return <span className="text-muted-foreground/60">orphaned</span>;
|
||||
}
|
||||
const [first] = nonDeleted;
|
||||
const title = first !== undefined && first.title.trim().length > 0 ? first.title : "Untitled";
|
||||
return (
|
||||
<span className="inline-flex min-w-0 max-w-56 items-baseline gap-1.5">
|
||||
<span className="truncate">{title}</span>
|
||||
{nonDeleted.length > 1 ? (
|
||||
<span className="shrink-0 text-muted-foreground/60">+{nonDeleted.length - 1}</span>
|
||||
) : null}
|
||||
{isSettledOnly(worktree) ? (
|
||||
<span className="shrink-0 text-xs text-muted-foreground/60">settled</span>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ChangesCell({ worktree }: { worktree: WorktreeInfo }) {
|
||||
if (worktree.dirty === null) {
|
||||
return <span className="text-muted-foreground/60">unknown</span>;
|
||||
}
|
||||
if (!worktree.dirty) {
|
||||
return <span className="text-muted-foreground/60">clean</span>;
|
||||
}
|
||||
const count = worktree.dirtyFileCount;
|
||||
return (
|
||||
<span className="font-medium text-warning-foreground">
|
||||
{count === null || count === 0 ? "dirty" : `${count} file${count === 1 ? "" : "s"}`}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function SyncCell({ worktree }: { worktree: WorktreeInfo }) {
|
||||
if (worktree.branch === null) {
|
||||
return <span className="text-muted-foreground/60">detached</span>;
|
||||
}
|
||||
if (worktree.hasUpstream && !worktree.upstreamGone) {
|
||||
const ahead = worktree.aheadOfUpstreamCount ?? 0;
|
||||
const behind = worktree.behindUpstreamCount ?? 0;
|
||||
if (ahead === 0 && behind === 0) {
|
||||
return <span className="text-muted-foreground/60">synced</span>;
|
||||
}
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5 font-mono text-xs">
|
||||
{ahead > 0 ? <span className="text-info-foreground">↑{ahead}</span> : null}
|
||||
{behind > 0 ? <span className="text-muted-foreground">↓{behind}</span> : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (worktree.upstreamGone) {
|
||||
return <span className="text-muted-foreground/60">remote gone</span>;
|
||||
}
|
||||
const aheadOfDefault = worktree.aheadOfDefaultCount;
|
||||
if (aheadOfDefault === null) {
|
||||
return <span className="text-muted-foreground/60">unknown</span>;
|
||||
}
|
||||
if (aheadOfDefault === 0) {
|
||||
return <span className="text-muted-foreground/60">nothing to push</span>;
|
||||
}
|
||||
return <span className="font-mono text-xs text-info-foreground">↑{aheadOfDefault} local</span>;
|
||||
}
|
||||
|
||||
function StateCell({ worktree }: { worktree: WorktreeInfo }) {
|
||||
if (worktree.safeToPrune) {
|
||||
return (
|
||||
<Badge size="sm" variant="success">
|
||||
Safe to prune
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (needsAttention(worktree)) {
|
||||
return (
|
||||
<Badge size="sm" variant="warning">
|
||||
Needs attention
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
if (hasActiveThread(worktree)) {
|
||||
return (
|
||||
<Badge size="sm" variant="info">
|
||||
In use
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Badge size="sm" variant="outline">
|
||||
Unknown
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
function WorktreeTable({
|
||||
worktrees,
|
||||
showProject,
|
||||
busyPaths,
|
||||
onDelete,
|
||||
}: {
|
||||
worktrees: ReadonlyArray<WorktreeInfo>;
|
||||
showProject: boolean;
|
||||
busyPaths: ReadonlySet<string>;
|
||||
onDelete: (worktree: WorktreeInfo) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="overflow-x-auto px-3 sm:px-4">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Branch</TableHead>
|
||||
{showProject ? <TableHead>Project</TableHead> : null}
|
||||
<TableHead>Threads</TableHead>
|
||||
<TableHead>Changes</TableHead>
|
||||
<TableHead>Sync</TableHead>
|
||||
<TableHead>Last activity</TableHead>
|
||||
<TableHead>State</TableHead>
|
||||
<TableHead className="w-0" />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{worktrees.map((worktree) => {
|
||||
const busy = busyPaths.has(worktree.path);
|
||||
return (
|
||||
<TableRow key={worktree.path}>
|
||||
<TableCell className="max-w-52">
|
||||
<span className="block truncate font-mono text-[13px]" title={worktree.path}>
|
||||
{worktreeDisplayName(worktree)}
|
||||
</span>
|
||||
</TableCell>
|
||||
{showProject ? (
|
||||
<TableCell className="text-muted-foreground">{worktree.projectTitle}</TableCell>
|
||||
) : null}
|
||||
<TableCell>
|
||||
<ThreadsCell worktree={worktree} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<ChangesCell worktree={worktree} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<SyncCell worktree={worktree} />
|
||||
</TableCell>
|
||||
<TableCell className="whitespace-nowrap text-muted-foreground">
|
||||
{worktree.lastActivityAt === null
|
||||
? "—"
|
||||
: formatRelativeTimeLabel(worktree.lastActivityAt)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<StateCell worktree={worktree} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button
|
||||
type="button"
|
||||
variant={worktree.safeToPrune ? "outline" : "destructive-outline"}
|
||||
size="sm"
|
||||
className="h-7 shrink-0 cursor-pointer gap-1.5 px-2.5"
|
||||
disabled={busy}
|
||||
onClick={() => onDelete(worktree)}
|
||||
>
|
||||
{busy ? (
|
||||
<LoaderIcon className="size-3.5 animate-spin" />
|
||||
) : (
|
||||
<Trash2Icon className="size-3.5" />
|
||||
)}
|
||||
<span className="whitespace-nowrap">
|
||||
{worktree.safeToPrune ? "Delete" : "Force delete"}
|
||||
</span>
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function WorktreesSettingsPanel() {
|
||||
const primaryEnvironment = usePrimaryEnvironment();
|
||||
const environmentId = primaryEnvironment?.environmentId ?? null;
|
||||
const worktreesAtom = useMemo(
|
||||
() =>
|
||||
environmentId === null ? null : vcsEnvironment.listWorktrees({ environmentId, input: {} }),
|
||||
[environmentId],
|
||||
);
|
||||
const { data, error, isPending, refresh } = useEnvironmentQuery(worktreesAtom);
|
||||
const pruneWorktrees = useAtomCommand(vcsEnvironment.pruneWorktrees, { reportFailure: false });
|
||||
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, { reportFailure: false });
|
||||
|
||||
const [search, setSearch] = useState("");
|
||||
const [projectFilter, setProjectFilter] = useState<string>(ALL_PROJECTS);
|
||||
const [statusFilters, setStatusFilters] = useState<ReadonlySet<StatusFilter>>(new Set());
|
||||
const [busyPaths, setBusyPaths] = useState<ReadonlySet<string>>(new Set());
|
||||
const [isBulkPruning, setIsBulkPruning] = useState(false);
|
||||
|
||||
const worktrees = useMemo(() => data?.worktrees ?? [], [data]);
|
||||
|
||||
const projectOptions = useMemo(() => {
|
||||
const byId = new Map<string, string>();
|
||||
for (const worktree of worktrees) {
|
||||
byId.set(worktree.projectId, worktree.projectTitle);
|
||||
}
|
||||
return [...byId.entries()].map(([id, title]) => ({ id, title }));
|
||||
}, [worktrees]);
|
||||
|
||||
const filtersActive =
|
||||
search.trim().length > 0 || projectFilter !== ALL_PROJECTS || statusFilters.size > 0;
|
||||
|
||||
const filteredWorktrees = useMemo(() => {
|
||||
const query = search.trim().toLowerCase();
|
||||
return worktrees.filter(
|
||||
(worktree) =>
|
||||
(projectFilter === ALL_PROJECTS || worktree.projectId === projectFilter) &&
|
||||
matchesSearch(worktree, query) &&
|
||||
matchesStatusFilters(worktree, statusFilters),
|
||||
);
|
||||
}, [worktrees, search, projectFilter, statusFilters]);
|
||||
|
||||
const attentionWorktrees = useMemo(
|
||||
() => filteredWorktrees.filter((worktree) => needsAttention(worktree)),
|
||||
[filteredWorktrees],
|
||||
);
|
||||
const remainingWorktrees = useMemo(
|
||||
() => filteredWorktrees.filter((worktree) => !needsAttention(worktree)),
|
||||
[filteredWorktrees],
|
||||
);
|
||||
const safeFiltered = useMemo(
|
||||
() => filteredWorktrees.filter((worktree) => worktree.safeToPrune),
|
||||
[filteredWorktrees],
|
||||
);
|
||||
|
||||
const toggleStatusFilter = useCallback((key: StatusFilter) => {
|
||||
setStatusFilters((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(key)) {
|
||||
next.delete(key);
|
||||
} else {
|
||||
next.add(key);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const reportSkipped = useCallback(
|
||||
(skipped: ReadonlyArray<{ path: string; reason: WorktreePruneSkipReason }>) => {
|
||||
if (skipped.length === 0) return;
|
||||
const [first] = skipped;
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "warning",
|
||||
title:
|
||||
skipped.length === 1
|
||||
? "Worktree was not removed"
|
||||
: `${skipped.length} worktrees were not removed`,
|
||||
description:
|
||||
first === undefined
|
||||
? undefined
|
||||
: `${first.path.split("/").pop() ?? first.path}: ${SKIP_REASON_LABEL[first.reason]}${
|
||||
skipped.length > 1 ? " (and more)" : ""
|
||||
}.`,
|
||||
}),
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const runPrune = useCallback(
|
||||
async (paths: ReadonlyArray<string>) => {
|
||||
if (environmentId === null || paths.length === 0) return;
|
||||
const result = await pruneWorktrees({
|
||||
environmentId,
|
||||
input: { paths: [...paths] },
|
||||
});
|
||||
if (result._tag === "Success") {
|
||||
reportSkipped(result.value.skipped.map(({ path, reason }) => ({ path, reason })));
|
||||
refresh();
|
||||
return;
|
||||
}
|
||||
if (!isAtomCommandInterrupted(result)) {
|
||||
const failure = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to prune worktrees",
|
||||
description: failure instanceof Error ? failure.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
[environmentId, pruneWorktrees, refresh, reportSkipped],
|
||||
);
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (worktree: WorktreeInfo) => {
|
||||
if (environmentId === null) return;
|
||||
setBusyPaths((current) => new Set(current).add(worktree.path));
|
||||
try {
|
||||
if (worktree.safeToPrune) {
|
||||
if (
|
||||
!window.confirm(
|
||||
`Delete the worktree for "${worktreeDisplayName(worktree)}"?\n\nIt has no uncommitted or unpushed work. The branch is kept, and the worktree can be recreated if its thread becomes active again.`,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await runPrune([worktree.path]);
|
||||
return;
|
||||
}
|
||||
|
||||
const lost = [
|
||||
worktree.pruneBlockers.includes("dirty") ? "uncommitted changes" : null,
|
||||
worktree.pruneBlockers.includes("unpushed") ? "unpushed commits" : null,
|
||||
].filter((value) => value !== null);
|
||||
const inUse = worktree.pruneBlockers.includes("active_thread");
|
||||
const lines = [`Force-delete the worktree for "${worktreeDisplayName(worktree)}"?`, ""];
|
||||
if (inUse) {
|
||||
lines.push(
|
||||
"It is in use by an active thread. The thread is kept and can recreate the worktree from its branch on the next turn.",
|
||||
);
|
||||
}
|
||||
if (lost.length > 0) {
|
||||
lines.push(
|
||||
`It has ${lost.join(" and ")}. Uncommitted changes will be PERMANENTLY LOST and cannot be restored later. Commits stay on the branch.`,
|
||||
);
|
||||
} else if (!inUse) {
|
||||
lines.push(
|
||||
"Its state could not be determined, so anything uncommitted in it will be PERMANENTLY LOST.",
|
||||
);
|
||||
}
|
||||
if (!window.confirm(lines.join("\n"))) {
|
||||
return;
|
||||
}
|
||||
const result = await removeWorktree({
|
||||
environmentId,
|
||||
input: { cwd: worktree.workspaceRoot, path: worktree.path, force: true },
|
||||
});
|
||||
if (result._tag === "Success") {
|
||||
refresh();
|
||||
return;
|
||||
}
|
||||
if (!isAtomCommandInterrupted(result)) {
|
||||
const failure = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Failed to delete worktree",
|
||||
description: failure instanceof Error ? failure.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
setBusyPaths((current) => {
|
||||
const next = new Set(current);
|
||||
next.delete(worktree.path);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
},
|
||||
[environmentId, refresh, removeWorktree, runPrune],
|
||||
);
|
||||
|
||||
const handleBulkPrune = useCallback(async () => {
|
||||
if (safeFiltered.length === 0 || isBulkPruning) return;
|
||||
const scope = filtersActive ? " matching the current filters" : "";
|
||||
if (
|
||||
!window.confirm(
|
||||
`Prune ${safeFiltered.length} safe ${safeFiltered.length === 1 ? "worktree" : "worktrees"}${scope}?\n\nOnly clean worktrees without active threads or unpushed work are removed. Branches are kept.`,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setIsBulkPruning(true);
|
||||
try {
|
||||
await runPrune(safeFiltered.map((worktree) => worktree.path));
|
||||
} finally {
|
||||
setIsBulkPruning(false);
|
||||
}
|
||||
}, [safeFiltered, filtersActive, isBulkPruning, runPrune]);
|
||||
|
||||
const onDelete = useCallback(
|
||||
(worktree: WorktreeInfo) => {
|
||||
void handleDelete(worktree);
|
||||
},
|
||||
[handleDelete],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection
|
||||
title="Worktrees"
|
||||
headerAction={
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
aria-label="Refresh worktrees"
|
||||
disabled={isPending}
|
||||
onClick={() => refresh()}
|
||||
>
|
||||
<RefreshCwIcon className={isPending ? "size-3.5 animate-spin" : "size-3.5"} />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 cursor-pointer gap-1.5 px-2.5"
|
||||
disabled={safeFiltered.length === 0 || isBulkPruning || environmentId === null}
|
||||
onClick={() => {
|
||||
void handleBulkPrune();
|
||||
}}
|
||||
>
|
||||
{isBulkPruning ? (
|
||||
<LoaderIcon className="size-3.5 animate-spin" />
|
||||
) : (
|
||||
<Trash2Icon className="size-3.5" />
|
||||
)}
|
||||
<span>
|
||||
Prune {safeFiltered.length} safe{" "}
|
||||
{safeFiltered.length === 1 ? "worktree" : "worktrees"}
|
||||
{filtersActive ? " (filtered)" : ""}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-2 px-3 pb-1 sm:px-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder="Search branch, folder, or thread…"
|
||||
className="h-8 w-full sm:max-w-xs"
|
||||
/>
|
||||
{projectOptions.length > 1 ? (
|
||||
<Select
|
||||
value={projectFilter}
|
||||
onValueChange={(value) => setProjectFilter(value ?? ALL_PROJECTS)}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-44">
|
||||
<SelectValue placeholder="All projects" />
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
<SelectItem value={ALL_PROJECTS}>All projects</SelectItem>
|
||||
{projectOptions.map((project) => (
|
||||
<SelectItem key={project.id} value={project.id}>
|
||||
{project.title}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{STATUS_FILTERS.map((filter) => (
|
||||
<Button
|
||||
key={filter.key}
|
||||
type="button"
|
||||
variant={statusFilters.has(filter.key) ? "secondary" : "ghost"}
|
||||
size="sm"
|
||||
className="h-6 cursor-pointer rounded-full px-2.5 text-xs"
|
||||
onClick={() => toggleStatusFilter(filter.key)}
|
||||
>
|
||||
{filter.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{environmentId === null || filteredWorktrees.length === 0 ? (
|
||||
<SettingsRow
|
||||
title={
|
||||
<span className="inline-flex items-center gap-2">
|
||||
{isPending ? (
|
||||
<LoaderIcon className="size-3.5 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<FolderGit2Icon className="size-3.5 text-muted-foreground" />
|
||||
)}
|
||||
{environmentId === null
|
||||
? "No environment connected"
|
||||
: isPending
|
||||
? "Loading worktrees"
|
||||
: error !== null
|
||||
? "Could not load worktrees"
|
||||
: filtersActive
|
||||
? "No worktrees match the current filters"
|
||||
: "No managed worktrees"}
|
||||
</span>
|
||||
}
|
||||
description={
|
||||
environmentId === null
|
||||
? "Connect an environment to manage its worktrees."
|
||||
: error !== null
|
||||
? error
|
||||
: "Worktrees created for threads will appear here."
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</SettingsSection>
|
||||
|
||||
{attentionWorktrees.length > 0 ? (
|
||||
<SettingsSection title="Needs attention">
|
||||
<p
|
||||
className={cn(
|
||||
"max-w-2xl px-3 pb-2 text-[13px] leading-[1.45] text-muted-foreground/80 sm:px-4",
|
||||
)}
|
||||
>
|
||||
These worktrees have been inactive but still hold uncommitted changes or unpushed
|
||||
commits, so automatic pruning never touches them. Commit or push the work to make them
|
||||
safe, or force delete to discard it permanently.
|
||||
</p>
|
||||
<WorktreeTable
|
||||
worktrees={attentionWorktrees}
|
||||
showProject
|
||||
busyPaths={busyPaths}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
</SettingsSection>
|
||||
) : null}
|
||||
|
||||
{remainingWorktrees.length > 0 ? (
|
||||
<SettingsSection
|
||||
title={attentionWorktrees.length > 0 ? "All worktrees" : "Managed worktrees"}
|
||||
>
|
||||
<WorktreeTable
|
||||
worktrees={remainingWorktrees}
|
||||
showProject
|
||||
busyPaths={busyPaths}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
</SettingsSection>
|
||||
) : null}
|
||||
|
||||
<AutoPruneSettingsSection />
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
function AutoPruneSettingsSection() {
|
||||
const worktreeSettings = usePrimarySettings((settings) => settings.worktrees);
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
|
||||
const autoPruneValue =
|
||||
worktreeSettings.autoPruneAfterDays === null
|
||||
? "off"
|
||||
: String(worktreeSettings.autoPruneAfterDays);
|
||||
|
||||
return (
|
||||
<SettingsSection title="Automatic pruning">
|
||||
<SettingsRow
|
||||
title="Prune inactive worktrees"
|
||||
description="Automatically delete worktrees that are safe to prune — no active threads, no uncommitted changes, and no unpushed commits — once they have been inactive this long. Branches are always kept."
|
||||
control={
|
||||
<Select
|
||||
value={autoPruneValue}
|
||||
onValueChange={(value) => {
|
||||
updateSettings({
|
||||
worktrees: {
|
||||
autoPruneAfterDays: value === "off" || value === null ? null : Number(value),
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-40">
|
||||
<SelectValue placeholder="After 14 days" />
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
{AUTO_PRUNE_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
}
|
||||
/>
|
||||
<SettingsRow
|
||||
title="Delete orphaned worktrees immediately"
|
||||
description="When the last thread using a worktree is deleted, remove the worktree right away instead of waiting for the inactivity schedule. Only applies to worktrees that are safe to prune."
|
||||
control={
|
||||
<Switch
|
||||
checked={worktreeSettings.deleteOrphanedImmediately}
|
||||
onCheckedChange={(checked) => {
|
||||
updateSettings({ worktrees: { deleteOrphanedImmediately: checked === true } });
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
@@ -31,7 +31,8 @@ import { useTerminalUiStateStore } from "../terminalUiStateStore";
|
||||
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
import { stackedThreadToast, toastManager } from "../components/ui/toast";
|
||||
import { useClientSettings } from "./useSettings";
|
||||
import { useClientSettings, usePrimarySettings } from "./useSettings";
|
||||
import { usePrimaryEnvironmentId } from "../state/environments";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
|
||||
export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArchiveBlockedError>()(
|
||||
@@ -126,6 +127,10 @@ export function useThreadActions() {
|
||||
});
|
||||
const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);
|
||||
const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const deleteOrphanedWorktreesImmediately = usePrimarySettings(
|
||||
(settings) => settings.worktrees.deleteOrphanedImmediately,
|
||||
);
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
|
||||
const clearProjectDraftThreadById = useComposerDraftStore(
|
||||
(store) => store.clearProjectDraftThreadById,
|
||||
@@ -258,9 +263,14 @@ export function useThreadActions() {
|
||||
? formatWorktreePathForDisplay(orphanedWorktreePath)
|
||||
: null;
|
||||
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== null;
|
||||
// When the server is configured to remove orphaned worktrees on its
|
||||
// own, skip the dialog and the client-side removal — the server's
|
||||
// thread-deletion reactor prunes the worktree (safely, never forced).
|
||||
const serverPrunesOrphan =
|
||||
deleteOrphanedWorktreesImmediately && threadRef.environmentId === primaryEnvironmentId;
|
||||
const localApi = readLocalApi();
|
||||
let shouldDeleteWorktree = false;
|
||||
if (canDeleteWorktree && localApi) {
|
||||
if (canDeleteWorktree && localApi && !serverPrunesOrphan) {
|
||||
const confirmationResult = await settlePromise(() =>
|
||||
localApi.dialogs.confirm(
|
||||
[
|
||||
@@ -401,8 +411,10 @@ export function useThreadActions() {
|
||||
clearProjectDraftThreadById,
|
||||
clearTerminalUiState,
|
||||
closeTerminal,
|
||||
deleteOrphanedWorktreesImmediately,
|
||||
deleteThreadMutation,
|
||||
getCurrentRouteThreadRef,
|
||||
primaryEnvironmentId,
|
||||
refreshVcsStatus,
|
||||
removeWorktree,
|
||||
router,
|
||||
|
||||
@@ -14,6 +14,7 @@ import { Route as PairRouteImport } from './routes/pair'
|
||||
import { Route as ConnectRouteImport } from './routes/connect'
|
||||
import { Route as ChatRouteImport } from './routes/_chat'
|
||||
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
|
||||
import { Route as SettingsWorktreesRouteImport } from './routes/settings.worktrees'
|
||||
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
|
||||
import { Route as SettingsProvidersRouteImport } from './routes/settings.providers'
|
||||
import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'
|
||||
@@ -51,6 +52,11 @@ const ChatIndexRoute = ChatIndexRouteImport.update({
|
||||
path: '/',
|
||||
getParentRoute: () => ChatRoute,
|
||||
} as any)
|
||||
const SettingsWorktreesRoute = SettingsWorktreesRouteImport.update({
|
||||
id: '/worktrees',
|
||||
path: '/worktrees',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsSourceControlRoute = SettingsSourceControlRouteImport.update({
|
||||
id: '/source-control',
|
||||
path: '/source-control',
|
||||
@@ -128,6 +134,7 @@ export interface FileRoutesByFullPath {
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/providers': typeof SettingsProvidersRoute
|
||||
'/settings/source-control': typeof SettingsSourceControlRoute
|
||||
'/settings/worktrees': typeof SettingsWorktreesRoute
|
||||
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
|
||||
'/draft/$draftId': typeof ChatDraftDraftIdRoute
|
||||
}
|
||||
@@ -145,6 +152,7 @@ export interface FileRoutesByTo {
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/providers': typeof SettingsProvidersRoute
|
||||
'/settings/source-control': typeof SettingsSourceControlRoute
|
||||
'/settings/worktrees': typeof SettingsWorktreesRoute
|
||||
'/': typeof ChatIndexRoute
|
||||
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
|
||||
'/draft/$draftId': typeof ChatDraftDraftIdRoute
|
||||
@@ -165,6 +173,7 @@ export interface FileRoutesById {
|
||||
'/settings/keybindings': typeof SettingsKeybindingsRoute
|
||||
'/settings/providers': typeof SettingsProvidersRoute
|
||||
'/settings/source-control': typeof SettingsSourceControlRoute
|
||||
'/settings/worktrees': typeof SettingsWorktreesRoute
|
||||
'/_chat/': typeof ChatIndexRoute
|
||||
'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
|
||||
'/_chat/draft/$draftId': typeof ChatDraftDraftIdRoute
|
||||
@@ -186,6 +195,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/keybindings'
|
||||
| '/settings/providers'
|
||||
| '/settings/source-control'
|
||||
| '/settings/worktrees'
|
||||
| '/$environmentId/$threadId'
|
||||
| '/draft/$draftId'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
@@ -203,6 +213,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/keybindings'
|
||||
| '/settings/providers'
|
||||
| '/settings/source-control'
|
||||
| '/settings/worktrees'
|
||||
| '/'
|
||||
| '/$environmentId/$threadId'
|
||||
| '/draft/$draftId'
|
||||
@@ -222,6 +233,7 @@ export interface FileRouteTypes {
|
||||
| '/settings/keybindings'
|
||||
| '/settings/providers'
|
||||
| '/settings/source-control'
|
||||
| '/settings/worktrees'
|
||||
| '/_chat/'
|
||||
| '/_chat/$environmentId/$threadId'
|
||||
| '/_chat/draft/$draftId'
|
||||
@@ -272,6 +284,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof ChatIndexRouteImport
|
||||
parentRoute: typeof ChatRoute
|
||||
}
|
||||
'/settings/worktrees': {
|
||||
id: '/settings/worktrees'
|
||||
path: '/worktrees'
|
||||
fullPath: '/settings/worktrees'
|
||||
preLoaderRoute: typeof SettingsWorktreesRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/source-control': {
|
||||
id: '/settings/source-control'
|
||||
path: '/source-control'
|
||||
@@ -383,6 +402,7 @@ interface SettingsRouteChildren {
|
||||
SettingsKeybindingsRoute: typeof SettingsKeybindingsRoute
|
||||
SettingsProvidersRoute: typeof SettingsProvidersRoute
|
||||
SettingsSourceControlRoute: typeof SettingsSourceControlRoute
|
||||
SettingsWorktreesRoute: typeof SettingsWorktreesRoute
|
||||
}
|
||||
|
||||
const SettingsRouteChildren: SettingsRouteChildren = {
|
||||
@@ -395,6 +415,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {
|
||||
SettingsKeybindingsRoute: SettingsKeybindingsRoute,
|
||||
SettingsProvidersRoute: SettingsProvidersRoute,
|
||||
SettingsSourceControlRoute: SettingsSourceControlRoute,
|
||||
SettingsWorktreesRoute: SettingsWorktreesRoute,
|
||||
}
|
||||
|
||||
const SettingsRouteWithChildren = SettingsRoute._addFileChildren(
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { WorktreesSettingsPanel } from "../components/settings/WorktreesSettingsPanel";
|
||||
|
||||
function SettingsWorktreesRoute() {
|
||||
return <WorktreesSettingsPanel />;
|
||||
}
|
||||
|
||||
export const Route = createFileRoute("/settings/worktrees")({
|
||||
component: SettingsWorktreesRoute,
|
||||
});
|
||||
@@ -13,7 +13,11 @@ import * as Stream from "effect/Stream";
|
||||
import * as SubscriptionRef from "effect/SubscriptionRef";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { createEnvironmentRpcCommand, createEnvironmentSubscriptionAtomFamily } from "./runtime.ts";
|
||||
import {
|
||||
createEnvironmentRpcCommand,
|
||||
createEnvironmentRpcQueryAtomFamily,
|
||||
createEnvironmentSubscriptionAtomFamily,
|
||||
} from "./runtime.ts";
|
||||
import type { EnvironmentRegistry } from "../connection/registry.ts";
|
||||
import { EnvironmentSupervisor } from "../connection/supervisor.ts";
|
||||
import { safeErrorLogAttributes } from "../errors/safeLog.ts";
|
||||
@@ -200,6 +204,22 @@ export function createVcsEnvironmentAtoms<R, E>(
|
||||
scheduler: vcsCommandScheduler,
|
||||
concurrency: vcsCommandConcurrency,
|
||||
}),
|
||||
listWorktrees: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:vcs:list-worktrees",
|
||||
tag: WS_METHODS.vcsListWorktrees,
|
||||
staleTimeMs: 10_000,
|
||||
}),
|
||||
pruneWorktrees: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:vcs:prune-worktrees",
|
||||
tag: WS_METHODS.vcsPruneWorktrees,
|
||||
scheduler: vcsCommandScheduler,
|
||||
// Prune spans repositories, so serialize per environment instead of
|
||||
// per-cwd like the other vcs commands.
|
||||
concurrency: {
|
||||
mode: "serial",
|
||||
key: ({ environmentId }) => JSON.stringify([environmentId, "worktrees.prune"]),
|
||||
},
|
||||
}),
|
||||
createRef: createEnvironmentRpcCommand(runtime, {
|
||||
label: "environment-data:vcs:create-ref",
|
||||
tag: WS_METHODS.vcsCreateRef,
|
||||
|
||||
@@ -16,6 +16,7 @@ export * from "./server.ts";
|
||||
export * from "./settings.ts";
|
||||
export * from "./git.ts";
|
||||
export * from "./vcs.ts";
|
||||
export * from "./worktrees.ts";
|
||||
export * from "./sourceControl.ts";
|
||||
export * from "./orchestration.ts";
|
||||
export * from "./t3ProjectFile.ts";
|
||||
|
||||
@@ -39,6 +39,12 @@ import {
|
||||
VcsStatusResult,
|
||||
VcsStatusStreamEvent,
|
||||
} from "./git.ts";
|
||||
import {
|
||||
VcsListWorktreesInput,
|
||||
VcsListWorktreesResult,
|
||||
VcsPruneWorktreesInput,
|
||||
VcsPruneWorktreesResult,
|
||||
} from "./worktrees.ts";
|
||||
import {
|
||||
ReviewDiffPreviewError,
|
||||
ReviewDiffPreviewInput,
|
||||
@@ -170,6 +176,8 @@ export const WS_METHODS = {
|
||||
vcsListRefs: "vcs.listRefs",
|
||||
vcsCreateWorktree: "vcs.createWorktree",
|
||||
vcsRemoveWorktree: "vcs.removeWorktree",
|
||||
vcsListWorktrees: "vcs.listWorktrees",
|
||||
vcsPruneWorktrees: "vcs.pruneWorktrees",
|
||||
vcsCreateRef: "vcs.createRef",
|
||||
vcsSwitchRef: "vcs.switchRef",
|
||||
vcsInit: "vcs.init",
|
||||
@@ -467,6 +475,18 @@ export const WsVcsRemoveWorktreeRpc = Rpc.make(WS_METHODS.vcsRemoveWorktree, {
|
||||
error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsVcsListWorktreesRpc = Rpc.make(WS_METHODS.vcsListWorktrees, {
|
||||
payload: VcsListWorktreesInput,
|
||||
success: VcsListWorktreesResult,
|
||||
error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsVcsPruneWorktreesRpc = Rpc.make(WS_METHODS.vcsPruneWorktrees, {
|
||||
payload: VcsPruneWorktreesInput,
|
||||
success: VcsPruneWorktreesResult,
|
||||
error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),
|
||||
});
|
||||
|
||||
export const WsVcsCreateRefRpc = Rpc.make(WS_METHODS.vcsCreateRef, {
|
||||
payload: VcsCreateRefInput,
|
||||
success: VcsCreateRefResult,
|
||||
@@ -734,6 +754,8 @@ export const WsRpcGroup = RpcGroup.make(
|
||||
WsVcsListRefsRpc,
|
||||
WsVcsCreateWorktreeRpc,
|
||||
WsVcsRemoveWorktreeRpc,
|
||||
WsVcsListWorktreesRpc,
|
||||
WsVcsPruneWorktreesRpc,
|
||||
WsVcsCreateRefRpc,
|
||||
WsVcsSwitchRefRpc,
|
||||
WsVcsInitRpc,
|
||||
|
||||
@@ -401,6 +401,33 @@ export const OpenCodeSettings = makeProviderSettingsSchema(
|
||||
);
|
||||
export type OpenCodeSettings = typeof OpenCodeSettings.Type;
|
||||
|
||||
export const MIN_WORKTREE_AUTO_PRUNE_AFTER_DAYS = 1;
|
||||
export const MAX_WORKTREE_AUTO_PRUNE_AFTER_DAYS = 365;
|
||||
export const WorktreeAutoPruneAfterDays = Schema.Int.check(
|
||||
Schema.isBetween({
|
||||
minimum: MIN_WORKTREE_AUTO_PRUNE_AFTER_DAYS,
|
||||
maximum: MAX_WORKTREE_AUTO_PRUNE_AFTER_DAYS,
|
||||
}),
|
||||
);
|
||||
export type WorktreeAutoPruneAfterDays = typeof WorktreeAutoPruneAfterDays.Type;
|
||||
export const DEFAULT_WORKTREE_AUTO_PRUNE_AFTER_DAYS: WorktreeAutoPruneAfterDays = 14;
|
||||
|
||||
export const WorktreeSettings = Schema.Struct({
|
||||
/**
|
||||
* Remove safe-to-prune worktrees after this many days without activity.
|
||||
* `null` disables the automatic sweep entirely.
|
||||
*/
|
||||
autoPruneAfterDays: Schema.NullOr(WorktreeAutoPruneAfterDays).pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_WORKTREE_AUTO_PRUNE_AFTER_DAYS)),
|
||||
),
|
||||
/**
|
||||
* Remove a worktree as soon as no thread references it anymore (still only
|
||||
* when it is safe to prune), instead of waiting for the inactivity sweep.
|
||||
*/
|
||||
deleteOrphanedImmediately: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
});
|
||||
export type WorktreeSettings = typeof WorktreeSettings.Type;
|
||||
|
||||
export const ObservabilitySettings = Schema.Struct({
|
||||
otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
@@ -479,6 +506,7 @@ export const ServerSettings = Schema.Struct({
|
||||
Schema.withDecodingDefault(Effect.succeed({})),
|
||||
),
|
||||
observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
worktrees: WorktreeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
|
||||
});
|
||||
export type ServerSettings = typeof ServerSettings.Type;
|
||||
|
||||
@@ -595,6 +623,12 @@ export const ServerSettingsPatch = Schema.Struct({
|
||||
otlpMetricsUrl: Schema.optionalKey(TrimmedString),
|
||||
}),
|
||||
),
|
||||
worktrees: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
autoPruneAfterDays: Schema.optionalKey(Schema.NullOr(WorktreeAutoPruneAfterDays)),
|
||||
deleteOrphanedImmediately: Schema.optionalKey(Schema.Boolean),
|
||||
}),
|
||||
),
|
||||
providers: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
codex: Schema.optionalKey(CodexSettingsPatch),
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
IsoDateTime,
|
||||
NonNegativeInt,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TrimmedNonEmptyString,
|
||||
} from "./baseSchemas.ts";
|
||||
|
||||
// Domain Types
|
||||
|
||||
export const WorktreeThreadStatus = Schema.Literals(["active", "settled", "archived", "deleted"]);
|
||||
export type WorktreeThreadStatus = typeof WorktreeThreadStatus.Type;
|
||||
|
||||
export const WorktreeThreadRef = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
title: Schema.String,
|
||||
status: WorktreeThreadStatus,
|
||||
});
|
||||
export type WorktreeThreadRef = typeof WorktreeThreadRef.Type;
|
||||
|
||||
/**
|
||||
* Why a worktree is not safe to prune automatically. `status_unavailable`
|
||||
* covers detached HEADs and failed status probes — never assume safety when
|
||||
* the state cannot be read.
|
||||
*/
|
||||
export const WorktreePruneBlocker = Schema.Literals([
|
||||
"active_thread",
|
||||
"dirty",
|
||||
"unpushed",
|
||||
"status_unavailable",
|
||||
]);
|
||||
export type WorktreePruneBlocker = typeof WorktreePruneBlocker.Type;
|
||||
|
||||
export const WorktreeInfo = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
projectTitle: Schema.String,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
path: TrimmedNonEmptyString,
|
||||
branch: Schema.NullOr(TrimmedNonEmptyString),
|
||||
threads: Schema.Array(WorktreeThreadRef),
|
||||
/** No non-deleted thread references this worktree. */
|
||||
orphaned: Schema.Boolean,
|
||||
/** null when the working-tree status could not be read. */
|
||||
dirty: Schema.NullOr(Schema.Boolean),
|
||||
/** Number of changed/untracked files; null when status could not be read. */
|
||||
dirtyFileCount: Schema.NullOr(NonNegativeInt),
|
||||
hasUpstream: Schema.NullOr(Schema.Boolean),
|
||||
/**
|
||||
* Upstream is configured but its remote ref no longer exists (typically
|
||||
* deleted after the PR merged).
|
||||
*/
|
||||
upstreamGone: Schema.Boolean,
|
||||
/** Commits on the branch that are not on its upstream. */
|
||||
aheadOfUpstreamCount: Schema.NullOr(NonNegativeInt),
|
||||
/** Commits on the upstream that are not on the branch. */
|
||||
behindUpstreamCount: Schema.NullOr(NonNegativeInt),
|
||||
/** Commits on the branch that are not on the default branch. */
|
||||
aheadOfDefaultCount: Schema.NullOr(NonNegativeInt),
|
||||
/** Latest linked-thread activity; falls back to directory mtime for orphans. */
|
||||
lastActivityAt: Schema.NullOr(IsoDateTime),
|
||||
safeToPrune: Schema.Boolean,
|
||||
pruneBlockers: Schema.Array(WorktreePruneBlocker),
|
||||
});
|
||||
export type WorktreeInfo = typeof WorktreeInfo.Type;
|
||||
|
||||
export const WorktreePruneSkipReason = Schema.Literals([
|
||||
"active_thread",
|
||||
"dirty",
|
||||
"unpushed",
|
||||
"status_unavailable",
|
||||
"unknown_worktree",
|
||||
"remove_failed",
|
||||
]);
|
||||
export type WorktreePruneSkipReason = typeof WorktreePruneSkipReason.Type;
|
||||
|
||||
// RPC Inputs
|
||||
|
||||
export const VcsListWorktreesInput = Schema.Struct({
|
||||
projectId: Schema.optional(ProjectId),
|
||||
});
|
||||
export type VcsListWorktreesInput = typeof VcsListWorktreesInput.Type;
|
||||
|
||||
export const VcsPruneWorktreesInput = Schema.Struct({
|
||||
paths: Schema.Array(TrimmedNonEmptyString).check(Schema.isMinLength(1)),
|
||||
});
|
||||
export type VcsPruneWorktreesInput = typeof VcsPruneWorktreesInput.Type;
|
||||
|
||||
// RPC Results
|
||||
|
||||
export const VcsListWorktreesResult = Schema.Struct({
|
||||
worktrees: Schema.Array(WorktreeInfo),
|
||||
});
|
||||
export type VcsListWorktreesResult = typeof VcsListWorktreesResult.Type;
|
||||
|
||||
export const VcsPruneWorktreesResult = Schema.Struct({
|
||||
removed: Schema.Array(
|
||||
Schema.Struct({
|
||||
path: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
}),
|
||||
),
|
||||
skipped: Schema.Array(
|
||||
Schema.Struct({
|
||||
path: TrimmedNonEmptyString,
|
||||
reason: WorktreePruneSkipReason,
|
||||
detail: Schema.optional(Schema.String),
|
||||
}),
|
||||
),
|
||||
});
|
||||
export type VcsPruneWorktreesResult = typeof VcsPruneWorktreesResult.Type;
|
||||
Reference in new issue
Block a user