@laoyuehanni/dsh-git-worktree 0.4.0 → 0.4.1

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/routes.js CHANGED
@@ -4,16 +4,87 @@
4
4
  */
5
5
  import { join } from 'node:path';
6
6
  import { mkdir } from 'node:fs/promises';
7
- import { GitError, addWorktree, addWorktreeCutout, cutoutBranchName, fsDirExists, isAbsoluteDir, probeRepo, switchBranch } from './git.js';
7
+ import { GitError, addWorktree, addWorktreeCutout, createBranch, cutoutBranchName, fetchAll, fsDirExists, isAbsoluteDir, probeRepo, probeWorkspaceGit, switchBranch, updateBranch } from './git.js';
8
8
  import { isAbsoluteConfigPath, sanitizeBranchDir } from './normalize.js';
9
9
  import { resolveRootDir } from './settings.js';
10
10
  /** Uniform failure envelope. */
11
11
  function fail(status, error) {
12
12
  return { status, body: { error } };
13
13
  }
14
+ /** Upper bound on distinct paths one /group request may probe. */
15
+ const GROUP_PATHS_LIMIT = 256;
16
+ /** Probes per in-flight batch — polite on Windows, where each git call is a process spawn. */
17
+ const GROUP_BATCH_SIZE = 8;
18
+ /**
19
+ * POST /group — git belonging facts for a batch of workspace directories.
20
+ * Deduplicates, validates, probes in bounded batches, and answers 200 with
21
+ * per-path facts (null for non-repositories); a repository-wide git failure
22
+ * is a per-path null, never a 500 — the sidebar must degrade to flat, not
23
+ * error out.
24
+ * @param deps - host dependencies.
25
+ * @param body - parsed request body: `{ paths }`.
26
+ */
27
+ export async function handleGroupWorktrees(deps, body) {
28
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
29
+ return fail(400, 'request body must be a JSON object');
30
+ const paths = body.paths;
31
+ if (!Array.isArray(paths))
32
+ return fail(400, 'body key "paths" must be an array of absolute directories');
33
+ const unknownKeys = Object.keys(body).filter(key => key !== 'paths');
34
+ if (unknownKeys.length > 0)
35
+ return fail(400, `unknown body key "${unknownKeys[0]}"`);
36
+ const distinct = [];
37
+ for (const candidate of paths) {
38
+ if (typeof candidate !== 'string' || !isAbsoluteDir(candidate))
39
+ return fail(400, 'body key "paths" must be an array of absolute directories');
40
+ if (!distinct.includes(candidate))
41
+ distinct.push(candidate);
42
+ }
43
+ if (distinct.length > GROUP_PATHS_LIMIT)
44
+ return fail(400, `body key "paths" accepts at most ${String(GROUP_PATHS_LIMIT)} distinct directories`);
45
+ const facts = {};
46
+ for (let start = 0; start < distinct.length; start += GROUP_BATCH_SIZE) {
47
+ const batch = distinct.slice(start, start + GROUP_BATCH_SIZE);
48
+ const probed = await Promise.all(batch.map(async (path) => {
49
+ // A probe never throws here by contract (gitMaybe folds non-zero exits),
50
+ // but a defensive catch keeps ONE bad path from sinking the batch.
51
+ try {
52
+ return [path, await probeWorkspaceGit(deps.exec, path) ?? null];
53
+ }
54
+ catch {
55
+ return [path, null];
56
+ }
57
+ }));
58
+ for (const [path, value] of probed)
59
+ facts[path] = value;
60
+ }
61
+ return { status: 200, body: { facts } };
62
+ }
14
63
  /** GitError to outcome: usage-shaped failures are 400, the rest 500. */
