Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .changeset/worktree-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
53 changes: 6 additions & 47 deletions apps/kimi-code/src/cli/v2/run-v2-print.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
IFlagService,
IOAuthToolkit,
IProjectAliases,
IProjectInstanceManager,
IProjectService,
ISessionIndex,
ISessionManager,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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<CreatedWorktree | undefined> {
let created: CreatedWorktree;
try {
created = await client.createWorktree({ cwd, name: opts.worktree, base: opts.worktreeBase });
Comment thread
Grapedge marked this conversation as resolved.
Resolved
} 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) {
Expand All @@ -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<boolean> {
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(
Expand Down
47 changes: 0 additions & 47 deletions apps/kimi-code/src/tui/components/dialogs/worktree-choices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
31 changes: 2 additions & 29 deletions apps/kimi-code/src/tui/components/messages/worktree-progress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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[] }
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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}`);
}
}
}

Expand Down
1 change: 0 additions & 1 deletion apps/kimi-code/src/tui/constant/worktree.ts
Original file line number Diff line number Diff line change
@@ -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;
Loading
Loading