mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Merge pull request #407 from chriswritescode-dev/feat/walkthrough-plan-explain
feat(walkthrough): plan-then-explain generation with selectable diff sources
This commit is contained in:
46 files changed
+5780
-496
No files matched your search
@@ -1,8 +1,13 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { ChangeWalkthroughSchema, type ChangeWalkthrough } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
ChangeWalkthroughSchema,
|
||||
walkthroughSourceKey,
|
||||
type ChangeWalkthrough,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
interface ChangeWalkthroughRow {
|
||||
session_id: string
|
||||
source_key: string
|
||||
diff_hash: string
|
||||
payload: string
|
||||
created_at: number
|
||||
@@ -19,10 +24,16 @@ export function ensureChangeWalkthroughTable(db: Database): void {
|
||||
`)
|
||||
}
|
||||
|
||||
export function getChangeWalkthrough(db: Database, sessionId: string): ChangeWalkthrough | null {
|
||||
export function getChangeWalkthrough(
|
||||
db: Database,
|
||||
sessionId: string,
|
||||
sourceKey: string,
|
||||
): ChangeWalkthrough | null {
|
||||
const row = db
|
||||
.prepare('SELECT session_id, diff_hash, payload, created_at FROM change_walkthroughs WHERE session_id = ?')
|
||||
.get(sessionId) as ChangeWalkthroughRow | undefined
|
||||
.prepare(
|
||||
'SELECT session_id, source_key, diff_hash, payload, created_at FROM change_walkthroughs WHERE session_id = ? AND source_key = ?',
|
||||
)
|
||||
.get(sessionId, sourceKey) as ChangeWalkthroughRow | undefined
|
||||
if (!row) {
|
||||
return null
|
||||
}
|
||||
@@ -33,17 +44,24 @@ export function getChangeWalkthrough(db: Database, sessionId: string): ChangeWal
|
||||
}
|
||||
}
|
||||
|
||||
export function deleteChangeWalkthrough(db: Database, sessionId: string): void {
|
||||
export function deleteChangeWalkthroughs(db: Database, sessionId: string): void {
|
||||
db.prepare('DELETE FROM change_walkthroughs WHERE session_id = ?').run(sessionId)
|
||||
}
|
||||
|
||||
export function saveChangeWalkthrough(db: Database, walkthrough: ChangeWalkthrough): void {
|
||||
const sourceKey = walkthroughSourceKey(walkthrough.source)
|
||||
db.prepare(`
|
||||
INSERT INTO change_walkthroughs(session_id, diff_hash, payload, created_at)
|
||||
VALUES(?,?,?,?)
|
||||
ON CONFLICT(session_id) DO UPDATE SET
|
||||
INSERT INTO change_walkthroughs(session_id, source_key, diff_hash, payload, created_at)
|
||||
VALUES(?,?,?,?,?)
|
||||
ON CONFLICT(session_id, source_key) DO UPDATE SET
|
||||
diff_hash = excluded.diff_hash,
|
||||
payload = excluded.payload,
|
||||
created_at = excluded.created_at
|
||||
`).run(walkthrough.sessionId, walkthrough.diffHash, JSON.stringify(walkthrough), walkthrough.createdAt)
|
||||
`).run(
|
||||
walkthrough.sessionId,
|
||||
sourceKey,
|
||||
walkthrough.diffHash,
|
||||
JSON.stringify(walkthrough),
|
||||
walkthrough.createdAt,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { Migration } from '../migration-runner'
|
||||
|
||||
const migration: Migration = {
|
||||
id: '202610081200-change-walkthrough-sources',
|
||||
up(db) {
|
||||
const columns = db.prepare('PRAGMA table_info(change_walkthroughs)').all() as Array<{ name: string }>
|
||||
if (columns.some((column) => column.name === 'source_key')) {
|
||||
return
|
||||
}
|
||||
|
||||
db.run('DROP TABLE IF EXISTS change_walkthroughs')
|
||||
db.run(`
|
||||
CREATE TABLE change_walkthroughs (
|
||||
session_id TEXT NOT NULL,
|
||||
source_key TEXT NOT NULL,
|
||||
diff_hash TEXT NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (session_id, source_key)
|
||||
)
|
||||
`)
|
||||
},
|
||||
down(db) {
|
||||
db.run('DROP TABLE IF EXISTS change_walkthroughs')
|
||||
},
|
||||
}
|
||||
|
||||
export default migration
|
||||
@@ -29,6 +29,7 @@ import migration027 from './027-multi-runs'
|
||||
import migration202610061345 from './202610061345-schedule-workspace-mode'
|
||||
import migration202610061700 from './202610061700-multi-run-fusions'
|
||||
import migration202610061701 from './202610061701-change-walkthroughs'
|
||||
import migration202610081200 from './202610081200-change-walkthrough-sources'
|
||||
|
||||
export const allMigrations: Migration[] = [
|
||||
migration001,
|
||||
@@ -61,4 +62,5 @@ export const allMigrations: Migration[] = [
|
||||
migration202610061345,
|
||||
migration202610061700,
|
||||
migration202610061701,
|
||||
migration202610081200,
|
||||
]
|
||||
@@ -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)
|
||||
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService, gitAuthService, gitService)
|
||||
|
||||
sseAggregator.onEvent((directory, event) => {
|
||||
sessionPermissionModeService.handleEvent(directory, event).catch((err) => {
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { Hono } from 'hono'
|
||||
import { GenerateChangeWalkthroughRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
DEFAULT_WALKTHROUGH_SOURCE,
|
||||
GenerateChangeWalkthroughRequestSchema,
|
||||
parseWalkthroughSourceKey,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type { ChangeWalkthroughService } from '../services/change-walkthroughs'
|
||||
import { handleServiceError, parseJsonBody } from '../utils/route-helpers'
|
||||
import { ServiceError } from '../utils/service-error'
|
||||
@@ -8,8 +12,15 @@ export function createChangeWalkthroughRoutes(service: ChangeWalkthroughService)
|
||||
const app = new Hono()
|
||||
|
||||
app.get('/:sessionId', async (c) => {
|
||||
const sourceParam = c.req.query('source')
|
||||
const source = sourceParam === undefined ? DEFAULT_WALKTHROUGH_SOURCE : parseWalkthroughSourceKey(sourceParam)
|
||||
if (!source) {
|
||||
return c.json({ error: 'Invalid walkthrough source' }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
const state = await service.getState(c.req.param('sessionId'))
|
||||
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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ServiceError } from '../utils/service-error'
|
||||
|
||||
export class ChangeWalkthroughError extends ServiceError {
|
||||
constructor(message: string, status: number, options?: { code?: string; details?: unknown }) {
|
||||
super(message, status, options)
|
||||
this.name = 'ChangeWalkthroughError'
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -738,6 +738,26 @@ export class GitService {
|
||||
)
|
||||
}
|
||||
|
||||
async fetchRemoteRef(
|
||||
repo: { id?: number; repoUrl?: string; fullPath: string },
|
||||
remote: string,
|
||||
refspecs: string[],
|
||||
database: Database,
|
||||
timeoutMs?: number,
|
||||
): Promise<void> {
|
||||
await this.withRemoteAuth(
|
||||
repo,
|
||||
async (env) => {
|
||||
await executeCommand(['git', '-C', repo.fullPath, 'fetch', '--no-tags', remote, ...refspecs], {
|
||||
env,
|
||||
silent: true,
|
||||
timeout: timeoutMs,
|
||||
})
|
||||
},
|
||||
{ database, silent: true }
|
||||
)
|
||||
}
|
||||
|
||||
async pull(repoId: number, database: Database): Promise<string> {
|
||||
const repo = getRepoById(database, repoId)
|
||||
if (!repo) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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() : {}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
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'
|
||||
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 {
|
||||
client: OpenCodeClient
|
||||
session: SessionInfo
|
||||
source: WalkthroughSource
|
||||
gitEnv?: Record<string, string>
|
||||
}
|
||||
|
||||
type GitWalkthroughSource = Exclude<WalkthroughSource, { kind: 'session' }>
|
||||
|
||||
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 PullRequestRefs {
|
||||
remote: string
|
||||
baseBranch: string
|
||||
headRef: string
|
||||
baseRef: string
|
||||
}
|
||||
|
||||
export interface PullRequestFetchPlan {
|
||||
remote: string
|
||||
refspecs: string[]
|
||||
headRef: string
|
||||
baseRef: string
|
||||
}
|
||||
|
||||
export type PullRequestFetchRunner = (
|
||||
remote: string,
|
||||
refspecs: string[],
|
||||
timeoutMs: number,
|
||||
) => Promise<void>
|
||||
|
||||
export async function resolvePullRequestRefs(
|
||||
directory: string,
|
||||
sessionId: string,
|
||||
source: PullRequestSource,
|
||||
gitEnv?: Record<string, string>,
|
||||
): Promise<PullRequestRefs> {
|
||||
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 baseBranch = source.base ?? await resolveRemoteDefaultBranch(directory, remote, gitEnv)
|
||||
return {
|
||||
remote,
|
||||
baseBranch,
|
||||
headRef: `refs/ocm-walkthrough/${sessionId}/pr/${source.number}/head`,
|
||||
baseRef: `refs/ocm-walkthrough/${sessionId}/pr/${source.number}/base/${baseBranch}`,
|
||||
}
|
||||
}
|
||||
|
||||
export async function planPullRequestFetch(
|
||||
directory: string,
|
||||
sessionId: string,
|
||||
source: PullRequestSource,
|
||||
gitEnv?: Record<string, string>,
|
||||
): Promise<PullRequestFetchPlan> {
|
||||
const { remote, baseBranch, headRef, baseRef } = await resolvePullRequestRefs(directory, sessionId, source, gitEnv)
|
||||
return {
|
||||
remote,
|
||||
refspecs: [
|
||||
`+refs/pull/${source.number}/head:${headRef}`,
|
||||
`+refs/heads/${baseBranch}:${baseRef}`,
|
||||
],
|
||||
headRef,
|
||||
baseRef,
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchPullRequestRef(
|
||||
directory: string,
|
||||
sessionId: string,
|
||||
source: PullRequestSource,
|
||||
gitEnv: Record<string, string> | undefined,
|
||||
runFetch: PullRequestFetchRunner,
|
||||
): Promise<string[]> {
|
||||
const plan = await planPullRequestFetch(directory, sessionId, source, gitEnv)
|
||||
await mapGitError(
|
||||
() => runFetch(plan.remote, plan.refspecs, GIT_FETCH_TIMEOUT_MS),
|
||||
'Failed to fetch the pull request',
|
||||
)
|
||||
return [plan.headRef, plan.baseRef]
|
||||
}
|
||||
|
||||
async function resolveRemoteDefaultBranch(
|
||||
directory: string,
|
||||
remote: string,
|
||||
gitEnv?: Record<string, string>,
|
||||
): Promise<string> {
|
||||
const prefix = `${remote}/`
|
||||
const ref = (await tryGit(directory, ['rev-parse', '--abbrev-ref', `${remote}/HEAD`], gitEnv))?.trim()
|
||||
if (ref && ref.startsWith(prefix)) {
|
||||
return ref.slice(prefix.length)
|
||||
}
|
||||
return resolveDefaultBranch(directory, gitEnv ?? {})
|
||||
}
|
||||
|
||||
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({
|
||||
client,
|
||||
session,
|
||||
source,
|
||||
gitEnv,
|
||||
}: ReadWalkthroughChangesOptions): Promise<FileDiffInfo[]> {
|
||||
if (source.kind === 'session') {
|
||||
return readSessionChanges(client, session.id)
|
||||
}
|
||||
return readGitChanges(session.location.directory, session.id, source, gitEnv)
|
||||
}
|
||||
|
||||
async function readGitChanges(
|
||||
directory: string,
|
||||
sessionId: string,
|
||||
source: GitWalkthroughSource,
|
||||
gitEnv?: Record<string, string>,
|
||||
): Promise<FileDiffInfo[]> {
|
||||
await assertGitRepository(directory, gitEnv)
|
||||
const repoRoot = await resolveRepoRoot(directory, gitEnv)
|
||||
|
||||
switch (source.kind) {
|
||||
case 'uncommitted':
|
||||
return collectChanges(repoRoot, await uncommittedRevision(repoRoot, gitEnv), true, gitEnv)
|
||||
case 'staged':
|
||||
return collectChanges(repoRoot, ['--cached'], false, gitEnv)
|
||||
case 'unstaged':
|
||||
return collectChanges(repoRoot, [], true, gitEnv)
|
||||
case 'branch': {
|
||||
const base = await resolveBase(repoRoot, source.base, gitEnv)
|
||||
return collectChanges(repoRoot, [`${base}...HEAD`], false, gitEnv)
|
||||
}
|
||||
case 'pullRequest': {
|
||||
const { headRef, baseRef } = await resolvePullRequestRefs(repoRoot, sessionId, source, gitEnv)
|
||||
return collectChanges(repoRoot, [`${baseRef}...${headRef}`], false, gitEnv)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 uncommittedRevision(directory: string, gitEnv?: Record<string, string>): Promise<string[]> {
|
||||
return (await headExists(directory, gitEnv)) ? ['HEAD'] : [EMPTY_TREE]
|
||||
}
|
||||
|
||||
async function collectChanges(
|
||||
directory: string,
|
||||
revisionArgs: string[],
|
||||
includeUntracked: boolean,
|
||||
gitEnv?: Record<string, string>,
|
||||
): Promise<FileDiffInfo[]> {
|
||||
const tracked = await runDiff(directory, revisionArgs, gitEnv)
|
||||
if (!includeUntracked) {
|
||||
return splitUnifiedDiffByFile(tracked)
|
||||
}
|
||||
const untracked = await readUntrackedDiff(directory, gitEnv)
|
||||
return splitUnifiedDiffByFile(`${tracked}${untracked}`)
|
||||
}
|
||||
|
||||
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 ''
|
||||
}
|
||||
|
||||
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> {
|
||||
let insideWorkTree = false
|
||||
try {
|
||||
insideWorkTree = (await runGit(directory, ['rev-parse', '--is-inside-work-tree'], gitEnv)).trim() === 'true'
|
||||
} catch {
|
||||
insideWorkTree = false
|
||||
}
|
||||
if (!insideWorkTree) {
|
||||
throw new ChangeWalkthroughError('Not a git repository', 409, { code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
|
||||
}
|
||||
}
|
||||
|
||||
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 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 = 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>,
|
||||
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' })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
export async function mapWithConcurrency<T, R>(
|
||||
items: T[],
|
||||
limit: number,
|
||||
fn: (item: T, index: number) => Promise<R>,
|
||||
): Promise<R[]> {
|
||||
const results = new Array<R>(items.length)
|
||||
const workerCount = Math.max(1, Math.min(limit, items.length))
|
||||
let nextIndex = 0
|
||||
|
||||
const worker = async (): Promise<void> => {
|
||||
while (true) {
|
||||
const index = nextIndex
|
||||
nextIndex += 1
|
||||
if (index >= items.length) {
|
||||
return
|
||||
}
|
||||
results[index] = await fn(items[index]!, index)
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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>>
|
||||
}
|
||||
@@ -2,25 +2,32 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import type { ChangeWalkthrough } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
deleteChangeWalkthrough,
|
||||
deleteChangeWalkthroughs,
|
||||
ensureChangeWalkthroughTable,
|
||||
getChangeWalkthrough,
|
||||
saveChangeWalkthrough,
|
||||
} from '../../src/db/change-walkthroughs'
|
||||
import { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
import migration202610081200 from '../../src/db/migrations/202610081200-change-walkthrough-sources'
|
||||
|
||||
const SESSION_ID = 'ses_walkthrough'
|
||||
const SESSION_SOURCE = 'session'
|
||||
const STAGED_SOURCE = 'staged'
|
||||
|
||||
function walkthrough(overrides: Partial<ChangeWalkthrough> = {}): ChangeWalkthrough {
|
||||
return {
|
||||
sessionId: SESSION_ID,
|
||||
source: { kind: 'session' },
|
||||
diffHash: 'hash-1',
|
||||
model: null,
|
||||
summary: 'A short summary',
|
||||
stops: [{ title: 'First stop', explanation: 'Why it matters', hunkIds: ['f0h0'] }],
|
||||
stops: [
|
||||
{ id: 's_1', title: 'First stop', explanation: 'Why it matters', hunkIds: ['h_1'], status: 'ready', explanationKey: null },
|
||||
],
|
||||
hunks: [
|
||||
{
|
||||
id: 'f0h0',
|
||||
id: 'h_1',
|
||||
file: 'src/app.ts',
|
||||
status: 'modified',
|
||||
header: '@@ -1,2 +1,2 @@',
|
||||
@@ -40,6 +47,12 @@ function walkthroughTableExists(db: Database): boolean {
|
||||
)
|
||||
}
|
||||
|
||||
function tableColumns(db: Database): string[] {
|
||||
return (db.prepare('PRAGMA table_info(change_walkthroughs)').all() as Array<{ name: string }>).map(
|
||||
(column) => column.name,
|
||||
)
|
||||
}
|
||||
|
||||
describe('change walkthroughs', () => {
|
||||
let db: Database
|
||||
|
||||
@@ -52,27 +65,82 @@ describe('change walkthroughs', () => {
|
||||
db.close()
|
||||
})
|
||||
|
||||
it('creates the change_walkthroughs table in migration 29', () => {
|
||||
it('creates the change_walkthroughs table with per-source storage', () => {
|
||||
expect(walkthroughTableExists(db)).toBe(true)
|
||||
expect(tableColumns(db)).toContain('source_key')
|
||||
})
|
||||
|
||||
it('creates the table idempotently', () => {
|
||||
it('upgrades an existing single-source table and stays idempotent', () => {
|
||||
const legacy = new Database(':memory:')
|
||||
try {
|
||||
ensureChangeWalkthroughTable(legacy)
|
||||
|
||||
migrate(legacy, allMigrations)
|
||||
expect(tableColumns(legacy)).toContain('source_key')
|
||||
|
||||
expect(() => migrate(legacy, allMigrations)).not.toThrow()
|
||||
expect(() => migration202610081200.up(legacy)).not.toThrow()
|
||||
expect(tableColumns(legacy)).toContain('source_key')
|
||||
} finally {
|
||||
legacy.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('creates the old table idempotently', () => {
|
||||
expect(() => ensureChangeWalkthroughTable(db)).not.toThrow()
|
||||
expect(walkthroughTableExists(db)).toBe(true)
|
||||
})
|
||||
|
||||
it('returns null for a session without a stored walkthrough', () => {
|
||||
expect(getChangeWalkthrough(db, 'ses_missing')).toBeNull()
|
||||
expect(getChangeWalkthrough(db, 'ses_missing', SESSION_SOURCE)).toBeNull()
|
||||
})
|
||||
|
||||
it('round-trips a stored walkthrough', () => {
|
||||
const stored = walkthrough()
|
||||
saveChangeWalkthrough(db, stored)
|
||||
|
||||
expect(getChangeWalkthrough(db, SESSION_ID)).toEqual(stored)
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)).toEqual(stored)
|
||||
})
|
||||
|
||||
it('keeps a single row holding the latest payload on repeated saves', () => {
|
||||
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' }))
|
||||
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)?.diffHash).toBe('hash-session')
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, STAGED_SOURCE)?.diffHash).toBe('hash-staged')
|
||||
})
|
||||
|
||||
it('keeps a single row holding the latest payload on repeated saves of one source', () => {
|
||||
saveChangeWalkthrough(db, walkthrough())
|
||||
saveChangeWalkthrough(db, walkthrough({ diffHash: 'hash-2', summary: 'Updated', createdAt: 2_000 }))
|
||||
|
||||
@@ -81,43 +149,39 @@ describe('change walkthroughs', () => {
|
||||
.get(SESSION_ID) as { count: number }
|
||||
expect(count.count).toBe(1)
|
||||
|
||||
const stored = getChangeWalkthrough(db, SESSION_ID)
|
||||
const stored = getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)
|
||||
expect(stored).toMatchObject({ diffHash: 'hash-2', summary: 'Updated', createdAt: 2_000 })
|
||||
})
|
||||
|
||||
it('deletes only the walkthrough of the given session', () => {
|
||||
it('deletes every source of the given session', () => {
|
||||
saveChangeWalkthrough(db, walkthrough())
|
||||
saveChangeWalkthrough(db, walkthrough({ source: { kind: 'staged' } }))
|
||||
saveChangeWalkthrough(db, walkthrough({ sessionId: 'ses_other' }))
|
||||
|
||||
deleteChangeWalkthrough(db, SESSION_ID)
|
||||
deleteChangeWalkthroughs(db, SESSION_ID)
|
||||
|
||||
expect(getChangeWalkthrough(db, SESSION_ID)).toBeNull()
|
||||
expect(getChangeWalkthrough(db, 'ses_other')).not.toBeNull()
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)).toBeNull()
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, STAGED_SOURCE)).toBeNull()
|
||||
expect(getChangeWalkthrough(db, 'ses_other', SESSION_SOURCE)).not.toBeNull()
|
||||
})
|
||||
|
||||
it('ignores deleting a session without a stored walkthrough', () => {
|
||||
expect(() => deleteChangeWalkthrough(db, 'ses_missing')).not.toThrow()
|
||||
expect(() => deleteChangeWalkthroughs(db, 'ses_missing')).not.toThrow()
|
||||
})
|
||||
|
||||
it('treats a corrupt payload as missing', () => {
|
||||
db.prepare('INSERT INTO change_walkthroughs(session_id, diff_hash, payload, created_at) VALUES(?,?,?,?)').run(
|
||||
SESSION_ID,
|
||||
'hash-1',
|
||||
'{not json',
|
||||
1_000,
|
||||
)
|
||||
db.prepare(
|
||||
'INSERT INTO change_walkthroughs(session_id, source_key, diff_hash, payload, created_at) VALUES(?,?,?,?,?)',
|
||||
).run(SESSION_ID, SESSION_SOURCE, 'hash-1', '{not json', 1_000)
|
||||
|
||||
expect(getChangeWalkthrough(db, SESSION_ID)).toBeNull()
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)).toBeNull()
|
||||
})
|
||||
|
||||
it('treats a payload that fails schema validation as missing', () => {
|
||||
db.prepare('INSERT INTO change_walkthroughs(session_id, diff_hash, payload, created_at) VALUES(?,?,?,?)').run(
|
||||
SESSION_ID,
|
||||
'hash-1',
|
||||
JSON.stringify({ sessionId: SESSION_ID }),
|
||||
1_000,
|
||||
)
|
||||
db.prepare(
|
||||
'INSERT INTO change_walkthroughs(session_id, source_key, diff_hash, payload, created_at) VALUES(?,?,?,?,?)',
|
||||
).run(SESSION_ID, SESSION_SOURCE, 'hash-1', JSON.stringify({ sessionId: SESSION_ID }), 1_000)
|
||||
|
||||
expect(getChangeWalkthrough(db, SESSION_ID)).toBeNull()
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, SESSION_SOURCE)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,13 +1,22 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Hono } from 'hono'
|
||||
import { Database } from 'bun:sqlite'
|
||||
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 } 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'
|
||||
|
||||
const SESSION_ID = 'ses_walkthrough'
|
||||
|
||||
@@ -17,9 +26,11 @@ function change(file: string, patch: string, status: FileDiffInfo['status'] = 'm
|
||||
|
||||
const CHANGES: FileDiffInfo[] = [change('src/a.ts', '@@ -1,2 +1,2 @@\n-const a = 1;\n+const a = 2;')]
|
||||
|
||||
const HUNK_ID = computeHunkId(CHANGES[0]!.file, CHANGES[0]!.status, CHANGES[0]!.patch)
|
||||
|
||||
const MODEL_REPLY = JSON.stringify({
|
||||
summary: 'A summary',
|
||||
stops: [{ title: 'First', explanation: 'Why', hunkIds: ['f0h0'] }],
|
||||
stops: [{ title: 'First', explanation: 'Why', hunkIds: [HUNK_ID] }],
|
||||
})
|
||||
|
||||
interface FakeSession {
|
||||
@@ -29,7 +40,7 @@ interface FakeSession {
|
||||
|
||||
function createFakeClient(sessions: Record<string, FakeSession>) {
|
||||
const generateCalls: string[] = []
|
||||
let generateImpl: () => Promise<string> = async () => MODEL_REPLY
|
||||
let generateImpl: (prompt: string) => Promise<string> = async () => MODEL_REPLY
|
||||
|
||||
const client = {
|
||||
api: {
|
||||
@@ -64,7 +75,7 @@ function createFakeClient(sessions: Record<string, FakeSession>) {
|
||||
generate: {
|
||||
text: vi.fn(async (input: { prompt: string }) => {
|
||||
generateCalls.push(input.prompt)
|
||||
return { text: await generateImpl() }
|
||||
return { text: await generateImpl(input.prompt) }
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -74,12 +85,34 @@ function createFakeClient(sessions: Record<string, FakeSession>) {
|
||||
return {
|
||||
client,
|
||||
generateCalls,
|
||||
setGenerateImpl: (impl: () => Promise<string>) => {
|
||||
setGenerateImpl: (impl: (prompt: string) => Promise<string>) => {
|
||||
generateImpl = impl
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const routeRepoRoot = mkdtempSync(path.join(tmpdir(), 'walkthrough-routes-'))
|
||||
|
||||
afterAll(() => {
|
||||
rmSync(routeRepoRoot, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function createRepoWithStagedChange(): string {
|
||||
const repo = path.join(routeRepoRoot, uniqueName('repo'))
|
||||
createCommittedRepo(repo)
|
||||
writeFileSync(path.join(repo, 'a.txt'), 'one\n')
|
||||
git(['add', 'a.txt'], repo)
|
||||
git(['commit', '-m', 'add a'], repo)
|
||||
writeFileSync(path.join(repo, 'a.txt'), 'two\n')
|
||||
git(['add', 'a.txt'], repo)
|
||||
return repo
|
||||
}
|
||||
|
||||
function replyForPrompt(prompt: string, summary = 'A summary'): string {
|
||||
const ids = [...prompt.matchAll(/^### (h_\S+) /gm)].map((match) => match[1]!)
|
||||
return JSON.stringify({ summary, stops: [{ title: 'A', explanation: 'Why', hunkIds: ids }] })
|
||||
}
|
||||
|
||||
describe('change walkthrough routes', () => {
|
||||
let db: Database
|
||||
let sessions: Record<string, FakeSession>
|
||||
@@ -91,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)
|
||||
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))
|
||||
})
|
||||
@@ -125,6 +164,88 @@ describe('change walkthrough routes', () => {
|
||||
await expect(res.json()).resolves.toMatchObject({ error: 'Session not found' })
|
||||
})
|
||||
|
||||
it('GET reads the diff of the requested source', async () => {
|
||||
const repo = createRepoWithStagedChange()
|
||||
sessions[SESSION_ID]!.info = { id: SESSION_ID, title: 'Title', location: { directory: repo } } as SessionInfo
|
||||
|
||||
const sessionRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
|
||||
const sessionBody = (await sessionRes.json()) as { currentDiffHash: string | null }
|
||||
const stagedRes = await app.request(`/change-walkthroughs/${SESSION_ID}?source=staged`)
|
||||
const stagedBody = (await stagedRes.json()) as { currentDiffHash: string | null }
|
||||
|
||||
expect(stagedRes.status).toBe(200)
|
||||
expect(typeof stagedBody.currentDiffHash).toBe('string')
|
||||
expect(stagedBody.currentDiffHash).not.toBe(sessionBody.currentDiffHash)
|
||||
})
|
||||
|
||||
it('GET rejects an invalid source with 400', async () => {
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}?source=branch:-x`)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
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
|
||||
fake.setGenerateImpl(async (prompt) => replyForPrompt(prompt, 'Staged summary'))
|
||||
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ source: { kind: 'staged' } }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(202)
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const getRes = await app.request(`/change-walkthroughs/${SESSION_ID}?source=staged`)
|
||||
const state = (await getRes.json()) as { walkthrough: { summary: string } | null }
|
||||
expect(state.walkthrough?.summary).toBe('Staged summary')
|
||||
})
|
||||
})
|
||||
|
||||
it('POST returns 202 while generating, then GET reads the walkthrough back', async () => {
|
||||
let resolveGenerate: (text: string) => void = () => {}
|
||||
fake.setGenerateImpl(() => new Promise<string>((resolve) => {
|
||||
@@ -248,16 +369,11 @@ describe('change walkthrough routes', () => {
|
||||
})
|
||||
|
||||
it('POST records an unparseable model reply that GET surfaces', async () => {
|
||||
let resolveGenerate: (text: string) => void = () => {}
|
||||
fake.setGenerateImpl(() => new Promise<string>((resolve) => {
|
||||
resolveGenerate = resolve
|
||||
}))
|
||||
fake.setGenerateImpl(async () => 'not json')
|
||||
|
||||
const res = await app.request(`/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
|
||||
expect(res.status).toBe(202)
|
||||
|
||||
resolveGenerate('not json')
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const getRes = await app.request(`/change-walkthroughs/${SESSION_ID}`)
|
||||
const state = (await getRes.json()) as { generating: boolean; error: { code?: string } | null }
|
||||
|
||||
@@ -353,4 +353,19 @@ describe('internal/settings routes', () => {
|
||||
expect(body.preferences.theme).toBe('light')
|
||||
expect(body.preferences.mode).toBe('plan')
|
||||
})
|
||||
|
||||
it('PATCH /api/internal/settings with { walkthroughModel } persists it', async () => {
|
||||
const res = await app.request('/api/internal/settings', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ walkthroughModel: 'openai/gpt-5-mini' }),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json() as { preferences: { walkthroughModel?: string } }
|
||||
expect(body.preferences.walkthroughModel).toBe('openai/gpt-5-mini')
|
||||
expect(settingsService.getSettings().preferences.walkthroughModel).toBe('openai/gpt-5-mini')
|
||||
})
|
||||
})
|
||||
@@ -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', () => {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,436 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterAll, describe, expect, it, vi } from 'vitest'
|
||||
import type { FileDiffInfo, SessionInfo } from '@opencode-manager/shared/opencode'
|
||||
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
DEFAULT_WALKTHROUGH_SOURCE,
|
||||
parseWalkthroughSourceKey,
|
||||
walkthroughSourceKey,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { ChangeWalkthroughError } from '../../src/services/change-walkthrough-error'
|
||||
import {
|
||||
planPullRequestFetch,
|
||||
readWalkthroughChanges,
|
||||
} from '../../src/services/walkthrough-sources'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { cloneOrigin, createCommittedRepo, createOrigin, git, uniqueName } from '../helpers/git-fixtures'
|
||||
|
||||
const TEST_SESSION_ID = 'ses_test'
|
||||
const workspaceRoot = mkdtempSync(path.join(tmpdir(), 'walkthrough-sources-'))
|
||||
process.env.GIT_CONFIG_NOSYSTEM = '1'
|
||||
process.env.GIT_CONFIG_GLOBAL = '/dev/null'
|
||||
|
||||
const GIT_ENV = { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_TERMINAL_PROMPT: '0' }
|
||||
|
||||
afterAll(() => {
|
||||
rmSync(workspaceRoot, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function repoPath(prefix: string): string {
|
||||
return path.join(workspaceRoot, uniqueName(prefix))
|
||||
}
|
||||
|
||||
function sessionAt(directory: string): SessionInfo {
|
||||
return { id: TEST_SESSION_ID, title: 'Test', location: { directory } } as SessionInfo
|
||||
}
|
||||
|
||||
function readAt(directory: string, source: WalkthroughSource): Promise<FileDiffInfo[]> {
|
||||
return readWalkthroughChanges({
|
||||
client: {} as OpenCodeClient,
|
||||
session: sessionAt(directory),
|
||||
source,
|
||||
gitEnv: GIT_ENV,
|
||||
})
|
||||
}
|
||||
|
||||
describe('readWalkthroughChanges', () => {
|
||||
it('delegates the session source to the session diff', async () => {
|
||||
const changes: FileDiffInfo[] = [
|
||||
{ file: 'src/a.ts', patch: '@@ -1 +1 @@\n-a\n+b', additions: 1, deletions: 1, status: 'modified' },
|
||||
]
|
||||
const client = {
|
||||
api: {
|
||||
message: { list: vi.fn(async () => ({ data: [{ id: 'msg-1' }], cursor: {} })) },
|
||||
session: { diff: vi.fn(async () => changes) },
|
||||
},
|
||||
} as unknown as OpenCodeClient
|
||||
|
||||
const result = await readWalkthroughChanges({
|
||||
client,
|
||||
session: sessionAt('/not/a/repo'),
|
||||
source: DEFAULT_WALKTHROUGH_SOURCE,
|
||||
gitEnv: GIT_ENV,
|
||||
})
|
||||
|
||||
expect(result).toEqual(changes)
|
||||
})
|
||||
|
||||
it('reports staged-only edits only in staged', async () => {
|
||||
const repo = repoPath('staged')
|
||||
createCommittedRepo(repo)
|
||||
writeFileSync(path.join(repo, 'a.txt'), 'one\n')
|
||||
git(['add', 'a.txt'], repo)
|
||||
git(['commit', '-m', 'add a'], repo)
|
||||
writeFileSync(path.join(repo, 'a.txt'), 'two\n')
|
||||
git(['add', 'a.txt'], repo)
|
||||
|
||||
const staged = await readAt(repo, { kind: 'staged' })
|
||||
const unstaged = await readAt(repo, { kind: 'unstaged' })
|
||||
const uncommitted = await readAt(repo, { kind: 'uncommitted' })
|
||||
|
||||
expect(staged.map((entry) => entry.file)).toEqual(['a.txt'])
|
||||
expect(staged[0]?.status).toBe('modified')
|
||||
expect(unstaged).toEqual([])
|
||||
expect(uncommitted.map((entry) => entry.file)).toEqual(['a.txt'])
|
||||
})
|
||||
|
||||
it('reports an untracked file as added in uncommitted and unstaged', async () => {
|
||||
const repo = repoPath('untracked')
|
||||
createCommittedRepo(repo)
|
||||
writeFileSync(path.join(repo, 'new.txt'), 'hello\n')
|
||||
|
||||
const uncommitted = await readAt(repo, { kind: 'uncommitted' })
|
||||
const unstaged = await readAt(repo, { kind: 'unstaged' })
|
||||
|
||||
expect(uncommitted).toHaveLength(1)
|
||||
expect(uncommitted[0]).toMatchObject({ file: 'new.txt', status: 'added', additions: 1, deletions: 0 })
|
||||
expect(unstaged.map((entry) => entry.file)).toEqual(['new.txt'])
|
||||
expect(unstaged[0]?.status).toBe('added')
|
||||
})
|
||||
|
||||
it('parses untracked paths with spaces and non-ASCII characters', async () => {
|
||||
const repo = repoPath('special-names')
|
||||
createCommittedRepo(repo)
|
||||
writeFileSync(path.join(repo, 'my file.txt'), 'hello\n')
|
||||
writeFileSync(path.join(repo, 'é.txt'), 'bonjour\n')
|
||||
|
||||
const unstaged = await readAt(repo, { kind: 'unstaged' })
|
||||
|
||||
expect(unstaged.map((entry) => entry.file).sort()).toEqual(['my file.txt', 'é.txt'])
|
||||
})
|
||||
|
||||
it('reports branch commits against the base', async () => {
|
||||
const repo = repoPath('branch')
|
||||
createCommittedRepo(repo, 'main')
|
||||
git(['checkout', '-b', 'feature'], repo)
|
||||
writeFileSync(path.join(repo, 'feature.txt'), 'feature\n')
|
||||
git(['add', 'feature.txt'], repo)
|
||||
git(['commit', '-m', 'feature'], repo)
|
||||
|
||||
const explicit = await readAt(repo, { kind: 'branch', base: 'main' })
|
||||
const resolved = await readAt(repo, { kind: 'branch' })
|
||||
|
||||
expect(explicit.map((entry) => entry.file)).toEqual(['feature.txt'])
|
||||
expect(explicit[0]?.status).toBe('added')
|
||||
expect(resolved.map((entry) => entry.file)).toEqual(['feature.txt'])
|
||||
})
|
||||
|
||||
it('reports a pull request ref pushed to the origin', async () => {
|
||||
const origin = repoPath('origin')
|
||||
const work = repoPath('work')
|
||||
const clone = repoPath('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 source = { kind: 'pullRequest', number: 1, base: 'main' } as const
|
||||
const plan = await planPullRequestFetch(clone, TEST_SESSION_ID, source)
|
||||
git(['fetch', 'origin', ...plan.refspecs], clone)
|
||||
|
||||
const changes = await readAt(clone, source)
|
||||
|
||||
expect(changes.map((entry) => entry.file)).toEqual(['pr.txt'])
|
||||
expect(changes[0]?.status).toBe('added')
|
||||
})
|
||||
|
||||
it('diffs a pull request against the base from the remote that supplies the head', async () => {
|
||||
const upstream = repoPath('pr-fork-upstream')
|
||||
const upstreamWork = repoPath('pr-fork-upstream-work')
|
||||
createOrigin(upstream, upstreamWork)
|
||||
writeFileSync(path.join(upstreamWork, 'upstream.txt'), 'upstream\n')
|
||||
git(['add', 'upstream.txt'], upstreamWork)
|
||||
git(['commit', '-m', 'upstream advance'], upstreamWork)
|
||||
git(['push', 'origin', 'main'], upstreamWork)
|
||||
|
||||
const origin = repoPath('pr-fork-origin')
|
||||
const originWork = repoPath('pr-fork-origin-work')
|
||||
createOrigin(origin, originWork)
|
||||
|
||||
const clone = repoPath('pr-fork-clone')
|
||||
cloneOrigin(origin, clone)
|
||||
git(['remote', 'add', 'upstream', upstream], clone)
|
||||
git(['fetch', 'upstream'], clone)
|
||||
|
||||
git(['checkout', '-b', 'feature', 'upstream/main'], clone)
|
||||
writeFileSync(path.join(clone, 'pr.txt'), 'pr\n')
|
||||
git(['add', 'pr.txt'], clone)
|
||||
git(['commit', '-m', 'pr'], clone)
|
||||
git(['push', 'upstream', 'HEAD:refs/pull/1/head'], clone)
|
||||
|
||||
const source = { kind: 'pullRequest', number: 1, base: 'main' } as const
|
||||
const plan = await planPullRequestFetch(clone, TEST_SESSION_ID, source)
|
||||
expect(plan.remote).toBe('upstream')
|
||||
git(['fetch', 'upstream', ...plan.refspecs], clone)
|
||||
|
||||
const changes = await readAt(clone, source)
|
||||
|
||||
expect(changes.map((entry) => entry.file)).toEqual(['pr.txt'])
|
||||
})
|
||||
|
||||
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, TEST_SESSION_ID, { kind: 'pullRequest', number: 7, base: 'main' })
|
||||
|
||||
expect(plan.remote).toBe('upstream')
|
||||
expect(plan.refspecs).toEqual([
|
||||
`+refs/pull/7/head:refs/ocm-walkthrough/${TEST_SESSION_ID}/pr/7/head`,
|
||||
`+refs/heads/main:refs/ocm-walkthrough/${TEST_SESSION_ID}/pr/7/base/main`,
|
||||
])
|
||||
expect(plan.headRef).toBe(`refs/ocm-walkthrough/${TEST_SESSION_ID}/pr/7/head`)
|
||||
expect(plan.baseRef).toBe(`refs/ocm-walkthrough/${TEST_SESSION_ID}/pr/7/base/main`)
|
||||
})
|
||||
|
||||
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, TEST_SESSION_ID, { kind: 'pullRequest', number: 3, base: 'main' })
|
||||
|
||||
expect(plan.remote).toBe('origin')
|
||||
expect(plan.refspecs).toEqual([
|
||||
`+refs/pull/3/head:refs/ocm-walkthrough/${TEST_SESSION_ID}/pr/3/head`,
|
||||
`+refs/heads/main:refs/ocm-walkthrough/${TEST_SESSION_ID}/pr/3/base/main`,
|
||||
])
|
||||
})
|
||||
|
||||
it('resolves the default base from the selected remote HEAD when no base is given', async () => {
|
||||
const repo = repoPath('pr-default-base')
|
||||
createCommittedRepo(repo)
|
||||
git(['remote', 'add', 'origin', 'https://example.com/base.git'], repo)
|
||||
git(['remote', 'add', 'upstream', 'https://example.com/fork.git'], repo)
|
||||
git(['update-ref', 'refs/remotes/upstream/trunk', 'HEAD'], repo)
|
||||
git(['symbolic-ref', 'refs/remotes/upstream/HEAD', 'refs/remotes/upstream/trunk'], repo)
|
||||
|
||||
const plan = await planPullRequestFetch(repo, TEST_SESSION_ID, { kind: 'pullRequest', number: 9 })
|
||||
|
||||
expect(plan.remote).toBe('upstream')
|
||||
expect(plan.refspecs).toEqual([
|
||||
`+refs/pull/9/head:refs/ocm-walkthrough/${TEST_SESSION_ID}/pr/9/head`,
|
||||
`+refs/heads/trunk:refs/ocm-walkthrough/${TEST_SESSION_ID}/pr/9/base/trunk`,
|
||||
])
|
||||
})
|
||||
|
||||
it('excludes untracked files from staged and branch sources', async () => {
|
||||
const repo = repoPath('not-untracked')
|
||||
createCommittedRepo(repo, 'main')
|
||||
git(['checkout', '-b', 'feature'], repo)
|
||||
writeFileSync(path.join(repo, 'feature.txt'), 'feature\n')
|
||||
git(['add', 'feature.txt'], repo)
|
||||
git(['commit', '-m', 'feature'], repo)
|
||||
writeFileSync(path.join(repo, 'loose.txt'), 'loose\n')
|
||||
|
||||
const staged = await readAt(repo, { kind: 'staged' })
|
||||
const branch = await readAt(repo, { kind: 'branch', base: 'main' })
|
||||
|
||||
expect(staged).toEqual([])
|
||||
expect(branch.map((entry) => entry.file)).toEqual(['feature.txt'])
|
||||
})
|
||||
|
||||
it('rejects a non-git directory with a 409 source error', async () => {
|
||||
const dir = repoPath('plain')
|
||||
mkdirSync(dir, { recursive: true })
|
||||
|
||||
const error = await readAt(dir, { kind: 'staged' }).catch((thrown) => thrown)
|
||||
|
||||
expect(error).toBeInstanceOf(ChangeWalkthroughError)
|
||||
expect(error).toMatchObject({ status: 409, code: 'WALKTHROUGH_SOURCE_UNAVAILABLE' })
|
||||
})
|
||||
|
||||
it('rejects a branch source when no base branch exists', async () => {
|
||||
const repo = repoPath('nobase')
|
||||
createCommittedRepo(repo, 'trunk')
|
||||
|
||||
const error = await readAt(repo, { kind: 'branch' }).catch((thrown) => thrown)
|
||||
|
||||
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', () => {
|
||||
it('round-trips every source kind', () => {
|
||||
const sources: WalkthroughSource[] = [
|
||||
{ kind: 'session' },
|
||||
{ kind: 'uncommitted' },
|
||||
{ kind: 'staged' },
|
||||
{ kind: 'unstaged' },
|
||||
{ kind: 'branch' },
|
||||
{ kind: 'branch', base: 'develop' },
|
||||
{ kind: 'pullRequest', number: 12 },
|
||||
{ kind: 'pullRequest', number: 12, base: 'develop' },
|
||||
]
|
||||
|
||||
for (const source of sources) {
|
||||
expect(parseWalkthroughSourceKey(walkthroughSourceKey(source))).toEqual(source)
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects invalid keys', () => {
|
||||
expect(parseWalkthroughSourceKey('branch:-x')).toBeNull()
|
||||
expect(parseWalkthroughSourceKey('pr:0:')).toBeNull()
|
||||
expect(parseWalkthroughSourceKey('pr:abc:main')).toBeNull()
|
||||
expect(parseWalkthroughSourceKey('nonsense')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createLimiter, mapWithConcurrency } from '../../src/utils/concurrency'
|
||||
|
||||
describe('mapWithConcurrency', () => {
|
||||
it('keeps result order', async () => {
|
||||
const result = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (item) => item * 2)
|
||||
expect(result).toEqual([2, 4, 6, 8, 10])
|
||||
})
|
||||
|
||||
it('runs at most limit calls at once', async () => {
|
||||
let inFlight = 0
|
||||
let maxInFlight = 0
|
||||
|
||||
await mapWithConcurrency([1, 2, 3, 4, 5, 6], 2, async (item) => {
|
||||
inFlight += 1
|
||||
maxInFlight = Math.max(maxInFlight, inFlight)
|
||||
await new Promise((resolve) => setTimeout(resolve, 1))
|
||||
inFlight -= 1
|
||||
return item
|
||||
})
|
||||
|
||||
expect(maxInFlight).toBe(2)
|
||||
})
|
||||
|
||||
it('propagates a rejection', async () => {
|
||||
await expect(
|
||||
mapWithConcurrency([1, 2, 3], 2, async (item) => {
|
||||
if (item === 2) {
|
||||
throw new Error('boom')
|
||||
}
|
||||
return item
|
||||
}),
|
||||
).rejects.toThrow('boom')
|
||||
})
|
||||
|
||||
it('passes the index to the callback', async () => {
|
||||
const result = await mapWithConcurrency(['a', 'b'], 2, async (item, index) => `${item}${index}`)
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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 })
|
||||
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
import { fetchWrapper } from './fetchWrapper'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { walkthroughSourceKey } from '@opencode-manager/shared/schemas'
|
||||
import type {
|
||||
ChangeWalkthroughState,
|
||||
ChangeWalkthroughStateWire,
|
||||
GenerateChangeWalkthroughRequest,
|
||||
WalkthroughSource,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
function walkthroughUrl(sessionId: string): string {
|
||||
return `${API_BASE_URL}/api/change-walkthroughs/${encodeURIComponent(sessionId)}`
|
||||
}
|
||||
|
||||
export async function getChangeWalkthrough(sessionId: string): Promise<ChangeWalkthroughState> {
|
||||
return fetchWrapper<ChangeWalkthroughState>(walkthroughUrl(sessionId))
|
||||
export async function getChangeWalkthrough(
|
||||
sessionId: string,
|
||||
source: WalkthroughSource,
|
||||
hunksFor?: string,
|
||||
): Promise<ChangeWalkthroughStateWire> {
|
||||
return fetchWrapper<ChangeWalkthroughStateWire>(walkthroughUrl(sessionId), {
|
||||
params: {
|
||||
source: walkthroughSourceKey(source),
|
||||
...(hunksFor === undefined ? {} : { hunksFor }),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function generateChangeWalkthrough(
|
||||
|
||||
@@ -27,6 +27,7 @@ vi.mock('@/components/session/ChangesWalkthroughSheet', () => ({
|
||||
ChangesWalkthroughProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
ChangesWalkthroughNav: () => null,
|
||||
ChangesWalkthroughRegenerate: () => null,
|
||||
ChangesWalkthroughSourcePicker: () => null,
|
||||
ChangesWalkthroughView: () => <div>walkthrough-tool</div>,
|
||||
}))
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
ChangesWalkthroughNav,
|
||||
ChangesWalkthroughProvider,
|
||||
ChangesWalkthroughRegenerate,
|
||||
ChangesWalkthroughSourcePicker,
|
||||
ChangesWalkthroughView,
|
||||
} from '@/components/session/ChangesWalkthroughSheet'
|
||||
import { PreviewWorkspace } from '@/components/preview/PreviewPanel'
|
||||
@@ -167,6 +168,7 @@ export function ToolSidePanel({
|
||||
<h2 className="min-w-0 flex-1 truncate text-sm font-semibold text-foreground">{activeLabel}</h2>
|
||||
{activeTool === 'walkthrough' ? (
|
||||
<>
|
||||
<ChangesWalkthroughSourcePicker />
|
||||
<ChangesWalkthroughRegenerate />
|
||||
<ChangesWalkthroughNav />
|
||||
</>
|
||||
@@ -188,7 +190,7 @@ export function ToolSidePanel({
|
||||
<>
|
||||
{panelContent ? (
|
||||
activeTool === 'walkthrough' && sessionId ? (
|
||||
<ChangesWalkthroughProvider sessionId={sessionId} active>
|
||||
<ChangesWalkthroughProvider key={sessionId} sessionId={sessionId} active>
|
||||
{panelContent}
|
||||
</ChangesWalkthroughProvider>
|
||||
) : (
|
||||
|
||||
@@ -500,7 +500,9 @@ describe('MultiRunSheet', () => {
|
||||
await user.click(within(card).getByRole('button', { name: /walkthrough/i }))
|
||||
|
||||
expect(await screen.findByText('Change walkthrough')).toBeInTheDocument()
|
||||
await waitFor(() => expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_11'))
|
||||
await waitFor(() =>
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_11', { kind: 'session' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('lists fusions with truncation and opens the fusion session', async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { ReactNode } from 'react'
|
||||
@@ -19,11 +19,27 @@ vi.mock('@/api/changeWalkthroughs', () => ({
|
||||
|
||||
const walkthrough: ChangeWalkthrough = {
|
||||
sessionId: 'ses_1',
|
||||
source: { kind: 'session' },
|
||||
diffHash: 'hash-1',
|
||||
model: null,
|
||||
summary: 'This change adds a greeting.',
|
||||
stops: [
|
||||
{ title: 'Add the greeting', explanation: 'Introduces the greeting helper.', hunkIds: ['f0h0'] },
|
||||
{ title: 'Wire it up', explanation: 'Calls the helper from the entry point.', hunkIds: ['f1h0'] },
|
||||
{
|
||||
id: 's_greet',
|
||||
title: 'Add the greeting',
|
||||
explanation: 'Introduces the greeting helper.',
|
||||
hunkIds: ['f0h0'],
|
||||
status: 'ready',
|
||||
explanationKey: null,
|
||||
},
|
||||
{
|
||||
id: 's_wire',
|
||||
title: 'Wire it up',
|
||||
explanation: 'Calls the helper from the entry point.',
|
||||
hunkIds: ['f1h0'],
|
||||
status: 'ready',
|
||||
explanationKey: null,
|
||||
},
|
||||
],
|
||||
hunks: [
|
||||
{
|
||||
@@ -47,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 }
|
||||
}
|
||||
@@ -96,7 +159,7 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
await user.click(generate)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', {})
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { source: { kind: 'session' } })
|
||||
})
|
||||
expect(await screen.findByText('This change adds a greeting.')).toBeInTheDocument()
|
||||
expect(screen.getByText('Overview')).toBeInTheDocument()
|
||||
@@ -168,7 +231,7 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
expect(screen.getByText('This change adds a greeting.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the stale warning and regenerates', async () => {
|
||||
it('updates a stale walkthrough incrementally', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ stale: true, currentDiffHash: 'hash-2' }))
|
||||
mocks.generateChangeWalkthrough.mockResolvedValue(state({ generating: true }))
|
||||
@@ -178,10 +241,10 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
await screen.findByText('Changes have been updated since this walkthrough was generated'),
|
||||
).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Regenerate' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Update walkthrough' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { regenerate: true })
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { source: { kind: 'session' } })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -195,10 +258,154 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'Regenerate walkthrough' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { regenerate: true })
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', {
|
||||
regenerate: true,
|
||||
source: { kind: 'session' },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('switches to staged changes', 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: 'Staged' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'staged' })
|
||||
})
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { source: { kind: 'staged' } })
|
||||
})
|
||||
})
|
||||
|
||||
it('renders the source picker in the drawer header before any walkthrough exists', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: null }))
|
||||
renderSheet()
|
||||
|
||||
const header = screen.getByRole('button', { name: 'Close' }).parentElement
|
||||
expect(header).not.toBeNull()
|
||||
expect(
|
||||
within(header as HTMLElement).getByRole('combobox', { name: 'Changes to walk through' }),
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('sends the branch base', 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: 'Branch vs base' }))
|
||||
|
||||
const base = await screen.findByLabelText('Base branch')
|
||||
await user.type(base, 'develop')
|
||||
await user.tab()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.getChangeWalkthrough).toHaveBeenCalledWith('ses_1', { kind: 'branch', base: 'develop' })
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Generate walkthrough' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', {
|
||||
source: { kind: 'branch', base: 'develop' },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
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())
|
||||
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, '0')
|
||||
await user.tab()
|
||||
|
||||
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 }))
|
||||
mocks.generateChangeWalkthrough.mockRejectedValue(
|
||||
new FetchError('Not a git repository', 409, 'WALKTHROUGH_NOT_A_REPO'),
|
||||
)
|
||||
renderSheet()
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Branch vs base' }))
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: 'Generate walkthrough' }))
|
||||
expect(await screen.findByText('Not a git repository')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'Changes to walk through' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Staged' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Not a git repository')).not.toBeInTheDocument()
|
||||
})
|
||||
expect(await screen.findByRole('button', { name: 'Generate walkthrough' })).toBeVisible()
|
||||
})
|
||||
|
||||
it('scrolls back to the top of the overview when a walkthrough is regenerated', async () => {
|
||||
const user = userEvent.setup()
|
||||
const scrollTo = vi.spyOn(Element.prototype, 'scrollTo')
|
||||
@@ -228,6 +435,55 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
expect(screen.queryByRole('button', { name: 'Generate walkthrough' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders ready and pending stops while generating', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(
|
||||
state({
|
||||
generating: true,
|
||||
walkthrough: {
|
||||
...walkthrough,
|
||||
stops: [
|
||||
{ ...walkthrough.stops[0], status: 'ready' },
|
||||
{ ...walkthrough.stops[1], status: 'pending', explanation: '' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
)
|
||||
renderSheet()
|
||||
|
||||
expect(await screen.findByText(/1 of 2 stops explained/)).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: '1. Add the greeting' })).toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Explaining')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '1. Add the greeting' }))
|
||||
expect(await screen.findByText('Introduces the greeting helper.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('retries unexplained stops', async () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(
|
||||
state({
|
||||
walkthrough: {
|
||||
...walkthrough,
|
||||
stops: [
|
||||
{ ...walkthrough.stops[0], status: 'failed', explanation: '' },
|
||||
{ ...walkthrough.stops[1], status: 'ready' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
)
|
||||
mocks.generateChangeWalkthrough.mockResolvedValue(state({ generating: true }))
|
||||
renderSheet()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /1\. Add the greeting/ }))
|
||||
expect(await screen.findByText('This stop could not be explained.')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Retry unexplained stops' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_1', { source: { kind: 'session' } })
|
||||
})
|
||||
})
|
||||
|
||||
it('renders a generation failure recorded by the server', async () => {
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(
|
||||
state({
|
||||
@@ -287,6 +543,81 @@ 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 () => {
|
||||
const user = userEvent.setup()
|
||||
mocks.getChangeWalkthrough.mockResolvedValue(state({ walkthrough: mechanicalWalkthrough }))
|
||||
renderSheet()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: '1. Mechanical changes' }))
|
||||
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 () => {
|
||||
const user = userEvent.setup()
|
||||
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()
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: '1. Mechanical changes' }))
|
||||
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="<script>parent.document.documentElement.dataset.walkthroughProbe = 1</script>"></iframe>'
|
||||
@@ -295,7 +626,9 @@ describe('ChangesWalkthroughSheet', () => {
|
||||
walkthrough: {
|
||||
...walkthrough,
|
||||
summary: `Summary ${payload}`,
|
||||
stops: [{ title: 'Stop', explanation: `Explanation ${payload}`, hunkIds: ['f0h0'] }],
|
||||
stops: [
|
||||
{ id: 's_x', title: 'Stop', explanation: `Explanation ${payload}`, hunkIds: ['f0h0'], status: 'ready', explanationKey: null },
|
||||
],
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -12,15 +12,24 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { DiffLines } from '@/components/file-browser/DiffLines'
|
||||
import { ScheduleRunMarkdown } from '@/components/schedules/ScheduleRunMarkdown'
|
||||
import { useChangeWalkthrough, useGenerateChangeWalkthrough } from '@/hooks/useChangeWalkthrough'
|
||||
import { GIT_STATUS_COLORS, GIT_STATUS_LABELS } from '@/lib/git-status-styles'
|
||||
import { WalkthroughOmittedFileSchema } from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
DEFAULT_WALKTHROUGH_SOURCE,
|
||||
describeWalkthroughSource,
|
||||
toWalkthroughSource,
|
||||
walkthroughSourceKey,
|
||||
WalkthroughOmittedFileSchema,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import type {
|
||||
ChangeWalkthrough,
|
||||
WalkthroughHunk,
|
||||
WalkthroughOmittedFile,
|
||||
WalkthroughSource,
|
||||
WalkthroughStop,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
@@ -62,6 +71,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[] }) {
|
||||
@@ -77,6 +88,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
|
||||
@@ -92,6 +133,16 @@ interface ChangesWalkthroughContextValue {
|
||||
selectedHunks: WalkthroughHunk[]
|
||||
selectStop: (index: number | null) => void
|
||||
scrollRef: RefObject<HTMLDivElement | null>
|
||||
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)
|
||||
@@ -102,6 +153,89 @@ function useChangesWalkthrough(): ChangesWalkthroughContextValue {
|
||||
return value
|
||||
}
|
||||
|
||||
const WALKTHROUGH_SOURCE_OPTIONS: { value: WalkthroughSource['kind']; label: string }[] = [
|
||||
{ value: 'session', label: 'This session' },
|
||||
{ value: 'uncommitted', label: 'Uncommitted' },
|
||||
{ value: 'staged', label: 'Staged' },
|
||||
{ value: 'unstaged', label: 'Unstaged' },
|
||||
{ value: 'branch', label: 'Branch vs base' },
|
||||
{ value: 'pullRequest', label: 'Pull request' },
|
||||
]
|
||||
|
||||
/** Chooses which set of changes the walkthrough covers from the surrounding chrome; git sources commit as soon as they are valid. */
|
||||
export const ChangesWalkthroughSourcePicker = memo(function ChangesWalkthroughSourcePicker() {
|
||||
const { sourceKind, setSourceKind, baseInput, setSource } = useChangesWalkthrough()
|
||||
|
||||
const handleKindChange = useCallback(
|
||||
(next: WalkthroughSource['kind']) => {
|
||||
setSourceKind(next)
|
||||
if (next === 'pullRequest') return
|
||||
const nextSource = toWalkthroughSource({ kind: next, base: baseInput })
|
||||
if (nextSource) setSource(nextSource)
|
||||
},
|
||||
[baseInput, setSourceKind, setSource],
|
||||
)
|
||||
|
||||
return (
|
||||
<Select value={sourceKind} onValueChange={(value) => handleKindChange(value as WalkthroughSource['kind'])}>
|
||||
<SelectTrigger
|
||||
aria-label="Changes to walk through"
|
||||
className="h-7 w-auto gap-1 px-2 text-xs md:text-xs"
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{WALKTHROUGH_SOURCE_OPTIONS.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)
|
||||
})
|
||||
|
||||
/** Collects the base branch or pull request number for git-backed walkthrough sources. */
|
||||
const WalkthroughSourceInputs = memo(function WalkthroughSourceInputs() {
|
||||
const { sourceKind, baseInput, setBaseInput, numberInput, setNumberInput, setSource } =
|
||||
useChangesWalkthrough()
|
||||
|
||||
const commitInputs = useCallback(() => {
|
||||
const next = toWalkthroughSource({ kind: sourceKind, base: baseInput, number: Number(numberInput) })
|
||||
if (next) setSource(next)
|
||||
}, [sourceKind, baseInput, numberInput, setSource])
|
||||
|
||||
if (sourceKind !== 'branch' && sourceKind !== 'pullRequest') return null
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
aria-label="Base branch"
|
||||
placeholder="Default branch"
|
||||
value={baseInput}
|
||||
onChange={(event) => setBaseInput(event.target.value)}
|
||||
onBlur={commitInputs}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') commitInputs()
|
||||
}}
|
||||
/>
|
||||
|
||||
{sourceKind === 'pullRequest' ? (
|
||||
<Input
|
||||
type="number"
|
||||
aria-label="Pull request number"
|
||||
value={numberInput}
|
||||
onChange={(event) => setNumberInput(event.target.value)}
|
||||
onBlur={commitInputs}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') commitInputs()
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
interface ChangesWalkthroughProviderProps {
|
||||
sessionId: string
|
||||
active: boolean
|
||||
@@ -110,8 +244,13 @@ 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 stateQuery = useChangeWalkthrough(sessionId, active)
|
||||
const generate = useGenerateChangeWalkthrough(sessionId)
|
||||
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)
|
||||
const resetGenerate = generate.reset
|
||||
const [stopIndex, setStopIndex] = useState<number | null>(null)
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
@@ -123,14 +262,19 @@ 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, resetGenerate])
|
||||
}, [active, sessionId, sourceKey, resetGenerate])
|
||||
|
||||
useEffect(() => {
|
||||
setStopIndex(null)
|
||||
scrollRef.current?.scrollTo?.({ top: 0 })
|
||||
}, [active, sessionId, walkthrough?.createdAt])
|
||||
}, [active, sessionId, sourceKey, walkthrough?.createdAt])
|
||||
|
||||
const hunksById = new Map(walkthrough?.hunks.map((hunk) => [hunk.id, hunk]) ?? [])
|
||||
const stops = walkthrough?.stops ?? []
|
||||
@@ -140,6 +284,10 @@ export function ChangesWalkthroughProvider({ sessionId, active, children }: Chan
|
||||
.map((id) => hunksById.get(id))
|
||||
.filter((hunk): hunk is WalkthroughHunk => hunk !== undefined)
|
||||
|
||||
const failedStopCount = stops.filter(
|
||||
(stop) => stop.status === 'failed' || (stop.status === 'pending' && !generating),
|
||||
).length
|
||||
|
||||
const selectStop = useCallback((index: number | null) => {
|
||||
setStopIndex(index)
|
||||
scrollRef.current?.scrollTo?.({ top: 0 })
|
||||
@@ -160,6 +308,16 @@ export function ChangesWalkthroughProvider({ sessionId, active, children }: Chan
|
||||
selectedHunks,
|
||||
selectStop,
|
||||
scrollRef,
|
||||
failedStopCount,
|
||||
source,
|
||||
setSource,
|
||||
sourceKind,
|
||||
setSourceKind,
|
||||
baseInput,
|
||||
setBaseInput,
|
||||
numberInput,
|
||||
setNumberInput,
|
||||
sourcePending,
|
||||
}
|
||||
|
||||
return <ChangesWalkthroughContext.Provider value={value}>{children}</ChangesWalkthroughContext.Provider>
|
||||
@@ -219,7 +377,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
|
||||
|
||||
@@ -229,7 +387,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>
|
||||
@@ -246,16 +404,33 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
|
||||
error,
|
||||
contextLimitFiles,
|
||||
generate,
|
||||
regenerate,
|
||||
stops,
|
||||
selectedStop,
|
||||
selectedHunks,
|
||||
selectStop,
|
||||
scrollRef,
|
||||
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">
|
||||
<WalkthroughSourceInputs />
|
||||
<p className="text-sm text-muted-foreground">Enter a pull request number</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={scrollRef} className="min-h-0 flex-1 space-y-4 overflow-y-auto p-4">
|
||||
<WalkthroughSourceInputs />
|
||||
|
||||
{error ? (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-destructive">{walkthroughErrorMessage(error)}</p>
|
||||
@@ -266,7 +441,11 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
|
||||
{generating ? (
|
||||
<div className="flex items-center gap-2 rounded-md border border-border bg-muted/20 px-3 py-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 shrink-0 animate-spin" />
|
||||
<span>Generating walkthrough… this can take a minute or two.</span>
|
||||
<span>
|
||||
{walkthrough && stops.length > 0
|
||||
? `Generating walkthrough… ${readyStopCount} of ${stops.length} stops explained`
|
||||
: 'Generating walkthrough… this can take a minute or two.'}
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
@@ -278,7 +457,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 the changes in this session.
|
||||
Generate a step-by-step walkthrough of {describeWalkthroughSource(source)}.
|
||||
</p>
|
||||
<Button onClick={generate}>Generate walkthrough</Button>
|
||||
</div>
|
||||
@@ -290,9 +469,18 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
|
||||
<p className="text-sm text-warning">
|
||||
Changes have been updated since this walkthrough was generated
|
||||
</p>
|
||||
<Button variant="outline" size="sm" onClick={regenerate}>
|
||||
<Button variant="outline" size="sm" onClick={generate}>
|
||||
<RefreshCw className="mr-2 h-3.5 w-3.5" />
|
||||
Regenerate
|
||||
Update walkthrough
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{failedStopCount > 0 && !generating ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border border-border bg-muted/20 px-3 py-2">
|
||||
<p className="text-sm text-muted-foreground">Some stops could not be explained</p>
|
||||
<Button variant="outline" size="sm" onClick={generate}>
|
||||
Retry unexplained stops
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
@@ -300,8 +488,15 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
|
||||
{selectedStop ? (
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-semibold text-foreground">{selectedStop.title}</h3>
|
||||
<ScheduleRunMarkdown content={selectedStop.explanation} />
|
||||
{selectedHunks.map((hunk) => (
|
||||
{selectedStop.status === 'ready' ? (
|
||||
<ScheduleRunMarkdown content={selectedStop.explanation} />
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{generating ? 'Explaining this stop…' : 'This stop could not be explained.'}
|
||||
</p>
|
||||
)}
|
||||
{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}>
|
||||
@@ -325,13 +520,22 @@ export const ChangesWalkthroughView = memo(function ChangesWalkthroughView() {
|
||||
{stops.length > 0 ? (
|
||||
<ol className="space-y-0.5">
|
||||
{stops.map((stop, index) => (
|
||||
<li key={index}>
|
||||
<li key={stop.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => selectStop(index)}
|
||||
className="w-full rounded-md px-2 py-1 text-left text-sm text-muted-foreground hover:bg-accent/20 hover:text-foreground"
|
||||
>
|
||||
{index + 1}. {stop.title}
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{index + 1}. {stop.title}
|
||||
</span>
|
||||
{stop.status === 'pending' && generating ? (
|
||||
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" aria-label="Explaining" />
|
||||
) : stop.status === 'failed' || stop.status === 'pending' ? (
|
||||
<span className="shrink-0 text-xs text-muted-foreground">not explained</span>
|
||||
) : null}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
@@ -359,12 +563,13 @@ 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}
|
||||
actions={
|
||||
<>
|
||||
<ChangesWalkthroughSourcePicker />
|
||||
<ChangesWalkthroughRegenerate />
|
||||
<ChangesWalkthroughNav />
|
||||
</>
|
||||
|
||||
@@ -70,6 +70,9 @@ describe('GeneralSettings', () => {
|
||||
expect(screen.getByRole('switch', { name: 'Show reasoning' })).not.toBeChecked()
|
||||
expect(screen.getByRole('switch', { name: 'Expand tool calls' })).not.toBeChecked()
|
||||
expect(screen.getByRole('switch', { name: 'Expand diffs' })).toBeChecked()
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Change walkthrough' })).toBeInTheDocument()
|
||||
expect(screen.getByText('Walkthrough model')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('writes the theme and toggle preferences', async () => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Label } from '@/components/ui/label'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { SessionAutomationSettings } from './SessionAutomationSettings'
|
||||
import { WalkthroughSettings } from './WalkthroughSettings'
|
||||
|
||||
export function GeneralSettings() {
|
||||
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
|
||||
@@ -196,6 +197,8 @@ export function GeneralSettings() {
|
||||
)}
|
||||
|
||||
<SessionAutomationSettings />
|
||||
|
||||
<WalkthroughSettings />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
|
||||
import { act, render, screen, fireEvent } from '@testing-library/react'
|
||||
import { WalkthroughSettings } from './WalkthroughSettings'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import type { UserPreferences } from '@/api/types/settings'
|
||||
import type { Provider } from '@/api/providers'
|
||||
import { createUseSettingsMock } from '@/test/test-utils'
|
||||
|
||||
vi.mock('@/hooks/useSettings')
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useProviders: vi.fn(),
|
||||
useOpenCodeModelState: vi.fn(),
|
||||
useOpenCodeDefaultModel: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useProviders', () => ({ useProviders: mocks.useProviders }))
|
||||
vi.mock('@/hooks/useModelSelection', () => ({
|
||||
useOpenCodeModelState: mocks.useOpenCodeModelState,
|
||||
useOpenCodeDefaultModel: mocks.useOpenCodeDefaultModel,
|
||||
}))
|
||||
|
||||
const providers: Provider[] = [
|
||||
{
|
||||
id: 'anthropic',
|
||||
name: 'Anthropic',
|
||||
models: [
|
||||
{ id: 'claude-sonnet-4', key: 'claude-sonnet-4', name: 'Claude Sonnet 4', released: 0, free: false },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const basePreferences: UserPreferences = {
|
||||
theme: 'dark',
|
||||
mode: 'build',
|
||||
autoScroll: true,
|
||||
expandDiffs: true,
|
||||
expandToolCalls: false,
|
||||
showReasoning: false,
|
||||
simpleChatMode: false,
|
||||
keyboardShortcuts: {},
|
||||
customCommands: [],
|
||||
}
|
||||
|
||||
function mockUseSettings(overrides: Partial<ReturnType<typeof useSettings>> = {}) {
|
||||
vi.mocked(useSettings).mockReturnValue(createUseSettingsMock({ preferences: basePreferences, ...overrides }))
|
||||
}
|
||||
|
||||
describe('WalkthroughSettings', () => {
|
||||
beforeAll(() => {
|
||||
Element.prototype.hasPointerCapture ??= () => false
|
||||
Element.prototype.setPointerCapture ??= () => {}
|
||||
Element.prototype.releasePointerCapture ??= () => {}
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useProviders.mockReturnValue({ data: { providers, models: [] } })
|
||||
mocks.useOpenCodeModelState.mockReturnValue({ data: { favorite: [], recent: [], variant: {} } })
|
||||
mocks.useOpenCodeDefaultModel.mockReturnValue({ data: null })
|
||||
})
|
||||
|
||||
it('saves a chosen model after the debounce', () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const updateSettings = vi.fn()
|
||||
mockUseSettings({ updateSettings })
|
||||
render(<WalkthroughSettings />)
|
||||
|
||||
fireEvent.focus(screen.getByLabelText('Walkthrough model'))
|
||||
fireEvent.click(screen.getByRole('option', { name: /Claude Sonnet 4/ }))
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(800)
|
||||
})
|
||||
|
||||
expect(updateSettings).toHaveBeenCalledTimes(1)
|
||||
expect(updateSettings).toHaveBeenCalledWith({ walkthroughModel: 'anthropic/claude-sonnet-4' })
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('clears the walkthrough model to an empty string', () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const updateSettings = vi.fn()
|
||||
mockUseSettings({
|
||||
preferences: { ...basePreferences, walkthroughModel: 'anthropic/claude-sonnet-4' },
|
||||
updateSettings,
|
||||
})
|
||||
render(<WalkthroughSettings />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Clear' }))
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(800)
|
||||
})
|
||||
|
||||
expect(updateSettings).toHaveBeenCalledTimes(1)
|
||||
expect(updateSettings).toHaveBeenCalledWith({ walkthroughModel: '' })
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not save an unchanged value', () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const updateSettings = vi.fn()
|
||||
mockUseSettings({
|
||||
preferences: { ...basePreferences, walkthroughModel: 'anthropic/claude-sonnet-4' },
|
||||
updateSettings,
|
||||
})
|
||||
render(<WalkthroughSettings />)
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(800)
|
||||
})
|
||||
|
||||
expect(updateSettings).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not save when no model is stored and the field is empty', () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const updateSettings = vi.fn()
|
||||
mockUseSettings({ updateSettings })
|
||||
render(<WalkthroughSettings />)
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(800)
|
||||
})
|
||||
|
||||
expect(updateSettings).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { useAutosavedSetting } from '@/hooks/useAutosavedSetting'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { ModelCombobox } from '@/components/model/ModelCombobox'
|
||||
|
||||
export function WalkthroughSettings() {
|
||||
const { preferences, updateSettings } = useSettings()
|
||||
const storedWalkthroughModel = preferences?.walkthroughModel
|
||||
|
||||
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">
|
||||
<h2 className="text-lg font-semibold text-foreground">Change walkthrough</h2>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<Label htmlFor="walkthroughModel">Walkthrough model</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Model that writes change walkthroughs. A small, fast model works well. Leave empty to use the session's model, or the OpenCode default.
|
||||
</p>
|
||||
</div>
|
||||
<ModelCombobox
|
||||
id="walkthroughModel"
|
||||
ariaLabel="Walkthrough model"
|
||||
value={walkthroughModel}
|
||||
onChange={setWalkthroughModel}
|
||||
placeholder="Session model"
|
||||
allowCustomValue
|
||||
showClear
|
||||
emptyMeansDefault={false}
|
||||
className="w-full shrink-0 sm:w-64"
|
||||
/>
|
||||
</div>
|
||||
</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)
|
||||
})
|
||||
})
|
||||
@@ -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,7 +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 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(),
|
||||
@@ -17,7 +22,9 @@ vi.mock('@/api/changeWalkthroughs', () => ({
|
||||
|
||||
const walkthroughForA: ChangeWalkthrough = {
|
||||
sessionId: 'ses_A',
|
||||
source: { kind: 'session' },
|
||||
diffHash: 'hash-a',
|
||||
model: null,
|
||||
summary: 'A summary',
|
||||
stops: [],
|
||||
hunks: [],
|
||||
@@ -53,7 +60,7 @@ describe('useGenerateChangeWalkthrough', () => {
|
||||
mocks.generateChangeWalkthrough.mockReturnValue(pending.promise)
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
({ sessionId }: { sessionId: string }) => useGenerateChangeWalkthrough(sessionId),
|
||||
({ sessionId }: { sessionId: string }) => useGenerateChangeWalkthrough(sessionId, DEFAULT_WALKTHROUGH_SOURCE),
|
||||
{ initialProps: { sessionId: 'ses_A' }, wrapper: createWrapper(queryClient) },
|
||||
)
|
||||
|
||||
@@ -61,7 +68,7 @@ describe('useGenerateChangeWalkthrough', () => {
|
||||
result.current.mutate({})
|
||||
})
|
||||
await waitFor(() => {
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_A', {})
|
||||
expect(mocks.generateChangeWalkthrough).toHaveBeenCalledWith('ses_A', { source: { kind: 'session' } })
|
||||
})
|
||||
|
||||
rerender({ sessionId: 'ses_B' })
|
||||
@@ -71,9 +78,11 @@ describe('useGenerateChangeWalkthrough', () => {
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryClient.getQueryData(changeWalkthroughQueryKey('ses_A'))).toEqual(state({ generating: true }))
|
||||
expect(queryClient.getQueryData(changeWalkthroughQueryKey('ses_A', 'session'))).toEqual(
|
||||
state({ generating: true }),
|
||||
)
|
||||
})
|
||||
expect(queryClient.getQueryData(changeWalkthroughQueryKey('ses_B'))).toBeUndefined()
|
||||
expect(queryClient.getQueryData(changeWalkthroughQueryKey('ses_B', 'session'))).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -90,7 +99,9 @@ describe('useChangeWalkthrough', () => {
|
||||
.mockResolvedValueOnce(state({ generating: true }))
|
||||
.mockResolvedValueOnce(state({ walkthrough: walkthroughForA }))
|
||||
|
||||
const { result } = renderHook(() => useChangeWalkthrough('ses_A', true), { wrapper: createWrapper(queryClient) })
|
||||
const { result } = renderHook(() => useChangeWalkthrough('ses_A', true, DEFAULT_WALKTHROUGH_SOURCE), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.data?.generating).toBe(true))
|
||||
|
||||
@@ -108,4 +119,71 @@ describe('useChangeWalkthrough', () => {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
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())
|
||||
|
||||
renderHook(() => useChangeWalkthrough('ses_A', true, { kind: 'staged' }), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
renderHook(() => useChangeWalkthrough('ses_A', true, { kind: 'unstaged' }), {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(mocks.getChangeWalkthrough).toHaveBeenCalledTimes(2))
|
||||
|
||||
await act(async () => {
|
||||
await queryClient.invalidateQueries({ queryKey: changeWalkthroughQueryKey('ses_A') })
|
||||
})
|
||||
|
||||
await waitFor(() => expect(mocks.getChangeWalkthrough).toHaveBeenCalledTimes(4))
|
||||
})
|
||||
})
|
||||
@@ -1,34 +1,83 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { generateChangeWalkthrough, getChangeWalkthrough } from '@/api/changeWalkthroughs'
|
||||
import type { GenerateChangeWalkthroughRequest } 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
|
||||
|
||||
export function changeWalkthroughQueryKey(sessionId: string) {
|
||||
return ['change-walkthrough', sessionId] as const
|
||||
export function changeWalkthroughQueryKey(sessionId: string, sourceKey?: string) {
|
||||
return sourceKey === undefined
|
||||
? (['change-walkthrough', sessionId] as const)
|
||||
: (['change-walkthrough', sessionId, sourceKey] as const)
|
||||
}
|
||||
|
||||
export function useChangeWalkthrough(sessionId: string | undefined, enabled: boolean) {
|
||||
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 ?? ''),
|
||||
queryFn: () => getChangeWalkthrough(sessionId!),
|
||||
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),
|
||||
})
|
||||
}
|
||||
|
||||
export function useGenerateChangeWalkthrough(sessionId: string | undefined) {
|
||||
export function useGenerateChangeWalkthrough(sessionId: string | undefined, source: WalkthroughSource) {
|
||||
const queryClient = useQueryClient()
|
||||
const sourceKey = walkthroughSourceKey(source)
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (request: GenerateChangeWalkthroughRequest) => {
|
||||
const targetSessionId = sessionId!
|
||||
const state = await generateChangeWalkthrough(targetSessionId, request)
|
||||
return { sessionId: targetSessionId, state }
|
||||
const state = await generateChangeWalkthrough(targetSessionId, { ...request, source })
|
||||
return { sessionId: targetSessionId, sourceKey, state }
|
||||
},
|
||||
onSuccess: ({ sessionId: targetSessionId, state }) => {
|
||||
queryClient.setQueryData(changeWalkthroughQueryKey(targetSessionId), state)
|
||||
onSuccess: ({ sessionId: targetSessionId, sourceKey: targetSourceKey, state }) => {
|
||||
queryClient.setQueryData(changeWalkthroughQueryKey(targetSessionId, targetSourceKey), state)
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseDiffLines, splitDiffHunks } 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);
|
||||
@@ -117,3 +142,222 @@ describe('splitDiffHunks', () => {
|
||||
expect(splitDiffHunks('')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('splitUnifiedDiffByFile', () => {
|
||||
it('splits a modified file and counts additions and removals', () => {
|
||||
const result = splitUnifiedDiffByFile(DIFF);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({ file: 'src/app.ts', status: 'modified', additions: 3, deletions: 2 });
|
||||
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',
|
||||
'new file mode 100644',
|
||||
'index 0000000..1111111',
|
||||
'--- /dev/null',
|
||||
'+++ b/src/new.ts',
|
||||
'@@ -0,0 +1,2 @@',
|
||||
'+one',
|
||||
'+two',
|
||||
].join('\n');
|
||||
|
||||
const [file] = splitUnifiedDiffByFile(diff);
|
||||
|
||||
expect(file).toMatchObject({ file: 'src/new.ts', status: 'added', additions: 2, deletions: 0 });
|
||||
});
|
||||
|
||||
it('reads a deleted file from the old side', () => {
|
||||
const diff = [
|
||||
'diff --git a/src/old.ts b/src/old.ts',
|
||||
'deleted file mode 100644',
|
||||
'index 1111111..0000000',
|
||||
'--- a/src/old.ts',
|
||||
'+++ /dev/null',
|
||||
'@@ -1,2 +0,0 @@',
|
||||
'-one',
|
||||
'-two',
|
||||
].join('\n');
|
||||
|
||||
const [file] = splitUnifiedDiffByFile(diff);
|
||||
|
||||
expect(file).toMatchObject({ file: 'src/old.ts', status: 'deleted', additions: 0, deletions: 2 });
|
||||
});
|
||||
|
||||
it('reads a renamed file with no content changes', () => {
|
||||
const diff = [
|
||||
'diff --git a/src/old.ts b/src/new.ts',
|
||||
'similarity index 100%',
|
||||
'rename from src/old.ts',
|
||||
'rename to src/new.ts',
|
||||
].join('\n');
|
||||
|
||||
const [file] = splitUnifiedDiffByFile(diff);
|
||||
|
||||
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',
|
||||
'index 1111111..2222222 100644',
|
||||
'Binary files a/assets/logo.png and b/assets/logo.png differ',
|
||||
].join('\n');
|
||||
|
||||
const [file] = splitUnifiedDiffByFile(diff);
|
||||
|
||||
expect(file).toMatchObject({ file: 'assets/logo.png', status: 'modified' });
|
||||
expect(file!.patch).not.toContain('@@');
|
||||
});
|
||||
|
||||
it('splits multiple files', () => {
|
||||
const diff = [
|
||||
DIFF,
|
||||
'',
|
||||
'diff --git a/src/other.ts b/src/other.ts',
|
||||
'--- a/src/other.ts',
|
||||
'+++ b/src/other.ts',
|
||||
'@@ -1 +1 @@',
|
||||
'-a',
|
||||
'+b',
|
||||
].join('\n');
|
||||
|
||||
expect(splitUnifiedDiffByFile(diff).map((entry) => entry.file)).toEqual(['src/app.ts', 'src/other.ts']);
|
||||
});
|
||||
|
||||
it('parses a path containing a space with the trailing tab git appends', () => {
|
||||
const diff = [
|
||||
'diff --git a/my file.txt b/my file.txt',
|
||||
'index 5626abf..f719efd 100644',
|
||||
'--- a/my file.txt\t',
|
||||
'+++ b/my file.txt\t',
|
||||
'@@ -1 +1 @@',
|
||||
'-one',
|
||||
'+two',
|
||||
].join('\n');
|
||||
|
||||
const [file] = splitUnifiedDiffByFile(diff);
|
||||
|
||||
expect(file).toMatchObject({ file: 'my file.txt', status: 'modified' });
|
||||
});
|
||||
|
||||
it('decodes a C-quoted octal UTF-8 path', () => {
|
||||
const diff = [
|
||||
'diff --git "a/\\303\\251.txt" "b/\\303\\251.txt"',
|
||||
'index 587be6b..ccc9bd6 100644',
|
||||
'--- "a/\\303\\251.txt"',
|
||||
'+++ "b/\\303\\251.txt"',
|
||||
'@@ -1 +1 @@',
|
||||
'-x',
|
||||
'+xx',
|
||||
].join('\n');
|
||||
|
||||
const [file] = splitUnifiedDiffByFile(diff);
|
||||
|
||||
expect(file).toMatchObject({ file: 'é.txt', status: 'modified' });
|
||||
});
|
||||
|
||||
it('decodes a quoted rename target', () => {
|
||||
const diff = [
|
||||
'diff --git "a/\\303\\251.txt" "b/\\303\\251 renamed.txt"',
|
||||
'similarity index 100%',
|
||||
'rename from "\\303\\251.txt"',
|
||||
'rename to "\\303\\251 renamed.txt"',
|
||||
].join('\n');
|
||||
|
||||
const [file] = splitUnifiedDiffByFile(diff);
|
||||
|
||||
expect(file).toMatchObject({ file: 'é renamed.txt', status: 'modified' });
|
||||
});
|
||||
|
||||
it('decodes a quoted path in the header fallback', () => {
|
||||
const diff = [
|
||||
'diff --git "a/\\303\\251.bin" "b/\\303\\251.bin"',
|
||||
'index 1111111..2222222 100644',
|
||||
'Binary files "a/\\303\\251.bin" and "b/\\303\\251.bin" differ',
|
||||
].join('\n');
|
||||
|
||||
const [file] = splitUnifiedDiffByFile(diff);
|
||||
|
||||
expect(file).toMatchObject({ file: 'é.bin', status: 'modified' });
|
||||
});
|
||||
|
||||
it('decodes a quoted header path when only the new side is quoted', () => {
|
||||
const diff = [
|
||||
'diff --git a/plain.bin "b/\\303\\251.bin"',
|
||||
'index 1111111..2222222 100644',
|
||||
'Binary files a/plain.bin and "b/\\303\\251.bin" differ',
|
||||
].join('\n');
|
||||
|
||||
const [file] = splitUnifiedDiffByFile(diff);
|
||||
|
||||
expect(file).toMatchObject({ file: 'é.bin', status: 'modified' });
|
||||
});
|
||||
|
||||
it('returns an empty list for an empty diff', () => {
|
||||
expect(splitUnifiedDiffByFile('')).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,107 @@
|
||||
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 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() }),
|
||||
])
|
||||
|
||||
export type WalkthroughSource = z.infer<typeof WalkthroughSourceSchema>
|
||||
|
||||
export const DEFAULT_WALKTHROUGH_SOURCE: WalkthroughSource = { kind: 'session' }
|
||||
|
||||
export function walkthroughSourceKey(source: WalkthroughSource): string {
|
||||
switch (source.kind) {
|
||||
case 'session':
|
||||
case 'uncommitted':
|
||||
case 'staged':
|
||||
case 'unstaged':
|
||||
return source.kind
|
||||
case 'branch':
|
||||
return `branch:${source.base ?? ''}`
|
||||
case 'pullRequest':
|
||||
return `pr:${source.number}:${source.base ?? ''}`
|
||||
}
|
||||
}
|
||||
|
||||
export function describeWalkthroughSource(source: WalkthroughSource): string {
|
||||
switch (source.kind) {
|
||||
case 'session':
|
||||
return 'the changes in this session'
|
||||
case 'uncommitted':
|
||||
return 'uncommitted changes'
|
||||
case 'staged':
|
||||
return 'staged changes'
|
||||
case 'unstaged':
|
||||
return 'unstaged changes'
|
||||
case 'branch':
|
||||
return source.base ? `branch against ${source.base}` : 'branch against the default branch'
|
||||
case 'pullRequest':
|
||||
return `pull request #${source.number}`
|
||||
}
|
||||
}
|
||||
|
||||
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:')) {
|
||||
return toWalkthroughSource({ kind: 'branch', base: key.slice('branch:'.length) })
|
||||
}
|
||||
if (key.startsWith('pr:')) {
|
||||
const rest = key.slice('pr:'.length)
|
||||
const separator = rest.indexOf(':')
|
||||
if (separator < 0) {
|
||||
return null
|
||||
}
|
||||
return toWalkthroughSource({
|
||||
kind: 'pullRequest',
|
||||
number: Number(rest.slice(0, separator)),
|
||||
base: rest.slice(separator + 1),
|
||||
})
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function parseWalkthroughSourceCandidate(candidate: unknown): WalkthroughSource | null {
|
||||
const parsed = WalkthroughSourceSchema.safeParse(candidate)
|
||||
return parsed.success ? parsed.data : null
|
||||
}
|
||||
|
||||
export const WalkthroughHunkSchema = z.object({
|
||||
id: z.string(),
|
||||
@@ -12,28 +110,35 @@ 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>;
|
||||
|
||||
export const WalkthroughStopSchema = z.object({
|
||||
id: z.string(),
|
||||
title: z.string(),
|
||||
explanation: z.string(),
|
||||
hunkIds: z.array(z.string()),
|
||||
status: z.enum(["pending", "ready", "failed"]),
|
||||
explanationKey: z.string().nullable(),
|
||||
});
|
||||
|
||||
export type WalkthroughStop = z.infer<typeof WalkthroughStopSchema>;
|
||||
|
||||
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>;
|
||||
|
||||
export const ChangeWalkthroughSchema = z.object({
|
||||
sessionId: z.string(),
|
||||
source: WalkthroughSourceSchema,
|
||||
diffHash: z.string(),
|
||||
model: z.string().nullable(),
|
||||
summary: z.string(),
|
||||
stops: z.array(WalkthroughStopSchema),
|
||||
hunks: z.array(WalkthroughHunkSchema),
|
||||
@@ -61,8 +166,27 @@ 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(),
|
||||
});
|
||||
|
||||
export type GenerateChangeWalkthroughRequest = z.infer<typeof GenerateChangeWalkthroughRequestSchema>;
|
||||
@@ -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,6 +51,7 @@ export const AssistantSettingsPatchSchema = UserPreferencesSchema.pick({
|
||||
colorTheme: true,
|
||||
mode: true,
|
||||
defaultModel: true,
|
||||
walkthroughModel: true,
|
||||
defaultAgent: true,
|
||||
autoScroll: true,
|
||||
expandDiffs: true,
|
||||
|
||||
@@ -177,6 +177,7 @@ export const UserPreferencesSchema = z.object({
|
||||
colorTheme: ColorThemeIdSchema.optional(),
|
||||
mode: z.enum(["plan", "build"]),
|
||||
defaultModel: z.string().optional(),
|
||||
walkthroughModel: z.string().optional(),
|
||||
defaultAgent: z.string().optional(),
|
||||
autoScroll: z.boolean(),
|
||||
expandDiffs: z.boolean(),
|
||||
|
||||
@@ -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;
|
||||
@@ -115,3 +130,159 @@ export function splitDiffHunks(patch: string): DiffHunk[] {
|
||||
function toHunk(lines: string[]): DiffHunk {
|
||||
return { header: lines[0]!, text: lines.join("\n") };
|
||||
}
|
||||
|
||||
export function splitUnifiedDiffByFile(diff: string): FileDiffInfo[] {
|
||||
const blocks: string[][] = [];
|
||||
|
||||
for (const line of diff.split("\n")) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
return blocks.map((lines) => toUnifiedFileDiff(lines));
|
||||
}
|
||||
|
||||
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: FileDiffInfo["status"] = "modified";
|
||||
|
||||
if (newPath && newPath.slice(4) !== "/dev/null") {
|
||||
file = parseDiffPathToken(newPath.slice(4), "b/");
|
||||
} else if (oldPath && oldPath.slice(4) !== "/dev/null") {
|
||||
file = parseDiffPathToken(oldPath.slice(4), "a/");
|
||||
} else if (renameTo) {
|
||||
file = parseDiffPathToken(renameTo.slice("rename to ".length), "");
|
||||
} else {
|
||||
file = newPathFromDiffHeader(header);
|
||||
}
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("new file mode")) {
|
||||
status = "added";
|
||||
} else if (line.startsWith("deleted file mode")) {
|
||||
status = "deleted";
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
return path.startsWith(prefix) ? path.slice(prefix.length) : path;
|
||||
}
|
||||
|
||||
const GIT_C_ESCAPES: Record<string, number> = {
|
||||
a: 0x07,
|
||||
b: 0x08,
|
||||
f: 0x0c,
|
||||
n: 0x0a,
|
||||
r: 0x0d,
|
||||
t: 0x09,
|
||||
v: 0x0b,
|
||||
"\\": 0x5c,
|
||||
'"': 0x22,
|
||||
};
|
||||
|
||||
function parseDiffPathToken(raw: string, prefix: string): string {
|
||||
const token = raw.startsWith('"') ? decodeGitQuotedPath(raw) : raw.split("\t")[0]!;
|
||||
return stripDiffPathPrefix(token, prefix);
|
||||
}
|
||||
|
||||
function decodeGitQuotedPath(raw: string): string {
|
||||
const bytes: number[] = [];
|
||||
const encoder = new TextEncoder();
|
||||
let index = 1;
|
||||
|
||||
while (index < raw.length) {
|
||||
const char = raw[index]!;
|
||||
if (char === '"') {
|
||||
break;
|
||||
}
|
||||
if (char === "\\") {
|
||||
const octal = /^[0-7]{1,3}/.exec(raw.slice(index + 1));
|
||||
if (octal) {
|
||||
bytes.push(parseInt(octal[0]!, 8) & 0xff);
|
||||
index += 1 + octal[0]!.length;
|
||||
continue;
|
||||
}
|
||||
const next = raw[index + 1];
|
||||
if (next === undefined) {
|
||||
break;
|
||||
}
|
||||
const escaped = GIT_C_ESCAPES[next];
|
||||
bytes.push(...(escaped === undefined ? encoder.encode(next) : [escaped]));
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
bytes.push(...encoder.encode(char));
|
||||
index += 1;
|
||||
}
|
||||
|
||||
return new TextDecoder().decode(new Uint8Array(bytes));
|
||||
}
|
||||
|
||||
function newPathFromDiffHeader(header: string): string {
|
||||
const match = /^diff --(?:git|cc|combined) (.*)$/.exec(header);
|
||||
const rest = match ? match[1]! : "";
|
||||
|
||||
if (rest.startsWith('"')) {
|
||||
const end = findClosingQuoteFrom(rest, 0);
|
||||
if (end >= 0) {
|
||||
let index = end + 1;
|
||||
while (rest[index] === " ") {
|
||||
index += 1;
|
||||
}
|
||||
return stripKnownDiffPrefix(parseDiffPathToken(rest.slice(index), ""));
|
||||
}
|
||||
}
|
||||
|
||||
const quoted = rest.indexOf(' "');
|
||||
if (quoted >= 0) {
|
||||
return stripKnownDiffPrefix(parseDiffPathToken(rest.slice(quoted + 1), ""));
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
if (raw[index] === '"') {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
Reference in new issue
Block a user