feat(walkthrough): plan-then-explain generation with selectable diff sources

This commit is contained in:
Chris Scott committed 2026-10-08 15:53:49 -04:00
1 parent aeea96b466
commit 88b3543dc1
35 files changed
+2583 -609

No files matched your search

+3 -2
View File
@@ -244,7 +244,8 @@ const terminalService = new TerminalService(
new CredentialProvider(db),
() => getOpenCodeUpstreamBaseUrl(opencodeServerManager.getEffectiveServerHost()),
)
const projectConfigService = new ProjectConfigService(db, createGitService(gitAuthService), gitAuthService)
const gitService = createGitService(gitAuthService)
const projectConfigService = new ProjectConfigService(db, gitService, gitAuthService)
const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, db)
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager)
scheduleService.setWorktreeRemovedHandler(async (directory) => {
@@ -272,7 +273,7 @@ const sessionGoalService = new SessionGoalService(db, openCodeClient, sessionSet
sessionGoalService.loadOpenGoals()
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService)
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService, gitAuthService)
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService, gitAuthService, gitService)
sseAggregator.onEvent((directory, event) => {
sessionPermissionModeService.handleEvent(directory, event).catch((err) => {
+2 -1
View File
@@ -19,7 +19,8 @@ export function createChangeWalkthroughRoutes(service: ChangeWalkthroughService)
}
try {
const state = await service.getState(c.req.param('sessionId'), source)
const hunksFor = c.req.query('hunksFor')
const state = await service.getState(c.req.param('sessionId'), source, hunksFor)
return c.json(state)
} catch (error) {
return handleServiceError(c, error, 'Failed to read change walkthrough', ServiceError)
+19 -8
View File
@@ -12,7 +12,7 @@ import {
fileExists,
ensureDirectoryExists,
} from './file-operations'
import { ASSISTANT_NOTIFICATION_LIMITS, OpenCodeConfigSchema, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@opencode-manager/shared/schemas'
import { ASSISTANT_NOTIFICATION_LIMITS, AssistantSettingsPatchSchema, OpenCodeConfigSchema, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@opencode-manager/shared/schemas'
import { MANAGER_COLOR_THEME_ID, OPENCODE_THEMES } from '@opencode-manager/shared/themes'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME } from '@opencode-manager/shared/utils'
import { getAssistantModePath, getReposPath } from '@opencode-manager/shared/config/env'
@@ -581,6 +581,23 @@ Sending is rate limited to **10 notifications per minute**. Beyond that the tool
`
}
type AssistantSettingsKey = keyof typeof AssistantSettingsPatchSchema.shape
const ASSISTANT_SETTINGS_KEY_NOTES: Partial<Record<AssistantSettingsKey, string>> = {
tts: 'Non-secret TTS preferences (`enabled`, `provider`, `autoPlay`, `voice`, `model`, `speed`). TTS must already be configured in the UI (the endpoint returns 400 otherwise).',
stt: 'Non-secret STT preferences (`enabled`, `provider`, `model`, `language`). STT must already be configured in the UI (the endpoint returns 400 otherwise).',
}
function buildAllowedSettingsKeysList(): string {
const keys = Object.keys(AssistantSettingsPatchSchema.shape) as AssistantSettingsKey[]
return keys
.map((key) => {
const note = ASSISTANT_SETTINGS_KEY_NOTES[key]
return note === undefined ? `- \`${key}\`` : `- \`${key}\` — ${note}`
})
.join('\n')
}
export function buildSettingsSkill(): string {
return `---
name: manager-settings
@@ -660,13 +677,7 @@ Update a subset of safe user preferences.
**Allowed Keys:**
The following preference keys can be modified:
- \`theme\`, \`colorTheme\`, \`mode\`, \`defaultModel\`, \`defaultAgent\`
- \`autoScroll\`, \`expandDiffs\`, \`expandToolCalls\`, \`showReasoning\`
- \`simpleChatMode\`, \`leaderKey\`, \`directShortcuts\`
- \`keyboardShortcuts\`, \`customCommands\`, \`notifications\`
- \`repoOrder\`, \`repoSortMode\`
- \`tts\` — Non-secret TTS preferences (\`enabled\`, \`provider\`, \`autoPlay\`, \`voice\`, \`model\`, \`speed\`). TTS must already be configured in the UI (the endpoint returns 400 otherwise).
- \`stt\` — Non-secret STT preferences (\`enabled\`, \`provider\`, \`model\`, \`language\`). STT must already be configured in the UI (the endpoint returns 400 otherwise).
${buildAllowedSettingsKeysList()}
**DO NOT attempt to set:**
- \`gitCredentials\` - Git credentials must be managed via the full UI
File diff suppressed because it is too large. Load diff
+20
View File
@@ -738,6 +738,26 @@ export class GitService {
)
}
async fetchRemoteRef(
repo: { id?: number; repoUrl?: string; fullPath: string },
remote: string,
refspec: string,
database: Database,
timeoutMs?: number,
): Promise<void> {
await this.withRemoteAuth(
repo,
async (env) => {
await executeCommand(['git', '-C', repo.fullPath, 'fetch', '--no-tags', remote, refspec], {
env,
silent: true,
timeout: timeoutMs,
})
},
{ database, silent: true }
)
}
async pull(repoId: number, database: Database): Promise<string> {
const repo = getRepoById(database, repoId)
if (!repo) {
+12
View File
@@ -1019,6 +1019,18 @@ export async function resolveDefaultBranch(repoPath: string, env: Record<string,
.catch(() => 'main')
}
export async function resolveBaseRef(repoPath: string, base: string, env: Record<string, string>): Promise<string | null> {
for (const candidate of [`refs/remotes/origin/${base}`, `refs/heads/${base}`]) {
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', candidate], { env, silent: true })
return candidate.startsWith('refs/remotes/') ? `origin/${base}` : base
} catch {
continue
}
}
return null
}
export async function removeWorktree(
baseRepoPath: string,
worktreePath: string,
+2 -20
View File
@@ -8,7 +8,7 @@ import type { Repo } from '../types/repo'
import type { GitAuthService } from './git-auth'
import { isSSHUrl } from '@opencode-manager/shared/utils'
import { executeCommand } from '../utils/process'
import { resolveDefaultBranch, createWorktreeSafely, listGitWorktrees, removeWorktree } from './repo'
import { resolveDefaultBranch, resolveBaseRef, createWorktreeSafely, listGitWorktrees, removeWorktree } from './repo'
import { logger } from '../utils/logger'
import { canonicalPathSync, mkdirSyncSafe } from '../utils/fs-safe'
import {
@@ -95,7 +95,7 @@ export class ScheduleWorktreeManager {
await executeCommand(['git', '-C', repo.fullPath, 'fetch', '--prune', 'origin'], { env }).catch(() => {})
const base = job.branch?.trim() || (await resolveDefaultBranch(repo.fullPath, env))
const baseRef = await this.resolveBaseRef(repo.fullPath, base, env)
const baseRef = await resolveBaseRef(repo.fullPath, base, env)
if (!baseRef) {
throw new Error(`Base branch "${base}" was not found in this repository. Choose an existing branch in the schedule settings.`)
}
@@ -319,24 +319,6 @@ export class ScheduleWorktreeManager {
}
}
/**
* Resolves a user-supplied base branch name to a verified git ref, preferring
* the remote-tracking branch for freshness. Returns null when neither the
* remote nor local ref exists, allowing the caller to fail with a clear error
* instead of a cryptic git "not a valid object name" failure.
*/
private async resolveBaseRef(repoPath: string, base: string, env: Record<string, string>): Promise<string | null> {
for (const candidate of [`refs/remotes/origin/${base}`, `refs/heads/${base}`]) {
try {
await executeCommand(['git', '-C', repoPath, 'rev-parse', '--verify', candidate], { env, silent: true })
return candidate.startsWith('refs/remotes/') ? `origin/${base}` : base
} catch {
continue
}
}
return null
}
private async buildGitEnv(repo: Repo, sshSetup: boolean, silent: boolean): Promise<Record<string, string>> {
const baseEnv = this.gitAuthService.getGitEnvironment(silent)
const sshEnv = sshSetup ? this.gitAuthService.getSSHEnvironment() : {}
+11 -26
View File
@@ -1,5 +1,6 @@
import { z } from 'zod'
import { SessionGoalVerdictSchema, type SessionGoalVerdict } from '@opencode-manager/shared/schemas'
import { extractFirstJsonObject } from '../utils/json-extract'
import { parseFirstJsonObject } from '../utils/json-extract'
import { truncateSessionReply } from './session-reply'
export const GOAL_AUDIT_REASON_MAX_CHARS = 500
@@ -51,39 +52,23 @@ export function buildGoalContinuationPrompt({ objective, reason }: GoalContinuat
].join('\n')
}
const goalVerdictSchema = z.object({
verdict: SessionGoalVerdictSchema,
reason: z.string(),
})
export function parseGoalVerdict(text: string): GoalVerdict | null {
const block = extractFirstJsonObject(text)
if (!block) {
const parsed = parseFirstJsonObject(text, goalVerdictSchema)
if (!parsed) {
return null
}
let parsed: unknown
try {
parsed = JSON.parse(block)
} catch {
return null
}
if (typeof parsed !== 'object' || parsed === null) {
return null
}
const candidate = parsed as { verdict?: unknown; reason?: unknown }
const verdict = SessionGoalVerdictSchema.safeParse(candidate.verdict)
if (!verdict.success) {
return null
}
if (typeof candidate.reason !== 'string') {
return null
}
const reason = candidate.reason.trim()
const reason = parsed.reason.trim()
if (!reason) {
return null
}
return { verdict: verdict.data, reason: reason.slice(0, GOAL_AUDIT_REASON_MAX_CHARS) }
return { verdict: parsed.verdict, reason: reason.slice(0, GOAL_AUDIT_REASON_MAX_CHARS) }
}
function truncateReply(reply: string | null): string {
+173 -71
View File
@@ -1,3 +1,6 @@
import { copyFileSync, existsSync, mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import type { FileDiffInfo, SessionInfo } from '@opencode-manager/shared/opencode'
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
import { splitUnifiedDiffByFile } from '@opencode-manager/shared/utils'
@@ -5,6 +8,7 @@ import { getErrorMessage } from '../utils/error-utils'
import { executeCommand } from '../utils/process'
import { ChangeWalkthroughError } from './change-walkthrough-error'
import type { OpenCodeClient } from './opencode/client'
import { resolveBaseRef, resolveDefaultBranch } from './repo'
import { readSessionChanges } from './session-changes'
export interface ReadWalkthroughChangesOptions {
@@ -16,14 +20,71 @@ export interface ReadWalkthroughChangesOptions {
type GitWalkthroughSource = Exclude<WalkthroughSource, { kind: 'session' }>
interface CommandResult {
exitCode: number
stdout: string
stderr: string
const GIT_DIFF_TIMEOUT_MS = 30_000
const GIT_FETCH_TIMEOUT_MS = 60_000
const GIT_DIFF_MAX_OUTPUT_CHARS = 5_000_000
const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
const DIFF_ARGS = ['--no-color', '--src-prefix=a/', '--dst-prefix=b/', '--no-ext-diff', '--no-textconv', '-U3']
const PULL_REQUEST_REMOTE_PREFERENCE = ['upstream', 'origin']
type PullRequestSource = Extract<GitWalkthroughSource, { kind: 'pullRequest' }>
export interface PullRequestFetchPlan {
remote: string
refspec: string
ref: string
}
function commandResult(result: string | CommandResult): CommandResult {
return typeof result === 'string' ? { exitCode: 0, stdout: result, stderr: '' } : result
export type PullRequestFetchRunner = (
remote: string,
refspec: string,
timeoutMs: number,
) => Promise<void>
export function walkthroughPullRequestRef(number: number): string {
return `refs/ocm-walkthrough/pr/${number}`
}
export async function planPullRequestFetch(
directory: string,
source: PullRequestSource,
gitEnv?: Record<string, string>,
): Promise<PullRequestFetchPlan> {
const remotes = (await tryGit(directory, ['remote'], gitEnv))?.split('\n').map((line) => line.trim()) ?? []
const remote = PULL_REQUEST_REMOTE_PREFERENCE.find((candidate) => remotes.includes(candidate)) ?? 'origin'
const ref = walkthroughPullRequestRef(source.number)
return { remote, refspec: `+refs/pull/${source.number}/head:${ref}`, ref }
}
export async function fetchPullRequestRef(
directory: string,
source: PullRequestSource,
gitEnv: Record<string, string> | undefined,
runFetch: PullRequestFetchRunner,
): Promise<string> {
const plan = await planPullRequestFetch(directory, source, gitEnv)
await mapGitError(
() => runFetch(plan.remote, plan.refspec, GIT_FETCH_TIMEOUT_MS),
'Failed to fetch the pull request',
)
return plan.ref
}
export async function deletePullRequestRef(
directory: string,
ref: string,
gitEnv?: Record<string, string>,
): Promise<void> {
try {
await executeCommand(['git', '-C', directory, 'update-ref', '-d', ref], {
env: gitEnv,
silent: true,
ignoreExitCode: true,
timeout: GIT_DIFF_TIMEOUT_MS,
})
} catch {
return
}
}
export async function readWalkthroughChanges({
@@ -44,39 +105,41 @@ async function readGitChanges(
gitEnv?: Record<string, string>,
): Promise<FileDiffInfo[]> {
await assertGitRepository(directory, gitEnv)
const repoRoot = await resolveRepoRoot(directory, gitEnv)
switch (source.kind) {
case 'uncommitted':
return collectChanges(directory, await uncommittedRevision(directory, gitEnv), true, gitEnv)
return collectChanges(repoRoot, await uncommittedRevision(repoRoot, gitEnv), true, gitEnv)
case 'staged':
return collectChanges(directory, ['--cached'], false, gitEnv)
return collectChanges(repoRoot, ['--cached'], false, gitEnv)
case 'unstaged':
return collectChanges(directory, await unstagedRevision(directory, gitEnv), true, gitEnv)
return collectChanges(repoRoot, [], true, gitEnv)
case 'branch': {
const base = await resolveBaseBranch(directory, source.base, gitEnv)
return collectChanges(directory, [`${base}...HEAD`], false, gitEnv)
const base = await resolveBase(repoRoot, source.base, gitEnv)
return collectChanges(repoRoot, [`${base}...HEAD`], false, gitEnv)
}
case 'pullRequest': {
const base = await resolveBaseBranch(directory, source.base, gitEnv)
const ref = `refs/ocm-walkthrough/pr/${source.number}`
try {
await runGit(directory, ['fetch', '--no-tags', 'origin', `+refs/pull/${source.number}/head:${ref}`], gitEnv)
} catch (error) {
throw new ChangeWalkthroughError(getErrorMessage(error) || 'Failed to fetch the pull request', 502, {
code: 'WALKTHROUGH_SOURCE_UNAVAILABLE',
})
}
return collectChanges(directory, [`${base}...${ref}`], false, gitEnv)
const base = await resolveBase(repoRoot, source.base, gitEnv)
const ref = walkthroughPullRequestRef(source.number)
return collectChanges(repoRoot, [`${base}...${ref}`], false, gitEnv)
}
}
}
async function uncommittedRevision(directory: string, gitEnv?: Record<string, string>): Promise<string[]> {
return (await headExists(directory, gitEnv)) ? ['HEAD'] : ['--cached']
async function resolveBase(directory: string, base: string | undefined, gitEnv?: Record<string, string>): Promise<string> {
const resolved = await resolveBaseRef(
directory,
base ?? await resolveDefaultBranch(directory, gitEnv ?? {}),
gitEnv ?? {},
)
if (!resolved) {
throw new ChangeWalkthroughError('No base branch found', 409, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
}
return resolved
}
async function unstagedRevision(directory: string, gitEnv?: Record<string, string>): Promise<string[]> {
return (await headExists(directory, gitEnv)) ? [] : ['--cached']
async function uncommittedRevision(directory: string, gitEnv?: Record<string, string>): Promise<string[]> {
return (await headExists(directory, gitEnv)) ? ['HEAD'] : [EMPTY_TREE]
}
async function collectChanges(
@@ -85,26 +148,60 @@ async function collectChanges(
includeUntracked: boolean,
gitEnv?: Record<string, string>,
): Promise<FileDiffInfo[]> {
const tracked = await runGit(directory, ['diff', '--no-color', '--no-ext-diff', '-U3', ...revisionArgs], gitEnv)
const tracked = await runDiff(directory, revisionArgs, gitEnv)
if (!includeUntracked) {
return splitUnifiedDiffByFile(tracked)
}
const untracked = await readUntrackedDiffs(directory, gitEnv)
return splitUnifiedDiffByFile([tracked, ...untracked].join(''))
const untracked = await readUntrackedDiff(directory, gitEnv)
return splitUnifiedDiffByFile(`${tracked}${untracked}`)
}
async function readUntrackedDiffs(directory: string, gitEnv?: Record<string, string>): Promise<string[]> {
const output = await runGit(directory, ['ls-files', '--others', '--exclude-standard', '-z'], gitEnv)
const paths = output.split('\0').filter((entry) => entry.length > 0).sort()
const diffs: string[] = []
for (const filePath of paths) {
const result = commandResult(await executeCommand(
['git', '-C', directory, 'diff', '--no-color', '--no-index', '--', '/dev/null', filePath],
{ env: gitEnv, silent: true, ignoreExitCode: true },
))
diffs.push(result.stdout)
async function readUntrackedDiff(directory: string, gitEnv?: Record<string, string>): Promise<string> {
const untracked = await runGit(directory, ['ls-files', '--others', '--exclude-standard', '-z'], gitEnv)
if (untracked.length === 0) {
return ''
}
return diffs
const tempDir = mkdtempSync(path.join(tmpdir(), 'ocm-walkthrough-index-'))
const tempIndex = path.join(tempDir, 'index')
const env = { ...gitEnv, GIT_INDEX_FILE: tempIndex }
try {
const indexPath = (await tryGit(directory, ['rev-parse', '--git-path', 'index'], gitEnv))?.trim()
if (indexPath) {
const realIndex = path.resolve(directory, indexPath)
if (existsSync(realIndex)) {
copyFileSync(realIndex, tempIndex)
}
}
await runGit(directory, ['add', '-N', '-A'], env)
return await runDiff(directory, ['--diff-filter=A', '--no-renames'], env)
} finally {
rmSync(tempDir, { recursive: true, force: true })
}
}
async function runDiff(directory: string, revisionArgs: string[], gitEnv?: Record<string, string>): Promise<string> {
const result = await mapGitError(
() => executeCommand(
['git', '-C', directory, 'diff', ...DIFF_ARGS, ...revisionArgs],
{
env: gitEnv,
silent: true,
ignoreExitCode: true,
timeout: GIT_DIFF_TIMEOUT_MS,
maxOutputChars: GIT_DIFF_MAX_OUTPUT_CHARS,
},
),
'git diff failed',
)
if (result.truncated) {
throw new ChangeWalkthroughError('The diff is too large to display', 413, { code: 'WALKTHROUGH_DIFF_TOO_LARGE' })
}
if (result.exitCode !== 0) {
throw new ChangeWalkthroughError(result.stderr.trim() || 'git diff failed', 502, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
}
return result.stdout
}
async function assertGitRepository(directory: string, gitEnv?: Record<string, string>): Promise<void> {
@@ -119,47 +216,52 @@ async function assertGitRepository(directory: string, gitEnv?: Record<string, st
}
}
async function headExists(directory: string, gitEnv?: Record<string, string>): Promise<boolean> {
const result = commandResult(await executeCommand(
['git', '-C', directory, 'rev-parse', '--verify', '--quiet', 'HEAD'],
{ env: gitEnv, silent: true, ignoreExitCode: true },
))
return result.exitCode === 0
async function resolveRepoRoot(directory: string, gitEnv?: Record<string, string>): Promise<string> {
const root = await tryGit(directory, ['rev-parse', '--show-toplevel'], gitEnv)
return root ? root.trim() : directory
}
async function resolveBaseBranch(
directory: string,
base: string | undefined,
gitEnv?: Record<string, string>,
): Promise<string> {
if (base) {
return base
}
const originHead = await tryGit(directory, ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], gitEnv)
if (originHead) {
return originHead.trim()
}
for (const candidate of ['main', 'master']) {
const resolved = await tryGit(directory, ['rev-parse', '--verify', '--quiet', candidate], gitEnv)
if (resolved) {
return candidate
}
}
throw new ChangeWalkthroughError('No base branch found', 409, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
async function headExists(directory: string, gitEnv?: Record<string, string>): Promise<boolean> {
return (await tryGit(directory, ['rev-parse', '--verify', '--quiet', 'HEAD'], gitEnv)) !== null
}
async function tryGit(directory: string, args: string[], gitEnv?: Record<string, string>): Promise<string | null> {
const result = commandResult(await executeCommand(['git', '-C', directory, ...args], {
const result = await executeCommand(['git', '-C', directory, ...args], {
env: gitEnv,
silent: true,
ignoreExitCode: true,
}))
timeout: GIT_DIFF_TIMEOUT_MS,
maxOutputChars: GIT_DIFF_MAX_OUTPUT_CHARS,
})
return result.exitCode === 0 ? result.stdout : null
}
async function runGit(directory: string, args: string[], gitEnv?: Record<string, string>): Promise<string> {
return executeCommand(['git', '-C', directory, ...args], { env: gitEnv, silent: true })
async function runGit(
directory: string,
args: string[],
gitEnv?: Record<string, string>,
timeout = GIT_DIFF_TIMEOUT_MS,
fallback = 'Git command failed',
): Promise<string> {
return mapGitError(
() => executeCommand(['git', '-C', directory, ...args], {
env: gitEnv,
silent: true,
timeout,
maxOutputChars: GIT_DIFF_MAX_OUTPUT_CHARS,
}),
fallback,
)
}
async function mapGitError<T>(run: () => Promise<T>, fallback: string): Promise<T> {
try {
return await run()
} catch (error) {
const message = getErrorMessage(error)
if (message.includes('timed out')) {
throw new ChangeWalkthroughError('git timed out', 504, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
}
throw new ChangeWalkthroughError(message || fallback, 502, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
}
}
+44
View File
@@ -21,3 +21,47 @@ export async function mapWithConcurrency<T, R>(
await Promise.all(Array.from({ length: workerCount }, () => worker()))
return results
}
export interface Limiter {
readonly activeCount: number
run<T>(task: () => Promise<T>): Promise<T>
}
export function createLimiter(limit: number): Limiter {
const max = Math.max(1, limit)
let active = 0
const waiters: Array<() => void> = []
const acquire = (): Promise<void> => {
if (active < max) {
active += 1
return Promise.resolve()
}
return new Promise<void>((resolve) => {
waiters.push(resolve)
})
}
const release = (): void => {
const next = waiters.shift()
if (next) {
next()
return
}
active -= 1
}
return {
get activeCount(): number {
return active
},
async run<T>(task: () => Promise<T>): Promise<T> {
await acquire()
try {
return await task()
} finally {
release()
}
},
}
}
+23
View File
@@ -1,3 +1,5 @@
import type { ZodType } from 'zod'
export function extractFirstJsonObject(text: string): string | null {
const start = text.indexOf('{')
if (start === -1) {
@@ -39,3 +41,24 @@ export function extractFirstJsonObject(text: string): string | null {
return null
}
export function parseFirstJsonObject<T>(text: string, schema: ZodType<T>): T | null {
const extracted = extractFirstJsonObject(text)
if (!extracted) {
return null
}
let raw: unknown
try {
raw = JSON.parse(extracted)
} catch {
return null
}
const parsed = schema.safeParse(raw)
if (!parsed.success) {
return null
}
return parsed.data
}
+15 -13
View File
@@ -10,23 +10,24 @@ interface ExecuteCommandOptions {
maxOutputChars?: number
}
export async function executeCommand(
export interface ExecuteCommandResult {
exitCode: number
stdout: string
stderr: string
truncated?: boolean
}
type ExecuteCommandReturn<O> = O extends { ignoreExitCode: true } ? ExecuteCommandResult : string
export async function executeCommand<O extends ExecuteCommandOptions = ExecuteCommandOptions>(
args: string[],
cwdOrOptions?: string | ExecuteCommandOptions
): Promise<string>
export async function executeCommand(
args: string[],
cwdOrOptions: string | (ExecuteCommandOptions & { ignoreExitCode: true })
): Promise<string | { exitCode: number; stdout: string; stderr: string }>
export async function executeCommand(
args: string[],
cwdOrOptions?: string | ExecuteCommandOptions
): Promise<string | { exitCode: number; stdout: string; stderr: string }> {
cwdOrOptions?: string | O
): Promise<ExecuteCommandReturn<O>> {
const options: ExecuteCommandOptions = typeof cwdOrOptions === 'string'
? { cwd: cwdOrOptions }
: cwdOrOptions || {}
return new Promise((resolve, reject) => {
return new Promise<string | ExecuteCommandResult>((resolve, reject) => {
const [command, ...cmdArgs] = args
const effectiveEnv = { ...process.env, ...options.env }
@@ -103,6 +104,7 @@ export async function executeCommand(
exitCode,
stdout,
stderr: terminatedBySignal ? `${stderr}Command terminated by signal ${signal}` : stderr,
truncated: true,
}
: stdout)
} else if (options.ignoreExitCode) {
@@ -121,5 +123,5 @@ export async function executeCommand(
reject(error)
}
})
})
}) as Promise<ExecuteCommandReturn<O>>
}
@@ -102,6 +102,36 @@ describe('change walkthroughs', () => {
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)).toEqual(stored)
})
it('reads a walkthrough whose mechanical hunks predate hunk counts', () => {
const legacy = walkthrough({
stops: [
{
id: 's_mech',
title: 'Mechanical changes',
explanation: 'Lock files',
hunkIds: ['h_lock'],
status: 'ready',
explanationKey: null,
},
],
hunks: [
{
id: 'h_lock',
file: 'pnpm-lock.yaml',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-old-lock\n+new-lock',
truncated: false,
},
],
})
saveChangeWalkthrough(db, legacy)
const stored = getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)
expect(stored).toEqual(legacy)
expect(stored!.hunks[0]!.additions).toBeUndefined()
})
it('stores walkthroughs for two sources of one session side by side', () => {
saveChangeWalkthrough(db, walkthrough({ diffHash: 'hash-session' }))
saveChangeWalkthrough(db, walkthrough({ source: { kind: 'staged' }, diffHash: 'hash-staged', summary: 'Staged' }))
@@ -5,12 +5,16 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import type { FileDiffInfo, SessionInfo } from '@opencode-manager/shared/opencode'
import { walkthroughHunksIdentity } from '@opencode-manager/shared/schemas'
import type { ChangeWalkthrough } from '@opencode-manager/shared/schemas'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import { ChangeWalkthroughService, computeHunkId } from '../../src/services/change-walkthroughs'
import { saveChangeWalkthrough } from '../../src/db/change-walkthroughs'
import { ChangeWalkthroughService, computeChangesHash, computeHunkId } from '../../src/services/change-walkthroughs'
import { SettingsService } from '../../src/services/settings'
import { createChangeWalkthroughRoutes } from '../../src/routes/change-walkthroughs'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import type { GitService } from '../../src/services/git/GitService'
import { stubLoadedModelCatalog } from '../helpers/stub-opencode-client'
import { createCommittedRepo, createGitAuthService, git, uniqueName } from '../helpers/git-fixtures'
@@ -120,7 +124,13 @@ describe('change walkthrough routes', () => {
migrate(db, allMigrations)
sessions = { [SESSION_ID]: { changes: CHANGES } }
fake = createFakeClient(sessions)
const service = new ChangeWalkthroughService(db, fake.client, new SettingsService(db), createGitAuthService())
const service = new ChangeWalkthroughService(
db,
fake.client,
new SettingsService(db),
createGitAuthService(),
{ fetchRemoteRef: vi.fn(async () => {}) } as unknown as GitService,
)
app = new Hono()
app.route('/change-walkthroughs', createChangeWalkthroughRoutes(service))
})
@@ -175,6 +185,47 @@ describe('change walkthrough routes', () => {
await expect(res.json()).resolves.toMatchObject({ error: 'Invalid walkthrough source' })
})
it('GET omits hunks when hunksFor matches the stored identity and returns them otherwise', async () => {
const stored: ChangeWalkthrough = {
sessionId: SESSION_ID,
source: { kind: 'session' },
diffHash: computeChangesHash(CHANGES),
model: null,
summary: 'A summary',
stops: [
{ id: 's_1', title: 'First', explanation: 'Why', hunkIds: [HUNK_ID], status: 'ready', explanationKey: null },
],
hunks: [
{
id: HUNK_ID,
file: CHANGES[0]!.file,
status: CHANGES[0]!.status,
header: '@@ -1,2 +1,2 @@',
text: CHANGES[0]!.patch,
truncated: false,
},
],
omittedFiles: [],
createdAt: 42,
}
saveChangeWalkthrough(db, stored)
const identity = walkthroughHunksIdentity(stored)
const fullRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
const compactRes = await app.request(
`/change-walkthroughs/${SESSION_ID}?hunksFor=${encodeURIComponent(identity)}`,
)
const mismatchRes = await app.request(`/change-walkthroughs/${SESSION_ID}?hunksFor=other`)
const full = (await fullRes.json()) as { walkthrough: { hunks?: unknown[] } }
const compact = (await compactRes.json()) as { walkthrough: { hunks?: unknown[] } }
const mismatch = (await mismatchRes.json()) as { walkthrough: { hunks?: unknown[] } }
expect(full.walkthrough.hunks).toHaveLength(1)
expect(compact.walkthrough.hunks).toBeUndefined()
expect(mismatch.walkthrough.hunks).toHaveLength(1)
})
it('POST stores the walkthrough under the requested source', async () => {
const repo = createRepoWithStagedChange()
sessions[SESSION_ID]!.info = { id: SESSION_ID, title: 'Title', location: { directory: repo } } as SessionInfo
@@ -2,6 +2,7 @@ import { describe, expect, it, beforeEach, afterEach } from 'bun:test'
import path from 'path'
import { access, readFile, writeFile } from 'fs/promises'
import { Hono } from 'hono'
import { AssistantSettingsPatchSchema } from '@opencode-manager/shared/schemas'
import { ensureAssistantMode, getAssistantModeStatus, buildSchedulesSkill, buildReposSkill, buildSettingsSkill, buildSessionsSkill, buildAssistantDefaultAgentMd, buildAssistantOpenCodeConfig, buildAssistantRepo, installAssistantWorkspace } from '../../src/services/assistant-mode'
import { createTempAssistantWorkspace, createTestDb, mockRepo } from '../helpers/assistant-workspace'
import { ScheduleService } from '../../src/services/schedules'
@@ -162,6 +163,15 @@ describe('buildSettingsSkill', () => {
expect(skill).toContain('stt.endpoint')
expect(skill).toContain('DO NOT attempt to set')
})
it('lists every AssistantSettingsPatchSchema key in the allowed keys section', () => {
const skill = buildSettingsSkill()
const allowedSection = skill.split('**Allowed Keys:**')[1]?.split('**DO NOT attempt to set:**')[0]
if (allowedSection === undefined) throw new Error('Allowed Keys section is missing')
for (const key of Object.keys(AssistantSettingsPatchSchema.shape)) {
expect(allowedSection).toContain(`\`${key}\``)
}
})
})
describe('buildAssistantDefaultAgentMd', () => {
+685 -14
View File
@@ -5,6 +5,7 @@ import path from 'node:path'
import { Database } from 'bun:sqlite'
import type { FileDiffInfo, ModelRef, SessionInfo, SessionMessageInfo } from '@opencode-manager/shared/opencode'
import {
MECHANICAL_TEXT_BUDGET,
WALKTHROUGH_DIFF_MAX_CHARS,
WALKTHROUGH_HUNK_MAX_CHARS,
WALKTHROUGH_MAX_STOPS,
@@ -13,16 +14,16 @@ import {
WALKTHROUGH_TEXT_MAX_CHARS,
type WalkthroughHunk,
} from '@opencode-manager/shared/schemas'
import { getChangeWalkthrough } from '../../src/db/change-walkthroughs'
import { getChangeWalkthrough, saveChangeWalkthrough, deleteChangeWalkthroughs } from '../../src/db/change-walkthroughs'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import { SettingsService } from '../../src/services/settings'
import type { GitService } from '../../src/services/git/GitService'
import type { SSEEvent } from '../../src/services/sse-aggregator'
import { stubLoadedModelCatalog } from '../helpers/stub-opencode-client'
import { createCommittedRepo, createGitAuthService, git, uniqueName } from '../helpers/git-fixtures'
import { createCommittedRepo, createGitAuthService, createOrigin, cloneOrigin, git, uniqueName } from '../helpers/git-fixtures'
import {
ChangeWalkthroughError,
ChangeWalkthroughService,
buildWalkthroughInput,
buildWalkthroughOutline,
@@ -37,6 +38,7 @@ import {
parseWalkthroughPlan,
parseWalkthroughResponse,
} from '../../src/services/change-walkthroughs'
import { ChangeWalkthroughError } from '../../src/services/change-walkthrough-error'
const SESSION_ID = 'ses_walkthrough'
@@ -231,6 +233,28 @@ function createChangedRepo(): string {
return repo
}
function createPullRequestRepo(): string {
const origin = path.join(walkthroughRepoRoot, uniqueName('pr-origin'))
const work = path.join(walkthroughRepoRoot, uniqueName('pr-work'))
const clone = path.join(walkthroughRepoRoot, uniqueName('pr-clone'))
createOrigin(origin, work)
cloneOrigin(origin, clone)
writeFileSync(path.join(clone, 'pr.txt'), 'pr\n')
git(['add', 'pr.txt'], clone)
git(['commit', '-m', 'pr'], clone)
git(['push', 'origin', 'HEAD:refs/pull/1/head'], clone)
return clone
}
function refExists(repo: string, ref: string): boolean {
try {
git(['rev-parse', '--verify', ref], repo)
return true
} catch {
return false
}
}
function sessionAt(directory: string): SessionInfo {
return { id: SESSION_ID, title: 'Title', location: { directory } } as SessionInfo
}
@@ -371,6 +395,44 @@ describe('buildWalkthroughInput', () => {
expect(omittedFiles).toEqual([])
})
it('keeps mechanical hunk text within the budget and summarizes every file with counts', () => {
const oversizedPatch = Array.from({ length: 40 }, (_, index) => bigHunk(index)).join('\n')
const { mechanicalHunks, omittedFiles } = buildWalkthroughInput([
{ file: 'pnpm-lock.yaml', patch: oversizedPatch, additions: 1200, deletions: 800, status: 'modified' },
{ file: 'src/__snapshots__/a.ts.snap', patch: hunkPatch(1), additions: 2, deletions: 3, status: 'modified' },
])
expect(mechanicalHunks.map((hunk) => hunk.file)).toEqual([
'pnpm-lock.yaml',
'src/__snapshots__/a.ts.snap',
])
expect(mechanicalHunks.reduce((total, hunk) => total + hunk.text.length, 0)).toBeLessThanOrEqual(
MECHANICAL_TEXT_BUDGET,
)
expect(mechanicalHunks[0]).toMatchObject({ text: '', truncated: true, additions: 1200, deletions: 800 })
expect(mechanicalHunks[1]).toMatchObject({ additions: 2, deletions: 3 })
expect(mechanicalHunks[1]!.text).toContain('@@')
expect(omittedFiles).toEqual([])
})
it('stores mechanical hunk text and counts while within the budget', () => {
const { mechanicalHunks } = buildWalkthroughInput([
{
file: 'pnpm-lock.yaml',
patch: `${hunkPatch(1)}\n${hunkPatch(2)}`,
additions: 2,
deletions: 2,
status: 'modified',
},
])
expect(mechanicalHunks).toHaveLength(1)
expect(mechanicalHunks[0]!.text).toContain('@@ -1,2 +1,2 @@')
expect(mechanicalHunks[0]!.text).toContain('@@ -2,2 +2,2 @@')
expect(mechanicalHunks[0]!.additions).toBe(2)
expect(mechanicalHunks[0]!.deletions).toBe(2)
})
it('omits a binary mechanical file as binary', () => {
const { mechanicalHunks, omittedFiles } = buildWalkthroughInput([
change('pnpm-lock.yaml', 'diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml\nBinary files differ'),
@@ -379,6 +441,25 @@ describe('buildWalkthroughInput', () => {
expect(mechanicalHunks).toEqual([])
expect(omittedFiles).toEqual([{ file: 'pnpm-lock.yaml', reason: 'binary' }])
})
it('labels a pure rename as renamed', () => {
const { omittedFiles } = buildWalkthroughInput([
change(
'src/new.ts',
'diff --git a/src/old.ts b/src/new.ts\nsimilarity index 100%\nrename from src/old.ts\nrename to src/new.ts',
),
])
expect(omittedFiles).toEqual([{ file: 'src/new.ts', reason: 'renamed' }])
})
it('labels a mode-only change as modeChange', () => {
const { omittedFiles } = buildWalkthroughInput([
change('script.sh', 'diff --git a/script.sh b/script.sh\nold mode 100644\nnew mode 100755'),
])
expect(omittedFiles).toEqual([{ file: 'script.sh', reason: 'modeChange' }])
})
})
describe('buildWalkthroughOutline', () => {
@@ -401,7 +482,7 @@ describe('buildWalkthroughOutline', () => {
it('omits trailing files as budget and never half-includes a file', () => {
const input = buildWalkthroughInput(
Array.from({ length: 120 }, (_, index) => change(`src/f${index}.ts`, longPatch(3, index * 3))),
Array.from({ length: 400 }, (_, index) => change(`src/f${index}.ts`, longPatch(3, index * 3))),
)
const { omittedFiles, outline } = buildWalkthroughOutline(input, 'My session')
@@ -453,7 +534,7 @@ describe('buildWalkthroughOutline', () => {
})
it('reserves the title in the budget so a long title admits less content', () => {
const input = buildWalkthroughInput(Array.from({ length: 500 }, (_, index) => smallChange(index)))
const input = buildWalkthroughInput(Array.from({ length: 800 }, (_, index) => smallChange(index)))
const longTitle = 'T'.repeat(20_000)
const withLongTitle = buildWalkthroughOutline(input, longTitle)
@@ -472,7 +553,7 @@ describe('buildWalkthroughOutline', () => {
it('bounds the included hunks and omits the remaining files as budget', () => {
const input = buildWalkthroughInput(
Array.from({ length: 40 }, (_, index) => change(`src/f${index}.ts`, longPatch(6, index * 6))),
Array.from({ length: 200 }, (_, index) => change(`src/f${index}.ts`, longPatch(6, index * 6))),
)
const { hunks, omittedFiles, outline } = buildWalkthroughOutline(input, 'My session')
@@ -485,7 +566,7 @@ describe('buildWalkthroughOutline', () => {
it('never half-includes a file', () => {
const input = buildWalkthroughInput([
change('src/small.ts', hunkPatch(1)),
change('src/huge.ts', longPatch(100)),
change('src/huge.ts', longPatch(2000)),
])
const { outline } = buildWalkthroughOutline(input, 'My session')
@@ -512,6 +593,31 @@ describe('buildWalkthroughOutline', () => {
buildWalkthroughPlanPrompt({ title: 'My session', outline, previousStops: [] }).length,
).toBeLessThanOrEqual(WALKTHROUGH_DIFF_MAX_CHARS)
})
it('retries at a shallower preview depth so every file fits when the single call does not', () => {
const input = buildWalkthroughInput(
Array.from({ length: 70 }, (_, index) => change(`src/f${index}.ts`, longPatch(1, index))),
)
expect(fitsSingleCall(input, 'My session')).toBe(false)
const { hunks, omittedFiles } = buildWalkthroughOutline(input, 'My session')
expect(omittedFiles).toEqual([])
expect(hunks).toHaveLength(70)
})
it('reserves room for the previous-stops hint', () => {
const input = buildWalkthroughInput(
Array.from({ length: 1000 }, (_, index) => smallChange(index)),
)
const previousStops = [{ title: 'A'.repeat(5000), hunkIds: [input.hunks[0]!.id] }]
const { outline } = buildWalkthroughOutline(input, 'My session', previousStops)
const prompt = buildWalkthroughPlanPrompt({ title: 'My session', outline, previousStops })
expect(prompt).toContain('Previous stops')
expect(prompt.length).toBeLessThanOrEqual(WALKTHROUGH_DIFF_MAX_CHARS)
})
})
describe('formatHunkOutline', () => {
@@ -522,7 +628,7 @@ describe('formatHunkOutline', () => {
expect(first).toBe(`### ${hunk.id} src/a.ts (modified) @@ -1,2 +1,2 @@ +1 -1`)
})
it('lists at most the preview line count of changed lines, skipping file headers', () => {
it('previews changed lines and counts content lines that start with -- or ++', () => {
const hunk = hunkFixture(
'src/a.ts',
'@@ -1,4 +1,4 @@\n--- a/x\n+++ b/x\n-const a = 1;\n+const a = 2;\n-const b = 1;\n+const b = 2;',
@@ -530,15 +636,16 @@ describe('formatHunkOutline', () => {
const single = formatHunkOutline(hunk, 1).split('\n')
expect(single).toHaveLength(2)
expect(single[1]!.startsWith('---')).toBe(false)
expect(single[1]!.startsWith('+++')).toBe(false)
expect(single[1]).toBe('-const a = 1;')
expect(single[1]).toBe('--- a/x')
const full = formatHunkOutline(hunk).split('\n')
expect(full).toContain('--- a/x')
expect(full).toContain('+++ b/x')
expect(full).toContain('-const a = 1;')
expect(full).toContain('+const a = 2;')
expect(full).toContain('-const b = 1;')
expect(full).toContain('+const b = 2;')
expect(full[0]).toContain('+3 -3')
})
it('defaults to the shared preview line count', () => {
@@ -806,6 +913,8 @@ describe('ChangeWalkthroughService', () => {
let sessions: Record<string, FakeSession>
let fake: ReturnType<typeof createFakeClient>
let service: ChangeWalkthroughService
let gitService: GitService
let fetchRemoteRef: ReturnType<typeof vi.fn>
const threeHunks: FileDiffInfo[] = THREE_HUNKS
@@ -813,7 +922,9 @@ describe('ChangeWalkthroughService', () => {
db = createTestDb()
sessions = { [SESSION_ID]: { changes: threeHunks } }
fake = createFakeClient(sessions)
service = new ChangeWalkthroughService(db, fake.client, new SettingsService(db), createGitAuthService())
fetchRemoteRef = vi.fn(async () => {})
gitService = { fetchRemoteRef } as unknown as GitService
service = new ChangeWalkthroughService(db, fake.client, new SettingsService(db), createGitAuthService(), gitService)
})
afterEach(() => {
@@ -902,6 +1013,26 @@ describe('ChangeWalkthroughService', () => {
expect(refreshed.currentDiffHash).toBe(computeChangesHash([change('src/a.ts', hunkPatch(99))]))
})
it.each(['session.revert.staged', 'session.revert.committed', 'session.revert.cleared'])(
'recomputes the hash after %s',
async (eventType) => {
fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: THREE_HUNK_IDS }]))
await service.generate(SESSION_ID, {})
await service.getState(SESSION_ID)
sessions[SESSION_ID]!.changes = [change('src/a.ts', hunkPatch(99))]
const cached = await service.getState(SESSION_ID)
expect(cached.stale).toBe(false)
service.handleEvent(sessionEvent(eventType, SESSION_ID))
const refreshed = await service.getState(SESSION_ID)
expect(refreshed.stale).toBe(true)
expect(refreshed.currentDiffHash).toBe(computeChangesHash([change('src/a.ts', hunkPatch(99))]))
},
)
it('stores stops covering every hunk exactly once', async () => {
fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: [THREE_HUNK_IDS[0]!, THREE_HUNK_IDS[2]!] }]))
@@ -934,6 +1065,34 @@ describe('ChangeWalkthroughService', () => {
expect(new Set(referenced)).toEqual(new Set(walkthrough.hunks.map((hunk) => hunk.id)))
})
it('bounds stored mechanical text yet lists every mechanical file with counts', async () => {
const oversizedPatch = Array.from({ length: 40 }, (_, index) => bigHunk(index)).join('\n')
sessions[SESSION_ID]!.changes = [
change('src/a.ts', hunkPatch(1)),
{ file: 'pnpm-lock.yaml', patch: oversizedPatch, additions: 1200, deletions: 800, status: 'modified' },
{ file: 'src/__snapshots__/a.ts.snap', patch: hunkPatch(2), additions: 2, deletions: 3, status: 'modified' },
]
fake.setGenerateImpl(async () =>
modelReply([{ title: 'A', explanation: 'x', hunkIds: [computeHunkId('src/a.ts', 'modified', hunkPatch(1))] }]),
)
const { walkthrough } = await service.generate(SESSION_ID, {})
const mechanicalHunks = walkthrough.hunks.filter((hunk) => isMechanicalChangePath(hunk.file))
expect(mechanicalHunks.map((hunk) => hunk.file)).toEqual([
'pnpm-lock.yaml',
'src/__snapshots__/a.ts.snap',
])
expect(mechanicalHunks.reduce((total, hunk) => total + hunk.text.length, 0)).toBeLessThanOrEqual(
MECHANICAL_TEXT_BUDGET,
)
expect(mechanicalHunks[0]).toMatchObject({ text: '', additions: 1200, deletions: 800 })
expect(mechanicalHunks[1]).toMatchObject({ additions: 2, deletions: 3 })
const mechanicalStop = walkthrough.stops.find((stop) => stop.title === 'Mechanical changes')!
expect(new Set(mechanicalStop.hunkIds)).toEqual(new Set(mechanicalHunks.map((hunk) => hunk.id)))
})
it('stores only a mechanical stop without a model call', async () => {
sessions[SESSION_ID]!.changes = [
change('pnpm-lock.yaml', hunkPatch(1)),
@@ -953,6 +1112,60 @@ describe('ChangeWalkthroughService', () => {
)
})
it('writes a truthful summary when source files are omitted but mechanical files changed', async () => {
const file = 'src/huge.ts'
const patch = Array.from(
{ length: 2000 },
(_, index) => `@@ -${index + 1},1 +${index + 1},1 @@\n+line${index}`,
).join('\n')
sessions[SESSION_ID]!.changes = [change(file, patch), change('pnpm-lock.yaml', hunkPatch(1))]
const { walkthrough } = await service.generate(SESSION_ID, {})
expect(walkthrough.summary).not.toBe('Only lock files, snapshots or generated files changed.')
expect(walkthrough.stops.map((stop) => stop.title)).toContain('Mechanical changes')
expect(fake.generateCalls).toHaveLength(0)
})
it('does not claim mechanical-only when a binary source file was omitted', async () => {
sessions[SESSION_ID]!.changes = [
change('assets/logo.png', 'diff --git a/assets/logo.png b/assets/logo.png\nBinary files differ'),
change('pnpm-lock.yaml', hunkPatch(1)),
]
const { walkthrough } = await service.generate(SESSION_ID, {})
expect(walkthrough.summary).not.toBe('Only lock files, snapshots or generated files changed.')
expect(walkthrough.stops[0]!.title).toBe('Mechanical changes')
})
it('never reuses the single-call remaining placeholder as a real explanation', async () => {
const remainingIds = [THREE_HUNK_IDS[1]!, THREE_HUNK_IDS[2]!]
fake.setGenerateImpl(async () =>
modelReply([{ title: 'A', explanation: 'x', hunkIds: [THREE_HUNK_IDS[0]!] }]),
)
const first = await service.generate(SESSION_ID, {})
const firstRemaining = first.walkthrough.stops.at(-1)!
expect(firstRemaining.title).toBe('Remaining changes')
expect(firstRemaining.explanationKey).toBeNull()
sessions[SESSION_ID]!.changes = [
change('src/a.ts', `${hunkPatch(99)}\n${hunkPatch(10)}`),
change('src/b.ts', hunkPatch(1)),
]
fake.setGenerateImpl(async () => modelReply([{ title: 'B', explanation: 'fresh', hunkIds: remainingIds }]))
const second = await service.generate(SESSION_ID, {})
const stopB = second.walkthrough.stops.find((stop) => stop.title === 'B')!
expect(stopB.explanation).toBe('fresh')
const placeholderStop = second.walkthrough.stops.find(
(stop) => stop.explanation === 'These changes were not covered by the generated walkthrough.',
)
expect(placeholderStop?.explanationKey).toBeNull()
})
it('returns the stored walkthrough without a model call when changes are unchanged', async () => {
fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: THREE_HUNK_IDS }]))
const first = await service.generate(SESSION_ID, {})
@@ -962,6 +1175,7 @@ describe('ChangeWalkthroughService', () => {
expect(second.created).toBe(false)
expect(second.walkthrough).toEqual(first.walkthrough)
expect(fake.generateCalls).toHaveLength(1)
expect(vi.mocked(fake.client.api.model.list)).toHaveBeenCalledTimes(1)
})
it('calls the model again when regenerate is set', async () => {
@@ -1019,6 +1233,38 @@ describe('ChangeWalkthroughService', () => {
expect(fake.generateModels[0]).toEqual({ providerID: 'anthropic', id: 'claude-sonnet-4' })
})
it('resolves the default model once per generation', async () => {
sessions[SESSION_ID]!.changes = LARGE_CHANGES
fake.setGenerateImpl((prompt) =>
Promise.resolve(prompt.includes(PLAN_MARKER) ? LARGE_PLAN_REPLY : EXPLANATION_REPLY),
)
await service.generate(SESSION_ID, {})
expect(vi.mocked(fake.client.api.model.list)).toHaveBeenCalledTimes(1)
})
it('includes the resolved default model in the explanation key', async () => {
fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: THREE_HUNK_IDS }]))
const first = await service.generate(SESSION_ID, {})
const firstKey = first.walkthrough.stops[0]!.explanationKey
vi.mocked(fake.client.api.model.list).mockResolvedValue({
data: [{ providerID: 'openai', id: 'gpt-5', enabled: true }],
} as never)
vi.mocked(fake.client.api.model.default).mockResolvedValue({
data: { providerID: 'openai', id: 'gpt-5', enabled: true },
} as never)
const second = await service.generate(SESSION_ID, { regenerate: true })
const secondKey = second.walkthrough.stops[0]!.explanationKey
expect(firstKey).not.toBeNull()
expect(secondKey).not.toBeNull()
expect(firstKey).not.toBe(secondKey)
})
it('coalesces concurrent generation into one model call', async () => {
let resolveGenerate: (text: string) => void = () => {}
const gate = new Promise<string>((resolve) => {
@@ -1044,6 +1290,31 @@ describe('ChangeWalkthroughService', () => {
})
})
it('names the source in the no-changes message', async () => {
const repo = createChangedRepo()
sessions[SESSION_ID] = { changes: threeHunks, info: sessionAt(repo) }
await expect(service.generate(SESSION_ID, { source: { kind: 'staged' } })).rejects.toMatchObject({
status: 409,
code: 'WALKTHROUGH_NO_CHANGES',
message: 'The staged changes contain no changes to walk through',
})
})
it('names the source in the no-text-changes message', async () => {
const repo = path.join(walkthroughRepoRoot, uniqueName('repo'))
createCommittedRepo(repo)
writeFileSync(path.join(repo, 'logo.png'), Buffer.from([0x00, 0x89, 0x50, 0x4e, 0x47]))
git(['add', 'logo.png'], repo)
sessions[SESSION_ID] = { changes: threeHunks, info: sessionAt(repo) }
await expect(service.generate(SESSION_ID, { source: { kind: 'staged' } })).rejects.toMatchObject({
status: 409,
code: 'WALKTHROUGH_NO_TEXT_CHANGES',
message: 'The staged changes contain no text changes',
})
})
it('rejects with 409 when every change is binary', async () => {
sessions[SESSION_ID]!.changes = [
change('assets/logo.png', 'diff --git a/assets/logo.png b/assets/logo.png\nBinary files differ'),
@@ -1082,7 +1353,7 @@ describe('ChangeWalkthroughService', () => {
})
it('rejects with 504 when generation times out', async () => {
const timingOut = new ChangeWalkthroughService(db, fake.client, new SettingsService(db), createGitAuthService(), { timeoutMs: 5 })
const timingOut = new ChangeWalkthroughService(db, fake.client, new SettingsService(db), createGitAuthService(), gitService, { timeoutMs: 5 })
fake.setGenerateImpl(() => new Promise<string>(() => {}))
await expect(timingOut.generate(SESSION_ID, {})).rejects.toMatchObject({
@@ -1296,6 +1567,43 @@ describe('ChangeWalkthroughService', () => {
expect(fake.generateCalls.length - callsAfterFirst).toBe(4)
})
it('marks resumed stops pending while they are being explained', async () => {
sessions[SESSION_ID]!.changes = LARGE_CHANGES
fake.setGenerateImpl((prompt) => {
if (prompt.includes(PLAN_MARKER)) {
return Promise.resolve(LARGE_PLAN_REPLY)
}
if (prompt.includes('## Stop: B')) {
return Promise.resolve('not json')
}
return Promise.resolve(explanationFor(prompt))
})
const first = await service.generate(SESSION_ID, {})
expect(first.walkthrough.stops.find((stop) => stop.title === 'B')!.status).toBe('failed')
let resolveExplain: (text: string) => void = () => {}
fake.setGenerateImpl((prompt) => {
if (prompt.includes('## Stop: B')) {
return new Promise<string>((resolve) => {
resolveExplain = resolve
})
}
return Promise.resolve(explanationFor(prompt))
})
const pending = service.generate(SESSION_ID, {})
await vi.waitFor(async () => {
const state = await service.getState(SESSION_ID)
expect(state.walkthrough?.stops.find((stop) => stop.title === 'B')?.status).toBe('pending')
})
resolveExplain(EXPLANATION_REPLY)
const resumed = await pending
expect(resumed.walkthrough.stops.find((stop) => stop.title === 'B')!.status).toBe('ready')
})
it('does not reuse explanations across models', async () => {
sessions[SESSION_ID]!.info = {
id: SESSION_ID,
@@ -1445,11 +1753,19 @@ describe('ChangeWalkthroughService', () => {
expect((await service.getState(SESSION_ID)).error).not.toBeNull()
})
fake.setGenerateImpl(() => new Promise<string>(() => {}))
let resolveGenerate: (text: string) => void = () => {}
fake.setGenerateImpl(() => new Promise<string>((resolve) => {
resolveGenerate = resolve
}))
const state = await service.startGeneration(SESSION_ID, { regenerate: true })
expect(state.generating).toBe(true)
expect(state.error).toBeNull()
resolveGenerate(coveringReply)
await vi.waitFor(async () => {
expect((await service.getState(SESSION_ID)).generating).toBe(false)
})
})
it('clears the recorded error when the session is deleted', async () => {
@@ -1510,6 +1826,112 @@ describe('ChangeWalkthroughService', () => {
expect(getChangeWalkthrough(db, SESSION_ID, 'session')).not.toBeNull()
})
it('skips queued stop explanations once the session is deleted', async () => {
sessions[SESSION_ID]!.changes = LARGE_CHANGES
const planStops = Array.from({ length: 8 }, (_, index) => {
const file = index < 4 ? 'src/a.ts' : 'src/b.ts'
const hunk = index < 4 ? index : index - 4 + 10
return { title: `S${index}`, hunkIds: [computeHunkId(file, 'modified', bigHunk(hunk))] }
})
const explainResolvers: Array<(text: string) => void> = []
fake.setGenerateImpl((prompt) => {
if (prompt.includes(PLAN_MARKER)) {
return Promise.resolve(planReply(planStops))
}
return new Promise<string>((resolve) => {
explainResolvers.push(resolve)
})
})
const pending = service.generate(SESSION_ID, {})
await vi.waitFor(() => expect(explainResolvers).toHaveLength(4))
service.handleEvent(sessionEvent('session.deleted', SESSION_ID))
for (const resolve of explainResolvers) {
resolve(EXPLANATION_REPLY)
}
await expect(pending).rejects.toMatchObject({ status: 404 })
expect(fake.generateCalls.filter((prompt) => prompt.includes('## Stop:'))).toHaveLength(4)
})
it('clears the cached hash and its epoch when the session is deleted', async () => {
fake.setGenerateImpl(async () => coveringReply)
await service.generate(SESSION_ID, {})
await service.getState(SESSION_ID)
const internals = service as unknown as {
currentHashes: Map<string, string>
hashEpochs: Map<string, number>
}
expect(internals.currentHashes.size).toBeGreaterThan(0)
service.handleEvent(sessionEvent('session.deleted', SESSION_ID))
expect(internals.currentHashes.size).toBe(0)
expect(internals.hashEpochs.size).toBe(0)
})
it('does not track a hash epoch for a session with no cached hash', () => {
service.handleEvent(sessionEvent('session.execution.succeeded', SESSION_ID))
const internals = service as unknown as { hashEpochs: Map<string, number> }
expect(internals.hashEpochs.size).toBe(0)
})
it('does not cache a hash from overlapping reads invalidated between completions', async () => {
const diffMock = vi.mocked(fake.client.api.session.diff)
const resolvers: Array<(changes: FileDiffInfo[]) => void> = []
diffMock.mockImplementation(() => new Promise<FileDiffInfo[]>((resolve) => {
resolvers.push(resolve)
}))
const first = service.getState(SESSION_ID)
const second = service.getState(SESSION_ID)
await vi.waitFor(() => expect(resolvers).toHaveLength(2))
service.handleEvent(sessionEvent('session.execution.succeeded', SESSION_ID))
resolvers[0]!(threeHunks)
resolvers[1]!(threeHunks)
await Promise.all([first, second])
const internals = service as unknown as {
currentHashes: Map<string, string>
hashEpochs: Map<string, number>
}
expect(internals.currentHashes.size).toBe(0)
expect(internals.hashEpochs.size).toBe(0)
diffMock.mockResolvedValue([change('src/a.ts', hunkPatch(99))])
const refreshed = await service.getState(SESSION_ID)
expect(refreshed.currentDiffHash).toBe(computeChangesHash([change('src/a.ts', hunkPatch(99))]))
})
it('drops a hash read that completes after the session is deleted', async () => {
const diffMock = vi.mocked(fake.client.api.session.diff)
let resolveDiff: (changes: FileDiffInfo[]) => void = () => {}
diffMock.mockImplementationOnce(() => new Promise<FileDiffInfo[]>((resolve) => {
resolveDiff = resolve
}))
const pending = service.getState(SESSION_ID)
await vi.waitFor(() => expect(diffMock).toHaveBeenCalledTimes(1))
service.handleEvent(sessionEvent('session.deleted', SESSION_ID))
resolveDiff(threeHunks)
await pending
const internals = service as unknown as {
currentHashes: Map<string, string>
hashEpochs: Map<string, number>
pendingHashReads: Map<string, number>
}
expect(internals.currentHashes.size).toBe(0)
expect(internals.hashEpochs.size).toBe(0)
expect(internals.pendingHashReads.size).toBe(0)
})
})
describe('per-source storage', () => {
@@ -1543,4 +1965,253 @@ describe('ChangeWalkthroughService', () => {
expect(getChangeWalkthrough(db, SESSION_ID, 'uncommitted')).toBeNull()
})
})
describe('pull request sources', () => {
it('does not fetch on GET and tolerates a missing pull request ref', async () => {
const repo = createChangedRepo()
sessions[SESSION_ID] = { changes: threeHunks, info: sessionAt(repo) }
const state = await service.getState(SESSION_ID, { kind: 'pullRequest', number: 1, base: 'main' })
expect(fetchRemoteRef).not.toHaveBeenCalled()
expect(state.error).toBeNull()
expect(state.currentDiffHash).toBeNull()
expect(state.stale).toBe(false)
})
it('fetches once during generation, reads the ref on GET, and deletes it with the session', async () => {
const repo = createPullRequestRepo()
sessions[SESSION_ID] = { changes: threeHunks, info: sessionAt(repo) }
fetchRemoteRef.mockImplementation(async (target: { fullPath: string }, remote: string, refspec: string) => {
git(['fetch', remote, refspec], target.fullPath)
})
fake.setGenerateImpl(async (prompt) => replyForPrompt(prompt))
await service.generate(SESSION_ID, { source: { kind: 'pullRequest', number: 1, base: 'main' } })
expect(fetchRemoteRef).toHaveBeenCalledTimes(1)
expect(refExists(repo, 'refs/ocm-walkthrough/pr/1')).toBe(true)
fetchRemoteRef.mockClear()
const state = await service.getState(SESSION_ID, { kind: 'pullRequest', number: 1, base: 'main' })
expect(fetchRemoteRef).not.toHaveBeenCalled()
expect(state.error).toBeNull()
expect(state.currentDiffHash).not.toBeNull()
service.handleEvent(sessionEvent('session.deleted', SESSION_ID))
await vi.waitFor(() => {
expect(refExists(repo, 'refs/ocm-walkthrough/pr/1')).toBe(false)
})
})
it('prefers the upstream remote when generating', async () => {
const repo = createPullRequestRepo()
const originUrl = git(['remote', 'get-url', 'origin'], repo)
git(['remote', 'add', 'upstream', originUrl], repo)
sessions[SESSION_ID] = { changes: threeHunks, info: sessionAt(repo) }
fake.setGenerateImpl(async (prompt) => replyForPrompt(prompt))
await service
.generate(SESSION_ID, { source: { kind: 'pullRequest', number: 1, base: 'main' } })
.catch(() => {})
expect(fetchRemoteRef).toHaveBeenCalledTimes(1)
expect(fetchRemoteRef.mock.calls[0]?.[1]).toBe('upstream')
})
})
describe('progressive persistence and in-memory state', () => {
it('writes once after the plan, every four explained stops, and at the end', async () => {
sessions[SESSION_ID]!.changes = LARGE_CHANGES
const hunkIds = [
...[0, 1, 2, 3].map((index) => computeHunkId('src/a.ts', 'modified', bigHunk(index))),
...[10, 11, 12, 13].map((index) => computeHunkId('src/b.ts', 'modified', bigHunk(index))),
...[20, 21, 22, 23].map((index) => computeHunkId('src/c.ts', 'modified', bigHunk(index))),
]
const planStops = Array.from({ length: 10 }, (_, index) => ({ title: `S${index}`, hunkIds: [] as string[] }))
hunkIds.forEach((id, index) => {
planStops[Math.min(index, planStops.length - 1)]!.hunkIds.push(id)
})
fake.setGenerateImpl((prompt) =>
Promise.resolve(prompt.includes(PLAN_MARKER) ? planReply(planStops) : EXPLANATION_REPLY),
)
const prepare = vi.spyOn(db, 'prepare')
try {
const { walkthrough } = await service.generate(SESSION_ID, {})
expect(walkthrough.stops).toHaveLength(10)
expect(walkthrough.stops.every((stop) => stop.status === 'ready')).toBe(true)
const writes = prepare.mock.calls.filter(
([sql]) => typeof sql === 'string' && sql.includes('INSERT INTO change_walkthroughs'),
).length
expect(writes).toBe(4)
} finally {
prepare.mockRestore()
}
})
it('serves an in-progress walkthrough from memory after its row is removed', async () => {
sessions[SESSION_ID]!.changes = LARGE_CHANGES
const explainResolvers: Array<(text: string) => void> = []
fake.setGenerateImpl((prompt) => {
if (prompt.includes(PLAN_MARKER)) {
return Promise.resolve(LARGE_PLAN_REPLY)
}
return new Promise<string>((resolve) => {
explainResolvers.push(resolve)
})
})
const pending = service.generate(SESSION_ID, {})
await vi.waitFor(async () => {
const state = await service.getState(SESSION_ID)
expect(state.walkthrough?.stops).toHaveLength(3)
expect(state.walkthrough?.stops.every((stop) => stop.status === 'pending')).toBe(true)
})
deleteChangeWalkthroughs(db, SESSION_ID)
const state = await service.getState(SESSION_ID)
expect(state.walkthrough?.stops).toHaveLength(3)
await vi.waitFor(() => expect(explainResolvers).toHaveLength(3))
for (const resolve of explainResolvers) {
resolve(EXPLANATION_REPLY)
}
await pending
})
it('resumes a walkthrough row saved after the plan', async () => {
sessions[SESSION_ID]!.changes = LARGE_CHANGES
const input = buildWalkthroughInput(LARGE_CHANGES)
const savedStops = input.hunks.slice(0, 3).map((hunk, index) => ({
id: computeStopId([hunk.id]),
title: `S${index}`,
explanation: '',
hunkIds: [hunk.id],
status: 'pending' as const,
explanationKey: null,
}))
saveChangeWalkthrough(db, {
sessionId: SESSION_ID,
source: { kind: 'session' },
diffHash: computeChangesHash(LARGE_CHANGES),
model: null,
summary: 'Saved plan',
stops: savedStops,
hunks: input.hunks,
omittedFiles: [],
createdAt: 1,
})
fake.setGenerateImpl((prompt) => Promise.resolve(explanationFor(prompt)))
const stored = getChangeWalkthrough(db, SESSION_ID, 'session')
expect(stored?.diffHash).toBe(computeChangesHash(LARGE_CHANGES))
expect(stored?.stops).toHaveLength(3)
const { walkthrough, created } = await service.generate(SESSION_ID, {})
expect(created).toBe(true)
expect(walkthrough.stops).toHaveLength(3)
expect(walkthrough.stops.every((stop) => stop.status === 'ready')).toBe(true)
expect(fake.generateCalls.filter((prompt) => prompt.includes(PLAN_MARKER))).toHaveLength(0)
expect(fake.generateCalls).toHaveLength(3)
})
})
describe('global model call limiter', () => {
it('never exceeds four in-flight model calls across concurrent generations', async () => {
const secondSession = 'ses_walkthrough_second'
sessions[SESSION_ID] = { changes: LARGE_CHANGES }
sessions[secondSession] = { changes: LARGE_CHANGES }
const planStops = Array.from({ length: 8 }, (_, index) => {
const file = index < 4 ? 'src/a.ts' : 'src/b.ts'
const hunk = index < 4 ? index : index - 4 + 10
return { title: `S${index}`, hunkIds: [computeHunkId(file, 'modified', bigHunk(hunk))] }
})
let inFlight = 0
let maxInFlight = 0
fake.setGenerateImpl(async (prompt) => {
inFlight += 1
maxInFlight = Math.max(maxInFlight, inFlight)
await new Promise((resolve) => setTimeout(resolve, 2))
inFlight -= 1
return prompt.includes(PLAN_MARKER) ? planReply(planStops) : EXPLANATION_REPLY
})
await Promise.all([service.generate(SESSION_ID, {}), service.generate(secondSession, {})])
expect(maxInFlight).toBeLessThanOrEqual(4)
expect(maxInFlight).toBeGreaterThanOrEqual(2)
})
it('skips a queued explain call when the session is deleted while waiting', async () => {
const victim = 'ses_walkthrough_victim'
const victimChanges = [
change('victim/a.ts', Array.from({ length: 8 }, (_, index) => bigHunk(index)).join('\n')),
]
const victimPlan = planReply(
Array.from({ length: 4 }, (_, group) => ({
title: `V${group}`,
hunkIds: [group * 2, group * 2 + 1].map((hunk) =>
computeHunkId('victim/a.ts', 'modified', bigHunk(hunk)),
),
})),
)
sessions[SESSION_ID] = { changes: LARGE_CHANGES }
sessions[victim] = { changes: victimChanges }
let saturatorExplainStarted = 0
let victimExplainStarted = 0
const saturatorResolvers: Array<(text: string) => void> = []
const victimResolvers: Array<(text: string) => void> = []
fake.setGenerateImpl((prompt) => {
if (prompt.includes('victim/')) {
if (prompt.includes('## Stop:')) {
victimExplainStarted += 1
return new Promise<string>((resolve) => {
victimResolvers.push(resolve)
})
}
return Promise.resolve(victimPlan)
}
if (prompt.includes(PLAN_MARKER)) {
return Promise.resolve(LARGE_PLAN_REPLY)
}
saturatorExplainStarted += 1
return new Promise<string>((resolve) => {
saturatorResolvers.push(resolve)
})
})
const saturator = service.generate(SESSION_ID, {})
await vi.waitFor(() => expect(saturatorExplainStarted).toBe(3))
const victimRun = service.generate(victim, {})
await vi.waitFor(() => expect(victimExplainStarted).toBe(1))
service.handleEvent(sessionEvent('session.deleted', victim))
for (const resolve of saturatorResolvers) {
resolve(EXPLANATION_REPLY)
}
for (const resolve of victimResolvers) {
resolve(EXPLANATION_REPLY)
}
await saturator
await expect(victimRun).rejects.toMatchObject({ status: 404 })
expect(victimExplainStarted).toBe(1)
})
})
})
@@ -10,7 +10,11 @@ import {
walkthroughSourceKey,
} from '@opencode-manager/shared/schemas'
import { ChangeWalkthroughError } from '../../src/services/change-walkthrough-error'
import { readWalkthroughChanges } from '../../src/services/walkthrough-sources'
import {
planPullRequestFetch,
readWalkthroughChanges,
walkthroughPullRequestRef,
} from '../../src/services/walkthrough-sources'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import { cloneOrigin, createCommittedRepo, createOrigin, git, uniqueName } from '../helpers/git-fixtures'
@@ -135,6 +139,7 @@ describe('readWalkthroughChanges', () => {
git(['add', 'pr.txt'], clone)
git(['commit', '-m', 'pr'], clone)
git(['push', 'origin', 'HEAD:refs/pull/1/head'], clone)
git(['fetch', 'origin', `+refs/pull/1/head:${walkthroughPullRequestRef(1)}`], clone)
const changes = await readAt(clone, { kind: 'pullRequest', number: 1, base: 'main' })
@@ -142,6 +147,49 @@ describe('readWalkthroughChanges', () => {
expect(changes[0]?.status).toBe('added')
})
it('does not fetch the pull request ref when reading changes', async () => {
const origin = repoPath('pr-no-fetch-origin')
const work = repoPath('pr-no-fetch-work')
const clone = repoPath('pr-no-fetch-clone')
createOrigin(origin, work)
cloneOrigin(origin, clone)
git(['checkout', '-b', 'feature'], clone)
writeFileSync(path.join(clone, 'pr.txt'), 'pr\n')
git(['add', 'pr.txt'], clone)
git(['commit', '-m', 'pr'], clone)
git(['push', 'origin', 'HEAD:refs/pull/1/head'], clone)
const error = await readAt(clone, { kind: 'pullRequest', number: 1, base: 'main' }).catch((thrown) => thrown)
expect(error).toBeInstanceOf(ChangeWalkthroughError)
expect(error).toMatchObject({ status: 502, code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
})
it('prefers the upstream remote when it exists', async () => {
const repo = repoPath('pr-upstream')
createCommittedRepo(repo)
git(['remote', 'add', 'origin', 'https://example.com/base.git'], repo)
git(['remote', 'add', 'upstream', 'https://example.com/fork.git'], repo)
const plan = await planPullRequestFetch(repo, { kind: 'pullRequest', number: 7, base: 'main' })
expect(plan.remote).toBe('upstream')
expect(plan.refspec).toBe('+refs/pull/7/head:refs/ocm-walkthrough/pr/7')
expect(plan.ref).toBe('refs/ocm-walkthrough/pr/7')
})
it('falls back to the origin remote when no upstream exists', async () => {
const repo = repoPath('pr-origin')
createCommittedRepo(repo)
git(['remote', 'add', 'origin', 'https://example.com/base.git'], repo)
const plan = await planPullRequestFetch(repo, { kind: 'pullRequest', number: 3, base: 'main' })
expect(plan.remote).toBe('origin')
expect(plan.refspec).toBe('+refs/pull/3/head:refs/ocm-walkthrough/pr/3')
})
it('excludes untracked files from staged and branch sources', async () => {
const repo = repoPath('not-untracked')
createCommittedRepo(repo, 'main')
@@ -177,6 +225,127 @@ describe('readWalkthroughChanges', () => {
expect(error).toBeInstanceOf(ChangeWalkthroughError)
expect(error).toMatchObject({ status: 409, code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
})
it('resolves a base branch that only exists as a remote-tracking ref', async () => {
const origin = repoPath('base-origin')
const work = repoPath('base-work')
const clone = repoPath('base-clone')
createOrigin(origin, work, ['develop'])
cloneOrigin(origin, clone)
git(['checkout', '-b', 'feature'], clone)
writeFileSync(path.join(clone, 'feature.txt'), 'feature\n')
git(['add', 'feature.txt'], clone)
git(['commit', '-m', 'feature'], clone)
const changes = await readAt(clone, { kind: 'branch', base: 'develop' })
expect(changes.map((entry) => entry.file)).toEqual(['feature.txt'])
})
it('rejects a branch source when the diff fails after the base resolves', async () => {
const repo = repoPath('diff-failure')
mkdirSync(repo, { recursive: true })
git(['init', '-b', 'main'], repo)
git(['config', 'user.email', 'test@test.com'], repo)
git(['config', 'user.name', 'Test'], repo)
writeFileSync(path.join(repo, 'base.txt'), 'base\n')
git(['add', 'base.txt'], repo)
git(['commit', '-m', 'base'], repo)
git(['checkout', '-b', 'feature'], repo)
writeFileSync(path.join(repo, 'feature.txt'), 'feature\n')
git(['add', 'feature.txt'], repo)
git(['commit', '-m', 'feature'], repo)
const tree = git(['rev-parse', 'main^{tree}'], repo)
rmSync(path.join(repo, '.git', 'objects', tree.slice(0, 2), tree.slice(2)), { force: true })
const error = await readAt(repo, { kind: 'branch', base: 'main' }).catch((thrown) => thrown)
expect(error).toBeInstanceOf(ChangeWalkthroughError)
expect(error).toMatchObject({ status: 502, code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
expect((error as Error).message).toContain('unable to read tree')
})
it('reads root-relative paths when diff prefix config changes the header', async () => {
for (const [key, value] of [['diff.mnemonicPrefix', 'true'], ['diff.noprefix', 'true']]) {
const repo = repoPath(`prefix-${key}`)
createCommittedRepo(repo)
writeFileSync(path.join(repo, 'tracked.txt'), 'one\n')
git(['add', 'tracked.txt'], repo)
git(['commit', '-m', 'add tracked'], repo)
writeFileSync(path.join(repo, 'tracked.txt'), 'two\n')
writeFileSync(path.join(repo, 'untracked.txt'), 'new\n')
git(['config', key!, value!], repo)
const unstaged = await readAt(repo, { kind: 'unstaged' })
expect(unstaged.map((entry) => entry.file).sort()).toEqual(['tracked.txt', 'untracked.txt'])
expect(unstaged.find((entry) => entry.file === 'tracked.txt')?.patch).toContain('-one')
expect(unstaged.find((entry) => entry.file === 'untracked.txt')?.status).toBe('added')
}
})
it('ignores an external diff driver for tracked and untracked files', async () => {
const repo = repoPath('external-diff')
createCommittedRepo(repo)
writeFileSync(path.join(repo, 'tracked.txt'), 'one\n')
git(['add', 'tracked.txt'], repo)
git(['commit', '-m', 'add tracked'], repo)
writeFileSync(path.join(repo, 'tracked.txt'), 'two\n')
writeFileSync(path.join(repo, 'untracked.txt'), 'new\n')
git(['config', 'diff.external', 'false'], repo)
const unstaged = await readAt(repo, { kind: 'unstaged' })
expect(unstaged.map((entry) => entry.file).sort()).toEqual(['tracked.txt', 'untracked.txt'])
})
it('reads unstaged worktree edits and uncommitted content without a HEAD commit', async () => {
const repo = repoPath('no-head')
mkdirSync(repo, { recursive: true })
git(['init', '-b', 'main'], repo)
git(['config', 'user.email', 'test@test.com'], repo)
git(['config', 'user.name', 'Test'], repo)
writeFileSync(path.join(repo, 'a.txt'), 'one\n')
git(['add', 'a.txt'], repo)
writeFileSync(path.join(repo, 'a.txt'), 'two\n')
const unstaged = await readAt(repo, { kind: 'unstaged' })
const uncommitted = await readAt(repo, { kind: 'uncommitted' })
expect(unstaged.map((entry) => entry.file)).toEqual(['a.txt'])
expect(unstaged[0]?.patch).toContain('-one')
expect(unstaged[0]?.patch).toContain('+two')
expect(uncommitted.map((entry) => entry.file)).toEqual(['a.txt'])
expect(uncommitted[0]?.patch).toContain('+two')
expect(uncommitted[0]?.patch).not.toContain('+one')
})
it('includes every untracked file in a single uncommitted read', async () => {
const repo = repoPath('many-untracked')
createCommittedRepo(repo)
mkdirSync(path.join(repo, 'nested'), { recursive: true })
writeFileSync(path.join(repo, 'b.txt'), 'b\n')
writeFileSync(path.join(repo, 'a.txt'), 'a\n')
writeFileSync(path.join(repo, 'nested', 'c.txt'), 'c\n')
const uncommitted = await readAt(repo, { kind: 'uncommitted' })
expect(uncommitted.map((entry) => entry.file).sort()).toEqual(['a.txt', 'b.txt', 'nested/c.txt'])
expect(uncommitted.every((entry) => entry.status === 'added')).toBe(true)
})
it('rejects a diff larger than the output cap with a 413 error', async () => {
const repo = repoPath('too-large')
createCommittedRepo(repo)
writeFileSync(path.join(repo, 'huge.txt'), 'x'.repeat(6_000_000))
const error = await readAt(repo, { kind: 'unstaged' }).catch((thrown) => thrown)
expect(error).toBeInstanceOf(ChangeWalkthroughError)
expect(error).toMatchObject({ status: 413, code: 'WALKTHROUGH_DIFF_TOO_LARGE' })
})
})
describe('walkthroughSourceKey', () => {
+56 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { mapWithConcurrency } from '../../src/utils/concurrency'
import { createLimiter, mapWithConcurrency } from '../../src/utils/concurrency'
describe('mapWithConcurrency', () => {
it('keeps result order', async () => {
@@ -38,3 +38,58 @@ describe('mapWithConcurrency', () => {
expect(result).toEqual(['a0', 'b1'])
})
})
describe('createLimiter', () => {
it('runs at most limit tasks at once', async () => {
const limiter = createLimiter(2)
let inFlight = 0
let maxInFlight = 0
const task = async (value: number): Promise<number> => {
inFlight += 1
maxInFlight = Math.max(maxInFlight, inFlight)
await new Promise((resolve) => setTimeout(resolve, 1))
inFlight -= 1
return value
}
const results = await Promise.all([1, 2, 3, 4, 5].map((value) => limiter.run(() => task(value))))
expect(results).toEqual([1, 2, 3, 4, 5])
expect(maxInFlight).toBe(2)
expect(limiter.activeCount).toBe(0)
})
it('queues tasks beyond the limit until a slot frees', async () => {
const limiter = createLimiter(1)
const order: string[] = []
let releaseFirst: () => void = () => {}
const first = limiter.run(async () => {
order.push('first')
await new Promise<void>((resolve) => {
releaseFirst = resolve
})
})
const second = limiter.run(async () => {
order.push('second')
})
await new Promise((resolve) => setTimeout(resolve, 0))
expect(order).toEqual(['first'])
releaseFirst()
await Promise.all([first, second])
expect(order).toEqual(['first', 'second'])
})
it('releases the slot when a task rejects', async () => {
const limiter = createLimiter(1)
await expect(limiter.run(async () => {
throw new Error('boom')
})).rejects.toThrow('boom')
await expect(limiter.run(async () => 'ok')).resolves.toBe('ok')
expect(limiter.activeCount).toBe(0)
})
})
+22 -1
View File
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest'
import { extractFirstJsonObject } from '../../src/utils/json-extract'
import { z } from 'zod'
import { extractFirstJsonObject, parseFirstJsonObject } from '../../src/utils/json-extract'
describe('extractFirstJsonObject', () => {
it('returns a plain JSON object', () => {
@@ -38,3 +39,23 @@ describe('extractFirstJsonObject', () => {
expect(extractFirstJsonObject('{"a":"unterminated}')).toBeNull()
})
})
describe('parseFirstJsonObject', () => {
const schema = z.object({ a: z.number() })
it('parses and validates the first object', () => {
expect(parseFirstJsonObject('prefix {"a":1} suffix', schema)).toEqual({ a: 1 })
})
it('returns null when there is no object', () => {
expect(parseFirstJsonObject('no object', schema)).toBeNull()
})
it('returns null for invalid JSON', () => {
expect(parseFirstJsonObject('{not json', schema)).toBeNull()
})
it('returns null when the object fails the schema', () => {
expect(parseFirstJsonObject('{"a":"nope"}', schema)).toBeNull()
})
})
+10
View File
@@ -35,6 +35,16 @@ describe('executeCommand signal handling', () => {
expect(result).toHaveLength(100)
})
it('flags truncated output on the structured result when exit codes are ignored', async () => {
const result = await executeCommand(
['sh', '-c', 'i=0; while [ $i -lt 1000 ]; do printf "0123456789"; i=$((i+1)); done'],
{ maxOutputChars: 100, silent: true, ignoreExitCode: true },
)
expect(result.truncated).toBe(true)
expect(result.stdout).toHaveLength(100)
})
it('returns the full stdout when it stays within maxOutputChars', async () => {
const result = await executeCommand(['sh', '-c', 'printf "hello"'], { maxOutputChars: 100, silent: true })
+9 -3
View File
@@ -3,6 +3,7 @@ import { API_BASE_URL } from '@/config'
import { walkthroughSourceKey } from '@opencode-manager/shared/schemas'
import type {
ChangeWalkthroughState,
ChangeWalkthroughStateWire,
GenerateChangeWalkthroughRequest,
WalkthroughSource,
} from '@opencode-manager/shared/schemas'
@@ -14,9 +15,14 @@ function walkthroughUrl(sessionId: string): string {
export async function getChangeWalkthrough(
sessionId: string,
source: WalkthroughSource,
): Promise<ChangeWalkthroughState> {
const query = `?source=${encodeURIComponent(walkthroughSourceKey(source))}`
return fetchWrapper<ChangeWalkthroughState>(`${walkthroughUrl(sessionId)}${query}`)
hunksFor?: string,
): Promise<ChangeWalkthroughStateWire> {
return fetchWrapper<ChangeWalkthroughStateWire>(walkthroughUrl(sessionId), {
params: {
source: walkthroughSourceKey(source),
...(hunksFor === undefined ? {} : { hunksFor }),
},
})
}
export async function generateChangeWalkthrough(
@@ -188,7 +188,7 @@ export function ToolSidePanel({
<>
{panelContent ? (
activeTool === 'walkthrough' && sessionId ? (
<ChangesWalkthroughProvider sessionId={sessionId} active>
<ChangesWalkthroughProvider key={sessionId} sessionId={sessionId} active>
{panelContent}
</ChangesWalkthroughProvider>
) : (
@@ -63,6 +63,53 @@ const walkthrough: ChangeWalkthrough = {
createdAt: 1,
}
const mechanicalWalkthrough: ChangeWalkthrough = {
...walkthrough,
stops: [
{
id: 's_mech',
title: 'Mechanical changes',
explanation: 'Lock files, snapshots and generated files.',
hunkIds: ['m_lock', 'm_snap', 'm_map'],
status: 'ready',
explanationKey: null,
},
],
hunks: [
{
id: 'm_lock',
file: 'pnpm-lock.yaml',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-old-lock\n+new-lock',
truncated: false,
additions: 120,
deletions: 80,
},
{
id: 'm_snap',
file: 'src/__snapshots__/a.ts.snap',
status: 'added',
header: '',
text: '',
truncated: true,
additions: 5,
deletions: 0,
},
{
id: 'm_map',
file: 'dist/app.js.map',
status: 'deleted',
header: '',
text: '',
truncated: true,
additions: 0,
deletions: 7,
},
],
omittedFiles: [],
}
function state(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthroughState {
return { walkthrough, currentDiffHash: 'hash-1', stale: false, generating: false, error: null, ...overrides }
}
@@ -223,7 +270,7 @@ describe('ChangesWalkthroughSheet', () => {
})
})
it('ignores an invalid pull request number', async () => {
it('prompts for a pull request number and withholds the actions until it is valid', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
mocks.generateChangeWalkthrough.mockResolvedValue(state())
@@ -236,17 +283,54 @@ describe('ChangesWalkthroughSheet', () => {
await user.type(number, '0')
await user.tab()
await user.click(screen.getByRole('button', { name: 'Generate walkthrough' }))
await waitFor(() => {
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { source: { kind: 'session' } })
})
expect(await screen.findByText('Enter a pull request number')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Generate walkthrough' })).not.toBeInTheDocument()
expect(mocks.generateChangeWalkthrough).not.toHaveBeenCalled()
expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith(
'ses_1',
expect.objectContaining({ kind: 'pullRequest' }),
)
})
it('commits a valid pull request number and restores the generate action', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
mocks.generateChangeWalkthrough.mockResolvedValue(state())
renderSheet()
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
await user.click(await screen.findByRole('option', { name: 'Pull request' }))
const number = await screen.findByLabelText('Pull request number')
await user.type(number, '12')
await user.tab()
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'pullRequest', number: 12 })
})
expect(screen.queryByText('Enter a pull request number')).not.toBeInTheDocument()
expect(await screen.findByRole('button', { name: 'Generate walkthrough' })).toBeEnabled()
})
it('resets the source before querying a new session', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
const { rerender, onOpenChange } = renderSheet()
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
await user.click(await screen.findByRole('option', { name: 'Staged' }))
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
})
rerender(<ChangesWalkthroughSheet sessionId="ses_2" open onOpenChange={onOpenChange} />)
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_2', { kind: 'session' })
})
expect(mocks.getChangeWalkthrough).not.toHaveBeenCalledWith('ses_2', { kind: 'staged' })
})
it('clears a generation error when the source changes', async () => {
const user = userEvent.setup()
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
@@ -381,6 +465,77 @@ describe('ChangesWalkthroughSheet', () => {
expect(screen.getByText('assets/logo.png — binary file')).toBeInTheDocument()
})
it('labels renamed and mode-change omitted files', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(
state({
walkthrough: {
...walkthrough,
omittedFiles: [
{ file: 'src/old.ts', reason: 'renamed' },
{ file: 'script.sh', reason: 'modeChange' },
],
},
}),
)
renderSheet()
expect(await screen.findByText('src/old.ts — renamed')).toBeInTheDocument()
expect(screen.getByText('script.sh — mode change')).toBeInTheDocument()
})
it('renders mechanical files as a compact summary list with counts and diff text for budgeted hunks', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: mechanicalWalkthrough }))
renderSheet()
expect(
await screen.findByRole('list', { name: 'Mechanical file summaries' }),
).toBeInTheDocument()
expect(screen.getByText('pnpm-lock.yaml')).toBeInTheDocument()
expect(screen.getByText('src/__snapshots__/a.ts.snap')).toBeInTheDocument()
expect(screen.getByText('dist/app.js.map')).toBeInTheDocument()
expect(screen.getByText('+120')).toBeInTheDocument()
expect(screen.getByText('-80')).toBeInTheDocument()
expect(screen.getByText('+5')).toBeInTheDocument()
expect(screen.getByText('-7')).toBeInTheDocument()
expect(screen.getByText('new-lock')).toBeInTheDocument()
})
it('renders a stored mechanical stop whose hunks predate hunk counts', async () => {
mocks.getChangeWalkthrough.mockResolvedValue(
state({
walkthrough: {
...walkthrough,
stops: [
{
id: 's_mech',
title: 'Mechanical changes',
explanation: 'Lock files',
hunkIds: ['m_lock'],
status: 'ready',
explanationKey: null,
},
],
hunks: [
{
id: 'm_lock',
file: 'pnpm-lock.yaml',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-old-lock\n+new-lock',
truncated: false,
},
],
omittedFiles: [],
},
}),
)
renderSheet()
expect(await screen.findByText('pnpm-lock.yaml')).toBeInTheDocument()
expect(screen.getByText('new-lock')).toBeInTheDocument()
expect(screen.queryByRole('list', { name: 'Mechanical file summaries' })).not.toBeInTheDocument()
})
it('renders raw HTML in the summary and stop explanation as inert text', async () => {
const payload =
'<iframe srcdoc="&lt;script&gt;parent.document.documentElement.dataset.walkthroughProbe = 1&lt;/script&gt;"></iframe>'
@@ -14,9 +14,9 @@ import { cn } from '@/lib/utils'
import {
DEFAULT_WALKTHROUGH_SOURCE,
describeWalkthroughSource,
toWalkthroughSource,
walkthroughSourceKey,
WalkthroughOmittedFileSchema,
WalkthroughSourceSchema,
} from '@opencode-manager/shared/schemas'
import type {
ChangeWalkthrough,
@@ -64,6 +64,8 @@ function walkthroughErrorMessage(error: unknown): string {
const OMITTED_REASON_LABELS: Record<WalkthroughOmittedFile['reason'], string> = {
binary: 'binary file',
budget: 'over the diff budget',
renamed: 'renamed',
modeChange: 'mode change',
}
function OmittedFiles({ files }: { files: WalkthroughOmittedFile[] }) {
@@ -79,6 +81,36 @@ function OmittedFiles({ files }: { files: WalkthroughOmittedFile[] }) {
)
}
function isMechanicalHunk(hunk: WalkthroughHunk): boolean {
return hunk.additions !== undefined || hunk.deletions !== undefined
}
function MechanicalHunks({ hunks }: { hunks: WalkthroughHunk[] }) {
return (
<ul aria-label="Mechanical file summaries" className="space-y-3">
{hunks.map((hunk) => (
<li key={hunk.id} className="overflow-hidden rounded-md border border-border">
<div className="flex items-center gap-2 px-3 py-1.5">
<span className="min-w-0 flex-1 truncate text-xs font-medium text-foreground" title={hunk.file}>
{hunk.file}
</span>
<span className={`text-xs ${GIT_STATUS_COLORS[hunk.status]}`}>
{GIT_STATUS_LABELS[hunk.status]}
</span>
<span className="text-xs text-diff-add">+{hunk.additions ?? 0}</span>
<span className="text-xs text-diff-delete">-{hunk.deletions ?? 0}</span>
</div>
{hunk.text.length > 0 ? (
<div className="overflow-x-auto border-t border-border">
<DiffLines diff={hunk.text} />
</div>
) : null}
</li>
))}
</ul>
)
}
interface ChangesWalkthroughContextValue {
isLoading: boolean
walkthrough: ChangeWalkthrough | null
@@ -97,6 +129,13 @@ interface ChangesWalkthroughContextValue {
failedStopCount: number
source: WalkthroughSource
setSource: (source: WalkthroughSource) => void
sourceKind: WalkthroughSource['kind']
setSourceKind: (kind: WalkthroughSource['kind']) => void
baseInput: string
setBaseInput: (base: string) => void
numberInput: string
setNumberInput: (number: string) => void
sourcePending: boolean
}
const ChangesWalkthroughContext = createContext<ChangesWalkthroughContextValue | null>(null)
@@ -116,76 +155,37 @@ const WALKTHROUGH_SOURCE_OPTIONS: { value: WalkthroughSource['kind']; label: str
{ value: 'pullRequest', label: 'Pull request' },
]
function walkthroughSourceLabel(source: WalkthroughSource): string {
return source.kind === 'session' ? 'the changes in this session' : describeWalkthroughSource(source)
}
function sourceBase(source: WalkthroughSource): string {
return source.kind === 'branch' || source.kind === 'pullRequest' ? source.base ?? '' : ''
}
function sourceNumber(source: WalkthroughSource): string {
return source.kind === 'pullRequest' ? String(source.number) : ''
}
/** Chooses which set of changes the walkthrough covers; git sources commit as soon as they are valid. */
const WalkthroughSourcePicker = memo(function WalkthroughSourcePicker() {
const { source, setSource } = useChangesWalkthrough()
const [kind, setKind] = useState<WalkthroughSource['kind']>(source.kind)
const [baseInput, setBaseInput] = useState(sourceBase(source))
const [numberInput, setNumberInput] = useState(sourceNumber(source))
const {
sourceKind,
setSourceKind,
baseInput,
setBaseInput,
numberInput,
setNumberInput,
setSource,
} = useChangesWalkthrough()
useEffect(() => {
setKind(source.kind)
setBaseInput(sourceBase(source))
setNumberInput(sourceNumber(source))
}, [source])
const commit = useCallback(
(candidate: unknown) => {
const parsed = WalkthroughSourceSchema.safeParse(candidate)
if (parsed.success) setSource(parsed.data)
},
[setSource],
)
const branchSource = useCallback((): WalkthroughSource => {
const base = baseInput.trim()
return base ? { kind: 'branch', base } : { kind: 'branch' }
}, [baseInput])
const pullRequestSource = useCallback((): WalkthroughSource => {
const base = baseInput.trim()
return base
? { kind: 'pullRequest', number: Number(numberInput), base }
: { kind: 'pullRequest', number: Number(numberInput) }
}, [baseInput, numberInput])
const commitBase = useCallback(() => {
if (kind === 'branch') {
commit(branchSource())
} else if (kind === 'pullRequest') {
commit(pullRequestSource())
}
}, [kind, commit, branchSource, pullRequestSource])
const commitNumber = useCallback(() => {
commit(pullRequestSource())
}, [commit, pullRequestSource])
const commitInputs = useCallback(() => {
const next = toWalkthroughSource({ kind: sourceKind, base: baseInput, number: Number(numberInput) })
if (next) setSource(next)
}, [sourceKind, baseInput, numberInput, setSource])
const handleKindChange = useCallback(
(next: WalkthroughSource['kind']) => {
setKind(next)
setSourceKind(next)
if (next === 'pullRequest') return
commit(next === 'branch' ? branchSource() : { kind: next })
const nextSource = toWalkthroughSource({ kind: next, base: baseInput })
if (nextSource) setSource(nextSource)
},
[commit, branchSource],
[baseInput, setSourceKind, setSource],
)
return (
<div className="space-y-2">
<Select
value={kind}
value={sourceKind}
onValueChange={(value) => handleKindChange(value as WalkthroughSource['kind'])}
>
<SelectTrigger aria-label="Changes to walk through">
@@ -200,28 +200,28 @@ const WalkthroughSourcePicker = memo(function WalkthroughSourcePicker() {
</SelectContent>
</Select>
{kind === 'branch' || kind === 'pullRequest' ? (
{sourceKind === 'branch' || sourceKind === 'pullRequest' ? (
<Input
aria-label="Base branch"
placeholder="Default branch"
value={baseInput}
onChange={(event) => setBaseInput(event.target.value)}
onBlur={commitBase}
onBlur={commitInputs}
onKeyDown={(event) => {
if (event.key === 'Enter') commitBase()
if (event.key === 'Enter') commitInputs()
}}
/>
) : null}
{kind === 'pullRequest' ? (
{sourceKind === 'pullRequest' ? (
<Input
type="number"
aria-label="Pull request number"
value={numberInput}
onChange={(event) => setNumberInput(event.target.value)}
onBlur={commitNumber}
onBlur={commitInputs}
onKeyDown={(event) => {
if (event.key === 'Enter') commitNumber()
if (event.key === 'Enter') commitInputs()
}}
/>
) : null}
@@ -238,6 +238,9 @@ interface ChangesWalkthroughProviderProps {
/** Loads a session's change walkthrough and shares its state with the surrounding chrome and body. */
export function ChangesWalkthroughProvider({ sessionId, active, children }: ChangesWalkthroughProviderProps) {
const [source, setSource] = useState<WalkthroughSource>(DEFAULT_WALKTHROUGH_SOURCE)
const [sourceKind, setSourceKind] = useState<WalkthroughSource['kind']>(DEFAULT_WALKTHROUGH_SOURCE.kind)
const [baseInput, setBaseInput] = useState('')
const [numberInput, setNumberInput] = useState('')
const sourceKey = walkthroughSourceKey(source)
const stateQuery = useChangeWalkthrough(sessionId, active, source)
const generate = useGenerateChangeWalkthrough(sessionId, source)
@@ -252,14 +255,15 @@ export function ChangesWalkthroughProvider({ sessionId, active, children }: Chan
const error = generate.error ?? stateQuery.error ?? (generating ? null : state?.error ?? null)
const contextLimitFiles = isContextLimitError(error) ? omittedFilesFromError(error) : []
const selectedSource = toWalkthroughSource({ kind: sourceKind, base: baseInput, number: Number(numberInput) })
const sourcePending =
sourceKind === 'pullRequest' &&
(selectedSource === null || walkthroughSourceKey(selectedSource) !== sourceKey)
useEffect(() => {
resetGenerate()
}, [active, sessionId, sourceKey, resetGenerate])
useEffect(() => {
setSource(DEFAULT_WALKTHROUGH_SOURCE)
}, [sessionId])
useEffect(() => {
setStopIndex(0)
}, [active, sessionId, sourceKey, walkthrough?.createdAt])
@@ -299,6 +303,13 @@ export function ChangesWalkthroughProvider({ sessionId, active, children }: Chan
failedStopCount,
source,
setSource,
sourceKind,
setSourceKind,
baseInput,
setBaseInput,
numberInput,
setNumberInput,
sourcePending,
}
return <ChangesWalkthroughContext.Provider value={value}>{children}</ChangesWalkthroughContext.Provider>
@@ -339,7 +350,7 @@ export const ChangesWalkthroughNav = memo(function ChangesWalkthroughNav() {
/** Regenerates the current walkthrough from the chrome; renders nothing until one exists. */
export const ChangesWalkthroughRegenerate = memo(function ChangesWalkthroughRegenerate() {
const { walkthrough, generating, regenerate } = useChangesWalkthrough()
const { walkthrough, generating, regenerate, sourcePending } = useChangesWalkthrough()
if (!walkthrough) return null
@@ -349,7 +360,7 @@ export const ChangesWalkthroughRegenerate = memo(function ChangesWalkthroughRege
size="icon-sm"
aria-label="Regenerate walkthrough"
onClick={regenerate}
disabled={generating}
disabled={generating || sourcePending}
>
<RefreshCw className={generating ? 'animate-spin' : undefined} />
</Button>
@@ -374,9 +385,21 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
detailRef,
failedStopCount,
source,
sourcePending,
} = useChangesWalkthrough()
const readyStopCount = stops.filter((stop) => stop.status === 'ready').length
const mechanicalHunks = selectedHunks.filter(isMechanicalHunk)
const diffHunks = selectedHunks.filter((hunk) => !isMechanicalHunk(hunk))
if (sourcePending) {
return (
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto p-4">
<WalkthroughSourcePicker />
<p className="text-sm text-muted-foreground">Enter a pull request number</p>
</div>
)
}
return (
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto p-4">
@@ -408,7 +431,7 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
generating ? null : (
<div className="space-y-4">
<p className="text-sm text-muted-foreground">
Generate a step-by-step walkthrough of {walkthroughSourceLabel(source)}.
Generate a step-by-step walkthrough of {describeWalkthroughSource(source)}.
</p>
<Button onClick={generate}>Generate walkthrough</Button>
</div>
@@ -481,7 +504,8 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
{generating ? 'Explaining this stop…' : 'This stop could not be explained.'}
</p>
)}
{selectedHunks.map((hunk) => (
{mechanicalHunks.length > 0 ? <MechanicalHunks hunks={mechanicalHunks} /> : null}
{diffHunks.map((hunk) => (
<div key={hunk.id} className="overflow-hidden rounded-md border border-border">
<div className="flex items-center gap-2 border-b border-border bg-muted/30 px-3 py-1.5">
<span className="min-w-0 flex-1 truncate text-xs font-medium text-foreground" title={hunk.file}>
@@ -519,7 +543,7 @@ export function ChangesWalkthroughSheet({ sessionId, open, onOpenChange }: Chang
return (
<SideDrawer isOpen={open} onClose={close} side="right" widthClass="w-full sm:w-[min(640px,92vw)]" ariaLabel="Change walkthrough">
<ChangesWalkthroughProvider sessionId={sessionId} active={open}>
<ChangesWalkthroughProvider key={sessionId} sessionId={sessionId} active={open}>
<SideDrawerHeader
title="Change walkthrough"
onClose={close}
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { useAutosavedSetting } from '@/hooks/useAutosavedSetting'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { ModelCombobox } from '@/components/model/ModelCombobox'
@@ -12,42 +13,37 @@ import {
type SessionPermissionMode,
} from '@opencode-manager/shared/schemas'
const AUTOSAVE_DELAY_MS = 800
interface GoalDraft {
goalAuditorModel: string
goalMaxContinuations: string
goalTokenBudget: string
}
interface GoalCommitted {
goalAuditorModel: string | undefined
goalMaxContinuations: number
goalTokenBudget: number | undefined
}
function maxContinuationsFromInput(value: string): number | null {
const parsed = Number(value)
if (!Number.isInteger(parsed)) return null
if (parsed < GOAL_MAX_CONTINUATIONS_MIN || parsed > GOAL_MAX_CONTINUATIONS_MAX) return null
return parsed
}
function tokenBudgetFromInput(value: string): { valid: boolean; value: number | undefined } {
const trimmed = value.trim()
if (trimmed === '') return { valid: true, value: undefined }
const parsed = Number(trimmed)
return Number.isInteger(parsed) && parsed > 0 ? { valid: true, value: parsed } : { valid: false, value: undefined }
}
export function SessionAutomationSettings() {
const { preferences, updateSettings } = useSettings()
const sessionDefaults = preferences?.sessionDefaults
const permissionMode = sessionDefaults?.permissionMode ?? DEFAULT_SESSION_DEFAULTS.permissionMode
const [goalAuditorModel, setGoalAuditorModel] = useState(sessionDefaults?.goalAuditorModel ?? '')
const [goalMaxContinuations, setGoalMaxContinuations] = useState(
String(sessionDefaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations),
)
const [goalTokenBudget, setGoalTokenBudget] = useState(
sessionDefaults?.goalTokenBudget !== undefined ? String(sessionDefaults.goalTokenBudget) : '',
)
const committed = useRef({
goalAuditorModel: sessionDefaults?.goalAuditorModel,
goalMaxContinuations: sessionDefaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations,
goalTokenBudget: sessionDefaults?.goalTokenBudget,
})
useEffect(() => {
setGoalAuditorModel(sessionDefaults?.goalAuditorModel ?? '')
setGoalMaxContinuations(
String(sessionDefaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations),
)
setGoalTokenBudget(
sessionDefaults?.goalTokenBudget !== undefined ? String(sessionDefaults.goalTokenBudget) : '',
)
committed.current = {
goalAuditorModel: sessionDefaults?.goalAuditorModel,
goalMaxContinuations: sessionDefaults?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations,
goalTokenBudget: sessionDefaults?.goalTokenBudget,
}
}, [sessionDefaults])
const updateSessionDefaults = useCallback(
(patch: Partial<SessionDefaults>) => {
updateSettings({
@@ -61,44 +57,46 @@ export function SessionAutomationSettings() {
[sessionDefaults, permissionMode, updateSettings],
)
const commitGoalFields = useCallback(() => {
const patch: Partial<SessionDefaults> = {}
const { draft, setDraft, commit: commitGoalFields } = useAutosavedSetting<SessionDefaults | undefined, GoalDraft, GoalCommitted>({
stored: sessionDefaults,
toDraft: (stored) => ({
goalAuditorModel: stored?.goalAuditorModel ?? '',
goalMaxContinuations: String(stored?.goalMaxContinuations ?? DEFAULT_SESSION_DEFAULTS.goalMaxContinuations),
goalTokenBudget: stored?.goalTokenBudget !== undefined ? String(stored.goalTokenBudget) : '',
}),
toCommitted: (current, previous) => {
const budget = tokenBudgetFromInput(current.goalTokenBudget)
return {
goalAuditorModel: current.goalAuditorModel.trim() || undefined,
goalMaxContinuations:
maxContinuationsFromInput(current.goalMaxContinuations) ??
previous?.goalMaxContinuations ??
DEFAULT_SESSION_DEFAULTS.goalMaxContinuations,
goalTokenBudget: budget.valid ? budget.value : previous?.goalTokenBudget,
}
},
isEqual: (a, b) =>
a.goalAuditorModel === b.goalAuditorModel &&
a.goalMaxContinuations === b.goalMaxContinuations &&
a.goalTokenBudget === b.goalTokenBudget,
save: (next, previous) => {
const patch: Partial<SessionDefaults> = {}
if (next.goalAuditorModel !== previous?.goalAuditorModel) patch.goalAuditorModel = next.goalAuditorModel
if (next.goalMaxContinuations !== previous?.goalMaxContinuations) {
patch.goalMaxContinuations = next.goalMaxContinuations
}
if (next.goalTokenBudget !== previous?.goalTokenBudget) patch.goalTokenBudget = next.goalTokenBudget
if (Object.keys(patch).length === 0) return
updateSessionDefaults(patch)
},
})
const nextAuditorModel = goalAuditorModel.trim() || undefined
if (nextAuditorModel !== committed.current.goalAuditorModel) {
committed.current.goalAuditorModel = nextAuditorModel
patch.goalAuditorModel = nextAuditorModel
}
const nextMaxContinuations = Number(goalMaxContinuations)
if (
Number.isInteger(nextMaxContinuations) &&
nextMaxContinuations >= GOAL_MAX_CONTINUATIONS_MIN &&
nextMaxContinuations <= GOAL_MAX_CONTINUATIONS_MAX &&
nextMaxContinuations !== committed.current.goalMaxContinuations
) {
committed.current.goalMaxContinuations = nextMaxContinuations
patch.goalMaxContinuations = nextMaxContinuations
}
const nextTokenBudget = goalTokenBudget.trim() === '' ? undefined : Number(goalTokenBudget)
const tokenBudgetValid = nextTokenBudget === undefined || (Number.isInteger(nextTokenBudget) && nextTokenBudget > 0)
if (tokenBudgetValid && nextTokenBudget !== committed.current.goalTokenBudget) {
committed.current.goalTokenBudget = nextTokenBudget
patch.goalTokenBudget = nextTokenBudget
}
if (Object.keys(patch).length === 0) return
updateSessionDefaults(patch)
}, [goalAuditorModel, goalMaxContinuations, goalTokenBudget, updateSessionDefaults])
useEffect(() => {
const timer = setTimeout(() => {
commitGoalFields()
}, AUTOSAVE_DELAY_MS)
return () => clearTimeout(timer)
}, [commitGoalFields])
const updateGoalDraft = useCallback(
(patch: Partial<GoalDraft>) => {
setDraft((current) => ({ ...current, ...patch }))
},
[setDraft],
)
return (
<div className="space-y-6">
@@ -135,8 +133,8 @@ export function SessionAutomationSettings() {
<ModelCombobox
id="goalAuditorModel"
ariaLabel="Goal auditor model"
value={goalAuditorModel}
onChange={setGoalAuditorModel}
value={draft.goalAuditorModel}
onChange={(value) => updateGoalDraft({ goalAuditorModel: value })}
placeholder="OpenCode default"
allowCustomValue
showClear
@@ -156,9 +154,9 @@ export function SessionAutomationSettings() {
type="number"
min={GOAL_MAX_CONTINUATIONS_MIN}
max={GOAL_MAX_CONTINUATIONS_MAX}
value={goalMaxContinuations}
value={draft.goalMaxContinuations}
className="w-full shrink-0 sm:w-40"
onChange={(event) => setGoalMaxContinuations(event.target.value)}
onChange={(event) => updateGoalDraft({ goalMaxContinuations: event.target.value })}
onBlur={commitGoalFields}
/>
</div>
@@ -174,10 +172,10 @@ export function SessionAutomationSettings() {
id="goalTokenBudget"
type="number"
min={1}
value={goalTokenBudget}
value={draft.goalTokenBudget}
placeholder="No limit"
className="w-full shrink-0 sm:w-40"
onChange={(event) => setGoalTokenBudget(event.target.value)}
onChange={(event) => updateGoalDraft({ goalTokenBudget: event.target.value })}
onBlur={commitGoalFields}
/>
</div>
@@ -138,4 +138,17 @@ describe('WalkthroughSettings', () => {
vi.useRealTimers()
}
})
it('keeps the OpenCode default as a selectable model when the field is unset', () => {
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: 'anthropic/claude-sonnet-4' })
mockUseSettings()
render(<WalkthroughSettings />)
const input = screen.getByLabelText('Walkthrough model')
expect(input).toHaveValue('')
fireEvent.focus(input)
expect(screen.getByRole('option', { name: /Claude Sonnet 4/ })).toBeInTheDocument()
expect(screen.queryByRole('option', { name: /^Default:/ })).not.toBeInTheDocument()
})
})
@@ -1,36 +1,19 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { useAutosavedSetting } from '@/hooks/useAutosavedSetting'
import { Label } from '@/components/ui/label'
import { ModelCombobox } from '@/components/model/ModelCombobox'
const AUTOSAVE_DELAY_MS = 800
export function WalkthroughSettings() {
const { preferences, updateSettings } = useSettings()
const storedWalkthroughModel = preferences?.walkthroughModel
const [walkthroughModel, setWalkthroughModel] = useState(storedWalkthroughModel ?? '')
const committed = useRef(storedWalkthroughModel)
useEffect(() => {
setWalkthroughModel(storedWalkthroughModel ?? '')
committed.current = storedWalkthroughModel
}, [storedWalkthroughModel])
const commitWalkthroughModel = useCallback(() => {
const next = walkthroughModel.trim()
if (next === (committed.current ?? '')) return
committed.current = next
updateSettings({ walkthroughModel: next })
}, [walkthroughModel, updateSettings])
useEffect(() => {
const timer = setTimeout(() => {
commitWalkthroughModel()
}, AUTOSAVE_DELAY_MS)
return () => clearTimeout(timer)
}, [commitWalkthroughModel])
const { draft: walkthroughModel, setDraft: setWalkthroughModel } = useAutosavedSetting({
stored: storedWalkthroughModel,
toDraft: (stored) => stored ?? '',
toCommitted: (draft) => draft.trim(),
isEqual: (a, b) => a === b,
save: (next) => updateSettings({ walkthroughModel: next }),
})
return (
<div className="space-y-6">
@@ -51,6 +34,7 @@ export function WalkthroughSettings() {
placeholder="Session model"
allowCustomValue
showClear
emptyMeansDefault={false}
className="w-full shrink-0 sm:w-64"
/>
</div>
@@ -0,0 +1,55 @@
import { renderHook, act } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { useAutosavedSetting } from './useAutosavedSetting'
function renderTrimmedSetting(stored: string | undefined, save: (next: string, previous: string | undefined) => void) {
return renderHook(
({ value }: { value: string | undefined }) =>
useAutosavedSetting<string | undefined, string, string>({
stored: value,
toDraft: (draftStored) => draftStored ?? '',
toCommitted: (draft) => draft.trim(),
isEqual: (a, b) => a === b,
save,
}),
{ initialProps: { value: stored } },
)
}
describe('useAutosavedSetting', () => {
it('saves the normalized value once after the debounce', () => {
vi.useFakeTimers()
try {
const save = vi.fn()
const { result } = renderTrimmedSetting(undefined, save)
act(() => result.current.setDraft(' anthropic/claude '))
act(() => {
vi.advanceTimersByTime(800)
})
expect(save).toHaveBeenCalledTimes(1)
expect(save).toHaveBeenCalledWith('anthropic/claude', '')
} finally {
vi.useRealTimers()
}
})
it('skips an unchanged value and resyncs from the stored value', () => {
const save = vi.fn()
const { result, rerender } = renderTrimmedSetting('a', save)
act(() => result.current.commit())
expect(save).not.toHaveBeenCalled()
act(() => result.current.setDraft('b'))
act(() => result.current.commit())
expect(save).toHaveBeenCalledWith('b', 'a')
rerender({ value: 'c' })
expect(result.current.draft).toBe('c')
act(() => result.current.commit())
expect(save).toHaveBeenCalledTimes(1)
})
})
+74
View File
@@ -0,0 +1,74 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { Dispatch, SetStateAction } from 'react'
import { useDebouncedValue } from './useDebouncedValue'
export const AUTOSAVE_DELAY_MS = 800
interface AutosavedSettingHandlers<TStored, TDraft, TCommitted> {
toDraft: (stored: TStored) => TDraft
toCommitted: (draft: TDraft, previous: TCommitted | undefined) => TCommitted
isEqual: (a: TCommitted, b: TCommitted) => boolean
save: (next: TCommitted, previous: TCommitted | undefined) => void
}
interface UseAutosavedSettingOptions<TStored, TDraft, TCommitted>
extends AutosavedSettingHandlers<TStored, TDraft, TCommitted> {
stored: TStored
delayMs?: number
}
interface UseAutosavedSettingResult<TDraft> {
draft: TDraft
setDraft: Dispatch<SetStateAction<TDraft>>
commit: () => void
}
export function useAutosavedSetting<TStored, TDraft, TCommitted>({
stored,
toDraft,
toCommitted,
isEqual,
save,
delayMs = AUTOSAVE_DELAY_MS,
}: UseAutosavedSettingOptions<TStored, TDraft, TCommitted>): UseAutosavedSettingResult<TDraft> {
const handlers = useRef<AutosavedSettingHandlers<TStored, TDraft, TCommitted>>({
toDraft,
toCommitted,
isEqual,
save,
})
useEffect(() => {
handlers.current = { toDraft, toCommitted, isEqual, save }
})
const [draft, setDraft] = useState<TDraft>(() => toDraft(stored))
const committed = useRef<TCommitted>(toCommitted(draft, undefined))
useEffect(() => {
const nextDraft = handlers.current.toDraft(stored)
setDraft(nextDraft)
committed.current = handlers.current.toCommitted(nextDraft, committed.current)
}, [stored])
const commitDraft = useCallback((value: TDraft) => {
const { toCommitted: normalize, isEqual: equal, save: persist } = handlers.current
const next = normalize(value, committed.current)
if (equal(next, committed.current)) return
const previous = committed.current
committed.current = next
persist(next, previous)
}, [])
const debouncedDraft = useDebouncedValue(draft, delayMs)
useEffect(() => {
commitDraft(debouncedDraft)
}, [commitDraft, debouncedDraft])
const commit = useCallback(() => {
commitDraft(draft)
}, [commitDraft, draft])
return { draft, setDraft, commit }
}
@@ -3,8 +3,12 @@ import { act, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { changeWalkthroughQueryKey, useChangeWalkthrough, useGenerateChangeWalkthrough } from './useChangeWalkthrough'
import { DEFAULT_WALKTHROUGH_SOURCE } from '@opencode-manager/shared/schemas'
import type { ChangeWalkthrough, ChangeWalkthroughState } from '@opencode-manager/shared/schemas'
import { DEFAULT_WALKTHROUGH_SOURCE, walkthroughHunksIdentity } from '@opencode-manager/shared/schemas'
import type {
ChangeWalkthrough,
ChangeWalkthroughState,
ChangeWalkthroughStateWire,
} from '@opencode-manager/shared/schemas'
const mocks = vi.hoisted(() => ({
getChangeWalkthrough: vi.fn(),
@@ -116,6 +120,53 @@ describe('useChangeWalkthrough', () => {
}
})
it('merges cached hunks when the server omits them for a matching identity', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
try {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const walkthroughWithHunks: ChangeWalkthrough = {
...walkthroughForA,
hunks: [
{
id: 'h_1',
file: 'src/a.ts',
status: 'modified',
header: '@@ -1 +1 @@',
text: '@@ -1 +1 @@\n-a\n+b',
truncated: false,
},
],
}
const compact: ChangeWalkthroughStateWire = {
...state({ generating: true }),
walkthrough: { ...walkthroughWithHunks, hunks: undefined },
}
mocks.getChangeWalkthrough
.mockResolvedValueOnce(state({ walkthrough: walkthroughWithHunks, generating: true }))
.mockResolvedValueOnce(compact)
const { result } = renderHook(() => useChangeWalkthrough('ses_A', true, DEFAULT_WALKTHROUGH_SOURCE), {
wrapper: createWrapper(queryClient),
})
await waitFor(() => expect(result.current.data?.walkthrough?.hunks).toHaveLength(1))
await act(async () => {
await vi.advanceTimersByTimeAsync(2_000)
})
await waitFor(() => expect(mocks.getChangeWalkthrough).toHaveBeenCalledTimes(2))
expect(mocks.getChangeWalkthrough).toHaveBeenLastCalledWith(
'ses_A',
DEFAULT_WALKTHROUGH_SOURCE,
walkthroughHunksIdentity(walkthroughWithHunks),
)
expect(result.current.data?.walkthrough).toEqual(walkthroughWithHunks)
} finally {
vi.useRealTimers()
}
})
it('invalidating the session key refetches every source', async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
mocks.getChangeWalkthrough.mockResolvedValue(state())
+44 -4
View File
@@ -1,7 +1,14 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { generateChangeWalkthrough, getChangeWalkthrough } from '@/api/changeWalkthroughs'
import { walkthroughSourceKey } from '@opencode-manager/shared/schemas'
import type { GenerateChangeWalkthroughRequest, WalkthroughSource } from '@opencode-manager/shared/schemas'
import { walkthroughHunksIdentity, walkthroughSourceKey } from '@opencode-manager/shared/schemas'
import type {
ChangeWalkthrough,
ChangeWalkthroughState,
ChangeWalkthroughStateWire,
ChangeWalkthroughWire,
GenerateChangeWalkthroughRequest,
WalkthroughSource,
} from '@opencode-manager/shared/schemas'
const GENERATING_POLL_INTERVAL_MS = 2_000
@@ -11,15 +18,48 @@ export function changeWalkthroughQueryKey(sessionId: string, sourceKey?: string)
: (['change-walkthrough', sessionId, sourceKey] as const)
}
function isCompleteWalkthrough(walkthrough: ChangeWalkthroughWire): walkthrough is ChangeWalkthrough {
return walkthrough.hunks !== undefined
}
function mergeChangeWalkthroughState(
state: ChangeWalkthroughStateWire,
cached: ChangeWalkthrough | null,
): ChangeWalkthroughState {
const incoming = state.walkthrough
if (!incoming) {
return { ...state, walkthrough: null }
}
if (isCompleteWalkthrough(incoming)) {
return { ...state, walkthrough: incoming }
}
const hunks =
cached && walkthroughHunksIdentity(cached) === walkthroughHunksIdentity(incoming)
? cached.hunks
: []
return { ...state, walkthrough: { ...incoming, hunks } }
}
export function useChangeWalkthrough(
sessionId: string | undefined,
enabled: boolean,
source: WalkthroughSource,
) {
const sourceKey = walkthroughSourceKey(source)
const queryClient = useQueryClient()
const queryKey = changeWalkthroughQueryKey(sessionId ?? '', sourceKey)
return useQuery({
queryKey: changeWalkthroughQueryKey(sessionId ?? '', sourceKey),
queryFn: () => getChangeWalkthrough(sessionId!, source),
queryKey,
queryFn: async () => {
const cached = queryClient.getQueryData<ChangeWalkthroughState>(queryKey)
const cachedWalkthrough = cached?.walkthrough ?? null
const hunksFor = cachedWalkthrough ? walkthroughHunksIdentity(cachedWalkthrough) : undefined
const state =
hunksFor === undefined
? await getChangeWalkthrough(sessionId!, source)
: await getChangeWalkthrough(sessionId!, source, hunksFor)
return mergeChangeWalkthroughState(state, cachedWalkthrough)
},
enabled: enabled && !!sessionId,
staleTime: 30_000,
refetchInterval: (query) => (query.state.data?.generating ? GENERATING_POLL_INTERVAL_MS : false),
+87 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { parseDiffLines, splitDiffHunks, splitUnifiedDiffByFile } from '@opencode-manager/shared/utils';
import { countDiffLineChanges, parseDiffLines, splitDiffHunks, splitUnifiedDiffByFile } from '@opencode-manager/shared/utils';
const DIFF = [
'diff --git a/src/app.ts b/src/app.ts',
@@ -88,6 +88,31 @@ describe('parseDiffLines', () => {
});
});
describe('countDiffLineChanges', () => {
it('counts additions and removals across hunks', () => {
expect(countDiffLineChanges(DIFF)).toEqual({ added: 3, removed: 2 });
});
it('counts changed lines whose content starts with -- or ++', () => {
const diff = '@@ -1,3 +1,3 @@\n--- old comment\n+++ heading\n const a = 1;';
expect(countDiffLineChanges(diff)).toEqual({ added: 1, removed: 1 });
});
it('ignores file headers before a hunk', () => {
const diff = '--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b';
expect(countDiffLineChanges(diff)).toEqual({ added: 1, removed: 1 });
});
it('returns zero for a patch with no changed lines', () => {
expect(countDiffLineChanges('diff --git a/x b/x\nold mode 100644\nnew mode 100755')).toEqual({
added: 0,
removed: 0,
});
});
});
describe('splitDiffHunks', () => {
it('returns one entry per hunk with the header line and body', () => {
const hunks = splitDiffHunks(DIFF);
@@ -127,6 +152,21 @@ describe('splitUnifiedDiffByFile', () => {
expect(result[0]!.patch.startsWith('diff --git a/src/app.ts b/src/app.ts')).toBe(true);
});
it('counts changed lines whose content starts with -- or ++', () => {
const diff = [
'diff --git a/src/a.sql b/src/a.sql',
'--- a/src/a.sql',
'+++ b/src/a.sql',
'@@ -1,2 +1,2 @@',
'--- old comment',
'+++ heading',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'src/a.sql', status: 'modified', additions: 1, deletions: 1 });
});
it('reads an added file from the new side', () => {
const diff = [
'diff --git a/src/new.ts b/src/new.ts',
@@ -174,6 +214,52 @@ describe('splitUnifiedDiffByFile', () => {
expect(file).toMatchObject({ file: 'src/new.ts', status: 'modified', additions: 0, deletions: 0 });
});
it('reads a mode-only change path from a mnemonic diff header', () => {
const diff = [
'diff --git i/script.sh w/script.sh',
'old mode 100644',
'new mode 100755',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'script.sh', status: 'modified', additions: 0, deletions: 0 });
});
it('reads a mode-only change path from a prefix-less diff header', () => {
const diff = [
'diff --git script.sh script.sh',
'old mode 100644',
'new mode 100755',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'script.sh', status: 'modified' });
});
it('keeps a combined merge-conflict block instead of dropping it', () => {
const diff = [
'diff --cc f.txt',
'index d791e9b,00dbdcf..0000000',
'--- a/f.txt',
'+++ b/f.txt',
'@@@ -1,3 -1,3 +1,7 @@@',
' line1',
'++<<<<<<< HEAD',
' +MAIN',
'++=======',
'+ FEATURE',
'++>>>>>>> feat',
' line3',
].join('\n');
const [file] = splitUnifiedDiffByFile(diff);
expect(file).toMatchObject({ file: 'f.txt', status: 'modified' });
expect(file!.patch.startsWith('diff --cc f.txt')).toBe(true);
});
it('keeps a binary block with no hunks', () => {
const diff = [
'diff --git a/assets/logo.png b/assets/logo.png',
+55 -15
View File
@@ -1,21 +1,21 @@
import { z } from "zod";
import { gitRefSchema } from './git'
export const WALKTHROUGH_DIFF_MAX_CHARS = 60000;
export const WALKTHROUGH_HUNK_MAX_CHARS = 8000;
export const MECHANICAL_TEXT_BUDGET = 20000;
export const WALKTHROUGH_MAX_STOPS = 20;
export const WALKTHROUGH_TEXT_MAX_CHARS = 2000;
export const WALKTHROUGH_OUTLINE_PREVIEW_LINES = 6;
export const WALKTHROUGH_OUTLINE_LINE_MAX_CHARS = 160;
export const GitRefSchema = z.string().trim().min(1).max(200).regex(/^[^-\s][^\s]*$/)
export const WalkthroughSourceSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('session') }),
z.object({ kind: z.literal('uncommitted') }),
z.object({ kind: z.literal('staged') }),
z.object({ kind: z.literal('unstaged') }),
z.object({ kind: z.literal('branch'), base: GitRefSchema.optional() }),
z.object({ kind: z.literal('pullRequest'), number: z.number().int().positive(), base: GitRefSchema.optional() }),
z.object({ kind: z.literal('branch'), base: gitRefSchema.optional() }),
z.object({ kind: z.literal('pullRequest'), number: z.number().int().positive(), base: gitRefSchema.optional() }),
])
export type WalkthroughSource = z.infer<typeof WalkthroughSourceSchema>
@@ -39,7 +39,7 @@ export function walkthroughSourceKey(source: WalkthroughSource): string {
export function describeWalkthroughSource(source: WalkthroughSource): string {
switch (source.kind) {
case 'session':
return 'session changes'
return 'the changes in this session'
case 'uncommitted':
return 'uncommitted changes'
case 'staged':
@@ -53,13 +53,35 @@ export function describeWalkthroughSource(source: WalkthroughSource): string {
}
}
export function toWalkthroughSource(candidate: {
kind: WalkthroughSource['kind']
base?: string
number?: number
}): WalkthroughSource | null {
const base = candidate.base?.trim()
switch (candidate.kind) {
case 'session':
case 'uncommitted':
case 'staged':
case 'unstaged':
return { kind: candidate.kind }
case 'branch':
return parseWalkthroughSourceCandidate(base ? { kind: 'branch', base } : { kind: 'branch' })
case 'pullRequest':
return parseWalkthroughSourceCandidate(
base
? { kind: 'pullRequest', number: candidate.number, base }
: { kind: 'pullRequest', number: candidate.number },
)
}
}
export function parseWalkthroughSourceKey(key: string): WalkthroughSource | null {
if (key === 'session' || key === 'uncommitted' || key === 'staged' || key === 'unstaged') {
return { kind: key }
}
if (key.startsWith('branch:')) {
const base = key.slice('branch:'.length)
return parseWalkthroughSourceCandidate(base ? { kind: 'branch', base } : { kind: 'branch' })
return toWalkthroughSource({ kind: 'branch', base: key.slice('branch:'.length) })
}
if (key.startsWith('pr:')) {
const rest = key.slice('pr:'.length)
@@ -67,11 +89,11 @@ export function parseWalkthroughSourceKey(key: string): WalkthroughSource | null
if (separator < 0) {
return null
}
const number = Number(rest.slice(0, separator))
const base = rest.slice(separator + 1)
return parseWalkthroughSourceCandidate(
base ? { kind: 'pullRequest', number, base } : { kind: 'pullRequest', number },
)
return toWalkthroughSource({
kind: 'pullRequest',
number: Number(rest.slice(0, separator)),
base: rest.slice(separator + 1),
})
}
return null
}
@@ -88,6 +110,8 @@ export const WalkthroughHunkSchema = z.object({
header: z.string(),
text: z.string(),
truncated: z.boolean(),
additions: z.number().int().nonnegative().optional(),
deletions: z.number().int().nonnegative().optional(),
});
export type WalkthroughHunk = z.infer<typeof WalkthroughHunkSchema>;
@@ -103,11 +127,9 @@ export const WalkthroughStopSchema = z.object({
export type WalkthroughStop = z.infer<typeof WalkthroughStopSchema>;
export type WalkthroughStopStatus = WalkthroughStop["status"];
export const WalkthroughOmittedFileSchema = z.object({
file: z.string(),
reason: z.enum(["binary", "budget"]),
reason: z.enum(["binary", "budget", "renamed", "modeChange"]),
});
export type WalkthroughOmittedFile = z.infer<typeof WalkthroughOmittedFileSchema>;
@@ -144,6 +166,24 @@ export const ChangeWalkthroughStateSchema = z.object({
export type ChangeWalkthroughState = z.infer<typeof ChangeWalkthroughStateSchema>;
export const ChangeWalkthroughWireSchema = ChangeWalkthroughSchema.extend({
hunks: z.array(WalkthroughHunkSchema).optional(),
});
export type ChangeWalkthroughWire = z.infer<typeof ChangeWalkthroughWireSchema>;
export const ChangeWalkthroughStateWireSchema = ChangeWalkthroughStateSchema.extend({
walkthrough: ChangeWalkthroughWireSchema.nullable(),
});
export type ChangeWalkthroughStateWire = z.infer<typeof ChangeWalkthroughStateWireSchema>;
export function walkthroughHunksIdentity(
walkthrough: Pick<ChangeWalkthrough, 'diffHash' | 'createdAt'>,
): string {
return `${walkthrough.diffHash}:${walkthrough.createdAt}`
}
export const GenerateChangeWalkthroughRequestSchema = z.object({
regenerate: z.boolean().optional(),
source: WalkthroughSourceSchema.optional(),
+12 -2
View File
@@ -1,12 +1,22 @@
import { z } from 'zod'
import { getBranchNameError } from '../utils/repo'
const branchNameSchema = z.string().trim().superRefine((value, ctx) => {
function addBranchNameIssue(value: string, ctx: z.RefinementCtx) {
const error = getBranchNameError(value)
if (error) {
ctx.addIssue({ code: 'custom', message: error })
}
})
}
const branchNameSchema = z.string().trim().superRefine(addBranchNameIssue)
export const gitRefSchema = z
.string()
.trim()
.min(1)
.max(200)
.regex(/^\S+$/)
.superRefine(addBranchNameIssue)
export const RenameBranchRequestSchema = z.object({
from: branchNameSchema,
+51 -33
View File
@@ -1,3 +1,5 @@
import type { FileDiffInfo } from '../opencode'
export interface DiffLine {
type: "add" | "remove" | "context" | "header" | "hunk";
content: string;
@@ -90,6 +92,19 @@ export function parseDiffLines(diff: string): DiffLine[] {
return result;
}
export function countDiffLineChanges(text: string): { added: number; removed: number } {
let added = 0;
let removed = 0;
for (const line of parseDiffLines(text)) {
if (line.type === "add") {
added += 1;
} else if (line.type === "remove") {
removed += 1;
}
}
return { added, removed };
}
export function splitDiffHunks(patch: string): DiffHunk[] {
const hunks: DiffHunk[] = [];
let current: string[] | null = null;
@@ -116,19 +131,11 @@ function toHunk(lines: string[]): DiffHunk {
return { header: lines[0]!, text: lines.join("\n") };
}
export interface UnifiedFileDiff {
file: string;
status: "added" | "deleted" | "modified";
patch: string;
additions: number;
deletions: number;
}
export function splitUnifiedDiffByFile(diff: string): UnifiedFileDiff[] {
export function splitUnifiedDiffByFile(diff: string): FileDiffInfo[] {
const blocks: string[][] = [];
for (const line of diff.split("\n")) {
if (line.startsWith("diff --git ")) {
if (line.startsWith("diff --git ") || line.startsWith("diff --cc ") || line.startsWith("diff --combined ")) {
blocks.push([line]);
} else if (blocks.length > 0) {
blocks[blocks.length - 1]!.push(line);
@@ -138,15 +145,13 @@ export function splitUnifiedDiffByFile(diff: string): UnifiedFileDiff[] {
return blocks.map((lines) => toUnifiedFileDiff(lines));
}
function toUnifiedFileDiff(lines: string[]): UnifiedFileDiff {
function toUnifiedFileDiff(lines: string[]): FileDiffInfo {
const header = lines[0]!;
const newPath = lines.find((line) => line.startsWith("+++ "));
const oldPath = lines.find((line) => line.startsWith("--- "));
const renameTo = lines.find((line) => line.startsWith("rename to "));
let file = "";
let status: UnifiedFileDiff["status"] = "modified";
let additions = 0;
let deletions = 0;
let status: FileDiffInfo["status"] = "modified";
if (newPath && newPath.slice(4) !== "/dev/null") {
file = parseDiffPathToken(newPath.slice(4), "b/");
@@ -164,19 +169,12 @@ function toUnifiedFileDiff(lines: string[]): UnifiedFileDiff {
} else if (line.startsWith("deleted file mode")) {
status = "deleted";
}
if (line.startsWith("+++") || line.startsWith("---")) {
continue;
}
if (line.startsWith("+")) {
additions++;
} else if (line.startsWith("-")) {
deletions++;
}
}
return { file, status, patch: lines.join("\n"), additions, deletions };
const patch = lines.join("\n");
const { added: additions, removed: deletions } = countDiffLineChanges(patch);
return { file, status, patch, additions, deletions };
}
function stripDiffPathPrefix(path: string, prefix: string): string {
@@ -234,30 +232,50 @@ function decodeGitQuotedPath(raw: string): string {
}
function newPathFromDiffHeader(header: string): string {
const rest = header.slice("diff --git ".length);
const match = /^diff --(?:git|cc|combined) (.*)$/.exec(header);
const rest = match ? match[1]! : "";
if (rest.startsWith('"')) {
const end = findClosingQuote(rest);
const end = findClosingQuoteFrom(rest, 0);
if (end >= 0) {
let index = end + 1;
while (rest[index] === " ") {
index += 1;
}
return parseDiffPathToken(rest.slice(index), "b/");
return stripKnownDiffPrefix(parseDiffPathToken(rest.slice(index), ""));
}
}
const quoted = rest.indexOf(' "');
if (quoted >= 0) {
return parseDiffPathToken(rest.slice(quoted + 1), "b/");
return stripKnownDiffPrefix(parseDiffPathToken(rest.slice(quoted + 1), ""));
}
const index = rest.lastIndexOf(" b/");
return index >= 0 ? parseDiffPathToken(rest.slice(index + 1), "b/") : "";
for (const prefix of GIT_DIFF_DEST_PREFIXES) {
const index = rest.lastIndexOf(prefix);
if (index >= 0) {
return parseDiffPathToken(rest.slice(index + 1), prefix.trim());
}
}
const lastSpace = rest.lastIndexOf(" ");
return lastSpace >= 0 ? rest.slice(lastSpace + 1) : rest;
}
function findClosingQuote(raw: string): number {
for (let index = 1; index < raw.length; index += 1) {
const GIT_DIFF_DEST_PREFIXES = [" b/", " w/", " 2/", " 3/", " i/", " c/", " o/", " 1/", " a/"];
const GIT_DIFF_PREFIXES = ["a/", "b/", "i/", "w/", "c/", "o/", "1/", "2/", "3/"];
function stripKnownDiffPrefix(path: string): string {
for (const prefix of GIT_DIFF_PREFIXES) {
if (path.startsWith(prefix)) {
return path.slice(prefix.length);
}
}
return path;
}
function findClosingQuoteFrom(raw: string, start: number): number {
for (let index = start + 1; index < raw.length; index += 1) {
if (raw[index] === "\\") {
index += 1;
continue;