Files
openchamber/packages/web/server/lib/small-model/index.test.js
T
Bohdan Triapitsyn 34d0ff7383 feat(walkthrough): guided AI walkthrough for diffs, branches, and PRs (#2572)
A diff is ordered by file path, which is almost never the order in which a
change makes sense. This adds a Walkthrough surface that reorders it: the model
groups related hunks into stops, explains what each group changes about
behavior, and orders the stops so each builds on the last. It explains and
orders; judging code stays with the existing Review action.

Reviews uncommitted work (all, staged, unstaged), a branch against its base, or
a pull request. Generation is always user-initiated — nothing runs on a timer,
on a file change, or as a side effect of opening a panel.

Invariants worth preserving:

- Hunk identity is derived on the server and only there. Ids are content
  hashes, so an anchor that no longer resolves is proof the code it described
  changed, and staleness needs no heuristics. The client matches ids to ids and
  never recomputes them; two implementations would have to agree forever.
- The digest is never truncated. A diff that does not fit the model's context
  is refused with an actionable reason, because a walkthrough written against
  half a diff reads as confident and is wrong.
- Nothing disappears. Lockfiles and other generated output are excluded from
  the model's input by name — never by size — and everything no stop covers is
  listed at the end, so "have I seen all of it" stays answerable.
- Cost is explicit. Results are content-addressed, so returning the working
  tree to an earlier state costs nothing; generation outlives its request, so a
  refresh detaches the client rather than discarding paid-for work, and only an
  explicit cancel stops it.

Supporting changes to shared modules:

- git: expose the existing getRangeDiff as GET /api/git
  listUntrackedPaths and getUntrackedDiffs. The latter resolve the repository
  once for a batch instead of per file, taking a panel
  ~340ms on an 80-file working tree.
- small-model: structured output across four wire forma
  and abort signal, and an onOverflow policy so an oversized prompt fails
  loudly instead of being silently clipped. A provider
  remembered so the prompt-side fallback goes first next time.
- models.dev metadata: surface structured_output as tri
  false blocks a model, a missing field does not, because the catalog omits it
  for roughly half of all models.

Desktop and tablet only: VS Code serves Git through its
these routes, and the mobile shell does not consume the surface registry.

Docs: packages/docs walkthrough page in English and all eight locales.
2026-08-02 16:22:55 +03:00

222 lines
7.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import fs from 'fs';
import os from 'os';
import path from 'path';
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
// The settings override is read straight from disk at module load, so without
// this the suite would resolve whatever small model the developer running it
// happens to have configured.
const TEMP_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'small-model-settings-'));
process.env.OPENCHAMBER_DATA_DIR = TEMP_DATA_DIR;
vi.mock('../opencode/auth.js', () => ({ readAuthFile: vi.fn() }));
vi.mock('../opencode/shared.js', () => ({
readConfig: vi.fn(),
readConfigLayers: vi.fn(),
}));
vi.mock('./catalog.js', () => ({
getModelCatalog: vi.fn(),
getCatalogProvider: vi.fn(),
}));
vi.mock('./call.js', () => ({ callSmallModel: vi.fn() }));
const { generateSmallModelText, describeSmallModel } = await import('./index.js');
const { readAuthFile } = await import('../opencode/auth.js');
const { readConfigLayers } = await import('../opencode/shared.js');
const { getModelCatalog } = await import('./catalog.js');
const { callSmallModel } = await import('./call.js');
// 8k context leaves 4k input tokens after the output reserve → 16k chars.
const CATALOG = {
anthropic: {
id: 'anthropic',
models: {
'claude-haiku-4-5': { id: 'claude-haiku-4-5', limit: { context: 8_000 }, structured_output: true },
'legacy-tiny': { id: 'legacy-tiny', limit: { context: 8_000 }, structured_output: false },
'unlisted-capability': { id: 'unlisted-capability', limit: { context: 8_000 } },
},
},
};
const request = (overrides = {}) => ({
prompt: 'x'.repeat(20_000),
model: 'anthropic/claude-haiku-4-5',
directory: '/proj',
...overrides,
});
describe('generateSmallModelText — oversized input', () => {
beforeEach(() => {
readAuthFile.mockReturnValue({ anthropic: { type: 'api', key: 'sk-ant' } });
readConfigLayers.mockReturnValue({ mergedConfig: {} });
getModelCatalog.mockResolvedValue(CATALOG);
callSmallModel.mockReset();
callSmallModel.mockResolvedValue('generated');
});
afterEach(() => {
vi.clearAllMocks();
});
it('truncates and flags the response by default', async () => {
const result = await generateSmallModelText(request());
expect(result.inputTruncated).toBe(true);
const sent = callSmallModel.mock.calls.at(-1)[0].prompt;
expect(sent.length).toBeLessThan(20_000);
expect(sent.endsWith('…')).toBe(true);
});
it('refuses without calling the provider when the caller cannot survive truncation', async () => {
await expect(generateSmallModelText(request({ onOverflow: 'error' })))
.rejects.toMatchObject({
statusCode: 413,
code: 'context-too-small',
requiredChars: 20_000,
availableChars: 16_000,
});
expect(callSmallModel).not.toHaveBeenCalled();
});
it('leaves an input that fits untouched under either policy', async () => {
const result = await generateSmallModelText(request({ prompt: 'short prompt', onOverflow: 'error' }));
expect(result.inputTruncated).toBeUndefined();
expect(callSmallModel.mock.calls.at(-1)[0].prompt).toBe('short prompt');
});
it('forwards schema, timeout, and abort signal to the transport', async () => {
const controller = new AbortController();
const schema = { type: 'object' };
await generateSmallModelText(request({
prompt: 'short',
responseSchema: schema,
timeoutMs: 240_000,
signal: controller.signal,
}));
expect(callSmallModel.mock.calls.at(-1)[0]).toMatchObject({
responseSchema: schema,
timeoutMs: 240_000,
signal: controller.signal,
});
});
});
describe('describeSmallModel — capability reporting', () => {
beforeEach(() => {
readAuthFile.mockReturnValue({ anthropic: { type: 'api', key: 'sk-ant' } });
readConfigLayers.mockReturnValue({ mergedConfig: { small_model: 'anthropic/claude-haiku-4-5' } });
getModelCatalog.mockResolvedValue(CATALOG);
});
afterEach(() => {
vi.clearAllMocks();
});
it('reports the input budget and a known structured-output capability', async () => {
const described = await describeSmallModel({ directory: '/proj' });
expect(described).toMatchObject({
providerID: 'anthropic',
modelID: 'claude-haiku-4-5',
inputCharBudget: 16_000,
contextTokens: 8_000,
contextKnown: true,
structuredOutput: true,
});
});
it('reports an explicit false so callers can block the model', async () => {
readConfigLayers.mockReturnValue({ mergedConfig: { small_model: 'anthropic/legacy-tiny' } });
const described = await describeSmallModel({ directory: '/proj' });
expect(described.structuredOutput).toBe(false);
});
it('reports null — not false — when the catalog omits the capability', async () => {
readConfigLayers.mockReturnValue({ mergedConfig: { small_model: 'anthropic/unlisted-capability' } });
const described = await describeSmallModel({ directory: '/proj' });
expect(described.structuredOutput).toBeNull();
});
});
// The input reserve and the requested output budget are the same number seen
// from two sides; if they drift, a caller that asks for a large answer overruns
// the model's context and the failure looks like a truncation bug.
describe('output budget and input reserve', () => {
beforeEach(() => {
readAuthFile.mockReturnValue({ anthropic: { type: 'api', key: 'sk-ant' } });
readConfigLayers.mockReturnValue({ mergedConfig: {} });
getModelCatalog.mockResolvedValue({
anthropic: {
id: 'anthropic',
models: {
roomy: { id: 'roomy', limit: { context: 100_000, output: 8_000 } },
unlisted: { id: 'unlisted', limit: { context: 100_000 } },
},
},
});
callSmallModel.mockReset();
callSmallModel.mockResolvedValue('generated');
});
afterEach(() => {
vi.clearAllMocks();
});
it('caps the request at the model\'s advertised output limit', async () => {
await generateSmallModelText({
prompt: 'short',
model: 'anthropic/roomy',
maxOutputTokens: 24_000,
});
expect(callSmallModel.mock.calls.at(-1)[0].maxOutputTokens).toBe(8_000);
});
it('honours the requested budget when the catalog states no output limit', async () => {
await generateSmallModelText({
prompt: 'short',
model: 'anthropic/unlisted',
maxOutputTokens: 24_000,
});
expect(callSmallModel.mock.calls.at(-1)[0].maxOutputTokens).toBe(24_000);
});
it('reserves exactly the requested output budget from the input allowance', async () => {
// 100k context 24k reserved for the answer = 76k tokens ≈ 304k chars.
await expect(generateSmallModelText({
prompt: 'x'.repeat(304_001),
model: 'anthropic/unlisted',
maxOutputTokens: 24_000,
onOverflow: 'error',
})).rejects.toMatchObject({ code: 'context-too-small', availableChars: 304_000 });
await expect(generateSmallModelText({
prompt: 'x'.repeat(303_999),
model: 'anthropic/unlisted',
maxOutputTokens: 24_000,
onOverflow: 'error',
})).resolves.toBeTruthy();
});
it('reports the same budget through describeSmallModel', async () => {
readConfigLayers.mockReturnValue({ mergedConfig: { small_model: 'anthropic/unlisted' } });
const described = await describeSmallModel({ directory: '/proj', outputReserveTokens: 24_000 });
expect(described.inputCharBudget).toBe(304_000);
});
});
afterAll(() => {
fs.rmSync(TEMP_DATA_DIR, { recursive: true, force: true });
});