@laoyuehanni/dsh-git-worktree 0.4.7 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -56,6 +56,9 @@ window.__ModuleLoader__.load({
56
56
  const ROUTE_PREFIX = "/plugin/git-worktree";
57
57
  /** GET ROUTE_PREFIX/status?path=<absolute dir> */
58
58
  const ROUTE_STATUS = `${ROUTE_PREFIX}/status`;
59
+ /** GET ROUTE_PREFIX/head?path=<absolute dir> — checked-out branch only.
60
+ * A file read of HEAD, not a git process. */
61
+ const ROUTE_HEAD = `${ROUTE_PREFIX}/head`;
59
62
  /** POST ROUTE_PREFIX/worktree — create-or-reuse a worktree for a branch. */
60
63
  const ROUTE_WORKTREE = `${ROUTE_PREFIX}/worktree`;
61
64
  /** POST ROUTE_PREFIX/switch — in-place branch switch of the main checkout. */
@@ -146,6 +149,31 @@ window.__ModuleLoader__.load({
146
149
  }
147
150
  }
148
151
  /**
152
+ * Checked-out branch of one directory (the HEAD file, not a full status).
153
+ * @param path - absolute workspace directory.
154
+ */
155
+ async function fetchHead(path, signal) {
156
+ try {
157
+ const response = await fetch(`${ROUTE_HEAD}?path=${encodeURIComponent(path)}`, {
158
+ cache: "no-store",
159
+ ...signal === void 0 ? {} : { signal }
160
+ });
161
+ if (!response.ok) return {
162
+ ok: false,
163
+ error: `HTTP ${String(response.status)}`
164
+ };
165
+ return {
166
+ ...await response.json(),
167
+ ok: true
168
+ };
169
+ } catch (cause) {
170
+ return {
171
+ ok: false,
172
+ error: cause instanceof Error ? cause.message : String(cause)
173
+ };
174
+ }
175
+ }
176
+ /**
149
177
  * Create or reuse the worktree for a branch.
150
178
  * @param repoPath - absolute directory inside the repository.
151
179
  * @param branch - branch display name.
@@ -299,6 +327,135 @@ window.__ModuleLoader__.load({
299
327
  return post(ROUTE_PURGE, { path });
300
328
  }
301
329
  //#endregion
330
+ //#region src/client/head-poll.ts
331
+ /**
332
+ * Shared poll of the checked-out branch while the page is visible.
333
+ *
334
+ * One timer for every branch label. Subscribers on the same directory share
335
+ * one request per tick. The tick only reports a branch name; the label
336
+ * decides whether that name is news. Hidden pages do not tick. A directory
337
+ * watch was declined: git replaces HEAD by rename, which drops a file watch
338
+ * on Windows, and the poll does not need a push channel.
339
+ */
340
+ /** How often a visible page re-reads HEAD. Long enough to be idle noise,
341
+ * short enough that a checkout in this same window shows up on the label. */
342
+ const HEAD_POLL_MS = 5e3;
343
+ /** Bound a slow directory's read without delaying any other directory. */
344
+ const HEAD_POLL_TIMEOUT_MS = 5e3;
345
+ /** Separators, a trailing slash, and (for a drive-letter path) letter case. */
346
+ function pollKey(path) {
347
+ const slashed = path.replace(/\\/g, "/").replace(/\/+$/, "");
348
+ return /^[A-Za-z]:/.test(slashed) ? slashed.toLowerCase() : slashed;
349
+ }
350
+ /** A poll bound to `env`. Production uses one shared instance. */
351
+ function createHeadPoll(env) {
352
+ const buckets = /* @__PURE__ */ new Map();
353
+ let timer;
354
+ let unsubscribeVisibility;
355
+ const stop = () => {
356
+ if (timer === void 0) return;
357
+ env.clearInterval(timer);
358
+ timer = void 0;
359
+ };
360
+ const start = () => {
361
+ if (timer !== void 0 || env.visibility() !== "visible" || buckets.size === 0) return;
362
+ timer = env.setInterval(tick, HEAD_POLL_MS);
363
+ };
364
+ const onVisibility = () => {
365
+ if (env.visibility() === "visible") start();
366
+ else {
367
+ stop();
368
+ for (const bucket of buckets.values()) bucket.request?.abort();
369
+ }
370
+ };
371
+ function tick() {
372
+ if (env.visibility() !== "visible") {
373
+ stop();
374
+ return;
375
+ }
376
+ for (const bucket of buckets.values()) if (bucket.request === void 0) readBucket(bucket);
377
+ }
378
+ async function readBucket(bucket) {
379
+ const controller = new AbortController();
380
+ bucket.request = controller;
381
+ const timeout = env.setTimeout(() => {
382
+ controller.abort();
383
+ }, HEAD_POLL_TIMEOUT_MS);
384
+ const cancelled = new Promise((resolve) => {
385
+ controller.signal.addEventListener("abort", () => {
386
+ resolve(void 0);
387
+ }, { once: true });
388
+ });
389
+ try {
390
+ const result = await Promise.race([env.fetchHead(bucket.path, controller.signal), cancelled]);
391
+ if (controller.signal.aborted || env.visibility() !== "visible") return;
392
+ if (result === void 0 || !result.ok || !result.repo || !("currentBranch" in result)) return;
393
+ if (result.currentBranch === "") return;
394
+ for (const listener of [...bucket.listeners]) {
395
+ if (!bucket.listeners.has(listener)) continue;
396
+ try {
397
+ listener(result.currentBranch);
398
+ } catch {}
399
+ }
400
+ } catch {} finally {
401
+ env.clearTimeout(timeout);
402
+ delete bucket.request;
403
+ }
404
+ }
405
+ return { subscribe(path, listener) {
406
+ const key = pollKey(path);
407
+ let bucket = buckets.get(key);
408
+ if (bucket === void 0) {
409
+ bucket = {
410
+ path,
411
+ listeners: /* @__PURE__ */ new Set()
412
+ };
413
+ buckets.set(key, bucket);
414
+ }
415
+ bucket.listeners.add(listener);
416
+ if (unsubscribeVisibility === void 0) unsubscribeVisibility = env.onVisibility(onVisibility);
417
+ start();
418
+ return () => {
419
+ const current = buckets.get(key);
420
+ if (current !== bucket) return;
421
+ current.listeners.delete(listener);
422
+ if (current.listeners.size > 0) return;
423
+ buckets.delete(key);
424
+ current.request?.abort();
425
+ if (buckets.size > 0) return;
426
+ stop();
427
+ unsubscribeVisibility?.();
428
+ unsubscribeVisibility = void 0;
429
+ };
430
+ } };
431
+ }
432
+ let shared;
433
+ /** Join the page-wide HEAD poll. The unsubscribe drops this listener only. */
434
+ function subscribeCheckedOutBranch(path, listener) {
435
+ shared ??= createHeadPoll(browserEnv());
436
+ return shared.subscribe(path, listener);
437
+ }
438
+ function browserEnv() {
439
+ return {
440
+ fetchHead,
441
+ setInterval: (callback, ms) => window.setInterval(callback, ms),
442
+ clearInterval: (id) => {
443
+ window.clearInterval(id);
444
+ },
445
+ setTimeout: (callback, ms) => window.setTimeout(callback, ms),
446
+ clearTimeout: (id) => {
447
+ window.clearTimeout(id);
448
+ },
449
+ visibility: () => document.visibilityState === "visible" ? "visible" : "hidden",
450
+ onVisibility: (callback) => {
451
+ document.addEventListener("visibilitychange", callback);
452
+ return () => {
453
+ document.removeEventListener("visibilitychange", callback);
454
+ };
455
+ }
456
+ };
457
+ }
458
+ //#endregion
302
459
  //#region src/client/branch-tree.ts
303
460
  /** Segment order: natural (so `v2` precedes `v10`) and case-blind. */
304
461
  const segCmp = (a, b) => a.localeCompare(b, void 0, {
@@ -2291,19 +2448,23 @@ window.__ModuleLoader__.load({
2291
2448
  */
2292
2449
  function useRepoStatus(cwd) {
2293
2450
  const [state, setState] = (0, react.useState)({ facts: null });
2451
+ const gen = (0, react.useRef)(0);
2294
2452
  const load = (0, react.useCallback)(async () => {
2453
+ const ticket = ++gen.current;
2295
2454
  if (cwd === void 0) {
2296
2455
  setState({ facts: null });
2297
2456
  return;
2298
2457
  }
2299
2458
  const result = await fetchStatus(cwd);
2300
- setState({ facts: result.ok && result.repo ? result : null });
2459
+ if (ticket !== gen.current || !result.ok) return;
2460
+ setState({ facts: result.repo ? result : null });
2301
2461
  }, [cwd]);
2302
2462
  (0, react.useEffect)(() => {
2463
+ const ticket = ++gen.current;
2303
2464
  let live = true;
2304
2465
  setState({ facts: null });
2305
2466
  if (cwd !== void 0) fetchStatus(cwd).then((result) => {
2306
- if (live) setState({ facts: result.ok && result.repo ? result : null });
2467
+ if (live && ticket === gen.current) setState({ facts: result.ok && result.repo ? result : null });
2307
2468
  });
2308
2469
  return () => {
2309
2470
  live = false;
@@ -2580,6 +2741,13 @@ window.__ModuleLoader__.load({
2580
2741
  }, []);
2581
2742
  const chipRef = (0, react.useRef)(null);
2582
2743
  const busyRef = (0, react.useRef)(false);
2744
+ /** Branch the label is showing. The poll compares against this and does
2745
+ * not refetch while it is still empty (the mount fetch owns that). */
2746
+ const shownBranchRef = (0, react.useRef)(void 0);
2747
+ shownBranchRef.current = repo.facts?.currentBranch;
2748
+ /** One poll-triggered status fetch at a time. Focus and menu opens do not
2749
+ * take this flag; the generation in useRepoStatus orders those bodies. */
2750
+ const pollRefreshRef = (0, react.useRef)(false);
2583
2751
  (0, react.useEffect)(() => {
2584
2752
  setConfirm(null);
2585
2753
  setMenuOpen(false);
@@ -2602,6 +2770,23 @@ window.__ModuleLoader__.load({
2602
2770
  document.removeEventListener("visibilitychange", onVisibility);
2603
2771
  };
2604
2772
  }, [refresh]);
2773
+ const watchingBranch = cwd !== void 0 && repo.facts !== null;
2774
+ (0, react.useEffect)(() => {
2775
+ if (!watchingBranch || cwd === void 0) return;
2776
+ return subscribeCheckedOutBranch(cwd, (branch) => {
2777
+ if (busyRef.current || pollRefreshRef.current) return;
2778
+ const shown = shownBranchRef.current;
2779
+ if (shown === void 0 || shown === branch) return;
2780
+ pollRefreshRef.current = true;
2781
+ refresh().finally(() => {
2782
+ pollRefreshRef.current = false;
2783
+ });
2784
+ });
2785
+ }, [
2786
+ cwd,
2787
+ refresh,
2788
+ watchingBranch
2789
+ ]);
2605
2790
  const showError = (0, react.useCallback)((message) => {
2606
2791
  pushToast(t("errorGeneric", { message }));
2607
2792
  }, [pushToast, t]);
package/lib/head.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Checked-out branch by reading HEAD, not by spawning git.
3
+ *
4
+ * The branch label polls this while the page is visible. A full `git status`
5
+ * probe is several processes (and ahead/behind grows with the branch list);
6
+ * `git branch --show-current` is one process whose cost is mostly startup.
7
+ * HEAD is a single short text file, and the host process is already resident.
8
+ *
9
+ * Discovery follows git's own walk: from the directory upward until a `.git`
10
+ * entry. A directory is the git dir (main checkout). A file is a gitfile
11
+ * (`gitdir: <path>`, relative paths resolved against the file's directory) —
12
+ * linked worktrees and submodules. The branch name is whatever that git dir's
13
+ * HEAD says.
14
+ *
15
+ * This does not consult `GIT_DIR`. The full status route still goes through
16
+ * git, and that result is what the label actually renders; a disagreement
17
+ * here only decides whether to ask git again.
18
+ */
19
+ /** What a directory's checkout looks like to the poll. */
20
+ export type CheckedOutBranch = {
21
+ kind: 'absent';
22
+ }
23
+ /** `.git` was found, but HEAD could not be read completely this tick. */
24
+ | {
25
+ kind: 'unread';
26
+ }
27
+ /** `name` is the branch, or `HEAD` when detached (the label's existing word). */
28
+ | {
29
+ kind: 'branch';
30
+ name: string;
31
+ };
32
+ /** Checked-out branch of `dir`, walking parent directories the way git does. */
33
+ export declare function readCheckedOutBranch(dir: string): Promise<CheckedOutBranch>;
package/lib/head.js ADDED
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Checked-out branch by reading HEAD, not by spawning git.
3
+ *
4
+ * The branch label polls this while the page is visible. A full `git status`
5
+ * probe is several processes (and ahead/behind grows with the branch list);
6
+ * `git branch --show-current` is one process whose cost is mostly startup.
7
+ * HEAD is a single short text file, and the host process is already resident.
8
+ *
9
+ * Discovery follows git's own walk: from the directory upward until a `.git`
10
+ * entry. A directory is the git dir (main checkout). A file is a gitfile
11
+ * (`gitdir: <path>`, relative paths resolved against the file's directory) —
12
+ * linked worktrees and submodules. The branch name is whatever that git dir's
13
+ * HEAD says.
14
+ *
15
+ * This does not consult `GIT_DIR`. The full status route still goes through
16
+ * git, and that result is what the label actually renders; a disagreement
17
+ * here only decides whether to ask git again.
18
+ */
19
+ import { open, realpath, stat } from 'node:fs/promises';
20
+ import { dirname, join, resolve } from 'node:path';
21
+ /** HEAD is one short line. A buffer that comes back full is a partial write
22
+ * or not a HEAD file — a prefix must not be treated as a branch name. */
23
+ const HEAD_READ_MAX = 1024;
24
+ /** A gitfile is one path. Same rule as {@link HEAD_READ_MAX}. */
25
+ const GITDIR_READ_MAX = 4096;
26
+ /** Checked-out branch of `dir`, walking parent directories the way git does. */
27
+ export async function readCheckedOutBranch(dir) {
28
+ try {
29
+ return await discover(dir);
30
+ }
31
+ catch {
32
+ // A permission error or a path that vanishes mid-read is a skipped tick,
33
+ // not a reason to clear the label.
34
+ return { kind: 'unread' };
35
+ }
36
+ }
37
+ async function discover(dir) {
38
+ let cursor;
39
+ try {
40
+ cursor = await realpath(dir);
41
+ }
42
+ catch (error) {
43
+ return isEnoent(error) ? { kind: 'absent' } : { kind: 'unread' };
44
+ }
45
+ if (!(await stat(cursor)).isDirectory())
46
+ return { kind: 'absent' };
47
+ for (;;) {
48
+ const gitPath = join(cursor, '.git');
49
+ let info;
50
+ try {
51
+ info = await stat(gitPath);
52
+ }
53
+ catch (error) {
54
+ if (!isEnoent(error))
55
+ return { kind: 'unread' };
56
+ const parent = dirname(cursor);
57
+ if (parent === cursor)
58
+ return { kind: 'absent' };
59
+ cursor = parent;
60
+ continue;
61
+ }
62
+ if (info.isDirectory())
63
+ return readHeadFile(join(gitPath, 'HEAD'));
64
+ if (info.isFile())
65
+ return readGitfile(gitPath);
66
+ return { kind: 'unread' };
67
+ }
68
+ }
69
+ /** Linked worktree / submodule: `.git` is a file pointing at the real git dir. */
70
+ async function readGitfile(gitFile) {
71
+ const text = await readBounded(gitFile, GITDIR_READ_MAX);
72
+ if (typeof text !== 'string')
73
+ return { kind: 'unread' };
74
+ const line = firstLine(text).trim();
75
+ if (!line.startsWith('gitdir:'))
76
+ return { kind: 'unread' };
77
+ const target = line.slice('gitdir:'.length).trim();
78
+ if (target === '')
79
+ return { kind: 'unread' };
80
+ // One hop. A gitfile points at a git dir that holds HEAD, not at another gitfile.
81
+ return readHeadFile(join(resolve(dirname(gitFile), target), 'HEAD'));
82
+ }
83
+ async function readHeadFile(headPath) {
84
+ const text = await readBounded(headPath, HEAD_READ_MAX);
85
+ if (typeof text !== 'string')
86
+ return { kind: 'unread' };
87
+ const name = parseHead(text);
88
+ if (name === undefined)
89
+ return { kind: 'unread' };
90
+ return { kind: 'branch', name };
91
+ }
92
+ /**
93
+ * Read at most `max` bytes. `'missing'` is ENOENT; `'truncated'` means the
94
+ * file filled the cap (do not parse a prefix). Other IO errors throw.
95
+ */
96
+ async function readBounded(path, max) {
97
+ let handle;
98
+ try {
99
+ handle = await open(path, 'r');
100
+ }
101
+ catch (error) {
102
+ if (isEnoent(error))
103
+ return 'missing';
104
+ throw error;
105
+ }
106
+ try {
107
+ const buffer = Buffer.alloc(max);
108
+ const { bytesRead } = await handle.read(buffer, 0, max, 0);
109
+ if (bytesRead >= max)
110
+ return 'truncated';
111
+ return buffer.subarray(0, bytesRead).toString('utf8');
112
+ }
113
+ finally {
114
+ await handle.close();
115
+ }
116
+ }
117
+ /**
118
+ * The label's word for one HEAD file. `refs/heads/<name>` is that branch.
119
+ * Any other complete form git uses for "not on a branch" (a commit id, or a
120
+ * symbolic ref outside `refs/heads`) is `HEAD`, matching
121
+ * `git branch --show-current` printing nothing. A partial line is `undefined`
122
+ * so the tick is skipped.
123
+ */
124
+ function parseHead(text) {
125
+ const line = firstLine(text).trim();
126
+ if (line === '')
127
+ return undefined;
128
+ if (line.startsWith('ref:')) {
129
+ const ref = line.slice('ref:'.length).trim();
130
+ const heads = 'refs/heads/';
131
+ if (ref.startsWith(heads)) {
132
+ const name = ref.slice(heads.length);
133
+ if (name === '' || name.endsWith('/') || /\s/.test(name))
134
+ return undefined;
135
+ return name;
136
+ }
137
+ // A finished non-branch symref is `refs/<namespace>/<name>`. A torn write
138
+ // (`ref: refs/hea`) never has that second slash, so it stays unread.
139
+ if (/^refs\/[A-Za-z0-9_-]+\/\S+$/.test(ref))
140
+ return 'HEAD';
141
+ return undefined;
142
+ }
143
+ if (/^[0-9a-f]{40}$/i.test(line) || /^[0-9a-f]{64}$/i.test(line))
144
+ return 'HEAD';
145
+ return undefined;
146
+ }
147
+ function firstLine(text) {
148
+ return text.split(/\r?\n/, 1)[0] ?? '';
149
+ }
150
+ function isEnoent(error) {
151
+ return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';
152
+ }
package/lib/index.js CHANGED
@@ -8,9 +8,9 @@
8
8
  import { homedir } from 'node:os';
9
9
  import z from '@deepseek-ai/schemastery';
10
10
  import { childProcessExec } from './git.js';
11
- import { handleCreateBranch, handleCreateWorktree, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGroupWorktrees, handleInspectWorktree, handlePathExists, handlePurgeDirectory, handleRemoveWorktree, handleRenameBranch, handleStatus, handleSwitch, handleUpdate, handleWorktreesAll, } from './routes.js';
11
+ import { handleCreateBranch, handleCreateWorktree, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGroupWorktrees, handleHead, handleInspectWorktree, handlePathExists, handlePurgeDirectory, handleRemoveWorktree, handleRenameBranch, handleStatus, handleSwitch, handleUpdate, handleWorktreesAll, } from './routes.js';
12
12
  import { validateRootDir } from './settings.js';
13
- import { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_INSPECT, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
13
+ import { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_HEAD, ROUTE_INSPECT, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
14
14
  export const name = 'dsh-git-worktree';
15
15
  export const inject = [];
16
16
  /** Largest accepted request body (bytes) — these payloads are a few strings. */
@@ -174,12 +174,17 @@ export function apply(ctx, config = {}) {
174
174
  }
175
175
  } }), `git-worktree: ${label} route`);
176
176
  };
177
- // The one query-driven route; every mutation is a POST body.
177
+ // Query-driven reads. Every mutation is a POST body.
178
178
  webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_STATUS, handler: async (req, res) => {
179
179
  /* v8 ignore next -- node:http always sets url on server requests. */
180
180
  const query = new URL(req.url ?? '/', 'http://x').searchParams;
181
181
  send(res, await handleStatus(deps(), query.get('path') ?? undefined));
182
182
  } }), 'git-worktree: status route');
183
+ webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_HEAD, handler: async (req, res) => {
184
+ /* v8 ignore next -- node:http always sets url on server requests. */
185
+ const query = new URL(req.url ?? '/', 'http://x').searchParams;
186
+ send(res, await handleHead(query.get('path') ?? undefined));
187
+ } }), 'git-worktree: head route');
183
188
  postRoute(ROUTE_WORKTREE, 'worktree', handleCreateWorktree);
184
189
  postRoute(ROUTE_SWITCH, 'switch', handleSwitch);
185
190
  postRoute(ROUTE_BRANCH, 'branch', handleCreateBranch);
package/lib/routes.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import { type CopyFilesSeams } from './copy-files.js';
6
6
  import { type DirExists, type ExcludeSeams, type Exec } from './git.js';
7
- import type { CreateBranchResult, CreateWorktreeResult, EnsureDirectoryResult, FetchResult, GroupWorkspacesResult, InspectWorktreeResult, PathExistsResult, PurgeDirectoryResult, RemoveWorktreeResult, RepoStatus, RouteError, SwitchResult, UpdateResult, WorktreesAllResult } from './wire.js';
7
+ import type { CreateBranchResult, CreateWorktreeResult, EnsureDirectoryResult, FetchResult, GroupWorkspacesResult, HeadStatus, InspectWorktreeResult, PathExistsResult, PurgeDirectoryResult, RemoveWorktreeResult, RepoStatus, RouteError, SwitchResult, UpdateResult, WorktreesAllResult } from './wire.js';
8
8
  /** Everything the handlers need from the host half. */
9
9
  export interface RouteDeps {
10
10
  exec: Exec;
@@ -46,7 +46,7 @@ export declare function fsMkdirRecursive(path: string): Promise<void>;
46
46
  /** One route outcome: HTTP status plus the JSON body. */
47
47
  export interface RouteOutcome {
48
48
  status: number;
49
- body: RepoStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | WorktreesAllResult | PurgeDirectoryResult | RouteError;
49
+ body: RepoStatus | HeadStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | WorktreesAllResult | PurgeDirectoryResult | RouteError;
50
50
  }
51
51
  /**
52
52
  * POST /group — git belonging facts for a batch of workspace directories.
@@ -104,6 +104,12 @@ export declare function handlePurgeDirectory(deps: RouteDeps, body: unknown): Pr
104
104
  * @param path - absolute directory the workspace reports.
105
105
  */
106
106
  export declare function handleStatus(deps: RouteDeps, path: string | undefined): Promise<RouteOutcome>;
107
+ /**
108
+ * GET /head — the checked-out branch of one directory, from the HEAD file.
109
+ * `pending` is a skipped tick: the caller keeps the label it already has.
110
+ * @param path - absolute directory the workspace reports.
111
+ */
112
+ export declare function handleHead(path: string | undefined): Promise<RouteOutcome>;
107
113
  /**
108
114
  * POST /worktree — create or reuse the worktree for a branch, then report the
109
115
  * directory so the client can register it as a workspace. The worktree lands
package/lib/routes.js CHANGED
@@ -6,6 +6,7 @@ import { basename, dirname, join, resolve } from 'node:path';
6
6
  import { mkdir, readdir, rm, stat } from 'node:fs/promises';
7
7
  import { runPostCreateCopy } from './copy-files.js';
8
8
  import { appendWorktreeExclude, fsExcludeSeams, GitError, addWorktree, addWorktreeCutout, createBranch, cutoutBranchName, deleteBranch, fetchAll, fsDirExists, inspectWorktree, isAbsoluteDir, probeRepo, probeWorkspaceGit, removeWorktree, renameBranch, resolveBranch, switchBranch, updateBranch } from './git.js';
9
+ import { readCheckedOutBranch } from './head.js';
9
10
  import { isAbsoluteConfigPath, sanitizeBranchDir } from './normalize.js';
10
11
  import { resolveRootDir } from './settings.js';
11
12
  /** Real fs-backed one-level directory listing (names only). Plain FILES are
@@ -326,6 +327,21 @@ export async function handleStatus(deps, path) {
326
327
  },
327
328
  };
328
329
  }
330
+ /**
331
+ * GET /head — the checked-out branch of one directory, from the HEAD file.
332
+ * `pending` is a skipped tick: the caller keeps the label it already has.
333
+ * @param path - absolute directory the workspace reports.
334
+ */
335
+ export async function handleHead(path) {
336
+ if (path === undefined || !isAbsoluteDir(path))
337
+ return fail(400, 'query parameter "path" must be an absolute directory');
338
+ const read = await readCheckedOutBranch(path);
339
+ if (read.kind === 'absent')
340
+ return { status: 200, body: { repo: false } };
341
+ if (read.kind === 'unread')
342
+ return { status: 200, body: { repo: true, pending: true } };
343
+ return { status: 200, body: { repo: true, currentBranch: read.name } };
344
+ }
329
345
  /** Validate a JSON body object with exactly the expected keys. */
330
346
  function readBody(body, keys, booleanKeys = [], optionalKeys = []) {
331
347
  if (typeof body !== 'object' || body === null || Array.isArray(body))
package/lib/wire.d.ts CHANGED
@@ -8,6 +8,9 @@
8
8
  export declare const ROUTE_PREFIX = "/plugin/git-worktree";
9
9
  /** GET ROUTE_PREFIX/status?path=<absolute dir> */
10
10
  export declare const ROUTE_STATUS = "/plugin/git-worktree/status";
11
+ /** GET ROUTE_PREFIX/head?path=<absolute dir> — checked-out branch only.
12
+ * A file read of HEAD, not a git process. */
13
+ export declare const ROUTE_HEAD = "/plugin/git-worktree/head";
11
14
  /** POST ROUTE_PREFIX/worktree — create-or-reuse a worktree for a branch. */
12
15
  export declare const ROUTE_WORKTREE = "/plugin/git-worktree/worktree";
13
16
  /** POST ROUTE_PREFIX/switch — in-place branch switch of the main checkout. */
@@ -85,6 +88,22 @@ export type RepoStatus = {
85
88
  /** Resolved worktree storage root (absolute) — what the settings say today. */
86
89
  rootDir: string;
87
90
  };
91
+ /**
92
+ * Response of GET head. `repo: false` — the directory is not inside a
93
+ * repository. `pending` — a repository was found but HEAD could not be read
94
+ * completely this tick (mid-checkout, partial write); callers skip the tick
95
+ * rather than guess a name. `currentBranch` is the branch, or `HEAD` when
96
+ * detached.
97
+ */
98
+ export type HeadStatus = {
99
+ repo: false;
100
+ } | {
101
+ repo: true;
102
+ pending: true;
103
+ } | {
104
+ repo: true;
105
+ currentBranch: string;
106
+ };
88
107
  /** POST worktree request body. */
89
108
  export interface CreateWorktreeBody {
90
109
  /** Any directory inside the repository (workspace cwd). */
package/lib/wire.js CHANGED
@@ -8,6 +8,9 @@
8
8
  export const ROUTE_PREFIX = '/plugin/git-worktree';
9
9
  /** GET ROUTE_PREFIX/status?path=<absolute dir> */
10
10
  export const ROUTE_STATUS = `${ROUTE_PREFIX}/status`;
11
+ /** GET ROUTE_PREFIX/head?path=<absolute dir> — checked-out branch only.
12
+ * A file read of HEAD, not a git process. */
13
+ export const ROUTE_HEAD = `${ROUTE_PREFIX}/head`;
11
14
  /** POST ROUTE_PREFIX/worktree — create-or-reuse a worktree for a branch. */
12
15
  export const ROUTE_WORKTREE = `${ROUTE_PREFIX}/worktree`;
13
16
  /** POST ROUTE_PREFIX/switch — in-place branch switch of the main checkout. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@laoyuehanni/dsh-git-worktree",
3
- "version": "0.4.7",
3
+ "version": "0.4.8",
4
4
  "description": "DSH plugin: branch visibility and git worktree isolation for Web UI sessions",
5
5
  "keywords": [
6
6
  "dsh",