Merge branch 'dev' into fix/issue-2232

This commit is contained in:
YeonGyu-Kim
2026-03-11 20:20:04 +09:00
committed by GitHub
210 changed files with 7089 additions and 1274 deletions
@@ -0,0 +1,49 @@
import { describe, expect, test } from "bun:test"
import { tmpdir } from "node:os"
import type { PluginInput } from "@opencode-ai/plugin"
import { BackgroundManager } from "./manager"
describe("BackgroundManager session permission", () => {
test("passes explicit session permission rules to child session creation", async () => {
// given
const createCalls: Array<Record<string, unknown>> = []
const client = {
session: {
get: async () => ({ data: { directory: "/parent" } }),
create: async (input: Record<string, unknown>) => {
createCalls.push(input)
return { data: { id: "ses_child" } }
},
promptAsync: async () => ({}),
abort: async () => ({}),
},
}
const manager = new BackgroundManager({ client, directory: tmpdir() } as unknown as PluginInput)
// when
await manager.launch({
description: "Test task",
prompt: "Do something",
agent: "explore",
parentSessionID: "ses_parent",
parentMessageID: "msg_parent",
sessionPermission: [
{ permission: "question", action: "deny", pattern: "*" },
],
})
await new Promise(resolve => setTimeout(resolve, 50))
manager.shutdown()
// then
expect(createCalls).toHaveLength(1)
expect(createCalls[0]?.body).toEqual({
parentID: "ses_parent",
title: "Test task (@explore subagent)",
permission: [
{ permission: "question", action: "deny", pattern: "*" },
],
})
})
})
@@ -2,6 +2,7 @@ import { describe, test, expect } from "bun:test"
import { tmpdir } from "node:os"
import type { PluginInput } from "@opencode-ai/plugin"
import { BackgroundManager } from "./manager"
import type { BackgroundTask } from "./types"
function createManagerWithStatus(statusImpl: () => Promise<{ data: Record<string, { type: string }> }>): BackgroundManager {
const client = {
@@ -51,3 +52,105 @@ describe("BackgroundManager polling overlap", () => {
expect(statusCallCount).toBe(1)
})
})
function createRunningTask(sessionID: string): BackgroundTask {
return {
id: `bg_test_${sessionID}`,
sessionID,
parentSessionID: "parent-session",
parentMessageID: "parent-msg",
description: "test task",
prompt: "test",
agent: "explore",
status: "running",
startedAt: new Date(),
progress: { toolCalls: 0, lastUpdate: new Date() },
}
}
function injectTask(manager: BackgroundManager, task: BackgroundTask): void {
const tasks = (manager as unknown as { tasks: Map<string, BackgroundTask> }).tasks
tasks.set(task.id, task)
}
function createManagerWithClient(clientOverrides: Record<string, unknown> = {}): BackgroundManager {
const client = {
session: {
status: async () => ({ data: {} }),
prompt: async () => ({}),
promptAsync: async () => ({}),
abort: async () => ({}),
todo: async () => ({ data: [] }),
messages: async () => ({
data: [{
info: { role: "assistant", finish: "end_turn", id: "msg-2" },
parts: [{ type: "text", text: "done" }],
}, {
info: { role: "user", id: "msg-1" },
parts: [{ type: "text", text: "go" }],
}],
}),
...clientOverrides,
},
}
return new BackgroundManager({ client, directory: tmpdir() } as unknown as PluginInput)
}
describe("BackgroundManager pollRunningTasks", () => {
describe("#given a running task whose session is no longer in status response", () => {
test("#when pollRunningTasks runs #then completes the task instead of leaving it running", async () => {
//#given
const manager = createManagerWithClient()
const task = createRunningTask("ses-gone")
injectTask(manager, task)
//#when
const poll = (manager as unknown as { pollRunningTasks: () => Promise<void> }).pollRunningTasks
await poll.call(manager)
manager.shutdown()
//#then
expect(task.status).toBe("completed")
expect(task.completedAt).toBeDefined()
})
})
describe("#given a running task whose session status is idle", () => {
test("#when pollRunningTasks runs #then completes the task", async () => {
//#given
const manager = createManagerWithClient({
status: async () => ({ data: { "ses-idle": { type: "idle" } } }),
})
const task = createRunningTask("ses-idle")
injectTask(manager, task)
//#when
const poll = (manager as unknown as { pollRunningTasks: () => Promise<void> }).pollRunningTasks
await poll.call(manager)
manager.shutdown()
//#then
expect(task.status).toBe("completed")
})
})
describe("#given a running task whose session status is busy", () => {
test("#when pollRunningTasks runs #then keeps the task running", async () => {
//#given
const manager = createManagerWithClient({
status: async () => ({ data: { "ses-busy": { type: "busy" } } }),
})
const task = createRunningTask("ses-busy")
injectTask(manager, task)
//#when
const poll = (manager as unknown as { pollRunningTasks: () => Promise<void> }).pollRunningTasks
await poll.call(manager)
manager.shutdown()
//#then
expect(task.status).toBe("running")
})
})
})
+109 -13
View File
@@ -1334,6 +1334,100 @@ describe("BackgroundManager.tryCompleteTask", () => {
expect(getPendingByParent(manager).get(task.parentSessionID)).toBeUndefined()
})
test("should remove toast tracking before notifying completed task", async () => {
// given
const { removeTaskCalls, resetToastManager } = createToastRemoveTaskTracker()
const task: BackgroundTask = {
id: "task-toast-complete",
sessionID: "session-toast-complete",
parentSessionID: "parent-toast-complete",
parentMessageID: "msg-1",
description: "toast completion task",
prompt: "test",
agent: "explore",
status: "running",
startedAt: new Date(),
}
try {
// when
await tryCompleteTaskForTest(manager, task)
// then
expect(removeTaskCalls).toContain(task.id)
} finally {
resetToastManager()
}
})
test("should release task concurrencyKey when startTask throws after assigning it", async () => {
// given
const concurrencyKey = "anthropic/claude-opus-4-6"
const concurrencyManager = getConcurrencyManager(manager)
const task = createMockTask({
id: "task-process-key-concurrency",
sessionID: "session-process-key-concurrency",
parentSessionID: "parent-process-key-concurrency",
status: "pending",
agent: "explore",
})
const input = {
description: task.description,
prompt: task.prompt,
agent: task.agent,
parentSessionID: task.parentSessionID,
parentMessageID: task.parentMessageID,
model: { providerID: "anthropic", modelID: "claude-opus-4-6" },
}
getTaskMap(manager).set(task.id, task)
getQueuesByKey(manager).set(concurrencyKey, [{ task, input }])
;(manager as unknown as { startTask: (item: { task: BackgroundTask; input: typeof input }) => Promise<void> }).startTask = async (item) => {
item.task.concurrencyKey = concurrencyKey
throw new Error("startTask failed after assigning concurrencyKey")
}
// when
await processKeyForTest(manager, concurrencyKey)
// then
expect(concurrencyManager.getCount(concurrencyKey)).toBe(0)
expect(task.concurrencyKey).toBeUndefined()
})
test("should release queue slot when queued task is already interrupt", async () => {
// given
const concurrencyKey = "anthropic/claude-opus-4-6"
const concurrencyManager = getConcurrencyManager(manager)
const task = createMockTask({
id: "task-process-key-interrupt",
sessionID: "session-process-key-interrupt",
parentSessionID: "parent-process-key-interrupt",
status: "interrupt",
agent: "explore",
})
const input = {
description: task.description,
prompt: task.prompt,
agent: task.agent,
parentSessionID: task.parentSessionID,
parentMessageID: task.parentMessageID,
model: { providerID: "anthropic", modelID: "claude-opus-4-6" },
}
getTaskMap(manager).set(task.id, task)
getQueuesByKey(manager).set(concurrencyKey, [{ task, input }])
// when
await processKeyForTest(manager, concurrencyKey)
// then
expect(concurrencyManager.getCount(concurrencyKey)).toBe(0)
expect(getQueuesByKey(manager).get(concurrencyKey)).toEqual([])
})
test("should avoid overlapping promptAsync calls when tasks complete concurrently", async () => {
// given
type PromptAsyncBody = Record<string, unknown> & { noReply?: boolean }
@@ -3189,7 +3283,7 @@ describe("BackgroundManager.handleEvent - session.error", () => {
concurrencyKey,
fallbackChain: [
{ providers: ["anthropic"], model: "claude-opus-4-6", variant: "max" },
{ providers: ["anthropic"], model: "claude-opus-4-5" },
{ providers: ["anthropic"], model: "claude-opus-4-5", variant: "max" },
],
})
@@ -3271,21 +3365,23 @@ describe("BackgroundManager.handleEvent - session.error", () => {
})
//#when
const messageInfo = {
id: "msg_errored",
sessionID,
role: "assistant",
error: {
name: "UnknownError",
data: {
message:
"Bad Gateway: {\"error\":{\"message\":\"unknown provider for model claude-opus-4-6-thinking\"}}",
},
},
}
manager.handleEvent({
type: "message.updated",
properties: {
info: {
id: "msg_errored",
sessionID,
role: "assistant",
error: {
name: "UnknownError",
data: {
message:
"Bad Gateway: {\"error\":{\"message\":\"unknown provider for model claude-opus-4-6-thinking\"}}",
},
},
},
info: messageInfo,
},
})
+51 -40
View File
@@ -50,6 +50,7 @@ import { MESSAGE_STORAGE } from "../hook-message-injector"
import { join } from "node:path"
import { pruneStaleTasksAndNotifications } from "./task-poller"
import { checkAndInterruptStaleTasks } from "./task-poller"
import { removeTaskToastTracking } from "./remove-task-toast-tracking"
type OpencodeClient = PluginInput["client"]
@@ -225,7 +226,7 @@ export class BackgroundManager {
await this.concurrencyManager.acquire(key)
if (item.task.status === "cancelled" || item.task.status === "error") {
if (item.task.status === "cancelled" || item.task.status === "error" || item.task.status === "interrupt") {
this.concurrencyManager.release(key)
queue.shift()
continue
@@ -235,9 +236,10 @@ export class BackgroundManager {
await this.startTask(item)
} catch (error) {
log("[background-agent] Error starting task:", error)
// Release concurrency slot if startTask failed and didn't release it itself
// This prevents slot leaks when errors occur after acquire but before task.concurrencyKey is set
if (!item.task.concurrencyKey) {
if (item.task.concurrencyKey) {
this.concurrencyManager.release(item.task.concurrencyKey)
item.task.concurrencyKey = undefined
} else {
this.concurrencyManager.release(key)
}
}
@@ -273,6 +275,7 @@ export class BackgroundManager {
body: {
parentID: input.parentSessionID,
title: `${input.description} (@${input.agent} subagent)`,
...(input.sessionPermission ? { permission: input.sessionPermission } : {}),
} as Record<string, unknown>,
query: {
directory: parentDirectory,
@@ -387,6 +390,8 @@ export class BackgroundManager {
existingTask.concurrencyKey = undefined
}
removeTaskToastTracking(existingTask.id)
// Abort the session to prevent infinite polling hang
this.client.session.abort({
path: { id: sessionID },
@@ -656,6 +661,8 @@ export class BackgroundManager {
existingTask.concurrencyKey = undefined
}
removeTaskToastTracking(existingTask.id)
// Abort the session to prevent infinite polling hang
if (existingTask.sessionID) {
this.client.session.abort({
@@ -1107,11 +1114,9 @@ export class BackgroundManager {
SessionCategoryRegistry.remove(task.sessionID)
}
removeTaskToastTracking(task.id)
if (options?.skipNotification) {
const toastManager = getTaskToastManager()
if (toastManager) {
toastManager.removeTask(task.id)
}
log(`[background-agent] Task cancelled via ${source} (notification skipped):`, task.id)
return true
}
@@ -1197,6 +1202,8 @@ export class BackgroundManager {
task.completedAt = new Date()
this.taskHistory.record(task.parentSessionID, { id: task.id, sessionID: task.sessionID, agent: task.agent, description: task.description, status: "completed", category: task.category, startedAt: task.startedAt, completedAt: task.completedAt })
removeTaskToastTracking(task.id)
// Release concurrency BEFORE any async operations to prevent slot leaks
if (task.concurrencyKey) {
this.concurrencyManager.release(task.concurrencyKey)
@@ -1444,6 +1451,7 @@ Use \`background_output(task_id="${task.id}")\` to retrieve this result when rea
this.concurrencyManager.release(task.concurrencyKey)
task.concurrencyKey = undefined
}
removeTaskToastTracking(task.id)
this.cleanupPendingByParent(task)
if (wasPending) {
const key = task.model
@@ -1506,32 +1514,7 @@ Use \`background_output(task_id="${task.id}")\` to retrieve this result when rea
try {
const sessionStatus = allStatuses[sessionID]
if (sessionStatus?.type === "idle") {
// Edge guard: Validate session has actual output before completing
const hasValidOutput = await this.validateSessionHasOutput(sessionID)
if (!hasValidOutput) {
log("[background-agent] Polling idle but no valid output yet, waiting:", task.id)
continue
}
// Re-check status after async operation
if (task.status !== "running") continue
const hasIncompleteTodos = await this.checkSessionTodos(sessionID)
if (hasIncompleteTodos) {
log("[background-agent] Task has incomplete todos via polling, waiting:", task.id)
continue
}
await this.tryCompleteTask(task, "polling (idle status)")
continue
}
// Session is still actively running (not idle).
// Progress is already tracked via handleEvent(message.part.updated),
// so we skip the expensive session.messages() fetch here.
// Completion will be detected when session transitions to idle.
// Handle retry before checking running state
if (sessionStatus?.type === "retry") {
const retryMessage = typeof (sessionStatus as { message?: string }).message === "string"
? (sessionStatus as { message?: string }).message
@@ -1542,12 +1525,40 @@ Use \`background_output(task_id="${task.id}")\` to retrieve this result when rea
}
}
log("[background-agent] Session still running, relying on event-based progress:", {
taskId: task.id,
sessionID,
sessionStatus: sessionStatus?.type ?? "not_in_status",
toolCalls: task.progress?.toolCalls ?? 0,
})
// Match sync-session-poller pattern: only skip completion check when
// status EXISTS and is not idle (i.e., session is actively running).
// When sessionStatus is undefined, the session has completed and dropped
// from the status response — fall through to completion detection.
if (sessionStatus && sessionStatus.type !== "idle") {
log("[background-agent] Session still running, relying on event-based progress:", {
taskId: task.id,
sessionID,
sessionStatus: sessionStatus.type,
toolCalls: task.progress?.toolCalls ?? 0,
})
continue
}
// Session is idle or no longer in status response (completed/disappeared)
const completionSource = sessionStatus?.type === "idle"
? "polling (idle status)"
: "polling (session gone from status)"
const hasValidOutput = await this.validateSessionHasOutput(sessionID)
if (!hasValidOutput) {
log("[background-agent] Polling idle/gone but no valid output yet, waiting:", task.id)
continue
}
// Re-check status after async operation
if (task.status !== "running") continue
const hasIncompleteTodos = await this.checkSessionTodos(sessionID)
if (hasIncompleteTodos) {
log("[background-agent] Task has incomplete todos via polling, waiting:", task.id)
continue
}
await this.tryCompleteTask(task, completionSource)
} catch (error) {
log("[background-agent] Poll error for task:", { taskId: task.id, error })
}
@@ -0,0 +1,8 @@
import { getTaskToastManager } from "../task-toast-manager"
export function removeTaskToastTracking(taskId: string): void {
const toastManager = getTaskToastManager()
if (toastManager) {
toastManager.removeTask(taskId)
}
}
@@ -3,7 +3,7 @@ import { describe, test, expect } from "bun:test"
import { createTask, startTask } from "./spawner"
describe("background-agent spawner.startTask", () => {
test("does not override parent session permission rules when creating child session", async () => {
test("applies explicit child session permission rules when creating child session", async () => {
//#given
const createCalls: any[] = []
const parentPermission = [
@@ -41,6 +41,9 @@ describe("background-agent spawner.startTask", () => {
parentModel: task.parentModel,
parentAgent: task.parentAgent,
model: task.model,
sessionPermission: [
{ permission: "question", action: "deny", pattern: "*" },
],
},
}
@@ -57,6 +60,8 @@ describe("background-agent spawner.startTask", () => {
//#then
expect(createCalls).toHaveLength(1)
expect(createCalls[0]?.body?.permission).toBeUndefined()
expect(createCalls[0]?.body?.permission).toEqual([
{ permission: "question", action: "deny", pattern: "*" },
])
})
})
+1
View File
@@ -61,6 +61,7 @@ export async function startTask(
const createResult = await client.session.create({
body: {
parentID: input.parentSessionID,
...(input.sessionPermission ? { permission: input.sessionPermission } : {}),
} as Record<string, unknown>,
query: {
directory: parentDirectory,
@@ -391,6 +391,31 @@ describe("checkAndInterruptStaleTasks", () => {
expect(releaseMock).toHaveBeenCalledWith("anthropic/claude-opus-4-6")
expect(task.concurrencyKey).toBeUndefined()
})
it("should invoke interruption callback immediately when stale task is cancelled", async () => {
//#given
const task = createRunningTask({
progress: {
toolCalls: 1,
lastUpdate: new Date(Date.now() - 200_000),
},
})
const onTaskInterrupted = mock(() => {})
//#when
await checkAndInterruptStaleTasks({
tasks: [task],
client: mockClient as never,
config: { staleTimeoutMs: 180_000 },
concurrencyManager: mockConcurrencyManager as never,
notifyParentSession: mockNotify,
onTaskInterrupted,
})
//#then
expect(task.status).toBe("cancelled")
expect(onTaskInterrupted).toHaveBeenCalledWith(task)
})
})
describe("pruneStaleTasksAndNotifications", () => {
+15 -1
View File
@@ -11,6 +11,7 @@ import {
MIN_RUNTIME_BEFORE_STALE_MS,
TASK_TTL_MS,
} from "./constants"
import { removeTaskToastTracking } from "./remove-task-toast-tracking"
export function pruneStaleTasksAndNotifications(args: {
tasks: Map<string, BackgroundTask>
@@ -66,8 +67,17 @@ export async function checkAndInterruptStaleTasks(args: {
concurrencyManager: ConcurrencyManager
notifyParentSession: (task: BackgroundTask) => Promise<void>
sessionStatuses?: SessionStatusMap
onTaskInterrupted?: (task: BackgroundTask) => void
}): Promise<void> {
const { tasks, client, config, concurrencyManager, notifyParentSession, sessionStatuses } = args
const {
tasks,
client,
config,
concurrencyManager,
notifyParentSession,
sessionStatuses,
onTaskInterrupted = (task) => removeTaskToastTracking(task.id),
} = args
const staleTimeoutMs = config?.staleTimeoutMs ?? DEFAULT_STALE_TIMEOUT_MS
const now = Date.now()
@@ -98,6 +108,8 @@ export async function checkAndInterruptStaleTasks(args: {
task.concurrencyKey = undefined
}
onTaskInterrupted(task)
client.session.abort({ path: { id: sessionID } }).catch(() => {})
log(`[background-agent] Task ${task.id} interrupted: no progress since start`)
@@ -127,6 +139,8 @@ export async function checkAndInterruptStaleTasks(args: {
task.concurrencyKey = undefined
}
onTaskInterrupted(task)
client.session.abort({ path: { id: sessionID } }).catch(() => {})
log(`[background-agent] Task ${task.id} interrupted: stale timeout`)
+2
View File
@@ -1,4 +1,5 @@
import type { FallbackEntry } from "../../shared/model-requirements"
import type { SessionPermissionRule } from "../../shared/question-denied-session-permission"
export type BackgroundTaskStatus =
| "pending"
@@ -72,6 +73,7 @@ export interface LaunchInput {
skills?: string[]
skillContent?: string
category?: string
sessionPermission?: SessionPermissionRule[]
}
export interface ResumeInput {
@@ -0,0 +1,108 @@
/// <reference types="bun-types" />
import { describe, it, expect } from "bun:test"
import { mapClaudeModelToOpenCode } from "./claude-model-mapper"
describe("mapClaudeModelToOpenCode", () => {
describe("#given undefined or empty input", () => {
it("#when called with undefined #then returns undefined", () => {
expect(mapClaudeModelToOpenCode(undefined)).toBeUndefined()
})
it("#when called with empty string #then returns undefined", () => {
expect(mapClaudeModelToOpenCode("")).toBeUndefined()
})
it("#when called with whitespace-only string #then returns undefined", () => {
expect(mapClaudeModelToOpenCode(" ")).toBeUndefined()
})
})
describe("#given Claude Code alias", () => {
it("#when called with sonnet #then maps to anthropic claude-sonnet-4-6 object", () => {
expect(mapClaudeModelToOpenCode("sonnet")).toEqual({ providerID: "anthropic", modelID: "claude-sonnet-4-6" })
})
it("#when called with opus #then maps to anthropic claude-opus-4-6 object", () => {
expect(mapClaudeModelToOpenCode("opus")).toEqual({ providerID: "anthropic", modelID: "claude-opus-4-6" })
})
it("#when called with haiku #then maps to anthropic claude-haiku-4-5 object", () => {
expect(mapClaudeModelToOpenCode("haiku")).toEqual({ providerID: "anthropic", modelID: "claude-haiku-4-5" })
})
it("#when called with Sonnet (capitalized) #then maps case-insensitively to object", () => {
expect(mapClaudeModelToOpenCode("Sonnet")).toEqual({ providerID: "anthropic", modelID: "claude-sonnet-4-6" })
})
})
describe("#given inherit", () => {
it("#when called with inherit #then returns undefined", () => {
expect(mapClaudeModelToOpenCode("inherit")).toBeUndefined()
})
})
describe("#given bare Claude model name", () => {
it("#when called with claude-sonnet-4-5-20250514 #then adds anthropic object format", () => {
expect(mapClaudeModelToOpenCode("claude-sonnet-4-5-20250514")).toEqual({ providerID: "anthropic", modelID: "claude-sonnet-4-5-20250514" })
})
it("#when called with claude-opus-4-6 #then adds anthropic object format", () => {
expect(mapClaudeModelToOpenCode("claude-opus-4-6")).toEqual({ providerID: "anthropic", modelID: "claude-opus-4-6" })
})
it("#when called with claude-haiku-4-5-20251001 #then adds anthropic object format", () => {
expect(mapClaudeModelToOpenCode("claude-haiku-4-5-20251001")).toEqual({ providerID: "anthropic", modelID: "claude-haiku-4-5-20251001" })
})
it("#when called with claude-3-5-sonnet-20241022 #then adds anthropic object format", () => {
expect(mapClaudeModelToOpenCode("claude-3-5-sonnet-20241022")).toEqual({ providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" })
})
})
describe("#given model with dot version numbers", () => {
it("#when called with claude-3.5-sonnet #then normalizes dots and returns object format", () => {
expect(mapClaudeModelToOpenCode("claude-3.5-sonnet")).toEqual({ providerID: "anthropic", modelID: "claude-3-5-sonnet" })
})
it("#when called with claude-3.5-sonnet-20241022 #then normalizes dots and returns object format", () => {
expect(mapClaudeModelToOpenCode("claude-3.5-sonnet-20241022")).toEqual({ providerID: "anthropic", modelID: "claude-3-5-sonnet-20241022" })
})
})
describe("#given model already in provider/model format", () => {
it("#when called with anthropic/claude-sonnet-4-6 #then splits into object format", () => {
expect(mapClaudeModelToOpenCode("anthropic/claude-sonnet-4-6")).toEqual({ providerID: "anthropic", modelID: "claude-sonnet-4-6" })
})
it("#when called with openai/gpt-5.2 #then splits into object format", () => {
expect(mapClaudeModelToOpenCode("openai/gpt-5.2")).toEqual({ providerID: "openai", modelID: "gpt-5.2" })
})
})
describe("#given non-Claude bare model", () => {
it("#when called with gpt-5.2 #then returns undefined", () => {
expect(mapClaudeModelToOpenCode("gpt-5.2")).toBeUndefined()
})
it("#when called with gemini-3-flash #then returns undefined", () => {
expect(mapClaudeModelToOpenCode("gemini-3-flash")).toBeUndefined()
})
})
describe("#given prototype property name", () => {
it("#when called with constructor #then returns undefined", () => {
expect(mapClaudeModelToOpenCode("constructor")).toBeUndefined()
})
it("#when called with toString #then returns undefined", () => {
expect(mapClaudeModelToOpenCode("toString")).toBeUndefined()
})
})
describe("#given model with leading/trailing whitespace", () => {
it("#when called with padded string #then trims before returning object format", () => {
expect(mapClaudeModelToOpenCode(" claude-sonnet-4-6 ")).toEqual({ providerID: "anthropic", modelID: "claude-sonnet-4-6" })
})
})
})
@@ -0,0 +1,39 @@
import { normalizeModelFormat } from "../../shared/model-format-normalizer"
import { normalizeModelID } from "../../shared/model-normalization"
const ANTHROPIC_PREFIX = "anthropic/"
const CLAUDE_CODE_ALIAS_MAP = new Map<string, string>([
["sonnet", `${ANTHROPIC_PREFIX}claude-sonnet-4-6`],
["opus", `${ANTHROPIC_PREFIX}claude-opus-4-6`],
["haiku", `${ANTHROPIC_PREFIX}claude-haiku-4-5`],
])
function mapClaudeModelString(model: string | undefined): string | undefined {
if (!model) return undefined
const trimmed = model.trim()
if (trimmed.length === 0) return undefined
if (trimmed === "inherit") return undefined
const aliasResult = CLAUDE_CODE_ALIAS_MAP.get(trimmed.toLowerCase())
if (aliasResult) return aliasResult
if (trimmed.includes("/")) return trimmed
const normalized = normalizeModelID(trimmed)
if (normalized.startsWith("claude-")) {
return `${ANTHROPIC_PREFIX}${normalized}`
}
return undefined
}
export function mapClaudeModelToOpenCode(
model: string | undefined
): { providerID: string; modelID: string } | undefined {
const mappedModel = mapClaudeModelString(model)
return mappedModel ? normalizeModelFormat(mappedModel) : undefined
}
@@ -1,10 +1,10 @@
import { existsSync, readdirSync, readFileSync } from "fs"
import { join, basename } from "path"
import type { AgentConfig } from "@opencode-ai/sdk"
import { parseFrontmatter } from "../../shared/frontmatter"
import { isMarkdownFile } from "../../shared/file-utils"
import { getClaudeConfigDir } from "../../shared"
import type { AgentScope, AgentFrontmatter, LoadedAgent } from "./types"
import type { AgentScope, AgentFrontmatter, ClaudeCodeAgentConfig, LoadedAgent } from "./types"
import { mapClaudeModelToOpenCode } from "./claude-model-mapper"
function parseToolsConfig(toolsStr?: string): Record<string, boolean> | undefined {
if (!toolsStr) return undefined
@@ -42,10 +42,13 @@ function loadAgentsFromDir(agentsDir: string, scope: AgentScope): LoadedAgent[]
const formattedDescription = `(${scope}) ${originalDescription}`
const config: AgentConfig = {
const mappedModelOverride = mapClaudeModelToOpenCode(data.model)
const config: ClaudeCodeAgentConfig = {
description: formattedDescription,
mode: "subagent",
mode: data.mode || "subagent",
prompt: body.trim(),
...(mappedModelOverride ? { model: mappedModelOverride } : {}),
}
const toolsConfig = parseToolsConfig(data.tools)
@@ -67,22 +70,22 @@ function loadAgentsFromDir(agentsDir: string, scope: AgentScope): LoadedAgent[]
return agents
}
export function loadUserAgents(): Record<string, AgentConfig> {
export function loadUserAgents(): Record<string, ClaudeCodeAgentConfig> {
const userAgentsDir = join(getClaudeConfigDir(), "agents")
const agents = loadAgentsFromDir(userAgentsDir, "user")
const result: Record<string, AgentConfig> = {}
const result: Record<string, ClaudeCodeAgentConfig> = {}
for (const agent of agents) {
result[agent.name] = agent.config
}
return result
}
export function loadProjectAgents(directory?: string): Record<string, AgentConfig> {
export function loadProjectAgents(directory?: string): Record<string, ClaudeCodeAgentConfig> {
const projectAgentsDir = join(directory ?? process.cwd(), ".claude", "agents")
const agents = loadAgentsFromDir(projectAgentsDir, "project")
const result: Record<string, AgentConfig> = {}
const result: Record<string, ClaudeCodeAgentConfig> = {}
for (const agent of agents) {
result[agent.name] = agent.config
}
@@ -2,16 +2,21 @@ import type { AgentConfig } from "@opencode-ai/sdk"
export type AgentScope = "user" | "project"
export type ClaudeCodeAgentConfig = Omit<AgentConfig, "model"> & {
model?: string | { providerID: string; modelID: string }
}
export interface AgentFrontmatter {
name?: string
description?: string
model?: string
tools?: string
mode?: "subagent" | "primary" | "all"
}
export interface LoadedAgent {
name: string
path: string
config: AgentConfig
config: ClaudeCodeAgentConfig
scope: AgentScope
}
@@ -1,10 +1,10 @@
import { existsSync, readdirSync, readFileSync } from "fs"
import { basename, join } from "path"
import type { AgentConfig } from "@opencode-ai/sdk"
import { parseFrontmatter } from "../../shared/frontmatter"
import { isMarkdownFile } from "../../shared/file-utils"
import { log } from "../../shared/logger"
import type { AgentFrontmatter } from "../claude-code-agent-loader/types"
import type { AgentFrontmatter, ClaudeCodeAgentConfig } from "../claude-code-agent-loader/types"
import { mapClaudeModelToOpenCode } from "../claude-code-agent-loader/claude-model-mapper"
import type { LoadedPlugin } from "./types"
function parseToolsConfig(toolsStr?: string): Record<string, boolean> | undefined {
@@ -24,8 +24,8 @@ function parseToolsConfig(toolsStr?: string): Record<string, boolean> | undefine
return result
}
export function loadPluginAgents(plugins: LoadedPlugin[]): Record<string, AgentConfig> {
const agents: Record<string, AgentConfig> = {}
export function loadPluginAgents(plugins: LoadedPlugin[]): Record<string, ClaudeCodeAgentConfig> {
const agents: Record<string, ClaudeCodeAgentConfig> = {}
for (const plugin of plugins) {
if (!plugin.agentsDir || !existsSync(plugin.agentsDir)) continue
@@ -46,10 +46,13 @@ export function loadPluginAgents(plugins: LoadedPlugin[]): Record<string, AgentC
const originalDescription = data.description || ""
const formattedDescription = `(plugin: ${plugin.name}) ${originalDescription}`
const config: AgentConfig = {
const mappedModelOverride = mapClaudeModelToOpenCode(data.model)
const config: ClaudeCodeAgentConfig = {
description: formattedDescription,
mode: "subagent",
prompt: body.trim(),
...(mappedModelOverride ? { model: mappedModelOverride } : {}),
}
const toolsConfig = parseToolsConfig(data.tools)
@@ -1,7 +1,7 @@
import { log } from "../../shared/logger"
import type { AgentConfig } from "@opencode-ai/sdk"
import type { CommandDefinition } from "../claude-code-command-loader/types"
import type { McpServerConfig } from "../claude-code-mcp-loader/types"
import type { ClaudeCodeAgentConfig } from "../claude-code-agent-loader/types"
import type { HooksConfig, LoadedPlugin, PluginLoadError, PluginLoaderOptions } from "./types"
import { discoverInstalledPlugins } from "./discovery"
import { loadPluginCommands } from "./command-loader"
@@ -20,7 +20,7 @@ export { loadPluginHooksConfigs } from "./hook-loader"
export interface PluginComponentsResult {
commands: Record<string, CommandDefinition>
skills: Record<string, CommandDefinition>
agents: Record<string, AgentConfig>
agents: Record<string, ClaudeCodeAgentConfig>
mcpServers: Record<string, McpServerConfig>
hooksConfigs: HooksConfig[]
plugins: LoadedPlugin[]
@@ -58,7 +58,7 @@ function convertSDKMessageToStoredMessage(msg: SDKMessage): StoredMessage | null
// TODO: These SDK-based functions are exported for future use when hooks migrate to async.
// Currently, callers still use the sync JSON-based functions which return null on beta.
// Migration requires making callers async, which is a larger refactoring.
// See: https://github.com/code-yeongyu/oh-my-opencode/pull/1837
// See: https://github.com/code-yeongyu/oh-my-openagent/pull/1837
/**
* Finds the nearest message with required fields using SDK (for beta/SQLite backend).
@@ -0,0 +1,155 @@
/// <reference types="bun-types" />
import { describe, it, expect } from "bun:test"
import { injectGitMasterConfig } from "./git-master-template-injection"
const SAMPLE_TEMPLATE = [
"# Git Master Agent",
"",
"## MODE DETECTION (FIRST STEP)",
"",
"Analyze the request.",
"",
"```bash",
"git status",
"git merge-base HEAD main 2>/dev/null || git merge-base HEAD master 2>/dev/null",
"MERGE_BASE=$(git merge-base HEAD main)",
"GIT_SEQUENCE_EDITOR=: git rebase -i --autosquash $MERGE_BASE",
"```",
"",
"```",
"</execution>",
].join("\n")
describe("#given git_env_prefix config", () => {
describe("#when default config (GIT_MASTER=1)", () => {
it("#then injects env prefix section before MODE DETECTION", () => {
const result = injectGitMasterConfig(SAMPLE_TEMPLATE, {
commit_footer: false,
include_co_authored_by: false,
git_env_prefix: "GIT_MASTER=1",
})
expect(result).toContain("## GIT COMMAND PREFIX (MANDATORY)")
expect(result).toContain("GIT_MASTER=1 git status")
expect(result).toContain("GIT_MASTER=1 git commit")
expect(result).toContain("GIT_MASTER=1 git push")
expect(result).toContain("EVERY git command MUST be prefixed with `GIT_MASTER=1`")
const prefixIndex = result.indexOf("## GIT COMMAND PREFIX")
const modeIndex = result.indexOf("## MODE DETECTION")
expect(prefixIndex).toBeLessThan(modeIndex)
})
})
describe("#when git_env_prefix is empty string", () => {
it("#then does NOT inject env prefix section", () => {
const result = injectGitMasterConfig(SAMPLE_TEMPLATE, {
commit_footer: false,
include_co_authored_by: false,
git_env_prefix: "",
})
expect(result).not.toContain("## GIT COMMAND PREFIX")
expect(result).not.toContain("GIT_MASTER=1")
expect(result).not.toContain("git_env_prefix")
})
})
describe("#when git_env_prefix is custom value", () => {
it("#then injects custom prefix in section", () => {
const result = injectGitMasterConfig(SAMPLE_TEMPLATE, {
commit_footer: false,
include_co_authored_by: false,
git_env_prefix: "MY_HOOK=active",
})
expect(result).toContain("MY_HOOK=active git status")
expect(result).toContain("MY_HOOK=active git commit")
expect(result).not.toContain("GIT_MASTER=1")
})
})
describe("#when git_env_prefix contains shell metacharacters", () => {
it("#then rejects the malicious value", () => {
expect(() =>
injectGitMasterConfig(SAMPLE_TEMPLATE, {
commit_footer: false,
include_co_authored_by: false,
git_env_prefix: "A=1; rm -rf /",
})
).toThrow('git_env_prefix must be empty or use shell-safe env assignments like "GIT_MASTER=1"')
})
})
describe("#when no config provided", () => {
it("#then uses default GIT_MASTER=1 prefix", () => {
const result = injectGitMasterConfig(SAMPLE_TEMPLATE)
expect(result).toContain("GIT_MASTER=1 git status")
expect(result).toContain("## GIT COMMAND PREFIX (MANDATORY)")
})
})
})
describe("#given git_env_prefix with commit footer", () => {
describe("#when both env prefix and footer are enabled", () => {
it("#then commit examples include the env prefix", () => {
const result = injectGitMasterConfig(SAMPLE_TEMPLATE, {
commit_footer: true,
include_co_authored_by: false,
git_env_prefix: "GIT_MASTER=1",
})
expect(result).toContain("GIT_MASTER=1 git commit")
expect(result).toContain("Ultraworked with [Sisyphus]")
})
})
describe("#when the template already contains bare git commands in bash blocks", () => {
it("#then prefixes every git invocation in the final output", () => {
const result = injectGitMasterConfig(SAMPLE_TEMPLATE, {
commit_footer: false,
include_co_authored_by: false,
git_env_prefix: "GIT_MASTER=1",
})
expect(result).toContain("GIT_MASTER=1 git status")
expect(result).toContain(
"GIT_MASTER=1 git merge-base HEAD main 2>/dev/null || GIT_MASTER=1 git merge-base HEAD master 2>/dev/null"
)
expect(result).toContain("MERGE_BASE=$(GIT_MASTER=1 git merge-base HEAD main)")
expect(result).toContain(
"GIT_SEQUENCE_EDITOR=: GIT_MASTER=1 git rebase -i --autosquash $MERGE_BASE"
)
})
})
describe("#when env prefix disabled but footer enabled", () => {
it("#then commit examples have no env prefix", () => {
const result = injectGitMasterConfig(SAMPLE_TEMPLATE, {
commit_footer: true,
include_co_authored_by: false,
git_env_prefix: "",
})
expect(result).not.toContain("GIT_MASTER=1 git commit")
expect(result).toContain("git commit -m")
expect(result).toContain("Ultraworked with [Sisyphus]")
})
})
describe("#when both env prefix and co-author are enabled", () => {
it("#then commit example includes prefix, footer, and co-author", () => {
const result = injectGitMasterConfig(SAMPLE_TEMPLATE, {
commit_footer: true,
include_co_authored_by: true,
git_env_prefix: "GIT_MASTER=1",
})
expect(result).toContain("GIT_MASTER=1 git commit")
expect(result).toContain("Ultraworked with [Sisyphus]")
expect(result).toContain("Co-authored-by: Sisyphus")
})
})
})
@@ -1,14 +1,88 @@
import type { GitMasterConfig } from "../../config/schema"
import { assertValidGitEnvPrefix, type GitMasterConfig } from "../../config/schema"
const BASH_CODE_BLOCK_PATTERN = /```bash\r?\n([\s\S]*?)```/g
const LEADING_GIT_COMMAND_PATTERN = /^([ \t]*(?:[A-Za-z_][A-Za-z0-9_]*=[^ \t]+\s+)*)git(?=[ \t]|$)/gm
const INLINE_GIT_COMMAND_PATTERN = /([;&|()][ \t]*)git(?=[ \t]|$)/g
export function injectGitMasterConfig(template: string, config?: GitMasterConfig): string {
const commitFooter = config?.commit_footer ?? true
const includeCoAuthoredBy = config?.include_co_authored_by ?? true
const gitEnvPrefix = assertValidGitEnvPrefix(config?.git_env_prefix ?? "GIT_MASTER=1")
if (!commitFooter && !includeCoAuthoredBy) {
return template
let result = gitEnvPrefix ? injectGitEnvPrefix(template, gitEnvPrefix) : template
if (commitFooter || includeCoAuthoredBy) {
const injection = buildCommitFooterInjection(commitFooter, includeCoAuthoredBy, gitEnvPrefix)
const insertionPoint = result.indexOf("```\n</execution>")
result =
insertionPoint !== -1
? result.slice(0, insertionPoint) +
"```\n\n" +
injection +
"\n</execution>" +
result.slice(insertionPoint + "```\n</execution>".length)
: result + "\n\n" + injection
}
return gitEnvPrefix ? prefixGitCommandsInBashCodeBlocks(result, gitEnvPrefix) : result
}
function injectGitEnvPrefix(template: string, prefix: string): string {
const envPrefixSection = [
"## GIT COMMAND PREFIX (MANDATORY)",
"",
`<git_env_prefix>`,
`**EVERY git command MUST be prefixed with \`${prefix}\`.**`,
"",
"This allows custom git hooks to detect when git-master skill is active.",
"",
"```bash",
`${prefix} git status`,
`${prefix} git add <files>`,
`${prefix} git commit -m "message"`,
`${prefix} git push`,
`${prefix} git rebase ...`,
`${prefix} git log ...`,
"```",
"",
"**NO EXCEPTIONS. Every `git` invocation must include this prefix.**",
`</git_env_prefix>`,
].join("\n")
const modeDetectionMarker = "## MODE DETECTION (FIRST STEP)"
const markerIndex = template.indexOf(modeDetectionMarker)
if (markerIndex !== -1) {
return (
template.slice(0, markerIndex) +
envPrefixSection +
"\n\n---\n\n" +
template.slice(markerIndex)
)
}
return envPrefixSection + "\n\n---\n\n" + template
}
function prefixGitCommandsInBashCodeBlocks(template: string, prefix: string): string {
return template.replace(BASH_CODE_BLOCK_PATTERN, (block, codeBlock: string) => {
return block.replace(codeBlock, prefixGitCommandsInCodeBlock(codeBlock, prefix))
})
}
function prefixGitCommandsInCodeBlock(codeBlock: string, prefix: string): string {
return codeBlock
.replace(LEADING_GIT_COMMAND_PATTERN, `$1${prefix} git`)
.replace(INLINE_GIT_COMMAND_PATTERN, `$1${prefix} git`)
}
function buildCommitFooterInjection(
commitFooter: boolean | string,
includeCoAuthoredBy: boolean,
gitEnvPrefix: string,
): string {
const sections: string[] = []
const cmdPrefix = gitEnvPrefix ? `${gitEnvPrefix} ` : ""
sections.push("### 5.5 Commit Footer & Co-Author")
sections.push("")
@@ -19,7 +93,7 @@ export function injectGitMasterConfig(template: string, config?: GitMasterConfig
const footerText =
typeof commitFooter === "string"
? commitFooter
: "Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)"
: "Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)"
sections.push("1. **Footer in commit body:**")
sections.push("```")
sections.push(footerText)
@@ -39,43 +113,30 @@ export function injectGitMasterConfig(template: string, config?: GitMasterConfig
const footerText =
typeof commitFooter === "string"
? commitFooter
: "Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)"
: "Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)"
sections.push("**Example (both enabled):**")
sections.push("```bash")
sections.push(
`git commit -m "{Commit Message}" -m "${footerText}" -m "Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>"`
`${cmdPrefix}git commit -m "{Commit Message}" -m "${footerText}" -m "Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>"`
)
sections.push("```")
} else if (commitFooter) {
const footerText =
typeof commitFooter === "string"
? commitFooter
: "Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)"
: "Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)"
sections.push("**Example:**")
sections.push("```bash")
sections.push(`git commit -m "{Commit Message}" -m "${footerText}"`)
sections.push(`${cmdPrefix}git commit -m "{Commit Message}" -m "${footerText}"`)
sections.push("```")
} else if (includeCoAuthoredBy) {
sections.push("**Example:**")
sections.push("```bash")
sections.push(
"git commit -m \"{Commit Message}\" -m \"Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>\""
`${cmdPrefix}git commit -m "{Commit Message}" -m "Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>"`
)
sections.push("```")
}
const injection = sections.join("\n")
const insertionPoint = template.indexOf("```\n</execution>")
if (insertionPoint !== -1) {
return (
template.slice(0, insertionPoint) +
"```\n\n" +
injection +
"\n</execution>" +
template.slice(insertionPoint + "```\n</execution>".length)
)
}
return template + "\n\n" + injection
return sections.join("\n")
}
@@ -228,6 +228,7 @@ describe("resolveMultipleSkillsAsync", () => {
gitMasterConfig: {
commit_footer: false,
include_co_authored_by: false,
git_env_prefix: "GIT_MASTER=1",
},
}
@@ -249,6 +250,7 @@ describe("resolveMultipleSkillsAsync", () => {
gitMasterConfig: {
commit_footer: true,
include_co_authored_by: true,
git_env_prefix: "GIT_MASTER=1",
},
}
@@ -269,6 +271,7 @@ describe("resolveMultipleSkillsAsync", () => {
gitMasterConfig: {
commit_footer: true,
include_co_authored_by: false,
git_env_prefix: "GIT_MASTER=1",
},
}
@@ -302,6 +305,7 @@ describe("resolveMultipleSkillsAsync", () => {
gitMasterConfig: {
commit_footer: false,
include_co_authored_by: true,
git_env_prefix: "GIT_MASTER=1",
},
}
@@ -322,6 +326,7 @@ describe("resolveMultipleSkillsAsync", () => {
gitMasterConfig: {
commit_footer: customFooter,
include_co_authored_by: false,
git_env_prefix: "GIT_MASTER=1",
},
}
@@ -341,6 +346,7 @@ describe("resolveMultipleSkillsAsync", () => {
gitMasterConfig: {
commit_footer: true,
include_co_authored_by: false,
git_env_prefix: "GIT_MASTER=1",
},
}
@@ -0,0 +1,125 @@
import type { TmuxPaneInfo } from "./types"
const MANDATORY_PANE_FIELD_COUNT = 8
type ParsedPaneState = {
windowWidth: number
windowHeight: number
panes: TmuxPaneInfo[]
}
type ParsedPaneLine = {
pane: TmuxPaneInfo
windowWidth: number
windowHeight: number
}
type MandatoryPaneFields = [
paneId: string,
widthString: string,
heightString: string,
leftString: string,
topString: string,
activeString: string,
windowWidthString: string,
windowHeightString: string,
]
export function parsePaneStateOutput(stdout: string): ParsedPaneState | null {
const lines = stdout
.split("\n")
.map((line) => line.replace(/\r$/, ""))
.filter((line) => line.length > 0)
if (lines.length === 0) return null
const parsedPaneLines = lines
.map(parsePaneLine)
.filter((parsedPaneLine): parsedPaneLine is ParsedPaneLine => parsedPaneLine !== null)
if (parsedPaneLines.length === 0) return null
const latestPaneLine = parsedPaneLines[parsedPaneLines.length - 1]
if (!latestPaneLine) return null
return {
windowWidth: latestPaneLine.windowWidth,
windowHeight: latestPaneLine.windowHeight,
panes: parsedPaneLines.map(({ pane }) => pane),
}
}
function parsePaneLine(line: string): ParsedPaneLine | null {
const fields = line.split("\t")
const mandatoryFields = getMandatoryPaneFields(fields)
if (!mandatoryFields) return null
const [paneId, widthString, heightString, leftString, topString, activeString, windowWidthString, windowHeightString] = mandatoryFields
const width = parseInteger(widthString)
const height = parseInteger(heightString)
const left = parseInteger(leftString)
const top = parseInteger(topString)
const windowWidth = parseInteger(windowWidthString)
const windowHeight = parseInteger(windowHeightString)
if (
width === null ||
height === null ||
left === null ||
top === null ||
windowWidth === null ||
windowHeight === null
) {
return null
}
return {
pane: {
paneId,
width,
height,
left,
top,
title: fields.slice(MANDATORY_PANE_FIELD_COUNT).join("\t"),
isActive: activeString === "1",
},
windowWidth,
windowHeight,
}
}
function getMandatoryPaneFields(fields: string[]): MandatoryPaneFields | null {
if (fields.length < MANDATORY_PANE_FIELD_COUNT) return null
const [paneId, widthString, heightString, leftString, topString, activeString, windowWidthString, windowHeightString] = fields
if (
paneId === undefined ||
widthString === undefined ||
heightString === undefined ||
leftString === undefined ||
topString === undefined ||
activeString === undefined ||
windowWidthString === undefined ||
windowHeightString === undefined
) {
return null
}
return [
paneId,
widthString,
heightString,
leftString,
topString,
activeString,
windowWidthString,
windowHeightString,
]
}
function parseInteger(value: string): number | null {
const parsedValue = Number.parseInt(value, 10)
return Number.isNaN(parsedValue) ? null : parsedValue
}
@@ -0,0 +1,75 @@
/// <reference types="bun-types/test" />
import { describe, expect, it } from "bun:test"
import { parsePaneStateOutput } from "./pane-state-parser"
describe("parsePaneStateOutput", () => {
it("accepts a single pane when tmux omits the empty trailing title field", () => {
// given
const stdout = "%0\t120\t40\t0\t0\t1\t120\t40\n"
// when
const result = parsePaneStateOutput(stdout)
// then
expect(result).not.toBe(null)
expect(result).toEqual({
windowWidth: 120,
windowHeight: 40,
panes: [
{
paneId: "%0",
width: 120,
height: 40,
left: 0,
top: 0,
title: "",
isActive: true,
},
],
})
})
it("handles CRLF line endings without dropping panes", () => {
// given
const stdout = "%0\t120\t40\t0\t0\t1\t120\t40\r\n%1\t60\t40\t60\t0\t0\t120\t40\tagent\r\n"
// when
const result = parsePaneStateOutput(stdout)
// then
expect(result).not.toBe(null)
expect(result?.panes).toEqual([
{
paneId: "%0",
width: 120,
height: 40,
left: 0,
top: 0,
title: "",
isActive: true,
},
{
paneId: "%1",
width: 60,
height: 40,
left: 60,
top: 0,
title: "agent",
isActive: false,
},
])
})
it("preserves tabs inside pane titles", () => {
// given
const stdout = "%0\t120\t40\t0\t0\t1\t120\t40\ttitle\twith\ttabs\n"
// when
const result = parsePaneStateOutput(stdout)
// then
expect(result).not.toBe(null)
expect(result?.panes[0]?.title).toBe("title\twith\ttabs")
})
})
@@ -1,5 +1,6 @@
import { spawn } from "bun"
import type { WindowState, TmuxPaneInfo } from "./types"
import { parsePaneStateOutput } from "./pane-state-parser"
import { getTmuxPath } from "../../tools/interactive-bash/tmux-path-resolver"
import { log } from "../../shared"
@@ -27,31 +28,12 @@ export async function queryWindowState(sourcePaneId: string): Promise<WindowStat
return null
}
const lines = stdout.trim().split("\n").filter(Boolean)
if (lines.length === 0) return null
const parsedPaneState = parsePaneStateOutput(stdout)
if (!parsedPaneState) return null
let windowWidth = 0
let windowHeight = 0
const panes: TmuxPaneInfo[] = []
for (const line of lines) {
const fields = line.split("\t")
if (fields.length < 9) continue
const [paneId, widthStr, heightStr, leftStr, topStr, activeStr, windowWidthStr, windowHeightStr] = fields
const title = fields.slice(8).join("\t")
const width = parseInt(widthStr, 10)
const height = parseInt(heightStr, 10)
const left = parseInt(leftStr, 10)
const top = parseInt(topStr, 10)
const isActive = activeStr === "1"
windowWidth = parseInt(windowWidthStr, 10)
windowHeight = parseInt(windowHeightStr, 10)
if (!isNaN(width) && !isNaN(left) && !isNaN(height) && !isNaN(top)) {
panes.push({ paneId, width, height, left, top, title, isActive })
}
}
const { panes } = parsedPaneState
const windowWidth = parsedPaneState.windowWidth
const windowHeight = parsedPaneState.windowHeight
panes.sort((a, b) => a.left - b.left || a.top - b.top)