mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
section 12: Phase 12 — Per-source storage, service and routes
This commit is contained in:
1 parent
11c23da67e
commit
d5f56fc061
12 files changed
+459
-152
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,
|
||||
]
|
||||
@@ -272,7 +272,7 @@ const sessionGoalService = new SessionGoalService(db, openCodeClient, sessionSet
|
||||
sessionGoalService.loadOpenGoals()
|
||||
|
||||
const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService)
|
||||
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService)
|
||||
const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService, gitAuthService)
|
||||
|
||||
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,14 @@ 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 state = await service.getState(c.req.param('sessionId'), source)
|
||||
return c.json(state)
|
||||
} catch (error) {
|
||||
return handleServiceError(c, error, 'Failed to read change walkthrough', ServiceError)
|
||||
|
||||
@@ -10,22 +10,26 @@ import {
|
||||
type SessionInfo,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import {
|
||||
DEFAULT_WALKTHROUGH_SOURCE,
|
||||
WALKTHROUGH_DIFF_MAX_CHARS,
|
||||
WALKTHROUGH_HUNK_MAX_CHARS,
|
||||
WALKTHROUGH_MAX_STOPS,
|
||||
WALKTHROUGH_OUTLINE_LINE_MAX_CHARS,
|
||||
WALKTHROUGH_OUTLINE_PREVIEW_LINES,
|
||||
WALKTHROUGH_TEXT_MAX_CHARS,
|
||||
describeWalkthroughSource,
|
||||
walkthroughSourceKey,
|
||||
type ChangeWalkthrough,
|
||||
type ChangeWalkthroughState,
|
||||
type GenerateChangeWalkthroughRequest,
|
||||
type WalkthroughGenerationError,
|
||||
type WalkthroughHunk,
|
||||
type WalkthroughOmittedFile,
|
||||
type WalkthroughSource,
|
||||
type WalkthroughStop,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { splitDiffHunks, type DiffHunk } from '@opencode-manager/shared/utils'
|
||||
import { deleteChangeWalkthrough, getChangeWalkthrough, saveChangeWalkthrough } from '../db/change-walkthroughs'
|
||||
import { deleteChangeWalkthroughs, getChangeWalkthrough, saveChangeWalkthrough } from '../db/change-walkthroughs'
|
||||
import { getErrorMessage } from '../utils/error-utils'
|
||||
import { ServiceError } from '../utils/service-error'
|
||||
import { truncateText } from '../utils/text-truncate'
|
||||
@@ -35,7 +39,8 @@ import { logger } from '../utils/logger'
|
||||
import { GenerateTextTimeoutError, generateTextWithTimeout } from './opencode/generate-text'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { ChangeWalkthroughError } from './change-walkthrough-error'
|
||||
import { readSessionChanges } from './session-changes'
|
||||
import { readWalkthroughChanges } from './walkthrough-sources'
|
||||
import type { GitAuthService } from './git-auth'
|
||||
import type { SettingsService } from './settings'
|
||||
import type { SSEEvent } from './sse-aggregator'
|
||||
|
||||
@@ -141,6 +146,15 @@ function computeModelKey(model: ModelRef | undefined): string {
|
||||
return model ? formatOpenCodeModelRef(model) : 'default'
|
||||
}
|
||||
|
||||
function entryKey(sessionId: string, source: WalkthroughSource): string {
|
||||
return `${sessionId}\0${walkthroughSourceKey(source)}`
|
||||
}
|
||||
|
||||
function walkthroughTitle(session: SessionInfo, source: WalkthroughSource): string {
|
||||
const base = session.title ?? session.id
|
||||
return source.kind === 'session' ? base : `${base} — ${describeWalkthroughSource(source)}`
|
||||
}
|
||||
|
||||
function applyReuse(stop: WalkthroughStop, reusable: Map<string, string>, modelKey: string): WalkthroughStop {
|
||||
const key = computeExplanationKey(modelKey, stop.hunkIds)
|
||||
const explanation = reusable.get(key)
|
||||
@@ -613,40 +627,56 @@ export class ChangeWalkthroughService {
|
||||
private readonly db: Database,
|
||||
private readonly openCodeClient: OpenCodeClient,
|
||||
private readonly settingsService: SettingsService,
|
||||
private readonly gitAuthService: GitAuthService,
|
||||
options: ChangeWalkthroughServiceOptions = {},
|
||||
) {
|
||||
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
||||
}
|
||||
|
||||
async getState(sessionId: string): Promise<ChangeWalkthroughState> {
|
||||
await this.readSession(sessionId)
|
||||
async getState(
|
||||
sessionId: string,
|
||||
source: WalkthroughSource = DEFAULT_WALKTHROUGH_SOURCE,
|
||||
): Promise<ChangeWalkthroughState> {
|
||||
const session = await this.readSession(sessionId)
|
||||
const key = entryKey(sessionId, source)
|
||||
|
||||
const currentDiffHash = this.inFlight.has(sessionId)
|
||||
? this.currentHashes.get(sessionId) ?? null
|
||||
: await this.readCurrentDiffHash(sessionId)
|
||||
const currentDiffHash = this.inFlight.has(key)
|
||||
? this.currentHashes.get(key) ?? null
|
||||
: await this.readCurrentDiffHash(session, source, key)
|
||||
|
||||
const walkthrough = getChangeWalkthrough(this.db, sessionId)
|
||||
const walkthrough = getChangeWalkthrough(this.db, sessionId, walkthroughSourceKey(source))
|
||||
return {
|
||||
walkthrough,
|
||||
currentDiffHash,
|
||||
stale: walkthrough !== null && currentDiffHash !== null && walkthrough.diffHash !== currentDiffHash,
|
||||
generating: this.inFlight.has(sessionId),
|
||||
error: this.failures.get(sessionId) ?? null,
|
||||
generating: this.inFlight.has(key),
|
||||
error: this.failures.get(key) ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
private async readCurrentDiffHash(sessionId: string): Promise<string | null> {
|
||||
const cached = this.currentHashes.get(sessionId)
|
||||
if (cached !== undefined) {
|
||||
return cached
|
||||
private async readCurrentDiffHash(
|
||||
session: SessionInfo,
|
||||
source: WalkthroughSource,
|
||||
key: string,
|
||||
): Promise<string | null> {
|
||||
if (source.kind === 'session') {
|
||||
const cached = this.currentHashes.get(key)
|
||||
if (cached !== undefined) {
|
||||
return cached
|
||||
}
|
||||
}
|
||||
|
||||
const epoch = this.hashEpochs.get(sessionId) ?? 0
|
||||
const epoch = this.hashEpochs.get(key) ?? 0
|
||||
try {
|
||||
const changes = await readSessionChanges(this.openCodeClient, sessionId)
|
||||
const changes = await readWalkthroughChanges({
|
||||
client: this.openCodeClient,
|
||||
session,
|
||||
source,
|
||||
gitEnv: this.gitAuthService.getGitEnvironment(true),
|
||||
})
|
||||
const hash = computeChangesHash(changes)
|
||||
if ((this.hashEpochs.get(sessionId) ?? 0) === epoch) {
|
||||
this.currentHashes.set(sessionId, hash)
|
||||
if ((this.hashEpochs.get(key) ?? 0) === epoch) {
|
||||
this.currentHashes.set(key, hash)
|
||||
}
|
||||
return hash
|
||||
} catch {
|
||||
@@ -654,52 +684,77 @@ export class ChangeWalkthroughService {
|
||||
}
|
||||
}
|
||||
|
||||
private invalidateCurrentHash(sessionId: string): void {
|
||||
this.currentHashes.delete(sessionId)
|
||||
this.hashEpochs.set(sessionId, (this.hashEpochs.get(sessionId) ?? 0) + 1)
|
||||
private invalidateCurrentHash(key: string): void {
|
||||
this.currentHashes.delete(key)
|
||||
this.hashEpochs.set(key, (this.hashEpochs.get(key) ?? 0) + 1)
|
||||
}
|
||||
|
||||
generate(sessionId: string, request: GenerateChangeWalkthroughRequest): Promise<{ walkthrough: ChangeWalkthrough; created: boolean }> {
|
||||
generate(
|
||||
sessionId: string,
|
||||
request: GenerateChangeWalkthroughRequest,
|
||||
): Promise<{ walkthrough: ChangeWalkthrough; created: boolean }> {
|
||||
return this.begin(sessionId, request).result
|
||||
}
|
||||
|
||||
async startGeneration(sessionId: string, request: GenerateChangeWalkthroughRequest): Promise<ChangeWalkthroughState> {
|
||||
const entry = this.begin(sessionId, request)
|
||||
await Promise.race([entry.modelStarted, entry.result])
|
||||
return this.getState(sessionId)
|
||||
return this.getState(sessionId, request.source ?? DEFAULT_WALKTHROUGH_SOURCE)
|
||||
}
|
||||
|
||||
/** Removes the stored walkthrough of a deleted session, including one still being generated. */
|
||||
/** Removes the stored walkthroughs of a deleted session, including one still being generated. */
|
||||
handleEvent(event: SSEEvent): void {
|
||||
switch (event.type) {
|
||||
case 'session.deleted': {
|
||||
const { sessionID } = event.data
|
||||
if (this.inFlight.has(sessionID)) {
|
||||
this.deletedDuringGeneration.add(sessionID)
|
||||
const prefix = `${sessionID}\0`
|
||||
for (const key of this.inFlight.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
this.deletedDuringGeneration.add(key)
|
||||
}
|
||||
}
|
||||
this.failures.delete(sessionID)
|
||||
this.invalidateCurrentHash(sessionID)
|
||||
deleteChangeWalkthrough(this.db, sessionID)
|
||||
this.clearSessionState(sessionID)
|
||||
deleteChangeWalkthroughs(this.db, sessionID)
|
||||
return
|
||||
}
|
||||
case 'session.execution.started':
|
||||
case 'session.execution.succeeded':
|
||||
case 'session.execution.failed':
|
||||
case 'session.execution.interrupted':
|
||||
this.invalidateCurrentHash(event.data.sessionID)
|
||||
this.invalidateCurrentHash(entryKey(event.data.sessionID, DEFAULT_WALKTHROUGH_SOURCE))
|
||||
return
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private clearSessionState(sessionId: string): void {
|
||||
const prefix = `${sessionId}\0`
|
||||
const keys = new Set([
|
||||
...this.inFlight.keys(),
|
||||
...this.failures.keys(),
|
||||
...this.currentHashes.keys(),
|
||||
...this.hashEpochs.keys(),
|
||||
])
|
||||
for (const key of keys) {
|
||||
if (!key.startsWith(prefix)) {
|
||||
continue
|
||||
}
|
||||
this.inFlight.delete(key)
|
||||
this.failures.delete(key)
|
||||
this.invalidateCurrentHash(key)
|
||||
}
|
||||
}
|
||||
|
||||
private begin(sessionId: string, request: GenerateChangeWalkthroughRequest): InFlightGeneration {
|
||||
const existing = this.inFlight.get(sessionId)
|
||||
const source = request.source ?? DEFAULT_WALKTHROUGH_SOURCE
|
||||
const key = entryKey(sessionId, source)
|
||||
const existing = this.inFlight.get(key)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
|
||||
this.failures.delete(sessionId)
|
||||
this.failures.delete(key)
|
||||
|
||||
let resolveModelStarted: () => void = () => {}
|
||||
const modelStarted = new Promise<void>((resolve) => {
|
||||
@@ -711,37 +766,47 @@ export class ChangeWalkthroughService {
|
||||
resolveModelStarted()
|
||||
}
|
||||
|
||||
const result = this.runGenerate(sessionId, request, markModelStarted)
|
||||
const result = this.runGenerate(sessionId, source, request, markModelStarted)
|
||||
.catch((error) => {
|
||||
if (modelCalled) {
|
||||
this.failures.set(sessionId, toGenerationError(error))
|
||||
this.failures.set(key, toGenerationError(error))
|
||||
}
|
||||
throw error
|
||||
})
|
||||
.finally(() => {
|
||||
this.inFlight.delete(sessionId)
|
||||
this.deletedDuringGeneration.delete(sessionId)
|
||||
this.invalidateCurrentHash(sessionId)
|
||||
this.inFlight.delete(key)
|
||||
this.deletedDuringGeneration.delete(key)
|
||||
this.invalidateCurrentHash(key)
|
||||
})
|
||||
|
||||
result.catch(() => {})
|
||||
|
||||
const entry: InFlightGeneration = { modelStarted, result }
|
||||
this.inFlight.set(sessionId, entry)
|
||||
this.inFlight.set(key, entry)
|
||||
return entry
|
||||
}
|
||||
|
||||
private async runGenerate(
|
||||
sessionId: string,
|
||||
source: WalkthroughSource,
|
||||
request: GenerateChangeWalkthroughRequest,
|
||||
onModelStart: () => void,
|
||||
): Promise<{ walkthrough: ChangeWalkthrough; created: boolean }> {
|
||||
const session = await this.readSession(sessionId)
|
||||
const key = entryKey(sessionId, source)
|
||||
|
||||
let changes: FileDiffInfo[]
|
||||
try {
|
||||
changes = await readSessionChanges(this.openCodeClient, sessionId)
|
||||
changes = await readWalkthroughChanges({
|
||||
client: this.openCodeClient,
|
||||
session,
|
||||
source,
|
||||
gitEnv: this.gitAuthService.getGitEnvironment(true),
|
||||
})
|
||||
} catch (error) {
|
||||
if (error instanceof ChangeWalkthroughError) {
|
||||
throw error
|
||||
}
|
||||
throw new ChangeWalkthroughError(getErrorMessage(error) || 'Failed to read session changes', 502, {
|
||||
code: 'WALKTHROUGH_CHANGES_UNAVAILABLE',
|
||||
})
|
||||
@@ -754,10 +819,10 @@ export class ChangeWalkthroughService {
|
||||
}
|
||||
|
||||
const diffHash = computeChangesHash(changes)
|
||||
this.currentHashes.set(sessionId, diffHash)
|
||||
this.currentHashes.set(key, diffHash)
|
||||
|
||||
const previous = getChangeWalkthrough(this.db, sessionId)
|
||||
const title = session.title ?? sessionId
|
||||
const previous = getChangeWalkthrough(this.db, sessionId, walkthroughSourceKey(source))
|
||||
const title = walkthroughTitle(session, source)
|
||||
const model = this.resolveWalkthroughModel(session)
|
||||
const modelKey = computeModelKey(model)
|
||||
const storedModel = model ? formatOpenCodeModelRef(model) : null
|
||||
@@ -777,7 +842,7 @@ export class ChangeWalkthroughService {
|
||||
{ ...previous, model: storedModel },
|
||||
onModelStart,
|
||||
)
|
||||
if (this.deletedDuringGeneration.has(sessionId)) {
|
||||
if (this.deletedDuringGeneration.has(key)) {
|
||||
throw new ChangeWalkthroughError('Session not found', 404)
|
||||
}
|
||||
return { walkthrough: resumed, created: true }
|
||||
@@ -796,6 +861,7 @@ export class ChangeWalkthroughService {
|
||||
if (hunks.length === 0) {
|
||||
const walkthrough: ChangeWalkthrough = {
|
||||
sessionId,
|
||||
source,
|
||||
diffHash,
|
||||
model: storedModel,
|
||||
summary: MECHANICAL_ONLY_SUMMARY,
|
||||
@@ -831,6 +897,7 @@ export class ChangeWalkthroughService {
|
||||
const stops = parsed.stops.map((stop) => applyReuse(stop, reusable, modelKey))
|
||||
const walkthrough: ChangeWalkthrough = {
|
||||
sessionId,
|
||||
source,
|
||||
diffHash,
|
||||
model: storedModel,
|
||||
summary: parsed.summary,
|
||||
@@ -857,6 +924,7 @@ export class ChangeWalkthroughService {
|
||||
|
||||
const walkthrough: ChangeWalkthrough = {
|
||||
sessionId,
|
||||
source,
|
||||
diffHash,
|
||||
model: storedModel,
|
||||
summary: MECHANICAL_ONLY_SUMMARY,
|
||||
@@ -890,6 +958,7 @@ export class ChangeWalkthroughService {
|
||||
const stops = planned.stops.map((stop) => applyReuse(stop, reusable, modelKey))
|
||||
let walkthrough: ChangeWalkthrough = {
|
||||
sessionId,
|
||||
source,
|
||||
diffHash,
|
||||
model: storedModel,
|
||||
summary: planned.summary,
|
||||
@@ -916,7 +985,7 @@ export class ChangeWalkthroughService {
|
||||
)
|
||||
}
|
||||
|
||||
if (this.deletedDuringGeneration.has(sessionId)) {
|
||||
if (this.deletedDuringGeneration.has(key)) {
|
||||
throw new ChangeWalkthroughError('Session not found', 404)
|
||||
}
|
||||
|
||||
@@ -1005,7 +1074,7 @@ export class ChangeWalkthroughService {
|
||||
}
|
||||
|
||||
private saveIfSessionLive(walkthrough: ChangeWalkthrough): boolean {
|
||||
if (this.deletedDuringGeneration.has(walkthrough.sessionId)) {
|
||||
if (this.deletedDuringGeneration.has(entryKey(walkthrough.sessionId, walkthrough.source))) {
|
||||
return false
|
||||
}
|
||||
saveChangeWalkthrough(this.db, walkthrough)
|
||||
|
||||
@@ -2,19 +2,23 @@ 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',
|
||||
@@ -43,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
|
||||
|
||||
@@ -55,27 +65,52 @@ 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('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 }))
|
||||
|
||||
@@ -84,43 +119,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,6 +1,9 @@
|
||||
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 { migrate } from '../../src/db/migration-runner'
|
||||
import { allMigrations } from '../../src/db/migrations'
|
||||
@@ -9,6 +12,7 @@ import { SettingsService } from '../../src/services/settings'
|
||||
import { createChangeWalkthroughRoutes } from '../../src/routes/change-walkthroughs'
|
||||
import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { stubLoadedModelCatalog } from '../helpers/stub-opencode-client'
|
||||
import { createCommittedRepo, createGitAuthService, git, uniqueName } from '../helpers/git-fixtures'
|
||||
|
||||
const SESSION_ID = 'ses_walkthrough'
|
||||
|
||||
@@ -32,7 +36,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: {
|
||||
@@ -67,7 +71,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) }
|
||||
}),
|
||||
},
|
||||
},
|
||||
@@ -77,12 +81,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>
|
||||
@@ -94,7 +120,7 @@ describe('change walkthrough routes', () => {
|
||||
migrate(db, allMigrations)
|
||||
sessions = { [SESSION_ID]: { changes: CHANGES } }
|
||||
fake = createFakeClient(sessions)
|
||||
const service = new ChangeWalkthroughService(db, fake.client, new SettingsService(db))
|
||||
const service = new ChangeWalkthroughService(db, fake.client, new SettingsService(db), createGitAuthService())
|
||||
app = new Hono()
|
||||
app.route('/change-walkthroughs', createChangeWalkthroughRoutes(service))
|
||||
})
|
||||
@@ -128,6 +154,47 @@ 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('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) => {
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { Database } from 'bun:sqlite'
|
||||
import type { FileDiffInfo, ModelRef, SessionInfo, SessionMessageInfo } from '@opencode-manager/shared/opencode'
|
||||
import {
|
||||
@@ -17,6 +20,7 @@ import type { OpenCodeClient } from '../../src/services/opencode/client'
|
||||
import { SettingsService } from '../../src/services/settings'
|
||||
import type { SSEEvent } from '../../src/services/sse-aggregator'
|
||||
import { stubLoadedModelCatalog } from '../helpers/stub-opencode-client'
|
||||
import { createCommittedRepo, createGitAuthService, git, uniqueName } from '../helpers/git-fixtures'
|
||||
import {
|
||||
ChangeWalkthroughError,
|
||||
ChangeWalkthroughService,
|
||||
@@ -211,6 +215,31 @@ function sessionEvent(type: string, sessionID: string): SSEEvent {
|
||||
} as unknown as SSEEvent
|
||||
}
|
||||
|
||||
const walkthroughRepoRoot = mkdtempSync(path.join(tmpdir(), 'walkthrough-service-'))
|
||||
|
||||
afterAll(() => {
|
||||
rmSync(walkthroughRepoRoot, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function createChangedRepo(): string {
|
||||
const repo = path.join(walkthroughRepoRoot, 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')
|
||||
return repo
|
||||
}
|
||||
|
||||
function sessionAt(directory: string): SessionInfo {
|
||||
return { id: SESSION_ID, title: 'Title', location: { directory } } as SessionInfo
|
||||
}
|
||||
|
||||
function replyForPrompt(prompt: string): string {
|
||||
const ids = [...prompt.matchAll(/^### (h_\S+) /gm)].map((match) => match[1]!)
|
||||
return modelReply([{ title: 'A', explanation: 'x', hunkIds: ids }])
|
||||
}
|
||||
|
||||
describe('computeChangesHash', () => {
|
||||
it('is stable for identical changes', () => {
|
||||
const changes = [change('src/a.ts', hunkPatch(1))]
|
||||
@@ -784,7 +813,7 @@ describe('ChangeWalkthroughService', () => {
|
||||
db = createTestDb()
|
||||
sessions = { [SESSION_ID]: { changes: threeHunks } }
|
||||
fake = createFakeClient(sessions)
|
||||
service = new ChangeWalkthroughService(db, fake.client, new SettingsService(db))
|
||||
service = new ChangeWalkthroughService(db, fake.client, new SettingsService(db), createGitAuthService())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -1053,7 +1082,7 @@ describe('ChangeWalkthroughService', () => {
|
||||
})
|
||||
|
||||
it('rejects with 504 when generation times out', async () => {
|
||||
const timingOut = new ChangeWalkthroughService(db, fake.client, new SettingsService(db), { timeoutMs: 5 })
|
||||
const timingOut = new ChangeWalkthroughService(db, fake.client, new SettingsService(db), createGitAuthService(), { timeoutMs: 5 })
|
||||
fake.setGenerateImpl(() => new Promise<string>(() => {}))
|
||||
|
||||
await expect(timingOut.generate(SESSION_ID, {})).rejects.toMatchObject({
|
||||
@@ -1445,7 +1474,7 @@ describe('ChangeWalkthroughService', () => {
|
||||
|
||||
service.handleEvent(sessionEvent('session.deleted', SESSION_ID))
|
||||
|
||||
expect(getChangeWalkthrough(db, SESSION_ID)).toBeNull()
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, 'session')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the stored walkthrough for other session events', async () => {
|
||||
@@ -1455,7 +1484,7 @@ describe('ChangeWalkthroughService', () => {
|
||||
service.handleEvent(sessionEvent('session.execution.succeeded', SESSION_ID))
|
||||
service.handleEvent(sessionEvent('session.deleted', 'ses_other'))
|
||||
|
||||
expect(getChangeWalkthrough(db, SESSION_ID)).not.toBeNull()
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, 'session')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('does not store a walkthrough whose session was deleted during generation', async () => {
|
||||
@@ -1470,7 +1499,7 @@ describe('ChangeWalkthroughService', () => {
|
||||
resolveGenerate(coveringReply)
|
||||
|
||||
await expect(pending).rejects.toMatchObject({ status: 404 })
|
||||
expect(getChangeWalkthrough(db, SESSION_ID)).toBeNull()
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, 'session')).toBeNull()
|
||||
})
|
||||
|
||||
it('stores walkthroughs again after an earlier deletion of the same session id', async () => {
|
||||
@@ -1479,7 +1508,39 @@ describe('ChangeWalkthroughService', () => {
|
||||
|
||||
await service.generate(SESSION_ID, {})
|
||||
|
||||
expect(getChangeWalkthrough(db, SESSION_ID)).not.toBeNull()
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, 'session')).not.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('per-source storage', () => {
|
||||
it('stores walkthroughs per source', async () => {
|
||||
const repo = createChangedRepo()
|
||||
sessions[SESSION_ID] = { changes: threeHunks, info: sessionAt(repo) }
|
||||
fake.setGenerateImpl(async (prompt) => replyForPrompt(prompt))
|
||||
|
||||
await service.generate(SESSION_ID, {})
|
||||
await service.generate(SESSION_ID, { source: { kind: 'uncommitted' } })
|
||||
|
||||
const sessionStored = getChangeWalkthrough(db, SESSION_ID, 'session')
|
||||
const uncommittedStored = getChangeWalkthrough(db, SESSION_ID, 'uncommitted')
|
||||
expect(sessionStored).not.toBeNull()
|
||||
expect(uncommittedStored).not.toBeNull()
|
||||
expect(sessionStored!.diffHash).not.toBe(uncommittedStored!.diffHash)
|
||||
expect(uncommittedStored!.source).toEqual({ kind: 'uncommitted' })
|
||||
})
|
||||
|
||||
it('deletes every source when the session is deleted', async () => {
|
||||
const repo = createChangedRepo()
|
||||
sessions[SESSION_ID] = { changes: threeHunks, info: sessionAt(repo) }
|
||||
fake.setGenerateImpl(async (prompt) => replyForPrompt(prompt))
|
||||
|
||||
await service.generate(SESSION_ID, {})
|
||||
await service.generate(SESSION_ID, { source: { kind: 'uncommitted' } })
|
||||
|
||||
service.handleEvent(sessionEvent('session.deleted', SESSION_ID))
|
||||
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, 'session')).toBeNull()
|
||||
expect(getChangeWalkthrough(db, SESSION_ID, 'uncommitted')).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -19,6 +19,7 @@ vi.mock('@/api/changeWalkthroughs', () => ({
|
||||
|
||||
const walkthrough: ChangeWalkthrough = {
|
||||
sessionId: 'ses_1',
|
||||
source: { kind: 'session' },
|
||||
diffHash: 'hash-1',
|
||||
model: null,
|
||||
summary: 'This change adds a greeting.',
|
||||
|
||||
@@ -17,6 +17,7 @@ vi.mock('@/api/changeWalkthroughs', () => ({
|
||||
|
||||
const walkthroughForA: ChangeWalkthrough = {
|
||||
sessionId: 'ses_A',
|
||||
source: { kind: 'session' },
|
||||
diffHash: 'hash-a',
|
||||
model: null,
|
||||
summary: 'A summary',
|
||||
|
||||
@@ -7,6 +7,80 @@ export const WALKTHROUGH_TEXT_MAX_CHARS = 2000;
|
||||
export const WALKTHROUGH_OUTLINE_PREVIEW_LINES = 6;
|
||||
export const WALKTHROUGH_OUTLINE_LINE_MAX_CHARS = 160;
|
||||
|
||||
export const GitRefSchema = z.string().trim().min(1).max(200).regex(/^[^-\s][^\s]*$/)
|
||||
|
||||
export const WalkthroughSourceSchema = z.discriminatedUnion('kind', [
|
||||
z.object({ kind: z.literal('session') }),
|
||||
z.object({ kind: z.literal('uncommitted') }),
|
||||
z.object({ kind: z.literal('staged') }),
|
||||
z.object({ kind: z.literal('unstaged') }),
|
||||
z.object({ kind: z.literal('branch'), base: GitRefSchema.optional() }),
|
||||
z.object({ kind: z.literal('pullRequest'), number: z.number().int().positive(), base: GitRefSchema.optional() }),
|
||||
])
|
||||
|
||||
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 'session changes'
|
||||
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 parseWalkthroughSourceKey(key: string): WalkthroughSource | null {
|
||||
if (key === 'session' || key === 'uncommitted' || key === 'staged' || key === 'unstaged') {
|
||||
return { kind: key }
|
||||
}
|
||||
if (key.startsWith('branch:')) {
|
||||
const base = key.slice('branch:'.length)
|
||||
return parseWalkthroughSourceCandidate(base ? { kind: 'branch', base } : { kind: 'branch' })
|
||||
}
|
||||
if (key.startsWith('pr:')) {
|
||||
const rest = key.slice('pr:'.length)
|
||||
const separator = rest.indexOf(':')
|
||||
if (separator < 0) {
|
||||
return null
|
||||
}
|
||||
const number = Number(rest.slice(0, separator))
|
||||
const base = rest.slice(separator + 1)
|
||||
return parseWalkthroughSourceCandidate(
|
||||
base ? { kind: 'pullRequest', number, base } : { kind: 'pullRequest', number },
|
||||
)
|
||||
}
|
||||
return 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(),
|
||||
file: z.string(),
|
||||
@@ -40,6 +114,7 @@ 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(),
|
||||
@@ -71,63 +146,7 @@ export type ChangeWalkthroughState = z.infer<typeof ChangeWalkthroughStateSchema
|
||||
|
||||
export const GenerateChangeWalkthroughRequestSchema = z.object({
|
||||
regenerate: z.boolean().optional(),
|
||||
source: WalkthroughSourceSchema.optional(),
|
||||
});
|
||||
|
||||
export type GenerateChangeWalkthroughRequest = z.infer<typeof GenerateChangeWalkthroughRequestSchema>;
|
||||
|
||||
export const GitRefSchema = z.string().trim().min(1).max(200).regex(/^[^-\s][^\s]*$/)
|
||||
|
||||
export const WalkthroughSourceSchema = z.discriminatedUnion('kind', [
|
||||
z.object({ kind: z.literal('session') }),
|
||||
z.object({ kind: z.literal('uncommitted') }),
|
||||
z.object({ kind: z.literal('staged') }),
|
||||
z.object({ kind: z.literal('unstaged') }),
|
||||
z.object({ kind: z.literal('branch'), base: GitRefSchema.optional() }),
|
||||
z.object({ kind: z.literal('pullRequest'), number: z.number().int().positive(), base: GitRefSchema.optional() }),
|
||||
])
|
||||
|
||||
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 parseWalkthroughSourceKey(key: string): WalkthroughSource | null {
|
||||
if (key === 'session' || key === 'uncommitted' || key === 'staged' || key === 'unstaged') {
|
||||
return { kind: key }
|
||||
}
|
||||
if (key.startsWith('branch:')) {
|
||||
const base = key.slice('branch:'.length)
|
||||
return parseWalkthroughSourceCandidate(base ? { kind: 'branch', base } : { kind: 'branch' })
|
||||
}
|
||||
if (key.startsWith('pr:')) {
|
||||
const rest = key.slice('pr:'.length)
|
||||
const separator = rest.indexOf(':')
|
||||
if (separator < 0) {
|
||||
return null
|
||||
}
|
||||
const number = Number(rest.slice(0, separator))
|
||||
const base = rest.slice(separator + 1)
|
||||
return parseWalkthroughSourceCandidate(
|
||||
base ? { kind: 'pullRequest', number, base } : { kind: 'pullRequest', number },
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function parseWalkthroughSourceCandidate(candidate: unknown): WalkthroughSource | null {
|
||||
const parsed = WalkthroughSourceSchema.safeParse(candidate)
|
||||
return parsed.success ? parsed.data : null
|
||||
}
|
||||
Reference in new issue
Block a user