dsh-worktree-workspace 0.0.0-stage → 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 limingyi_100
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # Git Worktree + 新工作区(@local/worktree-workspace)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DSH 插件:在**新建会话屏**顶部选项区新增「⑂ 工作树…」按钮,弹窗内可
4
+ **创建 git 工作树**(基于任意分支,自动生成 `dsh-xxxx-xxxx` 命名)并把它
5
+ **注册为独立工作区**自动跳转;也可一键**切换到已有工作树**。
6
+ 与原生「添加工作区」流程完全无关,不替换任何内置功能。
7
+
8
+ ## 使用方法
9
+
10
+ 1. 重启 DeepSeek Harness 后打开**新建会话屏**(点侧栏「新建会话」);
11
+ 2. 顶部控件行(项目选择器、模式选择器右侧)找到「⑂ 工作树…」按钮;
12
+ 3. 弹窗内:
13
+ - **项目**:下拉选择一个 git 仓库型工作区(如 fengqun-scm);
14
+ - **已有工作树**:列出该仓库全部 worktree,点「打开」切换过去
15
+ (目录尚未注册为工作区时会自动注册);
16
+ - **新建工作树**:选基线分支、填分支名(留空自动生成)、
17
+ 工作区名称(默认取分支名最后一段)、位置(默认 `<仓库>/.agents/worktrees`,
18
+ 记住上次选择);点「创建并打开」完成创建与跳转。
19
+
20
+ ## 安装 / 卸载
21
+
22
+ - 安装:`plugin_manager` 工具 `install_bundle`,target 指向本目录;
23
+ 或 DSH 界面 Settings → Plugins → Add plugin 选择本目录。
24
+ - 卸载:Settings → Plugins 移除 `@local/worktree-workspace` 即可,
25
+ 不改动任何仓库文件与 git 状态。
26
+
27
+ ## 设计说明
28
+
29
+ - **Host 半边**(index.js):typert Remote 服务 `worktree-workspace`,
30
+ 暴露 `inspect`(仓库/分支/工作树/上次位置)与 `create`(建树)两个方法;
31
+ git 序列复刻官方 @deepseek-ai/dsh-experimental-worktree(check-ref-format →
32
+ rev-parse 校验基线 → show-ref 查重 → worktree add --no-checkout →
33
+ reset --hard,含 clean/smudge filter 屏蔽与 hooksPath=/dev/null),
34
+ 经 ctx.sandbox.confine 执行;子进程超时 120s。
35
+ - **Client 半边**(client.js):注册到 `conversation.hero.options` 槽位
36
+ (与官方 forge「新建工作树」开关同槽);工作区注册与跳转复用官方
37
+ WorkspaceController(`workspace.create`)与 uiWorkspace.openWorkspace。
38
+ typert remote-info 实现内联(官方该包无 client 声明,不会进入浏览器模块表)。
39
+ - **位置记忆**:存于 `<仓库主目录>/.git/dsh-worktree-prefs.json`(lastParentDir),
40
+ 全部工作树共享,不污染工作树目录。
41
+
42
+ ## 诊断
43
+
44
+ 按钮未出现时:Ctrl+Shift+I 打开控制台,查看 `[worktree-workspace]` 前缀日志;
45
+ 或直接查看 `window.__WTW__`(loaded / applied / steps / errors 四个字段
46
+ 记录从 bundle 注册到槽位挂载的完整链路)。
47
+
48
+ ## 限制
49
+
50
+ - 仅支持 git 仓库型工作区;目标仓库需存在 `.git`;
51
+ - 新工作树的分支基于本地引用(`from` 需能被 `rev-parse <from>^{commit}` 解析);
52
+ - Desktop 布局下按钮位于新建会话屏顶部选项区,若官方改版槽位,
53
+ 需同步调整 `conversation.hero.options` 注册点;
54
+ - 主分支/受保护分支不做额外拦截(git 自身会拒绝非法操作并回显错误)。
package/client.js ADDED
@@ -0,0 +1,521 @@
1
+ /**
2
+ * Git Worktree + 新工作区 插件(浏览器半边)。
3
+ *
4
+ * 在新建会话屏顶部选项区(conversation.hero.options,官方 forge「新建工作树」
5
+ * 开关同一槽位)注册独立按钮「⑂ 工作树…」,打开自有弹窗:
6
+ * - 选择目标项目(已注册工作区),读取该仓库的工作树/分支清单;
7
+ * - 切换已有工作树(打开该目录并注册为工作区,若尚未注册);
8
+ * - 新建工作树(基线分支/分支名/工作区名称/位置,位置记忆上次选择);
9
+ * - 创建成功后调用官方 WorkspaceController 注册工作区并自动跳转。
10
+ *
11
+ * 与原生「添加工作区」流程完全无关(不占用 directoryFlow 槽位)。
12
+ *
13
+ * typert 说明:@deepseek-ai/dsh-typert-protocol 没有 client 声明,永远不会进入
14
+ * 浏览器模块表(裸 client.js 的 require 会 missed the module table);官方 forge
15
+ * 是预构建 bundle(实现已内联)。此处将官方 lib/types/remote-info.js(自包含、
16
+ * 无运行时依赖,仅用调用方传入的 zod)原样内联,创建 RemoteInfo 贡献供 $mount。
17
+ */
18
+ window.__ModuleLoader__.load({
19
+ id: '@local/worktree-workspace',
20
+ factory(require) {
21
+ // —— 诊断面包屑:任何阶段失败都能在控制台定位断点 ——
22
+ const boot = (window.__WTW__ = window.__WTW__ ?? { loaded: false, applied: false, steps: [], errors: [] });
23
+ const step = (message) => { boot.steps.push(message); console.info('[worktree-workspace]', message); };
24
+ const fail = (message, error) => { boot.errors.push(String(error ?? message)); console.error('[worktree-workspace]', message, error); };
25
+
26
+ step('bundle 已执行,factory 开始');
27
+ const React = require('react');
28
+ step('require(react) 成功');
29
+ const { z } = require('zod');
30
+ step('require(zod) 成功');
31
+ const el = React.createElement;
32
+
33
+ // ============================================================
34
+ // 内联 @deepseek-ai/dsh-typert-protocol/lib/types/remote-info.js
35
+ // (官方自包含实现,无运行时依赖;export 关键字已剥离)
36
+ // ============================================================
37
+ function createTypertRemoteInfo(spec, zod) {
38
+ return new RemoteInfo(spec, zod);
39
+ }
40
+ class RemoteInfo {
41
+ spec; zod; index;
42
+ constructor(spec, zod) { this.spec = spec; this.zod = zod; }
43
+ get package() { return this.spec.package; }
44
+ get descriptors() { return this.resolve().descriptors; }
45
+ get methods() { return this.resolve().methods; }
46
+ resolve() {
47
+ if (this.index !== undefined) return this.index;
48
+ const zod = this.zod;
49
+ const descriptors = [];
50
+ const methods = Object.create(null);
51
+ for (const [endpoint, definition] of Object.entries(this.spec.methods)) {
52
+ const separator = endpoint.indexOf('/');
53
+ const namespace = endpoint.slice(0, separator);
54
+ const method = endpoint.slice(separator + 1);
55
+ const parameters = definition.parameters.map(parameter => ({ ...parameter, wire: parameter.wire ?? parameter.name }));
56
+ const descriptor = {
57
+ ...definition,
58
+ id: `${this.spec.package}#${endpoint}`,
59
+ namespace,
60
+ method,
61
+ parameters,
62
+ result: definition.result.description === undefined ? definition.result : new ResultValue(definition.result),
63
+ };
64
+ if (definition.invocation.kind === 'direct') {
65
+ const inputs = [];
66
+ const direct = Object.assign(descriptor, {
67
+ input(options) {
68
+ const strict = options?.strict === true;
69
+ return inputs[strict ? 1 : 0] ??= new NamedInput(parameters, strict, zod);
70
+ },
71
+ invoke(remote, input, signal) {
72
+ const named = input;
73
+ const values = parameters.map(parameter => named[parameter.wire]);
74
+ if (definition.cancellation !== undefined) values.push(signal);
75
+ const receiver = Reflect.get(remote, namespace);
76
+ const call = Reflect.get(receiver, method);
77
+ return call.apply(receiver, values);
78
+ },
79
+ });
80
+ methods[endpoint] = direct;
81
+ }
82
+ descriptors.push(descriptor);
83
+ }
84
+ return this.index = { descriptors, methods };
85
+ }
86
+ }
87
+ function optional(parameter) {
88
+ return parameter.source === 'json' && parameter.acceptsUndefined === true;
89
+ }
90
+ class NamedInput {
91
+ parameters; strict; zod; schema; projection;
92
+ constructor(parameters, strict, zod) { this.parameters = parameters; this.strict = strict; this.zod = zod; }
93
+ codec(parameter) { return this.strict ? parameter.strictCodec : parameter.codec; }
94
+ create = () => this.schema ??= this.zod.strictObject(Object.fromEntries(this.parameters.map((parameter) => {
95
+ const value = this.codec(parameter).create();
96
+ return [parameter.wire, optional(parameter) ? value.optional() : value.nonoptional()];
97
+ })));
98
+ get jsonSchema() { return this.project().jsonSchema; }
99
+ get jsonSchemaError() { return this.project().jsonSchemaError; }
100
+ project() {
101
+ if (this.projection !== undefined) return this.projection;
102
+ const unavailable = this.parameters.find(parameter => this.codec(parameter).jsonSchema === undefined);
103
+ if (unavailable !== undefined) {
104
+ return this.projection = { jsonSchemaError: this.codec(unavailable).jsonSchemaError ?? `No JSON Schema for parameter ${unavailable.wire}` };
105
+ }
106
+ return this.projection = {
107
+ jsonSchema: {
108
+ type: 'object',
109
+ properties: Object.fromEntries(this.parameters.map(parameter => [parameter.wire, {
110
+ ...this.codec(parameter).jsonSchema,
111
+ ...(parameter.description === undefined ? {} : { description: parameter.description }),
112
+ }])),
113
+ required: this.parameters.filter(parameter => !optional(parameter)).map(parameter => parameter.wire),
114
+ additionalProperties: false,
115
+ },
116
+ };
117
+ }
118
+ }
119
+ class ResultValue {
120
+ spec; projection;
121
+ constructor(spec) { this.spec = spec; }
122
+ get mode() { return this.spec.mode; }
123
+ get typeSymbol() { return this.spec.typeSymbol; }
124
+ get create() { return this.spec.create; }
125
+ get decode() { return this.spec.decode; }
126
+ get encode() { return this.spec.encode; }
127
+ get description() { return this.spec.description; }
128
+ get jsonSchemaError() { return this.spec.jsonSchemaError; }
129
+ get jsonSchema() {
130
+ if (this.projection === undefined) {
131
+ const schema = this.spec.jsonSchema;
132
+ this.projection = { value: schema === undefined ? undefined : { ...schema, description: this.spec.description } };
133
+ }
134
+ return this.projection.value;
135
+ }
136
+ }
137
+ step('typert remote-info 已内联');
138
+
139
+ const NS = '@local/worktree-workspace';
140
+ const HERO_OPTIONS = 'conversation.hero.options';
141
+
142
+ // —— UI 字典(内联,避免依赖 locale 子路径的运行时 require) ——
143
+ const zh = {
144
+ button: '⑂ 工作树…',
145
+ buttonTitle: '创建或切换 git 工作树',
146
+ title: 'Git 工作树',
147
+ subtitle: '创建新的工作树并作为独立工作区打开,或切换到已有工作树',
148
+ project: '项目',
149
+ existing: '已有工作树',
150
+ existingHint: '点击「打开」切换到对应工作树目录',
151
+ emptyWorktrees: '(尚无其他工作树)',
152
+ mainBadge: '主目录',
153
+ newSection: '新建工作树',
154
+ baseBranch: '基于分支',
155
+ branchName: '分支名',
156
+ branchPlaceholder: '留空自动生成 dsh-xxxx-xxxx',
157
+ workspaceName: '工作区名称',
158
+ workspacePlaceholder: '默认取分支名最后一段',
159
+ location: '位置',
160
+ locationPlaceholder: '默认为仓库下 .agents/worktrees',
161
+ create: '创建并打开',
162
+ creating: '创建中…',
163
+ opening: '正在打开…',
164
+ open: '打开',
165
+ close: '关闭',
166
+ browseOther: '浏览其他目录…',
167
+ loadFailed: '读取仓库信息失败',
168
+ pickProjectFirst: '请先选择项目',
169
+ adoptFailed: '打开工作区失败',
170
+ };
171
+ const en = {
172
+ button: '⑂ Worktree…',
173
+ buttonTitle: 'Create or switch a git worktree',
174
+ title: 'Git Worktree',
175
+ subtitle: 'Create a new worktree and open it as a standalone workspace, or switch to an existing one',
176
+ project: 'Project',
177
+ existing: 'Existing worktrees',
178
+ existingHint: 'Click "Open" to switch to that worktree directory',
179
+ emptyWorktrees: '(no other worktrees yet)',
180
+ mainBadge: 'main',
181
+ newSection: 'New worktree',
182
+ baseBranch: 'Base branch',
183
+ branchName: 'Branch',
184
+ branchPlaceholder: 'Leave empty to auto-generate dsh-xxxx-xxxx',
185
+ workspaceName: 'Workspace name',
186
+ workspacePlaceholder: 'Defaults to the last segment of the branch name',
187
+ location: 'Location',
188
+ locationPlaceholder: 'Defaults to .agents/worktrees in the repository',
189
+ create: 'Create and open',
190
+ creating: 'Creating…',
191
+ opening: 'Opening…',
192
+ open: 'Open',
193
+ close: 'Close',
194
+ browseOther: 'Browse other directory…',
195
+ loadFailed: 'Failed to read repository info',
196
+ pickProjectFirst: 'Select a project first',
197
+ adoptFailed: 'Failed to open the workspace',
198
+ };
199
+
200
+ // —— zod schema + typert 编解码描述(与 Host inspect/create 一一对应) ——
201
+ const INSPECT_SCHEMA = z.object({ cwd: z.string() }).readonly();
202
+ const INSPECT_RESULT = z.object({
203
+ repositoryRoot: z.string(),
204
+ currentBranch: z.string(),
205
+ defaultBase: z.string(),
206
+ branches: z.array(z.string()),
207
+ worktrees: z.array(z.object({
208
+ path: z.string(),
209
+ head: z.string().optional(),
210
+ branch: z.string().optional(),
211
+ isMain: z.boolean(),
212
+ })),
213
+ lastParentDir: z.string().nullable(),
214
+ }).readonly();
215
+ const CREATE_SCHEMA = z.object({
216
+ cwd: z.string(),
217
+ from: z.string().optional(),
218
+ branch: z.string().optional(),
219
+ directory: z.string().optional(),
220
+ parentDir: z.string().optional(),
221
+ sessionId: z.string().optional(),
222
+ }).readonly();
223
+ const CREATE_RESULT = z.object({
224
+ path: z.string(),
225
+ branch: z.string(),
226
+ baseCommit: z.string(),
227
+ repositoryRoot: z.string(),
228
+ }).readonly();
229
+
230
+ const jsonSchemaOf = (schema) => {
231
+ try {
232
+ const symbol = Symbol('worktree-workspace');
233
+ return { mode: 'strict', typeSymbol: symbol, create: () => schema, jsonSchema: { type: 'object' } };
234
+ } catch {
235
+ return undefined;
236
+ }
237
+ };
238
+ const codec = (schema) => ({
239
+ mode: 'strict',
240
+ typeSymbol: Symbol('worktree-workspace'),
241
+ create: () => schema,
242
+ jsonSchema: { type: 'object' },
243
+ });
244
+
245
+ const remote = createTypertRemoteInfo({
246
+ package: NS,
247
+ methods: {
248
+ 'worktreeWorkspace/inspect': {
249
+ service: 'worktreeWorkspace',
250
+ description: '读取 git 仓库信息(分支/工作树/上次位置)',
251
+ invocation: { kind: 'direct' },
252
+ parameters: [{ name: 'request', source: 'json', codec: codec(INSPECT_SCHEMA), strictCodec: codec(INSPECT_SCHEMA), jsonSchema: { type: 'object' } }],
253
+ result: { mode: 'strict', typeSymbol: Symbol('worktree-workspace.inspect'), create: () => INSPECT_RESULT, jsonSchema: { type: 'object' } },
254
+ },
255
+ 'worktreeWorkspace/create': {
256
+ service: 'worktreeWorkspace',
257
+ description: '创建 git 工作树(官方序列,不切会话不建工作区)',
258
+ invocation: { kind: 'direct' },
259
+ parameters: [{ name: 'request', source: 'json', codec: codec(CREATE_SCHEMA), strictCodec: codec(CREATE_SCHEMA), jsonSchema: { type: 'object' } }],
260
+ result: { mode: 'strict', typeSymbol: Symbol('worktree-workspace.create'), create: () => CREATE_RESULT, jsonSchema: { type: 'object' } },
261
+ },
262
+ },
263
+ }, z);
264
+ step('typert remote 贡献已构建');
265
+ void jsonSchemaOf;
266
+
267
+ // —— 样式 ——
268
+ const overlayStyle = {
269
+ position: 'fixed', inset: 0, zIndex: 10000,
270
+ background: 'rgba(0,0,0,0.36)', display: 'flex',
271
+ alignItems: 'center', justifyContent: 'center',
272
+ };
273
+ const cardStyle = {
274
+ width: 'min(640px, 92vw)', maxHeight: '86vh', overflow: 'auto',
275
+ background: 'var(--dsh-color-background, #fff)', color: 'var(--dsh-color-text, #1f2329)',
276
+ border: '1px solid var(--dsh-color-border, #e2e5e9)', borderRadius: 12,
277
+ boxShadow: '0 12px 40px rgba(0,0,0,0.18)', padding: '20px 22px',
278
+ fontFamily: 'inherit',
279
+ };
280
+ const rowStyle = { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 };
281
+ const labelStyle = { width: 92, flexShrink: 0, fontSize: 13, opacity: 0.75 };
282
+ const inputStyle = {
283
+ flex: 1, minWidth: 0, boxSizing: 'border-box', padding: '6px 10px',
284
+ border: '1px solid var(--dsh-color-border, #d9dce1)', borderRadius: 8,
285
+ background: 'transparent', color: 'inherit', fontSize: 13, fontFamily: 'inherit',
286
+ };
287
+ const primaryStyle = {
288
+ padding: '8px 18px', borderRadius: 8, border: 'none',
289
+ background: 'var(--dsh-color-primary, #3370ff)', color: '#fff',
290
+ fontSize: 13, cursor: 'pointer',
291
+ };
292
+ const ghostStyle = {
293
+ padding: '8px 14px', borderRadius: 8,
294
+ border: '1px solid var(--dsh-color-border, #d9dce1)',
295
+ background: 'transparent', color: 'inherit', fontSize: 13, cursor: 'pointer',
296
+ };
297
+ const heroButtonStyle = {
298
+ display: 'inline-flex', alignItems: 'center', gap: 4,
299
+ padding: '4px 10px', borderRadius: 8, border: '1px solid var(--dsh-color-border, #d9dce1)',
300
+ background: 'transparent', color: 'var(--dsh-color-text, #1f2329)',
301
+ fontSize: 12, cursor: 'pointer', whiteSpace: 'nowrap',
302
+ };
303
+ const badgeStyle = {
304
+ fontSize: 11, padding: '1px 6px', borderRadius: 6,
305
+ background: 'var(--dsh-color-primary-bg, #eef3ff)', color: 'var(--dsh-color-primary, #3370ff)',
306
+ marginLeft: 6,
307
+ };
308
+ const errorStyle = { fontSize: 12, color: '#d4553f', marginTop: 10, whiteSpace: 'pre-wrap' };
309
+ const wtRowStyle = {
310
+ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 8px',
311
+ borderRadius: 8, fontSize: 13,
312
+ };
313
+
314
+ // —— 数据访问(懒取,避免模块级注入缺失导致整个插件 parked) ——
315
+ const workspacesApi = (ctx) => ctx.get('workspaces');
316
+ const uiWorkspaceApi = (ctx) => ctx.get('uiWorkspace');
317
+ const listWorkspaces = (ctx) => {
318
+ try {
319
+ const snapshot = workspacesApi(ctx).list.getSnapshot();
320
+ return (snapshot?.items ?? []).map((item) => ({ workspaceId: item.workspaceId, path: item.path, title: item.title }));
321
+ } catch {
322
+ return [];
323
+ }
324
+ };
325
+
326
+ /** 采纳路径:注册为工作区(已注册则复用原生 IWorkspaces.create 幂等语义)并跳转打开。 */
327
+ async function adoptPath(ctx, t, path) {
328
+ let workspaceId;
329
+ try {
330
+ const view = await workspacesApi(ctx).create({ path });
331
+ workspaceId = view?.workspaceId;
332
+ } catch (error) {
333
+ return { ok: false, error: { code: 'adoptFailed', message: String(error) } };
334
+ }
335
+ if (typeof workspaceId !== 'string' || workspaceId.length === 0) {
336
+ return { ok: false, error: { code: 'adoptFailed', message: 'workspaceId 缺失' } };
337
+ }
338
+ try {
339
+ await uiWorkspaceApi(ctx).openWorkspace(workspaceId);
340
+ } catch (error) {
341
+ return { ok: false, error: { code: 'adoptFailed', message: String(error) } };
342
+ }
343
+ return { ok: true };
344
+ }
345
+
346
+ // —— 弹窗组件 ——
347
+ function WorktreeDialog({ ctx, t, onClose }) {
348
+ const workspaces = listWorkspaces(ctx);
349
+ const [selectedPath, setSelectedPath] = React.useState(workspaces[0]?.path ?? '');
350
+ const [inspect, setInspect] = React.useState({ status: workspaces.length > 0 ? 'loading' : 'idle', data: null, error: null });
351
+ const [from, setFrom] = React.useState('');
352
+ const [branch, setBranch] = React.useState('');
353
+ const [directory, setDirectory] = React.useState('');
354
+ const [directoryTouched, setDirectoryTouched] = React.useState(false);
355
+ const [parentDir, setParentDir] = React.useState('');
356
+ const [busy, setBusy] = React.useState(null);
357
+ const [error, setError] = React.useState(null);
358
+
359
+ React.useEffect(() => {
360
+ if (selectedPath === '') return;
361
+ let cancelled = false;
362
+ setInspect({ status: 'loading', data: null, error: null });
363
+ ctx.remote.worktreeWorkspace.inspect({ cwd: selectedPath }).then((result) => {
364
+ if (cancelled) return;
365
+ if (result?.ok) {
366
+ setInspect({ status: 'ok', data: result.value, error: null });
367
+ setFrom(result.value.defaultBase ?? '');
368
+ if (!directoryTouched) setDirectory('');
369
+ setParentDir((current) => current === '' ? (result.value.lastParentDir ?? '') : current);
370
+ } else {
371
+ setInspect({ status: 'error', data: null, error: result?.error });
372
+ }
373
+ }).catch((cause) => {
374
+ if (!cancelled) setInspect({ status: 'error', data: null, error: { message: String(cause) } });
375
+ });
376
+ return () => { cancelled = true; };
377
+ }, [selectedPath]);
378
+
379
+ const branchTail = (name) => name.split('/').filter((segment) => segment.length > 0).pop() ?? '';
380
+ const directoryValue = directoryTouched || directory !== '' ? directory : branchTail(branch);
381
+
382
+ const submit = async () => {
383
+ if (selectedPath === '') { setError({ message: t('pickProjectFirst') }); return; }
384
+ setError(null);
385
+ setBusy('create');
386
+ try {
387
+ const request = {
388
+ cwd: selectedPath,
389
+ from: from === '' ? undefined : from,
390
+ branch: branch.trim() === '' ? undefined : branch.trim(),
391
+ directory: directoryValue.trim() === '' ? undefined : directoryValue.trim(),
392
+ parentDir: parentDir.trim() === '' ? undefined : parentDir.trim(),
393
+ };
394
+ const result = await ctx.remote.worktreeWorkspace.create(request);
395
+ if (!result?.ok) {
396
+ const detail = result?.error?.message ?? result?.error?.code ?? 'unknown';
397
+ setError({ message: `${t('loadFailed')}:${detail}` });
398
+ setBusy(null);
399
+ return;
400
+ }
401
+ setBusy('adopt');
402
+ const adopted = await adoptPath(ctx, t, result.value.path);
403
+ if (!adopted.ok) {
404
+ setError({ message: `${t('adoptFailed')}:${adopted.error.message}` });
405
+ setBusy(null);
406
+ return;
407
+ }
408
+ onClose();
409
+ } catch (cause) {
410
+ setError({ message: String(cause) });
411
+ setBusy(null);
412
+ }
413
+ };
414
+
415
+ const browse = async () => {
416
+ try {
417
+ const picked = await uiWorkspaceApi(ctx).pickDirectory();
418
+ if (typeof picked === 'string' && picked.length > 0) setParentDir(picked);
419
+ } catch (cause) {
420
+ setError({ message: String(cause) });
421
+ }
422
+ };
423
+
424
+ const inspectData = inspect.data;
425
+ return el('div', { style: overlayStyle, onClick: onClose },
426
+ el('div', { style: cardStyle, onClick: (event) => event.stopPropagation() },
427
+ el('div', { style: { fontSize: 16, fontWeight: 600, marginBottom: 4 } }, t('title')),
428
+ el('div', { style: { fontSize: 12, opacity: 0.65, marginBottom: 14 } }, t('subtitle')),
429
+ el('div', { style: rowStyle },
430
+ el('label', { style: labelStyle }, t('project')),
431
+ el('select', {
432
+ style: inputStyle,
433
+ value: selectedPath,
434
+ onChange: (event) => { setSelectedPath(event.target.value); setError(null); },
435
+ }, workspaces.map((item) => el('option', { key: item.workspaceId, value: item.path }, item.title || item.path)))),
436
+ el('div', { style: { fontSize: 13, fontWeight: 600, margin: '10px 0 6px' } }, t('existing')),
437
+ el('div', { style: { fontSize: 12, opacity: 0.6, marginBottom: 6 } }, t('existingHint')),
438
+ inspect.status === 'loading' && el('div', { style: { fontSize: 12, opacity: 0.6, margin: '8px 0' } }, '…'),
439
+ inspect.status === 'error' && el('div', { style: errorStyle }, `${t('loadFailed')}:${inspect.error?.message ?? inspect.error?.code ?? ''}`),
440
+ inspect.status === 'ok' && el('div', null,
441
+ inspectData.worktrees.length > 0
442
+ ? inspectData.worktrees.map((entry) => el('div', { key: entry.path, style: wtRowStyle },
443
+ el('span', { style: { flexShrink: 0 } }, entry.branch || (entry.head ?? '').slice(0, 8) || '—'),
444
+ entry.isMain && el('span', { style: badgeStyle }, t('mainBadge')),
445
+ el('span', { style: { flex: 1, opacity: 0.6, fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, entry.path),
446
+ el('button', {
447
+ style: ghostStyle, onClick: () => {
448
+ setBusy('adopt');
449
+ adoptPath(ctx, t, entry.path).then((adopted) => {
450
+ if (adopted.ok) { onClose(); } else { setError({ message: `${t('adoptFailed')}:${adopted.error.message}` }); setBusy(null); }
451
+ }).catch((cause) => { setError({ message: String(cause) }); setBusy(null); });
452
+ },
453
+ }, t('open') ?? '打开')))
454
+ : el('div', { style: { fontSize: 12, opacity: 0.55 } }, t('emptyWorktrees'))),
455
+ el('div', { style: { fontSize: 13, fontWeight: 600, margin: '14px 0 8px' } }, t('newSection')),
456
+ el('div', { style: rowStyle },
457
+ el('label', { style: labelStyle }, t('baseBranch')),
458
+ el('select', { style: inputStyle, value: from, onChange: (event) => setFrom(event.target.value) },
459
+ (inspectData?.branches ?? []).map((name) => el('option', { key: name, value: name }, name)))),
460
+ el('div', { style: rowStyle },
461
+ el('label', { style: labelStyle }, t('branchName')),
462
+ el('input', {
463
+ style: inputStyle, value: branch, placeholder: t('branchPlaceholder'),
464
+ onChange: (event) => { setBranch(event.target.value); if (!directoryTouched) setDirectory(''); },
465
+ })),
466
+ el('div', { style: rowStyle },
467
+ el('label', { style: labelStyle }, t('workspaceName')),
468
+ el('input', {
469
+ style: inputStyle, value: directoryValue, placeholder: t('workspacePlaceholder'),
470
+ onChange: (event) => { setDirectory(event.target.value); setDirectoryTouched(true); },
471
+ })),
472
+ el('div', { style: rowStyle },
473
+ el('label', { style: labelStyle }, t('location')),
474
+ el('input', {
475
+ style: inputStyle, value: parentDir, placeholder: t('locationPlaceholder'),
476
+ onChange: (event) => setParentDir(event.target.value),
477
+ }),
478
+ el('button', { style: ghostStyle, onClick: browse }, t('browseOther'))),
479
+ error !== null && el('div', { style: errorStyle }, error.message),
480
+ el('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 14 } },
481
+ el('button', { style: ghostStyle, onClick: onClose }, t('close')),
482
+ el('button', { style: primaryStyle, disabled: busy !== null, onClick: submit },
483
+ busy === 'create' ? t('creating') : busy === 'adopt' ? t('opening') : t('create')))),
484
+ );
485
+ }
486
+
487
+ // —— 新会话屏按钮 ——
488
+ function WorktreeButton({ ctx, t }) {
489
+ const [open, setOpen] = React.useState(false);
490
+ return el('span', null,
491
+ el('button', {
492
+ style: heroButtonStyle, title: t('buttonTitle'), onClick: () => setOpen(true),
493
+ }, t('button')),
494
+ open && el(WorktreeDialog, { ctx, t, onClose: () => setOpen(false) }));
495
+ }
496
+
497
+ async function apply(ctx) {
498
+ step('apply 开始(inject 全部满足,fiber 已激活)');
499
+ const t = ctx.locale.bind(NS);
500
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), `${NS}: dictionaries`);
501
+ step('locale 字典已注册');
502
+ const unmountRemote = await ctx.remote.$mount(remote);
503
+ ctx.effect(() => unmountRemote, `${NS}: remote`);
504
+ step('remote 贡献已挂载(worktreeWorkspace/inspect + create)');
505
+ // 关键:$mount 出来的命名空间必须显式注入,否则守卫拒绝访问
506
+ // (cannot get property "remote.worktreeWorkspace" without inject)。
507
+ // 与官方 forge 的 ctx.inject(['remote.forgePanel'], registerUi) 同款做法。
508
+ ctx.inject(['remote.worktreeWorkspace'], (ext) => {
509
+ ctx.slots.inject(HERO_OPTIONS, () => ctx.slots.register(
510
+ { name: HERO_OPTIONS, id: 'worktree-workspace.button', locale: NS },
511
+ (props) => el(WorktreeButton, { ...props, ctx: ext, t }),
512
+ ));
513
+ step(`槽位 ${HERO_OPTIONS} 已注册(ctx 已扩展 remote.worktreeWorkspace)`);
514
+ boot.applied = true;
515
+ });
516
+ }
517
+
518
+ step('factory 完成,模块返回');
519
+ return { inject: ['remote', 'slots', 'locale', 'workspaces', 'uiWorkspace'], apply };
520
+ },
521
+ });
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: worktree-workspace
3
+ name: '@local/worktree-workspace'
package/icon.svg ADDED
@@ -0,0 +1,13 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="36" height="36">
2
+ <rect x="0" y="0" width="36" height="36" rx="8" fill="#2f6f4f"/>
3
+ <g fill="none" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
4
+ <circle cx="12" cy="10" r="3"/>
5
+ <circle cx="12" cy="26" r="3"/>
6
+ <circle cx="24" cy="16" r="3"/>
7
+ <path d="M12 13v10"/>
8
+ <path d="M14.2 11.4c3.2 1 6.6 2 8 3.4"/>
9
+ <path d="M22.4 18.6c-1.6 2.6-5.4 4.4-8.2 5"/>
10
+ </g>
11
+ <path d="M21 24h11l-1.5 8H22.5z" fill="#ffffff" opacity="0.92"/>
12
+ <path d="M23 24v-1.6h4V24" fill="none" stroke="#ffffff" stroke-width="1.6"/>
13
+ </svg>