From eebf7a4fd4de37e61e6cd16f97accb156eda3a3f Mon Sep 17 00:00:00 2001 From: grapedge Date: Thu, 26 Nov 2026 01:39:47 -0800 Subject: [PATCH 1/2] refactor(worktree): remove worktree-setup.sh support and align print-mode trust --- .changeset/worktree-core.md | 2 +- apps/kimi-code/src/cli/v2/run-v2-print.ts | 53 +----- .../components/dialogs/worktree-choices.ts | 47 ----- .../components/messages/worktree-progress.ts | 31 +--- apps/kimi-code/src/tui/constant/worktree.ts | 1 - .../src/tui/controllers/worktree-creation.ts | 125 +------------ apps/kimi-code/test/cli/v2-run-print.test.ts | 128 ++++++------- .../messages/worktree-progress.test.ts | 48 ++--- .../tui/controllers/worktree-creation.test.ts | 125 +------------ .../src/app/worktree/worktree.ts | 15 -- .../src/app/worktree/worktreeService.ts | 109 +++-------- .../test/app/worktree/worktreeService.test.ts | 175 ++---------------- packages/node-sdk/src/index.ts | 2 - packages/node-sdk/src/kimi-harness.ts | 9 - packages/node-sdk/src/rpc.ts | 12 -- packages/node-sdk/src/sdk-rpc-client-v2.ts | 10 - packages/node-sdk/src/worktree.ts | 2 - .../node-sdk/test/sdk-rpc-client-v2.test.ts | 5 - 18 files changed, 121 insertions(+), 778 deletions(-) diff --git a/.changeset/worktree-core.md b/.changeset/worktree-core.md index f3a062a9279..6c46ba8e979 100644 --- a/.changeset/worktree-core.md +++ b/.changeset/worktree-core.md @@ -2,4 +2,4 @@ "@moonshot-ai/agent-core-v2": minor --- -Add Git worktree creation, inspection, and removal, along with live session occupancy tracking, project-scoped session listing, and missing-directory turn reminders. Setup script execution prefers the new worktree's `.kimi-code/worktree-setup.sh` (falling back to the source checkout) and runs it with the local host shell. +Add Git worktree creation, inspection, and removal, along with live session occupancy tracking, project-scoped session listing, and missing-directory turn reminders. diff --git a/apps/kimi-code/src/cli/v2/run-v2-print.ts b/apps/kimi-code/src/cli/v2/run-v2-print.ts index 97ecd53cb93..569c1aeb13c 100644 --- a/apps/kimi-code/src/cli/v2/run-v2-print.ts +++ b/apps/kimi-code/src/cli/v2/run-v2-print.ts @@ -16,7 +16,6 @@ import { IFlagService, IOAuthToolkit, IProjectAliases, - IProjectInstanceManager, IProjectService, ISessionIndex, ISessionManager, @@ -76,7 +75,7 @@ import type { ToolResultEvent, } from '@moonshot-ai/agent-core-v2/agent/toolExecutor/toolExecutorEvents'; import { sameDir } from '@moonshot-ai/agent-core-v2/_base/utils/workdir-slug'; -import { isAbsolute, relative } from 'pathe'; +import { relative } from 'pathe'; import { CLI_SHUTDOWN_TIMEOUT_MS, @@ -235,9 +234,8 @@ export async function runV2Print( } if (opts.worktree !== undefined) { - const prepared = await preparePrintWorktree(client, services, opts, workDir, stderr); - worktree = prepared.created; - if (!prepared.ready) { + worktree = await preparePrintWorktree(client, opts, workDir, stderr); + if (worktree === undefined) { process.exitCode = 1; return; } @@ -336,31 +334,16 @@ export async function runV2Print( async function preparePrintWorktree( client: SDKRpcClientV2, - services: ServicesAccessor, opts: CLIOptions, cwd: string, stderr: PromptOutput, -): Promise<{ readonly created?: CreatedWorktree; readonly ready: boolean }> { - let trusted: boolean; - try { - trusted = await isProjectTrusted(services, cwd); - } catch (error) { - stderr.write(`error: ${error instanceof Error ? error.message : String(error)}\n`); - return { ready: false }; - } - if (!trusted) { - stderr.write( - 'error: This project is not trusted; cannot create a worktree with -w/--worktree.\n' + - ' Run `kimi` here and choose "Trust and continue", or set KIMI_CODE_TRUST_WORKSPACE=1, to trust it first.\n', - ); - return { ready: false }; - } +): Promise { let created: CreatedWorktree; try { created = await client.createWorktree({ cwd, name: opts.worktree, base: opts.worktreeBase }); } catch (error) { stderr.write(`error: ${error instanceof Error ? error.message : String(error)}\n`); - return { ready: false }; + return undefined; } const copied = created.copiedFiles; if (copied.length > 0) { @@ -377,31 +360,7 @@ async function preparePrintWorktree( const subdir = relative(created.sourceRoot, cwd); stderr.write(`${subdir} doesn't exist at this commit, so the session starts at the worktree root.\n`); } - if (created.setupScript === undefined) return { created, ready: true }; - const fromWorktree = relative(created.worktree.path, created.setupScript); - const inWorktree = - fromWorktree !== '' && !/^\.\.(?:[\\/]|$)/.test(fromWorktree) && !isAbsolute(fromWorktree); - const script = inWorktree ? fromWorktree : relative(created.sourceRoot, created.setupScript); - try { - const { exitCode } = await client.runWorktreeSetupScript( - { worktreePath: created.worktree.path, sourceRoot: created.sourceRoot }, - { onOutput: (text) => stderr.write(text) }, - ); - if (exitCode === 0) return { created, ready: true }; - stderr.write(`error: The worktree setup script ${script} exited with code ${String(exitCode)}.\n`); - } catch (error) { - stderr.write(`error: ${error instanceof Error ? error.message : String(error)}\n`); - } - return { created, ready: false }; -} - -async function isProjectTrusted(services: ServicesAccessor, workDir: string): Promise { - const lease = await services.get(IProjectInstanceManager).acquire({ cwd: workDir }); - try { - return await lease.instance.program.trust.get(); - } finally { - lease.dispose(); - } + return created; } async function reportPrintWorktree( diff --git a/apps/kimi-code/src/tui/components/dialogs/worktree-choices.ts b/apps/kimi-code/src/tui/components/dialogs/worktree-choices.ts index f215d96dd96..18e42f94244 100644 --- a/apps/kimi-code/src/tui/components/dialogs/worktree-choices.ts +++ b/apps/kimi-code/src/tui/components/dialogs/worktree-choices.ts @@ -4,33 +4,7 @@ import { ChoicePickerComponent, type ChoiceNoticeLine, type ChoiceOption } from const escHint = (meaning: string): string => `↑↓ navigate · Enter select · Esc ${meaning}`; -export type SetupScriptChoice = 'run' | 'skip'; export type WorktreeFailedChoice = 'retry' | 'stay'; -export type SetupFailedChoice = 'again' | 'continue' | 'delete'; - -export function createSetupScriptPrompt(input: { - readonly script: string; - readonly sourceDir: string; - readonly onChoose: (choice: SetupScriptChoice) => void; -}): ChoicePickerComponent { - return new ChoicePickerComponent({ - title: 'Run the worktree setup script?', - hint: escHint('skip'), - notice: `${input.script} from ${abbreviateHome(input.sourceDir)}`, - noticeTone: 'text', - options: [ - { value: 'run', label: 'Run it' }, - { value: 'skip', label: 'Skip this time' }, - ], - spaceSelect: false, - onSelect: (value) => { - input.onChoose(value === 'run' ? 'run' : 'skip'); - }, - onCancel: () => { - input.onChoose('skip'); - }, - }); -} export function createWorktreeFailedPrompt(input: { readonly sourceDir: string; @@ -53,27 +27,6 @@ export function createWorktreeFailedPrompt(input: { }); } -export function createSetupFailedPrompt(input: { - readonly onChoose: (choice: SetupFailedChoice) => void; -}): ChoicePickerComponent { - return new ChoicePickerComponent({ - title: 'The setup script failed', - hint: escHint('continue'), - options: [ - { value: 'again', label: 'Run it again' }, - { value: 'continue', label: 'Continue without it' }, - { value: 'delete', label: 'Delete the worktree and exit', tone: 'danger' }, - ], - spaceSelect: false, - onSelect: (value) => { - input.onChoose(value === 'again' || value === 'delete' ? value : 'continue'); - }, - onCancel: () => { - input.onChoose('continue'); - }, - }); -} - export interface WorktreeRemoval { readonly repoRoot: string; readonly path: string; diff --git a/apps/kimi-code/src/tui/components/messages/worktree-progress.ts b/apps/kimi-code/src/tui/components/messages/worktree-progress.ts index 0377f21dbb8..f2d24b2f34c 100644 --- a/apps/kimi-code/src/tui/components/messages/worktree-progress.ts +++ b/apps/kimi-code/src/tui/components/messages/worktree-progress.ts @@ -3,7 +3,7 @@ import { truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from import { WORKTREE_LISTED_FILES, WORKTREE_SHORT_SHA_LENGTH } from '#/constant/worktree'; import { MESSAGE_INDENT } from '#/tui/constant/rendering'; import { FAILURE_MARK, STATUS_BULLET, SUCCESS_MARK } from '#/tui/constant/symbols'; -import { WORKTREE_ERROR_OUTPUT_LINES, WORKTREE_SETUP_OUTPUT_LINES } from '#/tui/constant/worktree'; +import { WORKTREE_ERROR_OUTPUT_LINES } from '#/tui/constant/worktree'; import { currentTheme } from '#/tui/theme'; import { SpinnerTicker } from '#/tui/utils/spinner-ticker'; import { abbreviateHome } from '#/utils/paths'; @@ -24,15 +24,7 @@ export type WorktreeProgressRow = readonly status: WorktreeStepStatus; readonly copiedFiles: readonly string[]; readonly output?: readonly string[]; - } - | { - readonly step: 'setup'; - readonly status: WorktreeStepStatus; - readonly script: string; - readonly output: readonly string[]; - readonly exitCode?: number; - } - | { readonly step: 'remove'; readonly status: WorktreeStepStatus; readonly path: string; readonly output?: readonly string[] }; + }; export type WorktreeProgress = | { readonly phase: 'creating' | 'stopped'; readonly name?: string; readonly rows: readonly WorktreeProgressRow[] } @@ -109,14 +101,6 @@ export class WorktreeProgressComponent implements Component { ? currentTheme.fg('success', SUCCESS_MARK) : currentTheme.fg('error', FAILURE_MARK); const rowLines = wrapped(`${MESSAGE_INDENT}${mark}`, rowLabel(row), width); - if (row.step === 'setup') { - return [ - ...rowLines, - ...row.output.slice(-WORKTREE_SETUP_OUTPUT_LINES).map((line) => - truncateToWidth(currentTheme.fg('textMuted', `${MESSAGE_INDENT} │ ${line}`), width, '…'), - ), - ]; - } const output = row.status === 'failed' ? (row.output ?? []).slice(-WORKTREE_ERROR_OUTPUT_LINES) : []; return [ ...rowLines, @@ -149,17 +133,6 @@ function rowLabel(row: WorktreeProgressRow): string { const more = count > WORKTREE_LISTED_FILES ? ` +${String(count - WORKTREE_LISTED_FILES)} more` : ''; return text(`Copied ${String(count)} ${count === 1 ? 'file' : 'files'} from ${INCLUDE_FILE}`) + detail(`${listed}${more}`); } - case 'setup': { - if (row.status === 'running') return text(`Running ${row.script}`); - if (row.status === 'done') return text(`Ran ${row.script}`); - return text( - row.exitCode === undefined ? 'Setup script was interrupted' : `Setup script exited with code ${String(row.exitCode)}`, - ); - } - case 'remove': { - const path = abbreviateHome(row.path); - return text(row.status === 'running' ? `Deleting ${path}` : row.status === 'done' ? `Deleted ${path}` : `Couldn't delete ${path}`); - } } } diff --git a/apps/kimi-code/src/tui/constant/worktree.ts b/apps/kimi-code/src/tui/constant/worktree.ts index a266d7a3980..7927a63d544 100644 --- a/apps/kimi-code/src/tui/constant/worktree.ts +++ b/apps/kimi-code/src/tui/constant/worktree.ts @@ -1,4 +1,3 @@ -export const WORKTREE_SETUP_OUTPUT_LINES = 5; export const WORKTREE_ERROR_OUTPUT_LINES = 8; export const WORKTREE_PANEL_PAGE_SIZE = 8; export const WORKTREE_PANEL_MAX_BODY_ROWS = 12; diff --git a/apps/kimi-code/src/tui/controllers/worktree-creation.ts b/apps/kimi-code/src/tui/controllers/worktree-creation.ts index 0ad40a8b810..94b128979a3 100644 --- a/apps/kimi-code/src/tui/controllers/worktree-creation.ts +++ b/apps/kimi-code/src/tui/controllers/worktree-creation.ts @@ -1,5 +1,5 @@ import { realpath } from 'node:fs/promises'; -import { isAbsolute, relative } from 'node:path'; +import { relative } from 'node:path'; import { stripVTControlCharacters } from 'node:util'; import { @@ -13,11 +13,7 @@ import { import type { Component, Focusable } from '@moonshot-ai/pi-tui'; import { - createSetupFailedPrompt, - createSetupScriptPrompt, createWorktreeFailedPrompt, - type SetupFailedChoice, - type SetupScriptChoice, type WorktreeFailedChoice, } from '#/tui/components/dialogs/worktree-choices'; import { @@ -25,7 +21,6 @@ import { type WorktreeProgress, type WorktreeProgressRow, } from '#/tui/components/messages/worktree-progress'; -import { WORKTREE_SETUP_OUTPUT_LINES } from '#/tui/constant/worktree'; import type { TUIState } from '#/tui/tui-state'; import type { WorkLocation } from '#/tui/types'; import { formatErrorMessage } from '#/tui/utils/event-payload'; @@ -43,14 +38,13 @@ export interface WorktreeCreationOptions { } export interface WorktreeCreationHost { - readonly harness: Pick; + readonly harness: Pick; readonly state: Pick; mountEditorReplacement(panel: Component & Focusable, onDisplaced?: () => void): void; restoreEditor(): void; applyWorkLocation(location: WorkLocation): Promise; showError(message: string): void; exitWithError(message: string): void; - stop(exitCode?: number): Promise; } type PlannedWorktree = Extract; @@ -103,12 +97,6 @@ export class WorktreeCreationController { try { const created = await this.create(request, sourceDir, progress, options); if (created === undefined) return; - if ( - created.setupScript !== undefined && - !(await this.runSetupScript(created, created.setupScript, progress)) - ) { - return; - } const location: WorkLocation = { cwd: created.cwd, projectRoot: created.repoRoot, @@ -226,89 +214,6 @@ export class WorktreeCreationController { } } - private async runSetupScript( - created: CreatedWorktree, - setupScript: string, - progress: ProgressRows, - ): Promise { - const fromWorktree = relative(created.worktree.path, setupScript); - const inWorktree = - fromWorktree !== '' && !/^\.\.(?:[\\/]|$)/.test(fromWorktree) && !isAbsolute(fromWorktree); - const scriptRoot = inWorktree ? created.worktree.path : created.sourceRoot; - const script = inWorktree ? fromWorktree : relative(created.sourceRoot, setupScript); - const choice = await this.choose( - (onChoose) => createSetupScriptPrompt({ script, sourceDir: scriptRoot, onChoose }), - 'skip', - ); - if (choice === 'skip') return true; - for (;;) { - const abort = new AbortController(); - this.abort = abort; - const output = new OutputTail(WORKTREE_SETUP_OUTPUT_LINES); - const show = (status: 'running' | 'done' | 'failed', exitCode?: number): void => { - progress.set({ step: 'setup', status, script, output: output.lines, exitCode }); - }; - progress.resume(); - show('running'); - let exitCode: number | undefined; - try { - ({ exitCode } = await this.host.harness.runWorktreeSetupScript( - { worktreePath: created.worktree.path, sourceRoot: created.sourceRoot }, - { - signal: abort.signal, - onOutput: (text) => { - output.push(text); - show('running'); - }, - }, - )); - } catch (error) { - if (this.disposed) return false; - if (!abort.signal.aborted) { - output.push(`${messageOf(error)}\n`); - exitCode = -1; - } - } - this.abort = undefined; - if (exitCode === 0) { - show('done'); - return true; - } - show('failed', exitCode); - progress.stop(); - const next = await this.choose( - (onChoose) => createSetupFailedPrompt({ onChoose }), - 'continue', - ); - if (next === 'continue') return true; - if (next === 'delete') { - await this.deleteAndExit(created, progress); - return false; - } - } - } - - private async deleteAndExit(created: CreatedWorktree, progress: ProgressRows): Promise { - const path = created.worktree.path; - progress.resume(); - progress.set({ step: 'remove', status: 'running', path }); - try { - await this.host.harness.removeWorktree({ - repoRoot: created.repoRoot, - path, - deleteBranch: false, - discard: 'all', - }); - } catch (error) { - progress.set({ step: 'remove', status: 'failed', path, output: errorOutput(error) }); - progress.stop(); - return; - } - progress.set({ step: 'remove', status: 'done', path }); - progress.stop(); - void this.host.stop(0); - } - private choose( build: (onChoose: (choice: T) => void) => Component & Focusable, fallback: T, @@ -364,11 +269,6 @@ class ProgressRows { this.render(); } - resume(): void { - this.phase = 'creating'; - this.render(); - } - stop(): void { this.phase = 'stopped'; this.render(); @@ -384,27 +284,6 @@ class ProgressRows { } } -class OutputTail { - private complete: string[] = []; - private partial = ''; - - constructor(private readonly limit: number) {} - - push(text: string): void { - const parts = `${this.partial}${text}`.replaceAll('\r\n', '\n').split('\n'); - this.partial = parts.pop() ?? ''; - this.complete = [ - ...this.complete, - ...parts.map(visibleLine).filter((line) => line !== ''), - ].slice(-this.limit); - } - - get lines(): readonly string[] { - const partial = visibleLine(this.partial); - return partial === '' ? this.complete : [...this.complete, partial].slice(-this.limit); - } -} - function visibleLine(line: string): string { return stripVTControlCharacters(line.slice(line.lastIndexOf('\r') + 1)) .replaceAll('\t', ' ') diff --git a/apps/kimi-code/test/cli/v2-run-print.test.ts b/apps/kimi-code/test/cli/v2-run-print.test.ts index d7f226a8236..8192531ecca 100644 --- a/apps/kimi-code/test/cli/v2-run-print.test.ts +++ b/apps/kimi-code/test/cli/v2-run-print.test.ts @@ -30,7 +30,6 @@ import { IModelService, IOAuthToolkit, IProjectAliases, - IProjectInstanceManager, IProjectService, IProviderService, IRegionService, @@ -368,15 +367,6 @@ function makeFakeHarness(toolUpdates = false) { [IFlagService, { enabled: vi.fn(() => false) }], [IProjectService, { peekImplicit: vi.fn(async () => ({ id: 'wd_v2', root: process.cwd() })) }], [IProjectAliases, { resolveAliasIds: vi.fn(async (id: string) => [id]) }], - [ - IProjectInstanceManager, - { - acquire: vi.fn(async () => ({ - instance: { program: { trust: { get: vi.fn(async () => true) } } }, - dispose: vi.fn(), - })), - }, - ], [IEnvironmentService, { addProvider: vi.fn(async () => ({ dispose: vi.fn() })) }], [ ITelemetryService, @@ -1553,7 +1543,6 @@ describe('runV2Print', () => { cwdFallback: false, copiedFiles: ['.env'], sourceDirty: true, - setupScript: undefined, ...overrides, }; } @@ -1567,19 +1556,13 @@ describe('runV2Print', () => { ).rejects.toThrow(OptionConflictError); }); - it('creates a worktree, runs trusted setup script, runs session in worktree cwd, and reports it', async () => { + it('creates a worktree, runs session in worktree cwd, and reports it', async () => { const stdout = writer(); const stderr = writer(); const { app, appServices } = makeFakeHarness(); (appServices.get(IFlagService) as { enabled: ReturnType }).enabled.mockReturnValue(true); - const created = sampleCreated({ setupScript: '/tmp/repo/.kimi-code/worktree-setup.sh' }); + const created = sampleCreated(); const createWt = vi.spyOn(SDKRpcClientV2.prototype, 'createWorktree').mockResolvedValueOnce(created); - const runSetup = vi - .spyOn(SDKRpcClientV2.prototype, 'runWorktreeSetupScript') - .mockImplementationOnce(async (_input, options) => { - options?.onOutput?.('setup ok\n'); - return { exitCode: 0 }; - }); const listWt = vi.spyOn(SDKRpcClientV2.prototype, 'listWorktrees').mockResolvedValueOnce({ repoRoot: created.repoRoot, currentCheckoutRoot: created.repoRoot, @@ -1593,47 +1576,65 @@ describe('runV2Print', () => { await runV2Print(opts({ worktree: 'fix-login', worktreeBase: 'v1' }) as never, '1.2.3-test', { stdout, stderr }); expect(createWt).toHaveBeenCalledWith({ cwd: process.cwd(), name: 'fix-login', base: 'v1' }); - expect(runSetup).toHaveBeenCalledTimes(1); const sessions = appServices.get(ISessionManager) as { create: ReturnType }; expect(sessions.create).toHaveBeenCalledWith(expect.objectContaining({ workDir: created.cwd })); expect(stderr.text()).toContain('Copied 1 file from .worktreeinclude: .env'); expect(stderr.text()).toContain('Uncommitted changes in /tmp/repo stay there.'); expect(stderr.text()).not.toContain('git stash'); - expect(stderr.text()).toContain('setup ok\n'); expect(stderr.text()).toContain('Worktree: /tmp/home/worktrees/wd_repo/fix-login (detached at 1234567)'); } finally { createWt.mockRestore(); - runSetup.mockRestore(); listWt.mockRestore(); } }); - it('refuses to create a worktree when the project is untrusted', async () => { + it('creates a worktree in an untrusted project and warns about skipped project-level MCP servers', async () => { const stdout = writer(); const stderr = writer(); const { app, appServices } = makeFakeHarness(); (appServices.get(IFlagService) as { enabled: ReturnType }).enabled.mockReturnValue(true); - (appServices.get(IProjectInstanceManager) as { acquire: ReturnType }).acquire.mockResolvedValueOnce({ - instance: { program: { trust: { get: vi.fn(async () => false) } } }, - dispose: vi.fn(), + const created = sampleCreated({ copiedFiles: [], sourceDirty: false }); + const createWt = vi.spyOn(SDKRpcClientV2.prototype, 'createWorktree').mockResolvedValueOnce(created); + const listWt = vi.spyOn(SDKRpcClientV2.prototype, 'listWorktrees').mockResolvedValueOnce({ + repoRoot: created.repoRoot, + currentCheckoutRoot: created.repoRoot, + bare: false, + worktrees: [created.worktree], }); - const createWt = vi.spyOn(SDKRpcClientV2.prototype, 'createWorktree'); - const runSetup = vi.spyOn(SDKRpcClientV2.prototype, 'runWorktreeSetupScript'); + trustInfo.mockResolvedValueOnce( + gated({ + name: 'proj-mcp', + transport: 'stdio', + command: 'node', + args: ['server.js'], + origin: '/tmp/repo/.mcp.json', + }), + ); mocks.bootstrap.mockReturnValue({ app }); + mocks.ensureMainAgent.mockResolvedValue({ agentId: 'main', generation: 1 }); const previousExitCode = process.exitCode; try { await runV2Print(opts({ worktree: 'fix-login' }) as never, '1.2.3-test', { stdout, stderr }); - expect(process.exitCode).toBe(1); - expect(createWt).not.toHaveBeenCalled(); - expect(runSetup).not.toHaveBeenCalled(); - expect(stderr.text()).toContain('This project is not trusted; cannot create a worktree with -w/--worktree.'); - expect(stdout.text()).toBe(''); + expect(process.exitCode).toBe(previousExitCode); + expect(createWt).toHaveBeenCalledOnce(); + expect(trustInfo).toHaveBeenCalledWith(created.cwd, { + sessionId: undefined, + environmentId: 'local', + environmentCwd: undefined, + }); + const sessions = appServices.get(ISessionManager) as { create: ReturnType }; + expect(sessions.create).toHaveBeenCalledWith(expect.objectContaining({ workDir: created.cwd })); + expect(stderr.text()).toContain( + 'Warning: this project is not trusted; skipped 1 project-level MCP server: proj-mcp (stdio: node server.js).', + ); + expect(stderr.text()).toContain('Worktree: /tmp/home/worktrees/wd_repo/fix-login (detached at 1234567)'); + expect(stdout.text()).toContain('hello world'); } finally { process.exitCode = previousExitCode; createWt.mockRestore(); - runSetup.mockRestore(); + listWt.mockRestore(); } }); @@ -1740,57 +1741,34 @@ describe('runV2Print', () => { } }); - it('aborts without creating a worktree when the trust lookup throws', async () => { - const { app, appServices } = makeFakeHarness(); - (appServices.get(IFlagService) as { enabled: ReturnType }).enabled.mockReturnValue(true); - (appServices.get(IProjectInstanceManager) as { acquire: ReturnType }).acquire.mockRejectedValueOnce( - new Error('trust store unreadable'), - ); - const createWt = vi.spyOn(SDKRpcClientV2.prototype, 'createWorktree'); - mocks.bootstrap.mockReturnValue({ app }); + it('exits with code 1 and skips session creation when createWorktree fails', async () => { + const stdout = writer(); const stderr = writer(); - const previousExitCode = process.exitCode; - try { - await runV2Print(opts({ worktree: 'fix-login' }) as never, '1.2.3-test', { stdout: writer(), stderr }); - expect(process.exitCode).toBe(1); - expect(createWt).not.toHaveBeenCalled(); - expect(stderr.text()).toContain('error: trust store unreadable'); - } finally { - process.exitCode = previousExitCode; - createWt.mockRestore(); - } - }); - - it('reports the retained worktree path when the setup script fails', async () => { const { app, appServices } = makeFakeHarness(); (appServices.get(IFlagService) as { enabled: ReturnType }).enabled.mockReturnValue(true); - const created = sampleCreated({ - setupScript: '/tmp/home/worktrees/wd_repo/fix-login/.kimi-code/worktree-setup.sh', - copiedFiles: [], - sourceDirty: false, - }); - const createWt = vi.spyOn(SDKRpcClientV2.prototype, 'createWorktree').mockResolvedValueOnce(created); - const runSetup = vi - .spyOn(SDKRpcClientV2.prototype, 'runWorktreeSetupScript') - .mockResolvedValueOnce({ exitCode: 2 }); - const listWt = vi.spyOn(SDKRpcClientV2.prototype, 'listWorktrees').mockResolvedValueOnce({ - repoRoot: '/tmp/repo', - currentCheckoutRoot: '/tmp/repo', - bare: false, - worktrees: [created.worktree], - }); + const createWt = vi + .spyOn(SDKRpcClientV2.prototype, 'createWorktree') + .mockRejectedValueOnce(new Error('A worktree already exists at /tmp/home/worktrees/wd_repo/fix-login.')); + const listWt = vi.spyOn(SDKRpcClientV2.prototype, 'listWorktrees'); mocks.bootstrap.mockReturnValue({ app }); - const stderr = writer(); const previousExitCode = process.exitCode; + try { - await runV2Print(opts({ worktree: 'fix-login' }) as never, '1.2.3-test', { stdout: writer(), stderr }); + await runV2Print(opts({ worktree: 'fix-login' }) as never, '1.2.3-test', { stdout, stderr }); + expect(process.exitCode).toBe(1); - expect(stderr.text()).toContain('error: The worktree setup script .kimi-code/worktree-setup.sh exited with code 2.'); - expect(stderr.text()).toContain('Worktree: /tmp/home/worktrees/wd_repo/fix-login'); + expect(stderr.text()).toContain( + 'error: A worktree already exists at /tmp/home/worktrees/wd_repo/fix-login.', + ); + expect(stderr.text()).not.toContain('Worktree:'); + expect(stdout.text()).toBe(''); + const sessions = appServices.get(ISessionManager) as { create: ReturnType }; + expect(sessions.create).not.toHaveBeenCalled(); + expect(listWt).not.toHaveBeenCalled(); + expect(trustInfo).not.toHaveBeenCalled(); } finally { process.exitCode = previousExitCode; createWt.mockRestore(); - runSetup.mockRestore(); listWt.mockRestore(); } }); diff --git a/apps/kimi-code/test/tui/components/messages/worktree-progress.test.ts b/apps/kimi-code/test/tui/components/messages/worktree-progress.test.ts index 28a7d3a16a9..8be1af80715 100644 --- a/apps/kimi-code/test/tui/components/messages/worktree-progress.test.ts +++ b/apps/kimi-code/test/tui/components/messages/worktree-progress.test.ts @@ -40,7 +40,26 @@ describe('WorktreeProgressComponent', () => { ).toBe(['', '● Creating worktree', ' ✓ Checked ~/code/repo'].join('\n')); }); - it('renders every finished step with its details and the running setup output', () => { + it('renders finished steps with their details and a running step spinner', () => { + expect( + rendered({ + phase: 'creating', + name: 'fix-login', + rows: [ + { step: 'check', status: 'done', sourceDir: '/home/me/code/repo' }, + { step: 'add', status: 'done', path: PATH, head: HEAD }, + { step: 'include', status: 'running', copiedFiles: [] }, + ], + }), + ).toBe( + [ + '', + '● Creating worktree fix-login', + ' ✓ Checked ~/code/repo', + ' ✓ Created ~/.kimi-code/worktrees/wd_repo/fix-login detached at abcdef1', + ` ${BRAILLE_SPINNER_FRAMES[0]!} Copying files from .worktreeinclude`, + ].join('\n'), + ); expect( rendered({ phase: 'creating', @@ -49,12 +68,6 @@ describe('WorktreeProgressComponent', () => { { step: 'check', status: 'done', sourceDir: '/home/me/code/repo' }, { step: 'add', status: 'done', path: PATH, head: HEAD }, { step: 'include', status: 'done', copiedFiles: ['.env', 'apps/web/.env.local', 'b', 'c', 'd'] }, - { - step: 'setup', - status: 'running', - script: '.kimi-code/worktree-setup.sh', - output: ['one', 'two', 'three', 'four', 'five', 'six'], - }, ], }), ).toBe( @@ -64,12 +77,6 @@ describe('WorktreeProgressComponent', () => { ' ✓ Checked ~/code/repo', ' ✓ Created ~/.kimi-code/worktrees/wd_repo/fix-login detached at abcdef1', ' ✓ Copied 5 files from .worktreeinclude .env, apps/web/.env.local, b +2 more', - ` ${BRAILLE_SPINNER_FRAMES[0]!} Running .kimi-code/worktree-setup.sh`, - ' │ two', - ' │ three', - ' │ four', - ' │ five', - ' │ six', ].join('\n'), ); }); @@ -110,21 +117,6 @@ describe('WorktreeProgressComponent', () => { ); }); - it('names how the setup script failed', () => { - const setup = { - step: 'setup', - status: 'failed', - script: '.kimi-code/worktree-setup.sh', - output: ['npm ERR! boom'], - } as const; - expect(rendered({ phase: 'stopped', name: 'x', rows: [{ ...setup, exitCode: 3 }] })).toContain( - [' ✗ Setup script exited with code 3', ' │ npm ERR! boom'].join('\n'), - ); - expect(rendered({ phase: 'stopped', name: 'x', rows: [setup] })).toContain( - ' ✗ Setup script was interrupted', - ); - }); - it('collapses into the entered line with its notes, or the cancel line', () => { expect( rendered({ diff --git a/apps/kimi-code/test/tui/controllers/worktree-creation.test.ts b/apps/kimi-code/test/tui/controllers/worktree-creation.test.ts index 60cee607fbb..508f0c3d6f5 100644 --- a/apps/kimi-code/test/tui/controllers/worktree-creation.test.ts +++ b/apps/kimi-code/test/tui/controllers/worktree-creation.test.ts @@ -15,7 +15,6 @@ import { } from '#/tui/controllers/worktree-creation'; const ENTER = '\r'; -const DOWN = '\u001B[B'; const ESC = '\u001B'; const WORKTREE_PATH = '/home/me/.kimi-code/worktrees/wd_repo/fix-login'; @@ -30,13 +29,11 @@ function createdWorktree(overrides: Partial = {}): CreatedWorkt cwdFallback: false, copiedFiles: [], sourceDirty: false, - setupScript: undefined, ...overrides, }; } type CreateOptions = { signal?: AbortSignal; onEvent?: (event: WorktreeCreateEvent) => void }; -type SetupOptions = { signal?: AbortSignal; onOutput?: (text: string) => void }; function emitUntil( onEvent: ((event: WorktreeCreateEvent) => void) | undefined, @@ -66,10 +63,6 @@ function makeHost() { const host = { harness: { createWorktree: vi.fn(succeed()), - runWorktreeSetupScript: vi.fn(async (_input: unknown, _options: SetupOptions = {}) => ({ - exitCode: 0, - })), - removeWorktree: vi.fn(async () => {}), }, state: { appState: { workDir: '/repo' }, @@ -89,7 +82,6 @@ function makeHost() { applyWorkLocation: vi.fn(async () => {}), showError: vi.fn(), exitWithError: vi.fn(), - stop: vi.fn(async () => {}), }; const controller = new WorktreeCreationController(host as unknown as WorktreeCreationHost); const text = (): string => @@ -105,7 +97,7 @@ function makeHost() { const panel = await picker(title); for (const key of keys) panel.handleInput?.(key); }; - return { host, controller, text, picker, choose }; + return { host, controller, text, choose }; } describe('WorktreeCreationController', () => { @@ -297,121 +289,6 @@ describe('WorktreeCreationController', () => { expect(host.applyWorkLocation).not.toHaveBeenCalled(); }); - it('skips the setup script on Esc and runs it on Run it', async () => { - const worktreeSetupScript = `${WORKTREE_PATH}/.kimi-code/worktree-setup.sh`; - const skipped = makeHost(); - skipped.host.harness.createWorktree.mockImplementation( - succeed(createdWorktree({ setupScript: worktreeSetupScript })), - ); - const skipRun = skipped.controller.run({}); - const prompt = await skipped.picker('Run the worktree setup script?'); - expect(stripVTControlCharacters(prompt.render(80).join('\n'))).toContain( - '.kimi-code/worktree-setup.sh from ~/.kimi-code/worktrees/wd_repo/fix-login', - ); - prompt.handleInput?.(ESC); - await skipRun; - expect(skipped.host.harness.runWorktreeSetupScript).not.toHaveBeenCalled(); - - const fallbackScript = '/repo/.kimi-code/worktree-setup.sh'; - const ran = makeHost(); - ran.host.harness.createWorktree.mockImplementation(succeed(createdWorktree({ setupScript: fallbackScript }))); - let finish!: (result: { exitCode: number }) => void; - ran.host.harness.runWorktreeSetupScript.mockImplementation( - (_input: unknown, options: SetupOptions = {}) => - new Promise<{ exitCode: number }>((resolve) => { - options.onOutput?.('one\ntwo\nthree\nfour\nfive\nsix\n\u001B[32mseven\u001B[0m partial'); - finish = resolve; - }), - ); - const run = ran.controller.run({}); - const fallbackPrompt = await ran.picker('Run the worktree setup script?'); - expect(stripVTControlCharacters(fallbackPrompt.render(80).join('\n'))).toContain( - '.kimi-code/worktree-setup.sh from /repo', - ); - fallbackPrompt.handleInput?.(ENTER); - await vi.waitFor(() => { - expect(ran.text()).toContain('Running .kimi-code/worktree-setup.sh'); - }); - expect(ran.text()).toContain( - [' │ three', ' │ four', ' │ five', ' │ six', ' │ seven partial'].join('\n'), - ); - ran.host.state.ui.requestRender.mockClear(); - ran.host.applyWorkLocation.mockClear(); - finish({ exitCode: 0 }); - await run; - - expect(ran.host.harness.runWorktreeSetupScript).toHaveBeenCalledWith( - { worktreePath: WORKTREE_PATH, sourceRoot: '/repo' }, - expect.objectContaining({ signal: expect.any(AbortSignal) }), - ); - expect(ran.host.applyWorkLocation).toHaveBeenCalledOnce(); - }); - - it('offers to rerun, continue, or delete after the setup script fails', async () => { - const setupScript = '/repo/.kimi-code/worktree-setup.sh'; - const again = makeHost(); - again.host.harness.createWorktree.mockImplementation(succeed(createdWorktree({ setupScript }))); - again.host.harness.runWorktreeSetupScript.mockResolvedValueOnce({ exitCode: 3 }); - const againRun = again.controller.run({}); - await again.choose('Run the worktree setup script?', [ENTER]); - await again.choose('The setup script failed', []); - expect(again.text()).toContain('✗ Setup script exited with code 3'); - await again.choose('The setup script failed', [ENTER]); - await againRun; - expect(again.host.harness.runWorktreeSetupScript).toHaveBeenCalledTimes(2); - expect(again.text()).toContain('✓ Entered worktree fix-login'); - - const skip = makeHost(); - skip.host.harness.createWorktree.mockImplementation(succeed(createdWorktree({ setupScript }))); - skip.host.harness.runWorktreeSetupScript.mockResolvedValueOnce({ exitCode: 1 }); - const skipRun = skip.controller.run({}); - await skip.choose('Run the worktree setup script?', [ENTER]); - await skip.choose('The setup script failed', [DOWN, ENTER]); - await skipRun; - expect(skip.host.applyWorkLocation).toHaveBeenCalledOnce(); - - const remove = makeHost(); - remove.host.harness.createWorktree.mockImplementation(succeed(createdWorktree({ setupScript }))); - remove.host.harness.runWorktreeSetupScript.mockResolvedValueOnce({ exitCode: 2 }); - const removeRun = remove.controller.run({}); - await remove.choose('Run the worktree setup script?', [ENTER]); - await remove.choose('The setup script failed', [DOWN, DOWN, ENTER]); - await removeRun; - expect(remove.host.harness.removeWorktree).toHaveBeenCalledWith({ - repoRoot: '/repo', - path: WORKTREE_PATH, - deleteBranch: false, - discard: 'all', - }); - expect(remove.host.stop).toHaveBeenCalledWith(0); - expect(remove.host.applyWorkLocation).not.toHaveBeenCalled(); - }); - - it('reports an interrupted setup script', async () => { - const { host, controller, text, choose } = makeHost(); - host.harness.createWorktree.mockImplementation( - succeed(createdWorktree({ setupScript: '/repo/.kimi-code/worktree-setup.sh' })), - ); - host.harness.runWorktreeSetupScript.mockImplementation( - (_input: unknown, options: SetupOptions = {}) => - new Promise<{ exitCode: number }>((_resolve, reject) => { - options.signal?.addEventListener('abort', () => { - reject(new KimiError(ErrorCodes.WORKTREE_CANCELLED, 'Worktree operation cancelled.')); - }); - }), - ); - const running = controller.run({}); - await choose('Run the worktree setup script?', [ENTER]); - await vi.waitFor(() => { - expect(controller.cancel()).toBe(true); - }); - await choose('The setup script failed', []); - expect(text()).toContain('✗ Setup script was interrupted'); - await choose('The setup script failed', [ESC]); - await running; - expect(host.applyWorkLocation).toHaveBeenCalledOnce(); - }); - it('falls back to projectRoot when creating a worktree from a missing workDir', async () => { const { host, controller } = makeHost(); host.state.appState = { workDir: '/nonexistent-kimi-missing-worktree', projectRoot: '/repo' } as { diff --git a/packages/agent-core-v2/src/app/worktree/worktree.ts b/packages/agent-core-v2/src/app/worktree/worktree.ts index 1585cce55ec..9fb488e5cd8 100644 --- a/packages/agent-core-v2/src/app/worktree/worktree.ts +++ b/packages/agent-core-v2/src/app/worktree/worktree.ts @@ -61,17 +61,6 @@ export interface CreatedWorktree { readonly cwdFallback: boolean; readonly copiedFiles: readonly string[]; readonly sourceDirty: boolean; - readonly setupScript: string | undefined; -} - -export interface RunSetupScriptInput { - readonly worktreePath: string; - readonly sourceRoot: string; -} - -export interface RunSetupScriptOptions { - readonly signal?: AbortSignal; - readonly onOutput?: (text: string) => void; } export interface InspectWorktreeRemovalInput { @@ -117,10 +106,6 @@ export interface IWorktreeService { worktreesDir(repoRoot: string): string; list(cwd: string): Promise; create(input: CreateWorktreeInput, options?: CreateWorktreeOptions): Promise; - runSetupScript( - input: RunSetupScriptInput, - options?: RunSetupScriptOptions, - ): Promise<{ readonly exitCode: number }>; inspectRemoval(input: InspectWorktreeRemovalInput): Promise; remove(input: RemoveWorktreeInput): Promise; } diff --git a/packages/agent-core-v2/src/app/worktree/worktreeService.ts b/packages/agent-core-v2/src/app/worktree/worktreeService.ts index 1989b58a40f..e303dc20cb3 100644 --- a/packages/agent-core-v2/src/app/worktree/worktreeService.ts +++ b/packages/agent-core-v2/src/app/worktree/worktreeService.ts @@ -25,8 +25,6 @@ import { type InspectWorktreeRemovalInput, type KimiWorktree, type RemoveWorktreeInput, - type RunSetupScriptInput, - type RunSetupScriptOptions, type WorktreeCheckout, type WorktreeCreateEvent, type WorktreeListing, @@ -51,7 +49,6 @@ const KILL_GRACE_MS = 2_000; const OUTPUT_GRACE_MS = 1_000; const MAX_NAME_ATTEMPTS = 20; const INCLUDE_FILE = '.worktreeinclude'; -const SETUP_SCRIPT = '.kimi-code/worktree-setup.sh'; interface Repository { readonly root: string; @@ -77,12 +74,10 @@ interface CreationPlan { interface RunOptions { readonly cwd: string; - readonly env?: Record; readonly stdin?: string; readonly timeoutMs?: number; readonly signal?: AbortSignal; readonly onOutput?: (text: string) => void; - readonly captureOutput?: boolean; } interface GitOptions { @@ -198,7 +193,6 @@ export class WorktreeService implements IWorktreeService { const relativeCwd = relative(plan.sourceRoot, plan.cwd); const mappedCwd = isOutsideRoot(relativeCwd) ? plan.path : join(plan.path, relativeCwd); const cwdFallback = !(await this.isDirectory(mappedCwd)); - const setupScript = await this.resolveSetupScript(plan.path, plan.sourceRoot); return { worktree: { path: plan.path, name: plan.name, head: plan.commit, branch: plan.branch, missing: false, managed: true }, repoRoot: plan.repoRoot, @@ -207,57 +201,9 @@ export class WorktreeService implements IWorktreeService { cwdFallback, copiedFiles, sourceDirty: plan.sourceDirty, - setupScript, }; } - async runSetupScript( - input: RunSetupScriptInput, - options: RunSetupScriptOptions = {}, - ): Promise<{ readonly exitCode: number }> { - this.requireEnabled(); - throwIfCancelled(options.signal); - const scriptPath = - (await this.resolveSetupScript(input.worktreePath, input.sourceRoot)) ?? - join(input.worktreePath, SETUP_SCRIPT); - await this.environments.ready; - const lease = this.environments.acquire({ environmentId: LOCAL_ENVIRONMENT_ID }, ['process']); - try { - const shell = - nonEmpty(lease.environment.host?.shellPath) ?? - localProgram('bash', input.worktreePath) ?? - localProgram('sh', input.worktreePath); - if (shell === undefined) { - throw new Error2( - ErrorCodes.SHELL_GIT_BASH_NOT_FOUND, - 'Running the worktree setup script needs bash or sh on PATH, or Git Bash (KIMI_SHELL_PATH) on Windows.', - ); - } - const scriptArg = lease.environment.shellPathBridge?.toShellPath(scriptPath) ?? scriptPath; - const result = await this.runWithLease(lease, shell, [scriptArg], { - cwd: input.worktreePath, - env: { - KIMI_CODE_WORKTREE_SOURCE_DIR: input.sourceRoot, - KIMI_CODE_WORKTREE_DIR: input.worktreePath, - }, - signal: options.signal, - onOutput: options.onOutput, - captureOutput: false, - }); - return { exitCode: result.exitCode }; - } finally { - lease.dispose(); - } - } - - private async resolveSetupScript(worktreePath: string, sourceRoot: string): Promise { - const worktreeScript = join(worktreePath, SETUP_SCRIPT); - if (await this.isFile(worktreeScript)) return worktreeScript; - const sourceScript = join(sourceRoot, SETUP_SCRIPT); - if (await this.isFile(sourceScript)) return sourceScript; - return undefined; - } - async inspectRemoval(input: InspectWorktreeRemovalInput): Promise { const repo = await this.readRepository(input.repoRoot, input.repoRoot); const target = await this.findLinkedEntry(repo, input.path); @@ -743,36 +689,27 @@ export class WorktreeService implements IWorktreeService { await this.environments.ready; const lease = this.environments.acquire({ environmentId: LOCAL_ENVIRONMENT_ID }, ['process']); try { - return await this.runWithLease(lease, program, args, options); + throwIfCancelled(options.signal); + const spawned = await lease.environment.process! + .spawn(program, args, { cwd: options.cwd }) + .then( + (proc) => ({ ok: true as const, proc }), + (error: unknown) => ({ ok: false as const, message: error instanceof Error ? error.message : String(error) }), + ); + if (!spawned.ok) { + options.onOutput?.(`${spawned.message}\n`); + return { exitCode: -1, stdout: '', stderr: spawned.message }; + } + try { + return await waitForProcess(spawned.proc, options); + } finally { + void spawned.proc.dispose(); + } } finally { lease.dispose(); } } - private async runWithLease( - lease: ReturnType, - program: string, - args: readonly string[], - options: RunOptions, - ): Promise { - throwIfCancelled(options.signal); - const spawned = await lease.environment.process! - .spawn(program, args, { cwd: options.cwd, env: options.env }) - .then( - (proc) => ({ ok: true as const, proc }), - (error: unknown) => ({ ok: false as const, message: error instanceof Error ? error.message : String(error) }), - ); - if (!spawned.ok) { - options.onOutput?.(`${spawned.message}\n`); - return { exitCode: -1, stdout: '', stderr: spawned.message }; - } - try { - return await waitForProcess(spawned.proc, options); - } finally { - void spawned.proc.dispose(); - } - } - private async exists(path: string): Promise { return this.fs.lstat(path).then( () => true, @@ -804,15 +741,14 @@ async function waitForProcess(proc: IHostProcess, options: RunOptions): Promise< options.onOutput?.(text); } catch {} }; - const capture = options.captureOutput !== false; let streamError: unknown; const output = Promise.all([ drain(proc.stdout, (text) => { - if (capture) stdout += text; + stdout += text; emitOutput(text); }), drain(proc.stderr, (text) => { - if (capture) stderr += text; + stderr += text; emitOutput(text); }), ]).catch((error: unknown) => { @@ -825,7 +761,7 @@ async function waitForProcess(proc: IHostProcess, options: RunOptions): Promise< const outcome = await firstOutcome(exit, options.timeoutMs, options.signal); if (outcome !== 'exit') await terminate(proc, exit); const exitCode = await exit; - if (outcome === 'exit' && capture) { + if (outcome === 'exit') { const drainMs = options.timeoutMs === undefined ? undefined @@ -849,11 +785,8 @@ async function waitForProcess(proc: IHostProcess, options: RunOptions): Promise< } await settlesWithin(output, OUTPUT_GRACE_MS); if (outcome === 'abort') throw cancelledError(); - if (outcome === 'timeout') { - const note = `timed out after ${(options.timeoutMs ?? 0) / 1000}s`; - return { exitCode: -1, stdout, stderr: stderr === '' ? note : `${stderr.trimEnd()}\n${note}` }; - } - return { exitCode, stdout, stderr }; + const note = `timed out after ${(options.timeoutMs ?? 0) / 1000}s`; + return { exitCode: -1, stdout, stderr: stderr === '' ? note : `${stderr.trimEnd()}\n${note}` }; } async function firstOutcome( diff --git a/packages/agent-core-v2/test/app/worktree/worktreeService.test.ts b/packages/agent-core-v2/test/app/worktree/worktreeService.test.ts index 50bf4e462bd..aaa04fc23ab 100644 --- a/packages/agent-core-v2/test/app/worktree/worktreeService.test.ts +++ b/packages/agent-core-v2/test/app/worktree/worktreeService.test.ts @@ -147,8 +147,6 @@ describe('WorktreeService', () => { let presence: ISessionPresence; let indexed: SessionSummary[]; let peekImplicitError: Error | undefined; - let hostShellPath: string | undefined; - let shellPathBridge: { toShellPath: (p: string) => string; fromShellPath: (p: string) => string } | undefined; beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'worktree-service-')); @@ -160,18 +158,10 @@ describe('WorktreeService', () => { flagEnabled = true; indexed = []; peekImplicitError = undefined; - hostShellPath = undefined; - shellPathBridge = undefined; disposables = new DisposableStore(); const processService = new HostProcessService(); const environment = { - get host() { - return hostShellPath === undefined ? undefined : { shellPath: hostShellPath }; - }, - get shellPathBridge() { - return shellPathBridge; - }, process: processService, } as unknown as Environment; const lease = { environment, track: (resource: T): T => resource, dispose: () => {} }; @@ -241,7 +231,6 @@ describe('WorktreeService', () => { expect(created.cwd).toBe(path); expect(created.cwdFallback).toBe(false); expect(created.sourceDirty).toBe(false); - expect(created.setupScript).toBeUndefined(); expect(git(path, 'rev-parse', 'HEAD')).toBe(head); expect(() => git(path, 'symbolic-ref', '-q', 'HEAD')).toThrow(); expect(branches(repo)).toEqual(['main']); @@ -513,23 +502,23 @@ describe('WorktreeService', () => { expect(existsSync(join(created.worktree.path, 'new.txt'))).toBe(false); }); - it('prefers the setup script checked out in the new worktree without running it', async () => { - commitFile(repo, '.kimi-code/worktree-setup.sh', 'touch ran\n'); - - const created = await create({ name: 'scripted-committed' }); - - expect(created.setupScript).toBe(join(created.worktree.path, '.kimi-code', 'worktree-setup.sh')); - expect(existsSync(join(created.worktree.path, 'ran'))).toBe(false); - }); - - it('falls back to the source checkout setup script when the new worktree does not have one', async () => { - mkdirSync(join(repo, '.kimi-code')); - writeFileSync(join(repo, '.kimi-code', 'worktree-setup.sh'), 'touch ran\n'); + it('does not execute .kimi-code/worktree-setup.sh while still copying .worktreeinclude files', async () => { + commitFile(repo, '.gitignore', '.env\n'); + commitFile(repo, '.kimi-code/worktree-setup.sh', 'touch ran-committed\n'); + writeFileSync(join(repo, '.worktreeinclude'), '.env\n'); + writeFileSync(join(repo, '.env'), 'SECRET=1\n'); - const created = await create({ name: 'scripted' }); + const fromCommitted = await create({ name: 'ignores-committed-script' }); + expect(fromCommitted.copiedFiles).toEqual(['.env']); + expect(readFileSync(join(fromCommitted.worktree.path, '.env'), 'utf8')).toBe('SECRET=1\n'); + expect(existsSync(join(fromCommitted.worktree.path, 'ran-committed'))).toBe(false); - expect(created.setupScript).toBe(join(realRepo, '.kimi-code', 'worktree-setup.sh')); - expect(existsSync(join(created.worktree.path, 'ran'))).toBe(false); + const beforeScript = git(repo, 'rev-parse', 'HEAD~1'); + writeFileSync(join(repo, '.kimi-code', 'worktree-setup.sh'), 'touch ran-uncommitted\n'); + const fromUncommitted = await create({ name: 'ignores-uncommitted-script', base: beforeScript }); + expect(fromUncommitted.copiedFiles).toEqual(['.env']); + expect(readFileSync(join(fromUncommitted.worktree.path, '.env'), 'utf8')).toBe('SECRET=1\n'); + expect(existsSync(join(fromUncommitted.worktree.path, 'ran-uncommitted'))).toBe(false); }); it('creates the requested branch', async () => { @@ -1254,140 +1243,6 @@ describe('WorktreeService', () => { }); }); - describe('runSetupScript', () => { - function writeScript(body: string): void { - mkdirSync(join(repo, '.kimi-code'), { recursive: true }); - writeFileSync(join(repo, '.kimi-code', 'worktree-setup.sh'), body); - } - - it.skipIf(isWindows)('runs in the worktree root with both directories in the environment', async () => { - writeScript('echo "source=$KIMI_CODE_WORKTREE_SOURCE_DIR"\necho "dir=$KIMI_CODE_WORKTREE_DIR"\necho "pwd=$(pwd -P)"\necho oops >&2\nexit 3\n'); - const created = await create({ name: 'setup' }); - let output = ''; - - const result = await service.runSetupScript( - { worktreePath: created.worktree.path, sourceRoot: created.sourceRoot }, - { onOutput: (text) => (output += text) }, - ); - - expect(result.exitCode).toBe(3); - expect(output).toContain(`source=${realRepo}\n`); - expect(output).toContain(`dir=${created.worktree.path}\n`); - expect(output).toContain(`pwd=${created.worktree.path}\n`); - expect(output).toContain('oops\n'); - }); - - it.skipIf(isWindows)('runs the setup script from the new worktree when checked out there', async () => { - const initial = git(repo, 'rev-parse', 'HEAD'); - commitFile(repo, '.kimi-code/worktree-setup.sh', 'echo "variant=committed"\necho "self=$0"\n'); - writeScript('echo "variant=local-uncommitted"\necho "self=$0"\n'); - - const fromHead = await create({ name: 'from-head' }); - let headOutput = ''; - const headResult = await service.runSetupScript( - { worktreePath: fromHead.worktree.path, sourceRoot: fromHead.sourceRoot }, - { onOutput: (text) => (headOutput += text) }, - ); - - expect(headResult.exitCode).toBe(0); - expect(headOutput).toContain('variant=committed\n'); - expect(headOutput).toContain(`self=${join(fromHead.worktree.path, '.kimi-code', 'worktree-setup.sh')}\n`); - - const fromOlder = await create({ name: 'from-older', base: initial }); - let olderOutput = ''; - const olderResult = await service.runSetupScript( - { worktreePath: fromOlder.worktree.path, sourceRoot: fromOlder.sourceRoot }, - { onOutput: (text) => (olderOutput += text) }, - ); - - expect(olderResult.exitCode).toBe(0); - expect(olderOutput).toContain('variant=local-uncommitted\n'); - expect(olderOutput).toContain(`self=${join(realRepo, '.kimi-code', 'worktree-setup.sh')}\n`); - }); - - it.skipIf(isWindows)('uses the local environment shellPath and shellPathBridge when available', async () => { - commitFile(repo, '.kimi-code/worktree-setup.sh', 'echo "unused"\n'); - const fakeShell = join(root, 'fake-bash.sh'); - writeFileSync(fakeShell, '#!/bin/sh\necho "runner=host-shell"\necho "arg=$1"\n'); - chmodSync(fakeShell, 0o755); - hostShellPath = fakeShell; - shellPathBridge = { - toShellPath: (nativePath) => `/bridged${nativePath}`, - fromShellPath: (shellPath) => shellPath, - }; - - const created = await create({ name: 'host-shell' }); - let output = ''; - const result = await service.runSetupScript( - { worktreePath: created.worktree.path, sourceRoot: created.sourceRoot }, - { onOutput: (text) => (output += text) }, - ); - - expect(result.exitCode).toBe(0); - expect(output).toContain('runner=host-shell\n'); - expect(output).toContain(`arg=/bridged${join(created.worktree.path, '.kimi-code', 'worktree-setup.sh')}\n`); - }); - - it.skipIf(isWindows)('returns once the script exits even if a background child holds its output', async () => { - writeScript('sleep 5 &\necho done\n'); - const created = await create({ name: 'background-setup' }); - const started = Date.now(); - - const result = await service.runSetupScript({ worktreePath: created.worktree.path, sourceRoot: created.sourceRoot }); - - expect(result.exitCode).toBe(0); - expect(Date.now() - started).toBeLessThan(4_000); - }); - - it.skipIf(isWindows)('kills the script on cancel', async () => { - writeScript('echo started\nsleep 30\n'); - const created = await create({ name: 'slow-setup' }); - const controller = new AbortController(); - const started = Date.now(); - - const error = await failure( - service.runSetupScript( - { worktreePath: created.worktree.path, sourceRoot: created.sourceRoot }, - { - signal: controller.signal, - onOutput: () => { - controller.abort(); - }, - }, - ), - ); - - expect(error.code).toBe('worktree.cancelled'); - expect(Date.now() - started).toBeLessThan(10_000); - }); - - it('refuses runSetupScript while the worktree flag is off', async () => { - writeScript('echo ran\n'); - const created = await create({ name: 'flag-off-setup' }); - flagEnabled = false; - - const error = await failure( - service.runSetupScript({ worktreePath: created.worktree.path, sourceRoot: created.sourceRoot }), - ); - expect(error.code).toBe('worktree.disabled'); - }); - - it.skipIf(isWindows)('keeps draining output when onOutput throws', async () => { - writeScript('head -c 200000 /dev/zero | tr "\\0" "a"\n'); - const created = await create({ name: 'noisy-callback' }); - - const result = await service.runSetupScript( - { worktreePath: created.worktree.path, sourceRoot: created.sourceRoot }, - { - onOutput: () => { - throw new Error('listener failed'); - }, - }, - ); - expect(result.exitCode).toBe(0); - }); - }); - it('keeps every created worktree under the per-repository directory', async () => { await create({ name: 'one' }); await create({ name: 'two' }); diff --git a/packages/node-sdk/src/index.ts b/packages/node-sdk/src/index.ts index 7b26bdd6a55..fba1b4c2494 100644 --- a/packages/node-sdk/src/index.ts +++ b/packages/node-sdk/src/index.ts @@ -131,8 +131,6 @@ export type { InspectWorktreeRemovalInput, KimiWorktree, RemoveWorktreeInput, - RunSetupScriptInput, - RunSetupScriptOptions, WorkLocation, WorktreeCreateEvent, WorktreeCreateStep, diff --git a/packages/node-sdk/src/kimi-harness.ts b/packages/node-sdk/src/kimi-harness.ts index 67163e7a318..09e0cdc2f4b 100644 --- a/packages/node-sdk/src/kimi-harness.ts +++ b/packages/node-sdk/src/kimi-harness.ts @@ -66,8 +66,6 @@ import type { CreateWorktreeOptions, InspectWorktreeRemovalInput, RemoveWorktreeInput, - RunSetupScriptInput, - RunSetupScriptOptions, WorkLocation, WorktreeListing, WorktreeRemovalCheck, @@ -401,13 +399,6 @@ export class KimiHarness { return this.rpc.createWorktree(input, options); } - async runWorktreeSetupScript( - input: RunSetupScriptInput, - options?: RunSetupScriptOptions, - ): Promise<{ readonly exitCode: number }> { - return this.rpc.runWorktreeSetupScript(input, options); - } - async inspectWorktreeRemoval(input: InspectWorktreeRemovalInput): Promise { return this.rpc.inspectWorktreeRemoval(input); } diff --git a/packages/node-sdk/src/rpc.ts b/packages/node-sdk/src/rpc.ts index 12f70b1f90a..cfa2f08d3a5 100644 --- a/packages/node-sdk/src/rpc.ts +++ b/packages/node-sdk/src/rpc.ts @@ -99,8 +99,6 @@ import type { CreateWorktreeOptions, InspectWorktreeRemovalInput, RemoveWorktreeInput, - RunSetupScriptInput, - RunSetupScriptOptions, WorkLocation, WorktreeListing, WorktreeRemovalCheck, @@ -506,16 +504,6 @@ export abstract class SDKRpcClientBase { ); } - async runWorktreeSetupScript( - _input: RunSetupScriptInput, - _options?: RunSetupScriptOptions, - ): Promise<{ readonly exitCode: number }> { - throw new KimiError( - ErrorCodes.NOT_IMPLEMENTED, - 'Worktree operations are not implemented for this engine', - ); - } - async inspectWorktreeRemoval(_input: InspectWorktreeRemovalInput): Promise { throw new KimiError( ErrorCodes.NOT_IMPLEMENTED, diff --git a/packages/node-sdk/src/sdk-rpc-client-v2.ts b/packages/node-sdk/src/sdk-rpc-client-v2.ts index 0ad3b884a84..e8bdb23e7e8 100644 --- a/packages/node-sdk/src/sdk-rpc-client-v2.ts +++ b/packages/node-sdk/src/sdk-rpc-client-v2.ts @@ -397,8 +397,6 @@ import type { CreateWorktreeOptions, InspectWorktreeRemovalInput, RemoveWorktreeInput, - RunSetupScriptInput, - RunSetupScriptOptions, WorkLocation, WorktreeListing, WorktreeRemovalCheck, @@ -874,14 +872,6 @@ export class SDKRpcClientV2 extends SDKRpcClientBase { return withKimiErrors(this.engineAccessor.get(IWorktreeService).create({ ...input, cwd }, options)); } - override async runWorktreeSetupScript( - input: RunSetupScriptInput, - options?: RunSetupScriptOptions, - ): Promise<{ readonly exitCode: number }> { - await this.configReady; - return withKimiErrors(this.engineAccessor.get(IWorktreeService).runSetupScript(input, options)); - } - override async inspectWorktreeRemoval(input: InspectWorktreeRemovalInput): Promise { return withKimiErrors(this.engineAccessor.get(IWorktreeService).inspectRemoval(input)); } diff --git a/packages/node-sdk/src/worktree.ts b/packages/node-sdk/src/worktree.ts index 96c1af0db2f..f222caa969e 100644 --- a/packages/node-sdk/src/worktree.ts +++ b/packages/node-sdk/src/worktree.ts @@ -5,8 +5,6 @@ export type { InspectWorktreeRemovalInput, KimiWorktree, RemoveWorktreeInput, - RunSetupScriptInput, - RunSetupScriptOptions, WorktreeCreateEvent, WorktreeCreateStep, WorktreeListing, diff --git a/packages/node-sdk/test/sdk-rpc-client-v2.test.ts b/packages/node-sdk/test/sdk-rpc-client-v2.test.ts index b3d516e72a1..4806b7972df 100644 --- a/packages/node-sdk/test/sdk-rpc-client-v2.test.ts +++ b/packages/node-sdk/test/sdk-rpc-client-v2.test.ts @@ -5386,11 +5386,6 @@ describe('KimiHarness worktrees', () => { await expect(SDKRpcClientBase.prototype.createWorktree({ cwd: '/tmp/repo' })).rejects.toMatchObject({ code: ErrorCodes.NOT_IMPLEMENTED, }); - await expect( - SDKRpcClientBase.prototype.runWorktreeSetupScript({ worktreePath: '/tmp/wt', sourceRoot: '/tmp/repo' }), - ).rejects.toMatchObject({ - code: ErrorCodes.NOT_IMPLEMENTED, - }); await expect( SDKRpcClientBase.prototype.inspectWorktreeRemoval({ repoRoot: '/tmp/repo', path: '/tmp/wt', deleteBranch: false }), ).rejects.toMatchObject({ From a3c6eb389182d76c2e5e84d8900f869c53b68c8e Mon Sep 17 00:00:00 2001 From: grapedge Date: Thu, 26 Nov 2026 01:39:48 -0800 Subject: [PATCH 2/2] docs: remove worktree-setup.sh and print-mode trust warning from worktree guides --- docs/en/guides/worktrees.md | 29 ++--------------------------- docs/zh/guides/worktrees.md | 29 ++--------------------------- 2 files changed, 4 insertions(+), 54 deletions(-) diff --git a/docs/en/guides/worktrees.md b/docs/en/guides/worktrees.md index 0a65c318b91..b638ae98fd6 100644 --- a/docs/en/guides/worktrees.md +++ b/docs/en/guides/worktrees.md @@ -51,19 +51,11 @@ New worktrees start on a detached HEAD (not tied to a local branch), so they do kimi -p "Fix the login retry logic and run the tests" -w fix-auth ``` -::: warning Note -Using `-w` in print mode requires the project to be trusted first: run `kimi` here to trust it, or set `KIMI_CODE_TRUST_WORKSPACE=1`. -::: - Print mode keeps the worktree when it finishes and prints its path so you can inspect or remove it later. -## Copying ignored files and setup scripts - -Git worktrees only include tracked files by default. When a new worktree needs ignored local files or automatic environment setup, add `.worktreeinclude` and `.kimi-code/worktree-setup.sh` to your repository (both can be committed and shared with your team). +## Copying ignored files -### `.worktreeinclude` - -Create `.worktreeinclude` at the repository root using `.gitignore` syntax to list ignored files to copy into each new worktree: +Git worktrees only include tracked files by default. To copy local files ignored by `.gitignore` into each new worktree, create `.worktreeinclude` at the repository root using `.gitignore` syntax (this file can be committed and shared with your team): ```text .env @@ -73,23 +65,6 @@ config/local.json Only Git-ignored files are copied, and existing files in the new worktree are never overwritten. -### `.kimi-code/worktree-setup.sh` - -Add `.kimi-code/worktree-setup.sh` to prepare the environment when a worktree is created, such as installing dependencies: - -```sh -#!/bin/sh -set -e -pnpm install -``` - -The script runs once on creation (never again when switching back), preferring the copy inside the new worktree and falling back to the source checkout when absent. It runs in the new worktree root with two environment variables: - -- **`KIMI_CODE_WORKTREE_SOURCE_DIR`**: root directory of the source checkout. -- **`KIMI_CODE_WORKTREE_DIR`**: root directory of the new worktree. - -In the TUI, Kimi Code CLI asks whether to run the script on each creation; in print mode, it runs automatically once the project is trusted. - ## Cleanup when exiting When exiting the TUI from a managed worktree that is not open in another window, Kimi Code CLI prompts you to keep or delete it (defaulting to keep). diff --git a/docs/zh/guides/worktrees.md b/docs/zh/guides/worktrees.md index 5f074f550ee..05ddc69e2b7 100644 --- a/docs/zh/guides/worktrees.md +++ b/docs/zh/guides/worktrees.md @@ -51,19 +51,11 @@ kimi -w fix-auth --worktree-base main kimi -p "修复登录重试逻辑并运行测试" -w fix-auth ``` -::: warning 注意 -在 print 模式下使用 `-w` 需要先信任当前项目:先在该目录运行 `kimi` 确认信任,或设置 `KIMI_CODE_TRUST_WORKSPACE=1`。 -::: - print 模式结束后会保留工作树,并在终端输出其路径,方便后续查看或清理。 -## 复制忽略文件与初始化脚本 - -Git worktree 默认只包含已跟踪文件。需要带上被 `.gitignore` 忽略的本地文件或自动准备环境时,可在仓库中配置 `.worktreeinclude` 和 `.kimi-code/worktree-setup.sh`(两者均可提交到仓库与团队共享)。 +## 复制被忽略的文件 -### `.worktreeinclude` - -在仓库根目录创建 `.worktreeinclude`,用 `.gitignore` 语法列出需要复制到新工作树的忽略文件: +Git worktree 默认只包含已跟踪文件。如需将 `.gitignore` 忽略的本地文件复制到新工作树,可在仓库根目录创建 `.worktreeinclude`(可提交到仓库与团队共享),并用 `.gitignore` 语法列出要复制的文件: ```text .env @@ -73,23 +65,6 @@ config/local.json 仅复制被 Git 忽略的文件,不会覆盖新工作树中已有的文件。 -### `.kimi-code/worktree-setup.sh` - -在仓库中放置 `.kimi-code/worktree-setup.sh`,可在新建工作树时自动准备环境(例如安装依赖): - -```sh -#!/bin/sh -set -e -pnpm install -``` - -该脚本仅在新建工作树后执行一次(切回已有工作树不会重复执行),优先读取新工作树中的版本,不存在时回退到源目录。运行时以新工作树根目录为工作目录,并提供两个环境变量: - -- **`KIMI_CODE_WORKTREE_SOURCE_DIR`**:源目录根路径。 -- **`KIMI_CODE_WORKTREE_DIR`**:新工作树根路径。 - -TUI 中每次新建都会询问是否运行;print 模式在项目受信任后自动运行。 - ## 退出时的清理 从托管工作树退出 TUI 时,如果该工作树未被其他窗口使用,会弹出确认面板(默认保留),由你决定保留还是删除。