15
64
  function gitFailure(error) {
16
- const usage = error.stderr.includes('usage:') || error.stderr.includes('fatal: invalid');
65
+ const usage = error.stderr.includes('usage:')
66
+ || error.stderr.includes('fatal: invalid')
67
+ // A user-typed branch name git refuses (`'bad..name' is not a valid
68
+ // branch name`) is caller misuse, not a host fault — the client
69
+ // pre-flights the same rules, this is the backstop.
70
+ || error.stderr.includes('not a valid branch name')
71
+ // A name or storage folder that already exists is caller misuse too
72
+ // (a stale worktree folder survives its branch's deletion): the client
73
+ // pre-flights branch duplicates, this is the backstop.
74
+ || error.stderr.includes('already exists')
75
+ // Diverged/branchless states an update cannot fast-forward through are
76
+ // the user's repo state, not host faults: no upstream to merge, a
77
+ // detached HEAD, or local commits `--ff-only` must not paper over.
78
+ || error.stderr.includes('Not possible to fast-forward')
79
+ || error.stderr.includes('no tracking information')
80
+ || error.stderr.includes("unknown revision")
81
+ // A display name that resolves to no branch at all (a stale row the
82
+ // menu no longer shows) is caller-side state, not a host fault. The
83
+ // failure is the SYNTHETIC GitError from git.ts (`branch "x" not
84
+ // found`), so match its `branch "` shape — git's own "not found"
85
+ // texts (a remote that vanished mid-fetch: `Repository '...' not
86
+ // found`) carry no quoted branch and stay 500 host faults.
87
+ || error.stderr.includes('branch "');
17
88
  return fail(usage ? 400 : 500, error.message);
18
89
  }
19
90
  /**
@@ -42,12 +113,12 @@ export async function handleStatus(deps, path) {
42
113
  };
43
114
  }
44
115
  /** Validate a JSON body object with exactly the expected keys. */
