mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-12-02 00:59:32 +01:00
feat(worktrees): worktree dialog, launch in a worktree, remove on close
The worktree API needs a front door that works from the place cases are already picked. The toolbar case picker gains a third action row, "Git worktrees…" (the phone case sheet gets a Worktrees button next to Create New Case; no header button anywhere), opening one dialog per case: - the repository's worktrees, with the managed ones (.claude/worktrees) offering Open (start another session in it) and Remove…, an inline confirmation with "Also delete its branch" (git branch -d) whose git refusal is shown verbatim through textContent; - a New worktree form (name, optional branch and start point) and a "Start sessions with" picker over every enabled, installed run mode, built from the registry catalogue as data, never an id branch. Launching goes through run() with options.worktree and the same temporary _runMode swap the custom-model entries use, so every mode keeps its own path: claude and shell create through POST /api/sessions with the worktree as workingDir, every other CLI through quick-start's worktree field. Tabs are named w<n>-<worktree> and the Run button's mode is left as it was. Close Session offers "Kill & remove worktree" for a session that runs in a Codeman-managed worktree; the removal waits for the server to confirm the session is gone (closeSession now resolves true/false), and a dirty tree keeps the worktree with git's reason in a toast that opens the dialog. zh-CN strings and toast patterns for all of it. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
517e12fe1d
commit
8cffcf4be5
8 files changed
+1201
-60
No files matched your search
@@ -42,11 +42,14 @@ afterAll(() => {
|
||||
en.dom.window.close();
|
||||
});
|
||||
|
||||
/** Latin words left after removing what may stay: key names, the AI acronym, the N placeholder. */
|
||||
/**
|
||||
* Latin words left after removing what may stay: key names, the AI acronym, the N placeholder,
|
||||
* and Git, a product name every translation that names it keeps (the Git status rows too).
|
||||
*/
|
||||
const leftover = (text: string) =>
|
||||
text
|
||||
.replace(/\b(Ctrl|Cmd|Shift|Alt|Option)\+\w+/g, '')
|
||||
.replace(/\b(Ctrl|Cmd|Shift|Alt|Option|Enter|Tab|Space|End|Home|Escape|G|AI|N)\b/g, '')
|
||||
.replace(/\b(Ctrl|Cmd|Shift|Alt|Option|Enter|Tab|Space|End|Home|Escape|G|AI|N|Git)\b/g, '')
|
||||
.match(/[A-Za-z]+/g) ?? [];
|
||||
|
||||
const helpers = new Function(
|
||||
@@ -204,7 +207,7 @@ describe('the case picker rows and the host-window and dictation toasts in zh-CN
|
||||
);
|
||||
|
||||
it('finds the strings it checks (the check is not vacuous)', () => {
|
||||
expect(pickerLabels).toEqual(['New or link a case\u2026', 'Case settings\u2026']);
|
||||
expect(pickerLabels).toEqual(['New or link a case\u2026', 'Case settings\u2026', 'Git worktrees\u2026']);
|
||||
expect(SESSION_UI).toContain('<div class="case-combobox-empty">No cases match</div>');
|
||||
expect(toasts.sort()).toEqual([
|
||||
'Could not open a new window for this dashboard',
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* @fileoverview The git worktree UI in Chinese (zh-CN), run through the real translator over the
|
||||
* real index.html in JSDOM:
|
||||
*
|
||||
* - every application string of the worktree dialog, Close Session's worktree option and the
|
||||
* phone case sheet's Worktrees button reads in Chinese, with no English left beyond Git (a
|
||||
* product name), git's own commands and the `.claude/worktrees/` and `worktree-<name>` paths;
|
||||
* - the strings session-ui.js inserts at runtime (row badges, buttons, the removal note, the
|
||||
* validation message) and its toasts translate too, the toasts keeping the user's worktree and
|
||||
* branch names verbatim;
|
||||
* - the slots holding user or git text (case name, repository path, worktree name) are skipped.
|
||||
*
|
||||
* Port: N/A.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { afterAll, describe, expect, it } from 'vitest';
|
||||
|
||||
const PUBLIC = resolve(import.meta.dirname, '../src/web/public');
|
||||
const I18N = readFileSync(resolve(PUBLIC, 'i18n.js'), 'utf8');
|
||||
const INDEX = readFileSync(resolve(PUBLIC, 'index.html'), 'utf8');
|
||||
const SESSION_UI = readFileSync(resolve(PUBLIC, 'session-ui.js'), 'utf8');
|
||||
|
||||
type Api = { t(s: string): string; configure(o: Record<string, string>): void; start(): void };
|
||||
|
||||
function translator(language: string) {
|
||||
const dom = new JSDOM(INDEX, { runScripts: 'outside-only', url: 'http://localhost/' });
|
||||
vm.runInContext(I18N, dom.getInternalVMContext(), { filename: 'i18n.js' });
|
||||
const api = (dom.window as unknown as { CodemanI18n: Api }).CodemanI18n;
|
||||
api.start();
|
||||
api.configure({ language });
|
||||
return { dom, api };
|
||||
}
|
||||
|
||||
const zh = translator('zh-CN');
|
||||
const en = translator('en');
|
||||
afterAll(() => {
|
||||
zh.dom.window.close();
|
||||
en.dom.window.close();
|
||||
});
|
||||
|
||||
/**
|
||||
* Latin left once the names that stay are removed: Git (product), git and its commands, the
|
||||
* `.claude/worktrees/` path, the branch template, HEAD, and the display name (Codeman by default).
|
||||
*/
|
||||
const leftover = (text: string) =>
|
||||
text
|
||||
.replace(/git (worktree remove|branch -d)/g, '')
|
||||
.replace(/\.claude\/worktrees\/|worktree-<name>|\bHEAD\b|\bGit\b|\bgit\b|\bCodeman\b/g, '')
|
||||
.match(/[A-Za-z]+/g) ?? [];
|
||||
|
||||
/** Visible text of the static surfaces, one entry per text-bearing element (skips excluded). */
|
||||
function staticStrings(doc: Document): string[] {
|
||||
const roots = [
|
||||
doc.getElementById('worktreeModal')!,
|
||||
doc.getElementById('closeConfirmWorktree')!,
|
||||
doc.querySelector('.btn-case-worktrees-mobile')!,
|
||||
];
|
||||
const out: string[] = [];
|
||||
for (const root of roots) {
|
||||
const walker = doc.createTreeWalker(root, 4 /* SHOW_TEXT */);
|
||||
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
||||
const text = (n.nodeValue || '').trim();
|
||||
if (!text || (n.parentElement && n.parentElement.closest('[data-i18n-skip]'))) continue;
|
||||
out.push(text);
|
||||
}
|
||||
for (const el of root.querySelectorAll('[aria-label], [title]')) {
|
||||
for (const attr of ['aria-label', 'title']) {
|
||||
const v = el.getAttribute(attr);
|
||||
if (v) out.push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('the git worktree UI in zh-CN', () => {
|
||||
const english = staticStrings(en.dom.window.document);
|
||||
const chinese = staticStrings(zh.dom.window.document);
|
||||
|
||||
it('finds the strings it checks (not vacuous)', () => {
|
||||
expect(english).toContain('Create & start session');
|
||||
expect(english).toContain('Kill & remove worktree');
|
||||
expect(english).toContain('Worktrees');
|
||||
expect(english).toContain('Close git worktrees');
|
||||
expect(english.length).toBe(chinese.length);
|
||||
expect(english.length).toBeGreaterThan(15);
|
||||
});
|
||||
|
||||
it('translates every static string, leaving only Git, git commands and paths in Latin', () => {
|
||||
// Symbols with no words (the close cross, the worktree glyph) have nothing to translate.
|
||||
const bad = chinese.filter(
|
||||
(text, i) => /[A-Za-z]/.test(english[i]) && (text === english[i] || leftover(text).length > 0)
|
||||
);
|
||||
expect(bad).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps the user/git slots out of the translator', () => {
|
||||
const doc = zh.dom.window.document;
|
||||
for (const id of ['worktreeModalCase', 'closeConfirmWorktreeName']) {
|
||||
expect(doc.getElementById(id)!.hasAttribute('data-i18n-skip'), id).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('translates the strings session-ui.js inserts at runtime', () => {
|
||||
const runtime = [
|
||||
'Git worktrees…',
|
||||
'Loading worktrees…',
|
||||
'No worktrees yet. Create one below.',
|
||||
'detached HEAD',
|
||||
'main checkout',
|
||||
'not created by Codeman',
|
||||
'locked',
|
||||
'missing',
|
||||
'Open',
|
||||
'Start a session in this worktree',
|
||||
'Remove…',
|
||||
'git worktree remove refuses while the worktree has uncommitted or untracked files. Codeman never forces it.',
|
||||
'Also delete its branch (git branch -d keeps a branch that is not merged)',
|
||||
'Remove worktree',
|
||||
'Cancel',
|
||||
'Name: letters, digits, ".", "_" and "-", starting with a letter or digit, at most 64 characters.',
|
||||
'A launch is already in progress',
|
||||
'Codeman did not answer.',
|
||||
'Worktrees…',
|
||||
'2 sessions',
|
||||
];
|
||||
// Each literal is really in session-ui.js (the count badge is built from `${n} session`).
|
||||
for (const s of runtime.filter((r) => r !== '2 sessions')) expect(SESSION_UI.includes(`'${s}'`), s).toBe(true);
|
||||
expect(SESSION_UI).toContain('session${wt.sessionCount === 1 ?');
|
||||
const bad = runtime.filter((s) => {
|
||||
const text = zh.api.t(s);
|
||||
return text === s || leftover(text).length > 0 || en.api.t(s) !== s;
|
||||
});
|
||||
expect(bad).toEqual([]);
|
||||
});
|
||||
|
||||
it('translates the toasts and keeps the names verbatim', () => {
|
||||
expect(zh.api.t('Worktree fix-login created on branch feat/login')).toBe('已创建工作树 fix-login,分支 feat/login');
|
||||
expect(zh.api.t('Worktree fix-login and branch worktree-fix-login removed')).toBe(
|
||||
'已移除工作树 fix-login 和分支 worktree-fix-login'
|
||||
);
|
||||
expect(zh.api.t('Worktree fix-login removed')).toBe('已移除工作树 fix-login');
|
||||
expect(
|
||||
zh.api.t("Worktree w2 removed. Branch worktree-w2 kept: error: the branch 'worktree-w2' is not fully merged")
|
||||
).toBe("已移除工作树 w2。保留了分支 worktree-w2:error: the branch 'worktree-w2' is not fully merged");
|
||||
expect(zh.api.t('Worktree w1 was kept: git refused to remove the worktree: fatal: x')).toBe(
|
||||
'工作树 w1 已保留:git refused to remove the worktree: fatal: x'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* @fileoverview The git worktree launch wiring in session-ui.js, in a vm sandbox (no real DOM),
|
||||
* the way test/run-mode-ui.test.ts drives the run*() methods:
|
||||
*
|
||||
* - `managedWorktreeOfDir()` names only `<local case path>/.claude/worktrees/<valid-name>`;
|
||||
* - a worktree launch goes through the EXISTING create paths with the worktree's folder:
|
||||
* POST /api/sessions with `workingDir` for claude and shell, quick-start with `worktree` for
|
||||
* every other CLI; never a case lookup or scaffold, and tabs named after the worktree;
|
||||
* - `_launchInWorktree()` swaps the run mode for the one launch and puts it back.
|
||||
*
|
||||
* Port: N/A.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const SESSION_UI = readFileSync(resolve(import.meta.dirname, '../src/web/public/session-ui.js'), 'utf8');
|
||||
|
||||
const WT = { caseName: 'myrepo', name: 'fix-login', path: '/cases/myrepo/.claude/worktrees/fix-login' };
|
||||
|
||||
function load(fetchImpl: (url: string, init?: { method?: string; body?: string }) => Promise<unknown>) {
|
||||
const elements: Record<string, any> = {
|
||||
// The toolbar still points at ANOTHER case: a worktree launch must not read it.
|
||||
quickStartCase: { value: 'other-case' },
|
||||
tabCount: { value: '3' },
|
||||
};
|
||||
const requests: Array<{ url: string; method?: string; body?: any }> = [];
|
||||
const CodemanApp = function CodemanApp(this: any) {};
|
||||
const context = vm.createContext({
|
||||
CodemanApp,
|
||||
localStorage: { getItem: () => null, setItem: () => {} },
|
||||
document: { getElementById: (id: string) => elements[id] ?? null },
|
||||
fetch: async (url: string, init?: { method?: string; body?: string }) => {
|
||||
requests.push({ url, method: init?.method, body: init?.body ? JSON.parse(init.body) : undefined });
|
||||
return fetchImpl(url, init);
|
||||
},
|
||||
console,
|
||||
setTimeout,
|
||||
});
|
||||
vm.runInContext(SESSION_UI, context, { filename: 'session-ui.js' });
|
||||
const app = new (CodemanApp as any)();
|
||||
app.terminal = { clear: () => {}, writeln: () => {}, focus: () => {} };
|
||||
app.sessions = new Map();
|
||||
app.cases = [
|
||||
{ name: 'myrepo', path: '/cases/myrepo', location: 'local' },
|
||||
{ name: 'dock', path: '/cases/dock', location: 'docker' },
|
||||
];
|
||||
app.getCaseSettings = () => ({});
|
||||
app.loadAppSettingsFromStorage = () => ({});
|
||||
app.buildEnvOverrides = () => ({});
|
||||
app.getEffortSetting = () => undefined;
|
||||
app.getAdvisorSetting = () => undefined;
|
||||
app.isRalphTrackerEnabledByDefault = () => false;
|
||||
app.getTerminalDimensions = () => null;
|
||||
app.loadQuickStartCases = () => {};
|
||||
app.isCliAvailable = () => true;
|
||||
app._ensureCreatedSessionVisible = async () => {};
|
||||
app.selectSession = vi.fn(async () => {});
|
||||
return { app, context, requests };
|
||||
}
|
||||
|
||||
const json = (data: unknown) => ({ ok: true, status: 200, json: async () => data });
|
||||
|
||||
describe('managedWorktreeOfDir', () => {
|
||||
const { context } = load(async () => json({}));
|
||||
const fn = (context as unknown as { managedWorktreeOfDir: (d: unknown, c: unknown) => unknown }).managedWorktreeOfDir;
|
||||
const cases = [
|
||||
{ name: 'myrepo', path: '/cases/myrepo', location: 'local' },
|
||||
{ name: 'linked', path: '/srv/linked', location: 'linked-local' },
|
||||
{ name: 'dock', path: '/cases/dock', location: 'docker' },
|
||||
];
|
||||
|
||||
it('names a worktree folder of a local or linked case', () => {
|
||||
expect(fn('/cases/myrepo/.claude/worktrees/fix-login', cases)).toEqual(WT);
|
||||
expect(fn('/srv/linked/.claude/worktrees/a.b_c/', cases)).toEqual({
|
||||
caseName: 'linked',
|
||||
name: 'a.b_c',
|
||||
path: '/srv/linked/.claude/worktrees/a.b_c',
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores the case folder, a subfolder, unknown or Docker cases and invalid names', () => {
|
||||
expect(fn('/cases/myrepo', cases)).toBeNull();
|
||||
expect(fn('/cases/myrepo/.claude/worktrees/fix-login/src', cases)).toBeNull();
|
||||
expect(fn('/elsewhere/.claude/worktrees/x', cases)).toBeNull();
|
||||
expect(fn('/cases/dock/.claude/worktrees/x', cases)).toBeNull();
|
||||
expect(fn('/cases/myrepo/.claude/worktrees/-x', cases)).toBeNull();
|
||||
expect(fn('/cases/myrepo/.claude/worktrees/a..b', cases)).toBeNull();
|
||||
expect(fn(undefined, cases)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('launching in a worktree', () => {
|
||||
it('claude: POST /api/sessions in the worktree folder, one tab named after the worktree', async () => {
|
||||
const { app, requests } = load(async (url) => {
|
||||
if (url === '/api/sessions') return json({ success: true, data: { session: { id: 's-1' } } });
|
||||
return json({ success: true });
|
||||
});
|
||||
await app.runClaude({ count: 1, worktree: WT });
|
||||
const create = requests.filter((r) => r.url === '/api/sessions');
|
||||
expect(create).toHaveLength(1);
|
||||
expect(create[0].body).toMatchObject({ workingDir: WT.path, name: 'w1-fix-login' });
|
||||
expect(requests.some((r) => r.url.startsWith('/api/cases'))).toBe(false);
|
||||
expect(requests.some((r) => r.url === '/api/sessions/s-1/interactive')).toBe(true);
|
||||
expect(app.selectSession).toHaveBeenCalledWith('s-1');
|
||||
});
|
||||
|
||||
it('shell: POST /api/sessions in the worktree folder, no case lookup', async () => {
|
||||
const { app, requests } = load(async (url) => {
|
||||
if (url === '/api/sessions') return json({ success: true, data: { session: { id: 's-2' } } });
|
||||
return json({ success: true });
|
||||
});
|
||||
await app.runShell({ count: 1, worktree: WT });
|
||||
expect(requests.find((r) => r.url === '/api/sessions')?.body).toMatchObject({
|
||||
workingDir: WT.path,
|
||||
mode: 'shell',
|
||||
name: 's1-fix-login',
|
||||
});
|
||||
expect(requests.some((r) => r.url.startsWith('/api/cases'))).toBe(false);
|
||||
});
|
||||
|
||||
it('other CLIs: quick-start with the case and the worktree name', async () => {
|
||||
const { app, requests } = load(async (url) => {
|
||||
if (url === '/api/codex/status') return json({ success: true, data: { available: true } });
|
||||
if (url === '/api/quick-start') return json({ success: true, data: { sessionId: 's-3' } });
|
||||
return json({ success: true });
|
||||
});
|
||||
await app._runCliMode('codex', { count: 1, worktree: WT });
|
||||
const qs = requests.filter((r) => r.url === '/api/quick-start');
|
||||
expect(qs).toHaveLength(1);
|
||||
expect(qs[0].body).toMatchObject({
|
||||
caseName: 'myrepo',
|
||||
mode: 'codex',
|
||||
worktree: 'fix-login',
|
||||
sessionName: 'w1-fix-login',
|
||||
});
|
||||
});
|
||||
|
||||
it('_launchInWorktree runs ONE session of the chosen mode and restores the Run button mode', async () => {
|
||||
const { app } = load(async () => json({}));
|
||||
app._runMode = 'claude';
|
||||
const seen: Array<{ mode: string; options: unknown }> = [];
|
||||
app.run = vi.fn(async (options: unknown) => {
|
||||
seen.push({ mode: app._runMode, options });
|
||||
});
|
||||
await app._launchInWorktree(WT, 'codex');
|
||||
expect(seen).toEqual([{ mode: 'codex', options: { count: 1, worktree: WT } }]);
|
||||
expect(app._runMode).toBe('claude');
|
||||
});
|
||||
|
||||
it('closing offers worktree removal only for a session in a managed worktree', () => {
|
||||
const { app } = load(async () => json({}));
|
||||
expect(app._managedWorktreeOfSession({ workingDir: WT.path })).toEqual(WT);
|
||||
expect(app._managedWorktreeOfSession({ workingDir: '/cases/myrepo' })).toBeNull();
|
||||
expect(app._managedWorktreeOfSession({ workingDir: WT.path, remote: { hostId: 'x' } })).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user