Skip to content
Closed
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
7 changes: 6 additions & 1 deletion src/app/managers/interaction-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ import { renameManager } from "./rename-manager.js";
import { taskCreationManager } from "./scheduled-task-creation-manager.js";
import { logger } from "../../utils/logger.js";

export const DEFAULT_ALLOWED_INTERACTION_COMMANDS = ["/help", "/status", "/abort", "/detach"] as const;
export const DEFAULT_ALLOWED_INTERACTION_COMMANDS = [
"/help",
"/status",
"/abort",
"/detach",
] as const;

function normalizeCommand(command: string): string | null {
const trimmed = command.trim().toLowerCase();
Expand Down
70 changes: 70 additions & 0 deletions src/app/services/worktree-service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { execFile } from "node:child_process";
import { readFile, stat } from "node:fs/promises";
import path from "node:path";
import { config } from "../../config.js";
import { logger } from "../../utils/logger.js";
import type { GitWorktreeContext, GitWorktreeEntry } from "../types/worktree.js";

const GIT_HEADS_PREFIX = "refs/heads/";
Expand Down Expand Up @@ -201,3 +203,71 @@ export async function getGitWorktreeContext(worktree: string): Promise<GitWorktr
worktrees,
};
}

export interface CreateWorktreeResult {
path: string;
apiBranch?: string;
error?: string;
}

interface OpenCodeWorktreeResponse {
name: string;
branch?: string;
directory: string;
}

/**
* Create a new git worktree using the OpenCode API.
* Calls POST /experimental/worktree with { name } in the body.
* The server creates the worktree directory and branch (opencode/<name>).
*/
export async function createGitWorktree(name?: string): Promise<CreateWorktreeResult> {
const url = `${config.opencode.apiUrl}/experimental/worktree`;

const headers: Record<string, string> = {
"Content-Type": "application/json",
};

if (config.opencode.password) {
const credentials = `${config.opencode.username}:${config.opencode.password}`;
headers["Authorization"] = `Basic ${Buffer.from(credentials).toString("base64")}`;
}

const body: Record<string, string> = {};
if (name !== undefined) {
body.name = name;
}

logger.debug(`[WorktreeService] Creating worktree via API: ${url}`, { name });

try {
const response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(body),
});

if (!response.ok) {
const errorBody = await response.text().catch(() => "");
const errorMessage = errorBody || `HTTP ${response.status} ${response.statusText}`;
logger.error(`[WorktreeService] API error creating worktree: ${errorMessage}`);
return { path: "", error: errorMessage };
}

const raw = (await response.json()) as OpenCodeWorktreeResponse;

const worktreePath = raw.directory || "";

if (!worktreePath) {
logger.error(`[WorktreeService] API returned empty directory (response keys: ${Object.keys(raw).join(", ")})`);
return { path: "", error: "API returned an empty worktree path" };
}

logger.info(`[WorktreeService] Worktree created successfully: ${worktreePath} (branch: ${raw.branch ?? "none"})`);
return { path: worktreePath, apiBranch: raw.branch };
} catch (err) {
const errorMessage = err instanceof Error ? err.message : String(err);
logger.error(`[WorktreeService] Failed to create worktree: ${errorMessage}`);
return { path: "", error: errorMessage };
}
}
9 changes: 8 additions & 1 deletion src/app/types/interaction.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
export type InteractionKind = "inline" | "permission" | "question" | "rename" | "task" | "custom";
export type InteractionKind =
| "inline"
| "permission"
| "question"
| "rename"
| "task"
| "custom"
| "worktree-add";

export type ExpectedInput = "callback" | "text" | "command" | "mixed";

Expand Down
56 changes: 54 additions & 2 deletions src/bot/callbacks/worktree-callback-handler.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import type { Context } from "grammy";
import { clearAllInteractionState } from "../../app/managers/interaction-manager.js";
import {
clearAllInteractionState,
interactionManager,
} from "../../app/managers/interaction-manager.js";
import { getProjectByWorktree } from "../../app/services/project-service.js";
import { isForegroundBusy } from "../../app/services/run-control-service.js";
import { switchToProject } from "../../app/services/project-switch-service.js";
import { getGitWorktreeContext } from "../../app/services/worktree-service.js";
import {
createGitWorktree,
getGitWorktreeContext,
} from "../../app/services/worktree-service.js";
import { upsertSessionDirectory } from "../../app/services/session-cache-service.js";
import { getCurrentProject } from "../../app/stores/settings-store.js";
import { t } from "../../i18n/index.js";
Expand Down Expand Up @@ -124,3 +130,49 @@ export async function handleWorktreeCallback(
return true;
}
}

export async function handleWorktreeAddTextAnswer(ctx: Context): Promise<boolean> {
const interactionState = interactionManager.getSnapshot();
if (interactionState?.kind !== "worktree-add") {
return false;
}

const text = ctx.message?.text;
if (!text || text.startsWith("/")) {
return false;
}

const name = text.trim();
if (!name) {
await ctx.reply(t("worktree_add.name_required"));
return true;
}

logger.info(`[WorktreeAddHandler] Creating worktree with name: ${name}`);

try {
const result = await createGitWorktree(name);

if (result.error) {
logger.error(`[WorktreeAddHandler] Creation failed: ${result.error}`);
await ctx.reply(t("worktree_add.error", { error: result.error }));
return true;
}

logger.info(`[WorktreeAddHandler] Worktree created: ${result.path}`);
await ctx.reply(
t("worktree_add.success", {
name,
api_branch: result.apiBranch ?? name,
path: result.path,
}),
);
} catch (err) {
logger.error("[WorktreeAddHandler] Unexpected error:", err);
await ctx.reply(t("worktree_add.error_generic"));
} finally {
interactionManager.clear("worktree-add-completed");
}

return true;
}
Loading