45
- function readBody(body, keys, booleanKeys = []) {
116
+ function readBody(body, keys, booleanKeys = [], optionalKeys = []) {
46
117
  if (typeof body !== 'object' || body === null || Array.isArray(body))
47
118
  return fail(400, 'request body must be a JSON object');
48
119
  const record = body;
49
120
  for (const key of Object.keys(record)) {
50
- if (!keys.includes(key) && !booleanKeys.includes(key)) {
121
+ if (!keys.includes(key) && !booleanKeys.includes(key) && !optionalKeys.includes(key)) {
51
122
  return fail(400, `unknown body key "${key}"`);
52
123
  }
53
124
  }
@@ -61,6 +132,12 @@ function readBody(body, keys, booleanKeys = []) {
61
132
  return fail(400, `body key "${key}" must be a boolean`);
62
133
  }
63
134
  }
135
+ for (const key of optionalKeys) {
136
+ // Optional string: absent stays absent (`name?: string`), present must type-check.
137
+ if (record[key] !== undefined && typeof record[key] !== 'string') {
138
+ return fail(400, `body key "${key}" must be a string`);
139
+ }
140
+ }
64
141
  return record;
65
142
  }
66
143
  /** Discriminator: a RouteOutcome carries the `status`/`body` pair no request body has. */
@@ -77,10 +154,10 @@ function isOutcome(value) {
77
154
  * @param body - parsed request body.
78
155
  */
79
156
  export async function handleCreateWorktree(deps, body) {
80
- const parsed = readBody(body, ['repoPath', 'branch'], ['cutout']);
157
+ const parsed = readBody(body, ['repoPath', 'branch'], ['cutout'], ['name']);
81
158
  if (isOutcome(parsed))
82
159
  return parsed;
83
- const { repoPath, branch, cutout } = parsed;
160
+ const { repoPath, branch, cutout, name } = parsed;
84
161
  if (!isAbsoluteDir(repoPath))
85
162
  return fail(400, '"repoPath" must be an absolute directory');
86
163
  if (branch.trim() === '')
@@ -95,6 +172,19 @@ export async function handleCreateWorktree(deps, body) {
95
172
  return fail(400, `"${repoPath}" is not inside a git repository`);
96
173
  const rootDir = resolveRootDir(deps.sectionRootDir(), deps.home(), deps.envHome());
97
174
  if (cutout === true) {
175
+ // An explicit name skips the `-wt` suffix walk and is used verbatim —
176
+ // both for the branch and the storage folder. A leading dash would
177
+ // ride `worktree add -b` as a flag; any other git-invalid name
178
+ // surfaces through the error envelope (the client pre-flights).
179
+ const custom = name?.trim();
180
+ if (custom !== undefined && custom !== '') {
181
+ if (custom.startsWith('-'))
182
+ return fail(400, '"name" must not start with "-"');
183
+ const target = join(rootDir, `${facts.repoName}-${sanitizeBranchDir(custom)}`);
184
+ await mkdir(rootDir, { recursive: true });
185
+ await addWorktreeCutout(deps.exec, facts.repoRoot, branch, custom, target);
186
+ return { status: 200, body: { path: target, created: true } };
187
+ }
98
188
  // The new branch name must be known before the folder name can be
99
189
  // computed: the folder carries `<repoName>-<NEW branch>`. The name
100
190
  // must be free in BOTH namespaces — the branch table and the storage
@@ -150,3 +240,96 @@ export async function handleSwitch(deps, body) {
150
240
  return fail(500, error instanceof Error ? error.message : String(error));
151
241
  }
152
242
  }
243
+ /**
244
+ * POST /branch 鈥?create a NEW branch from the queried directory's current
245
+ * checkout (whatever its HEAD points at, detached included) and check it out
246
+ * in place. Git validates the name; the client pre-flights the same rules
247
+ * and only sends names it already accepts.
248
+ * @param deps - host dependencies.
249
+ * @param body - parsed request body.
250
+ */
251
+ export async function handleCreateBranch(deps, body) {
252
+ const parsed = readBody(body, ['repoPath', 'name']);
253
+ if (isOutcome(parsed))
254
+ return parsed;
255
+ const { repoPath, name } = parsed;
256
+ if (!isAbsoluteDir(repoPath))
257
+ return fail(400, '"repoPath" must be an absolute directory');
258
+ if (name.trim() === '')
259
+ return fail(400, '"name" must be non-empty');
260
+ // A leading dash would ride `git switch -c` as a flag — reject before the
261
+ // exec, not as an "unknown switch" GitError.
262
+ if (name.startsWith('-'))
263
+ return fail(400, '"name" must not start with "-"');
264
+ try {
265
+ const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
266
+ if (facts === undefined)
267
+ return fail(400, `"${repoPath}" is not inside a git repository`);
268
+ const created = await createBranch(deps.exec, facts.repoRoot, name);
269
+ const result = { branch: created };
270
+ return { status: 200, body: result };
271
+ }
272
+ catch (error) {
273
+ if (error instanceof GitError)
274
+ return gitFailure(error);
275
+ return fail(500, error instanceof Error ? error.message : String(error));
276
+ }
277
+ }
278
+ /**
279
+ * POST /fetch 鈥?sync remote-tracking refs for the repository: fetch every
280
+ * remote and prune tracking branches the remotes no longer carry. Pure
281
+ * metadata — the working tree and the current checkout are untouched; the
282
+ * client refetches /status afterwards for the fresh branch list.
283
+ * @param deps - host dependencies.
284
+ * @param body - parsed request body.
285
+ */
286
+ export async function handleFetch(deps, body) {
287
+ const parsed = readBody(body, ['repoPath']);
288
+ if (isOutcome(parsed))
289
+ return parsed;
290
+ const { repoPath } = parsed;
291
+ if (!isAbsoluteDir(repoPath))
292
+ return fail(400, '"repoPath" must be an absolute directory');
293
+ try {
294
+ const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
295
+ if (facts === undefined)
296
+ return fail(400, `"${repoPath}" is not inside a git repository`);
297
+ await fetchAll(deps.exec, facts.repoRoot);
298
+ const result = { remote: 'all' };
299
+ return { status: 200, body: result };
300
+ }
301
+ catch (error) {
302
+ if (error instanceof GitError)
303
+ return gitFailure(error);
304
+ return fail(500, error instanceof Error ? error.message : String(error));
305
+ }
306
+ }
307
+ /**
308
+ * POST /update 鈥?update the CURRENT checkout: fetch every remote, then
309
+ * fast-forward the branch checked out by the queried directory to its
310
+ * upstream. Divergence, a missing upstream, and conflicting working-tree
311
+ * changes all surface as 400 envelopes carrying git's own explanation.
312
+ * @param deps - host dependencies.
313
+ * @param body - parsed request body.
314
+ */
315
+ export async function handleUpdate(deps, body) {
316
+ const parsed = readBody(body, ['repoPath']);
317
+ if (isOutcome(parsed))
318
+ return parsed;
319
+ const { repoPath } = parsed;
320
+ if (!isAbsoluteDir(repoPath))
321
+ return fail(400, '"repoPath" must be an absolute directory');
322
+ try {
323
+ const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
324
+ if (facts === undefined)
325
+ return fail(400, `"${repoPath}" is not inside a git repository`);
326
+ const outcome = await updateBranch(deps.exec, facts.repoRoot);
327
+ const result = { branch: outcome.branch, updated: outcome.updated };
328
+ return { status: 200, body: result };
329
+ }
330
+ catch (error) {
331
+ if (error instanceof GitError)
332
+ return gitFailure(error);
333
+ return fail(500, error instanceof Error ? error.message : String(error));
334
+ }
335
+ }
package/lib/wire.d.ts CHANGED
@@ -12,11 +12,24 @@ export declare const ROUTE_STATUS = "/plugin/git-worktree/status";
12
12
  export declare const ROUTE_WORKTREE = "/plugin/git-worktree/worktree";
13
13
  /** POST ROUTE_PREFIX/switch — in-place branch switch of the main checkout. */
14
14
  export declare const ROUTE_SWITCH = "/plugin/git-worktree/switch";
15
+ /** POST ROUTE_PREFIX/branch — create a NEW branch from the current checkout and switch to it. */
16
+ export declare const ROUTE_BRANCH = "/plugin/git-worktree/branch";
17
+ /** POST ROUTE_PREFIX/fetch — sync remote-tracking refs (fetch every remote + prune). */
18
+ export declare const ROUTE_FETCH = "/plugin/git-worktree/fetch";
19
+ /** POST ROUTE_PREFIX/update — fast-forward the current branch to its upstream. */
20
+ export declare const ROUTE_UPDATE = "/plugin/git-worktree/update";
21
+ /** POST ROUTE_PREFIX/group — git belonging facts for a batch of workspace paths. */
22
+ export declare const ROUTE_GROUP = "/plugin/git-worktree/group";
15
23
  /** One selectable branch row. */
16
24
  export interface BranchEntry {
17
25
  /** Display name: a bare local name (`main`) or `<remote>/<name>`. */
18
26
  name: string;
19
27
  kind: 'local' | 'remote';
28
+ /** Commits the local branch is AHEAD of its upstream (local rows with an
29
+ * upstream only; absent = no upstream or in sync). */
30
+ ahead?: number;
31
+ /** Commits the local branch is BEHIND its upstream (same conditions). */
32
+ behind?: number;
20
33
  }
21
34
  /** One existing worktree of the repository. */
22
35
  export interface WorktreeEntry {
@@ -38,7 +51,8 @@ export type RepoStatus = {
38
51
  repoRoot: string;
39
52
  /** Branch checked out by the directory the client asked about. */
40
53
  currentBranch: string;
41
- /** Local branches plus remote branches without a same-named local one. */
54
+ /** Local branches plus every remote's remote-only branches (those
55
+ * without a same-named local twin; `<remote>/HEAD` dropped). */
42
56
  branches: BranchEntry[];
43
57
  /** Every worktree of the repository, main first (git order). */
44
58
  worktrees: WorktreeEntry[];
@@ -55,6 +69,9 @@ export interface CreateWorktreeBody {
55
69
  * branch — occupied by the main worktree) and isolate it in a fresh
56
70
  * worktree. The storage folder is named after the new branch. */
57
71
  cutout?: boolean;
72
+ /** Cutout only: explicit name for the NEW branch. Default (absent):
73
+ * derived `<branch>-wt`, suffixing past taken names. */
74
+ name?: string;
58
75
  }
59
76
  /** POST worktree response body. */
60
77
  export interface CreateWorktreeResult {
@@ -75,7 +92,67 @@ export interface SwitchResult {
75
92
  /** The branch actually checked out after the switch. */
76
93
  branch: string;
77
94
  }
95
+ /** POST branch request body. */
96
+ export interface CreateBranchBody {
97
+ /** Any directory inside the repository (workspace cwd) — the new branch is
98
+ * cut from whatever this directory's HEAD points at and checked out HERE. */
99
+ repoPath: string;
100
+ /** User-typed name of the branch to create (a local name, verbatim). */
101
+ name: string;
102
+ }
103
+ /** POST branch response body. */
104
+ export interface CreateBranchResult {
105
+ /** The branch created and now checked out. */
106
+ branch: string;
107
+ }
108
+ /** POST fetch request body. */
109
+ export interface FetchBody {
110
+ /** Any directory inside the repository (workspace cwd). */
111
+ repoPath: string;
112
+ }
113
+ /** POST fetch response body — the fetch mutates refs server-side; the
114
+ * client refetches /status for the fresh branch list. */
115
+ export interface FetchResult {
116
+ /** What the fetch covered: "all" remotes (this plugin always fetches all). */
117
+ remote: string;
118
+ }
119
+ /** POST update request body. */
120
+ export interface UpdateBody {
121
+ /** Any directory inside the repository (workspace cwd) — the branch
122
+ * checked out by THIS directory is the one updated. */
123
+ repoPath: string;
124
+ }
125
+ /** POST update response body — fetch every remote, then fast-forward the
126
+ * checked-out branch to its upstream. */
127
+ export interface UpdateResult {
128
+ /** The branch that was updated (empty for a detached checkout, which
129
+ * cannot be updated and always errors before this response). */
130
+ branch: string;
131
+ /** False when the upstream already contained the branch (nothing moved). */
132
+ updated: boolean;
133
+ }
78
134
  /** Error envelope every non-2xx response carries. */
79
135
  export interface RouteError {
80
136
  error: string;
81
137
  }
138
+ /** Git belonging facts of one workspace directory; null = not a git repository. */
139
+ export interface WorkspaceGitFacts {
140
+ /** Grouping key: the repository's main worktree directory (canonical). */
141
+ repoRoot: string;
142
+ /** Group title: the main repository directory basename. */
143
+ repoName: string;
144
+ /** Branch checked out by this directory; null = detached or unborn HEAD. */
145
+ branch: string | null;
146
+ /** True when this directory IS the main worktree (holds the shared .git). */
147
+ main: boolean;
148
+ }
149
+ /** POST group request body. */
150
+ export interface GroupWorkspacesBody {
151
+ /** Absolute workspace directories to probe (deduped server-side). */
152
+ paths: string[];
153
+ }
154
+ /** POST group response body — one entry per DISTINCT requested path. */
155
+ export interface GroupWorkspacesResult {
156
+ /** Git facts per path; null marks a path outside any git repository. */
157
+ facts: Record<string, WorkspaceGitFacts | null>;
158
+ }
package/lib/wire.js CHANGED
@@ -12,3 +12,11 @@ export const ROUTE_STATUS = `${ROUTE_PREFIX}/status`;
12
12
  export const ROUTE_WORKTREE = `${ROUTE_PREFIX}/worktree`;
13
13
  /** POST ROUTE_PREFIX/switch — in-place branch switch of the main checkout. */
14
14
  export const ROUTE_SWITCH = `${ROUTE_PREFIX}/switch`;
15
+ /** POST ROUTE_PREFIX/branch — create a NEW branch from the current checkout and switch to it. */
16
+ export const ROUTE_BRANCH = `${ROUTE_PREFIX}/branch`;
17
+ /** POST ROUTE_PREFIX/fetch — sync remote-tracking refs (fetch every remote + prune). */
18
+ export const ROUTE_FETCH = `${ROUTE_PREFIX}/fetch`;
19
+ /** POST ROUTE_PREFIX/update — fast-forward the current branch to its upstream. */
20
+ export const ROUTE_UPDATE = `${ROUTE_PREFIX}/update`;
21
+ /** POST ROUTE_PREFIX/group — git belonging facts for a batch of workspace paths. */
22
+ export const ROUTE_GROUP = `${ROUTE_PREFIX}/group`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@laoyuehanni/dsh-git-worktree",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "DSH plugin: branch visibility and git worktree isolation for Web UI sessions",
5
5
  "keywords": [
6
6
  "dsh",
@@ -57,6 +57,7 @@
57
57
  "inject": [
58
58
  "@deepseek-ai/dsh-client-runtime",
59
59
  "@deepseek-ai/dsh-client-ui-conversation",
60
+ "@deepseek-ai/dsh-client-ui-sidebar",
60
61
  "@deepseek-ai/dsh-client-ui-settings",
61
62
  "@deepseek-ai/dsh-client-ui-settings-plugins"
62
63
  ]
@@ -86,10 +87,12 @@
86
87
  "@deepseek-ai/dsh-client-ui-primitives": "^0.1.0-rc.7",
87
88
  "@deepseek-ai/dsh-client-ui-settings": "^0.1.0-rc.7",
88
89
  "@deepseek-ai/dsh-client-ui-settings-plugins": "^0.1.0-rc.7",
90
+ "@deepseek-ai/dsh-client-ui-sidebar": "^0.1.0-rc.7",
89
91
  "@deepseek-ai/dsh-client-ui-slots": "^0.1.0-rc.7",
90
92
  "@deepseek-ai/dsh-host-webserver": "^0.1.0-rc.7",
91
93
  "@types/node": "^24.13.3",
92
94
  "@types/react": "~18.3.1",
95
+ "@types/react-dom": "~18.3.1",
93
96
  "playwright-core": "^1.55.1",
94
97
  "react": "^18.2.0",
95
98
  "tsdown": "^0.14.0",