Compare commits
6 Commits
infra/reco
...
cf03827cd5
| Author | SHA1 | Date | |
|---|---|---|---|
| cf03827cd5 | |||
| 69106b603d | |||
|
|
dbcdcda5e7 | ||
|
|
57595852a4 | ||
|
|
ae46cb99b3 | ||
| 403aef9d16 |
@@ -41,6 +41,18 @@ test.describe('live backlog', () => {
|
|||||||
await expect(
|
await expect(
|
||||||
win.getByText(/cold-start priors · \d+\/20 closed issues estimated|calibrated on \d+ closed/),
|
win.getByText(/cold-start priors · \d+\/20 closed issues estimated|calibrated on \d+ closed/),
|
||||||
).toBeVisible()
|
).toBeVisible()
|
||||||
|
// Real per-milestone forecasts — these milestone names come from gitea, not the
|
||||||
|
// fixture (which lists Beta / Pilot-ready / v1.0).
|
||||||
|
await expect(win.getByText(/P2 — Scheduler/)).toBeVisible()
|
||||||
|
await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-runway.png'), fullPage: true, animations: 'disabled' })
|
||||||
|
|
||||||
|
// Milestone drill-in — clicking a real milestone opens its real detail
|
||||||
|
await win.getByText(/P2 — Scheduler/).click()
|
||||||
|
await expect(win.getByRole('heading', { name: 'P2 — Scheduler + Monte Carlo' })).toBeVisible()
|
||||||
|
await expect(win.getByText(/\d+ issues · est \d+d/)).toBeVisible()
|
||||||
|
await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-milestone.png'), fullPage: true, animations: 'disabled' })
|
||||||
|
await rail.getByRole('button', { name: 'Runway' }).click()
|
||||||
|
|
||||||
await win.getByRole('button', { name: 'Full report' }).click()
|
await win.getByRole('button', { name: 'Full report' }).click()
|
||||||
await expect(win.getByText(/cold-start · \d+\/20|curve active · n ≥ 20/)).toBeVisible()
|
await expect(win.getByText(/cold-start · \d+\/20|curve active · n ≥ 20/)).toBeVisible()
|
||||||
await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-calibration.png'), fullPage: true, animations: 'disabled' })
|
await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-calibration.png'), fullPage: true, animations: 'disabled' })
|
||||||
|
|||||||
@@ -86,11 +86,15 @@ export function registerModelIpc(): void {
|
|||||||
return { configured: true, model }
|
return { configured: true, model }
|
||||||
})
|
})
|
||||||
|
|
||||||
ipcMain.handle('model:chat', async (_event, messages: ChatMessage[]) => {
|
ipcMain.handle('model:chat', async (event, messages: ChatMessage[]) => {
|
||||||
if (!router) return { ok: false as const, reason: 'unconfigured' as const }
|
if (!router) return { ok: false as const, reason: 'unconfigured' as const }
|
||||||
const client = getGiteaClient()
|
const client = getGiteaClient()
|
||||||
const model = await resolveLoadedModel(router.small.baseUrl, router.small.model)
|
const model = await resolveLoadedModel(router.small.baseUrl, router.small.model)
|
||||||
const chat = createChatClient({ ...router.small, model }, fetch)
|
const chat = createChatClient({ ...router.small, model }, fetch)
|
||||||
|
// stream the model's prose to the renderer token-by-token
|
||||||
|
const onToken = (delta: string) => {
|
||||||
|
if (!event.sender.isDestroyed()) event.sender.send('model:chat:token', delta)
|
||||||
|
}
|
||||||
|
|
||||||
// Proposals the model formulates this turn; the renderer approves them (the
|
// Proposals the model formulates this turn; the renderer approves them (the
|
||||||
// write happens through gitea:applyChange, never inside the loop).
|
// write happens through gitea:applyChange, never inside the loop).
|
||||||
@@ -129,10 +133,11 @@ export function registerModelIpc(): void {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const turn = await runAgentTurn({
|
const turn = await runAgentTurn({
|
||||||
complete: (m, t) => chat.complete(m, t),
|
complete: (m, t, ot) => chat.complete(m, t, ot),
|
||||||
messages: [{ role: 'system', content: REGINALD_SYSTEM }, ...messages],
|
messages: [{ role: 'system', content: REGINALD_SYSTEM }, ...messages],
|
||||||
tools: REGINALD_TOOLS,
|
tools: REGINALD_TOOLS,
|
||||||
execute,
|
execute,
|
||||||
|
onToken,
|
||||||
})
|
})
|
||||||
return { ok: true as const, content: turn.content, steps: turn.steps, proposals }
|
return { ok: true as const, content: turn.content, steps: turn.steps, proposals }
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@@ -25,6 +25,12 @@ const api = {
|
|||||||
status: () => ipcRenderer.invoke('model:status'),
|
status: () => ipcRenderer.invoke('model:status'),
|
||||||
/** One agent turn: messages in, Reginald's prose + the tools it consulted out. */
|
/** One agent turn: messages in, Reginald's prose + the tools it consulted out. */
|
||||||
chat: (messages: unknown) => ipcRenderer.invoke('model:chat', messages),
|
chat: (messages: unknown) => ipcRenderer.invoke('model:chat', messages),
|
||||||
|
/** Subscribe to streamed prose tokens for the in-flight turn; returns an unsubscribe. */
|
||||||
|
onToken: (cb: (delta: string) => void) => {
|
||||||
|
const listener = (_e: unknown, delta: string) => cb(delta)
|
||||||
|
ipcRenderer.on('model:chat:token', listener)
|
||||||
|
return () => ipcRenderer.removeListener('model:chat:token', listener)
|
||||||
|
},
|
||||||
/** Decompose a braindump into a proposed issue set (capture_work). */
|
/** Decompose a braindump into a proposed issue set (capture_work). */
|
||||||
capture: (braindump: string) => ipcRenderer.invoke('model:capture', braindump),
|
capture: (braindump: string) => ipcRenderer.invoke('model:capture', braindump),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,22 +1,44 @@
|
|||||||
import React from 'react'
|
import React from 'react'
|
||||||
|
|
||||||
import { COLUMNS, type IssueRef } from '../../data/fixtures.js'
|
import { COLUMNS, type IssueRef } from '../../data/fixtures.js'
|
||||||
|
import { type MilestoneView } from '../../lib/backlog.js'
|
||||||
import { BurnUpCone } from '../charts/chart.js'
|
import { BurnUpCone } from '../charts/chart.js'
|
||||||
import { Badge, Button, Card, Icon, Tag } from '../ui/index.js'
|
import { Badge, Button, Card, Icon, Tag } from '../ui/index.js'
|
||||||
|
|
||||||
// Milestone detail — scope, cone, issues; forecasts stay ranges
|
// Milestone detail — scope, cone, issues; forecasts stay ranges.
|
||||||
export function MilestoneScreen({ onBack, onOpenIssue }: { onBack: () => void; onOpenIssue: (issue: IssueRef) => void }) {
|
// `data` (real milestone forecast) overrides the demo fixture when present.
|
||||||
|
export function MilestoneScreen({
|
||||||
|
onBack,
|
||||||
|
onOpenIssue,
|
||||||
|
data,
|
||||||
|
}: {
|
||||||
|
onBack: () => void
|
||||||
|
onOpenIssue: (issue: IssueRef) => void
|
||||||
|
data?: MilestoneView
|
||||||
|
}) {
|
||||||
const cols = COLUMNS
|
const cols = COLUMNS
|
||||||
const byState = (ids: number[]) =>
|
const byState = (ids: number[]) =>
|
||||||
cols.flatMap((c) => c.issues.map((i) => ({ ...i, col: c.label }))).filter((i) => ids.includes(i.id))
|
cols.flatMap((c) => c.issues.map((i) => ({ ...i, col: c.label }))).filter((i) => ids.includes(i.id))
|
||||||
|
|
||||||
const groups = [
|
const fixtureGroups = [
|
||||||
{ label: 'Steeping', issues: byState([87, 84]) },
|
{ label: 'Steeping', issues: byState([87, 84]) },
|
||||||
{ label: 'In review', issues: byState([92]) },
|
{ label: 'In review', issues: byState([92]) },
|
||||||
{ label: 'Queued', issues: byState([102, 103, 99, 96, 78]) },
|
{ label: 'Queued', issues: byState([102, 103, 99, 96, 78]) },
|
||||||
{ label: 'Done', issues: byState([71, 69, 65]), muted: true },
|
{ label: 'Done', issues: byState([71, 69, 65]), muted: true },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
// real or demo, in one shape the render loop understands
|
||||||
|
const groups = data
|
||||||
|
? data.groups.map((g) => ({ label: g.label, issues: g.issues, muted: g.label === 'Done' }))
|
||||||
|
: fixtureGroups
|
||||||
|
const name = data ? data.name : 'Beta'
|
||||||
|
const dueLine = data
|
||||||
|
? `milestone · due ${data.due} · ${data.soft ? 'soft — scope may flex' : 'hard deadline'}`
|
||||||
|
: 'milestone · due Mar 15 · soft — scope may flex'
|
||||||
|
const forecastLabel = data ? (data.forecastRange ? `80% ${data.forecastRange}` : 'all shipped') : '80% Mar 3–12'
|
||||||
|
const scopeStat = data ? `${data.scopeCount} issues · est ${data.scopeEstDays}d` : '42 issues · est 61d'
|
||||||
|
const doneStat = data ? `${data.doneCount} · ${data.donePct}%` : '24 · 57%'
|
||||||
|
|
||||||
const Stat = ({ label, value, tone }: { label: string; value: string; tone?: string }) => (
|
const Stat = ({ label, value, tone }: { label: string; value: string; tone?: string }) => (
|
||||||
<div style={{ flex: 1, padding: '12px 18px', borderRight: '1px solid var(--line-1)' }}>
|
<div style={{ flex: 1, padding: '12px 18px', borderRight: '1px solid var(--line-1)' }}>
|
||||||
<div style={{ font: 'var(--text-overline)', letterSpacing: 'var(--letter-spacing-wide)', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 5 }}>{label}</div>
|
<div style={{ font: 'var(--text-overline)', letterSpacing: 'var(--letter-spacing-wide)', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 5 }}>{label}</div>
|
||||||
@@ -36,12 +58,12 @@ export function MilestoneScreen({ onBack, onOpenIssue }: { onBack: () => void; o
|
|||||||
<header style={{ borderBottom: 'var(--rule-double)', paddingBottom: 14, display: 'flex', alignItems: 'flex-start', gap: 16 }}>
|
<header style={{ borderBottom: 'var(--rule-double)', paddingBottom: 14, display: 'flex', alignItems: 'flex-start', gap: 16 }}>
|
||||||
<div style={{ flex: 1, minWidth: 0 }}>
|
<div style={{ flex: 1, minWidth: 0 }}>
|
||||||
<p style={{ font: '400 12px var(--font-mono)', color: 'var(--ink-3)', margin: '0 0 6px', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
|
<p style={{ font: '400 12px var(--font-mono)', color: 'var(--ink-3)', margin: '0 0 6px', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
|
||||||
<Icon name="milestone" size={13} /> milestone · due Mar 15 · soft — scope may flex
|
<Icon name="milestone" size={13} /> {dueLine}
|
||||||
</p>
|
</p>
|
||||||
<h1 style={{ font: 'var(--text-display)', color: 'var(--ink-1)', margin: 0 }}>Beta</h1>
|
<h1 style={{ font: 'var(--text-display)', color: 'var(--ink-1)', margin: 0 }}>{name}</h1>
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10 }}>
|
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10 }}>
|
||||||
<Badge tone="ok" dot>ahead of forecast</Badge>
|
<Badge tone="ok" dot>{data ? `${data.doneCount}/${data.scopeCount} done` : 'ahead of forecast'}</Badge>
|
||||||
<span style={{ font: '400 12px var(--font-mono)', color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>80% Mar 3–12</span>
|
<span style={{ font: '400 12px var(--font-mono)', color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>{forecastLabel}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Button variant="secondary" icon="arrow-up-right">Open in Gitea</Button>
|
<Button variant="secondary" icon="arrow-up-right">Open in Gitea</Button>
|
||||||
@@ -51,21 +73,25 @@ export function MilestoneScreen({ onBack, onOpenIssue }: { onBack: () => void; o
|
|||||||
{/* stats strip */}
|
{/* stats strip */}
|
||||||
<Card flush>
|
<Card flush>
|
||||||
<div style={{ display: 'flex' }}>
|
<div style={{ display: 'flex' }}>
|
||||||
<Stat label="Scope" value="42 issues · est 61d" />
|
<Stat label="Scope" value={scopeStat} />
|
||||||
<Stat label="Done" value="24 · 57%" />
|
<Stat label="Done" value={doneStat} />
|
||||||
<Stat label="Forecast" value="80% Mar 3–12" />
|
<Stat label="Forecast" value={forecastLabel} />
|
||||||
<div style={{ flex: 1, padding: '12px 18px' }}>
|
<div style={{ flex: 1, padding: '12px 18px' }}>
|
||||||
<div style={{ font: 'var(--text-overline)', letterSpacing: 'var(--letter-spacing-wide)', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 5 }}>Drift · 7d</div>
|
<div style={{ font: 'var(--text-overline)', letterSpacing: 'var(--letter-spacing-wide)', textTransform: 'uppercase', color: 'var(--ink-3)', marginBottom: 5 }}>Remaining</div>
|
||||||
<div style={{ font: '500 14px var(--font-mono)', color: 'var(--ok)', whiteSpace: 'nowrap' }}>−2d · cone narrowed</div>
|
<div style={{ font: '500 14px var(--font-mono)', color: 'var(--ink-1)', whiteSpace: 'nowrap' }}>{data ? `${data.scopeCount - data.doneCount} open` : '−2d · cone narrowed'}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 14, alignItems: 'start' }}>
|
<div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 14, alignItems: 'start' }}>
|
||||||
<Card overline="Burn-up" title={<>80% this lands <span style={{ whiteSpace: 'nowrap' }}>Mar 3–12</span></>} jade>
|
<Card overline="Burn-up" title={<>80% this lands <span style={{ whiteSpace: 'nowrap' }}>{data ? (data.forecastRange ?? 'shipped') : 'Mar 3–12'}</span></>} jade>
|
||||||
<BurnUpCone />
|
<BurnUpCone data={data?.cone ?? undefined} />
|
||||||
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: '10px 0 0' }}>
|
<p style={{ font: 'var(--text-agent)', color: 'var(--ink-2)', margin: '10px 0 0' }}>
|
||||||
Comfortably ahead. Beta needs #87 more than it needs my commentary.
|
{data
|
||||||
|
? data.cone
|
||||||
|
? `${data.scopeCount - data.doneCount} open of ${data.scopeCount}. Cone over what's left.`
|
||||||
|
: 'Everything here has shipped.'
|
||||||
|
: 'Comfortably ahead. Beta needs #87 more than it needs my commentary.'}
|
||||||
</p>
|
</p>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
|||||||
@@ -2,18 +2,22 @@ import React from 'react'
|
|||||||
|
|
||||||
import { RunwayBar } from '../charts/chart.js'
|
import { RunwayBar } from '../charts/chart.js'
|
||||||
import { Card, Badge, Tag, Icon, IconButton } from '../ui/index.js'
|
import { Card, Badge, Tag, Icon, IconButton } from '../ui/index.js'
|
||||||
import { RUNWAY, CAPACITY } from '../../data/fixtures.js'
|
import { RUNWAY, CAPACITY, type RunwayMilestone } from '../../data/fixtures.js'
|
||||||
|
|
||||||
// Runway — capacity vs milestone dates; ranges, never points
|
// Runway — capacity vs milestone dates; ranges, never points.
|
||||||
|
// `milestones` (real per-milestone forecasts) overrides the demo when present.
|
||||||
export function RunwayScreen({
|
export function RunwayScreen({
|
||||||
onOpenCalibration,
|
onOpenCalibration,
|
||||||
onOpenMilestone,
|
onOpenMilestone,
|
||||||
calibration,
|
calibration,
|
||||||
|
milestones,
|
||||||
}: {
|
}: {
|
||||||
onOpenCalibration: () => void
|
onOpenCalibration: () => void
|
||||||
onOpenMilestone: () => void
|
onOpenMilestone: (id?: number) => void
|
||||||
calibration?: { n: number; coldStart: boolean }
|
calibration?: { n: number; coldStart: boolean }
|
||||||
|
milestones?: RunwayMilestone[]
|
||||||
}) {
|
}) {
|
||||||
|
const rows = milestones && milestones.length ? milestones : RUNWAY
|
||||||
const calibNote = calibration
|
const calibNote = calibration
|
||||||
? calibration.coldStart
|
? calibration.coldStart
|
||||||
? `cold-start priors · ${calibration.n}/20 closed issues estimated`
|
? `cold-start priors · ${calibration.n}/20 closed issues estimated`
|
||||||
@@ -28,8 +32,8 @@ export function RunwayScreen({
|
|||||||
|
|
||||||
<Card overline="Milestones" flush>
|
<Card overline="Milestones" flush>
|
||||||
<div>
|
<div>
|
||||||
{RUNWAY.map((m, i) => (
|
{rows.map((m, i) => (
|
||||||
<div key={m.name} onClick={onOpenMilestone} style={{
|
<div key={m.name} onClick={() => onOpenMilestone(m.id)} style={{
|
||||||
display: 'grid', gridTemplateColumns: '160px 1fr 150px 90px', gap: 16, alignItems: 'center', cursor: 'pointer',
|
display: 'grid', gridTemplateColumns: '160px 1fr 150px 90px', gap: 16, alignItems: 'center', cursor: 'pointer',
|
||||||
padding: '14px 20px', borderTop: i === 0 ? 'none' : '1px solid var(--line-1)',
|
padding: '14px 20px', borderTop: i === 0 ? 'none' : '1px solid var(--line-1)',
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -4,7 +4,14 @@ import logoIcon from '../../design/assets/logo-icon.png'
|
|||||||
import type { IssueChange } from '@commitea/core'
|
import type { IssueChange } from '@commitea/core'
|
||||||
|
|
||||||
import type { IssueRef } from '../../data/fixtures.js'
|
import type { IssueRef } from '../../data/fixtures.js'
|
||||||
import { backlogCalibration, forecastBacklog, issuesToBoardColumns, scheduleFocus } from '../../lib/backlog.js'
|
import {
|
||||||
|
backlogCalibration,
|
||||||
|
forecastBacklog,
|
||||||
|
issuesToBoardColumns,
|
||||||
|
milestoneView,
|
||||||
|
runwayView,
|
||||||
|
scheduleFocus,
|
||||||
|
} from '../../lib/backlog.js'
|
||||||
import { useBacklog } from '../../lib/use-backlog.js'
|
import { useBacklog } from '../../lib/use-backlog.js'
|
||||||
import { PrimitivesGallery } from '../gallery.js'
|
import { PrimitivesGallery } from '../gallery.js'
|
||||||
import { BoardScreen } from '../screens/board-screen.js'
|
import { BoardScreen } from '../screens/board-screen.js'
|
||||||
@@ -87,6 +94,7 @@ export function AppShell() {
|
|||||||
const [offline, setOffline] = useState(false)
|
const [offline, setOffline] = useState(false)
|
||||||
const [issue, setIssue] = useState<IssueRef | null>(null)
|
const [issue, setIssue] = useState<IssueRef | null>(null)
|
||||||
const [readIds, setReadIds] = useState<number[]>([])
|
const [readIds, setReadIds] = useState<number[]>([])
|
||||||
|
const [milestoneId, setMilestoneId] = useState<number | null>(null)
|
||||||
const [backlog, refetchBacklog] = useBacklog()
|
const [backlog, refetchBacklog] = useBacklog()
|
||||||
const boardColumns =
|
const boardColumns =
|
||||||
backlog.status === 'ready' ? issuesToBoardColumns(backlog.issues, backlog.timelines) : undefined
|
backlog.status === 'ready' ? issuesToBoardColumns(backlog.issues, backlog.timelines) : undefined
|
||||||
@@ -98,6 +106,19 @@ export function AppShell() {
|
|||||||
backlog.status === 'ready'
|
backlog.status === 'ready'
|
||||||
? (forecastBacklog(backlog.issues, backlog.deps, new Date(), calibration?.model) ?? undefined)
|
? (forecastBacklog(backlog.issues, backlog.deps, new Date(), calibration?.model) ?? undefined)
|
||||||
: undefined
|
: undefined
|
||||||
|
const runwayMilestones =
|
||||||
|
backlog.status === 'ready' ? runwayView(backlog.issues, backlog.milestones, backlog.deps) : undefined
|
||||||
|
const milestone =
|
||||||
|
backlog.status === 'ready' && milestoneId != null
|
||||||
|
? (milestoneView(
|
||||||
|
milestoneId,
|
||||||
|
backlog.issues,
|
||||||
|
backlog.milestones,
|
||||||
|
backlog.deps,
|
||||||
|
backlog.timelines,
|
||||||
|
calibration?.model,
|
||||||
|
) ?? undefined)
|
||||||
|
: undefined
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light')
|
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light')
|
||||||
@@ -194,14 +215,18 @@ export function AppShell() {
|
|||||||
return (
|
return (
|
||||||
<RunwayScreen
|
<RunwayScreen
|
||||||
onOpenCalibration={() => setView('calibration')}
|
onOpenCalibration={() => setView('calibration')}
|
||||||
onOpenMilestone={() => setView('milestone')}
|
onOpenMilestone={(id) => {
|
||||||
|
setMilestoneId(id ?? null)
|
||||||
|
setView('milestone')
|
||||||
|
}}
|
||||||
calibration={calibration ? { n: calibration.model.n, coldStart: calibration.model.coldStart } : undefined}
|
calibration={calibration ? { n: calibration.model.n, coldStart: calibration.model.coldStart } : undefined}
|
||||||
|
milestones={runwayMilestones}
|
||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
case 'calibration':
|
case 'calibration':
|
||||||
return <CalibrationScreen onBack={() => setView('runway')} data={calibration?.data} />
|
return <CalibrationScreen onBack={() => setView('runway')} data={calibration?.data} />
|
||||||
case 'milestone':
|
case 'milestone':
|
||||||
return <MilestoneScreen onBack={() => setView('runway')} onOpenIssue={openIssue} />
|
return <MilestoneScreen onBack={() => setView('runway')} onOpenIssue={openIssue} data={milestone} />
|
||||||
case 'inbox':
|
case 'inbox':
|
||||||
return (
|
return (
|
||||||
<InboxScreen
|
<InboxScreen
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ export interface ChatPanelProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function ChatPanel({ onOpenDirectives, offline, onApplyChange }: ChatPanelProps) {
|
export function ChatPanel({ onOpenDirectives, offline, onApplyChange }: ChatPanelProps) {
|
||||||
const { msgs, thinking, live, model, steps, proposals, send: sendChat, approve, dismiss } = useChat(onApplyChange)
|
const { msgs, thinking, live, model, steps, proposals, streaming, send: sendChat, approve, dismiss } = useChat(onApplyChange)
|
||||||
// shorten "google/gemma-4-26b-a4b-qat" → "gemma-4-26b" for the header chip
|
// shorten "google/gemma-4-26b-a4b-qat" → "gemma-4-26b" for the header chip
|
||||||
const modelLabel = model ? (model.split('/').pop() ?? model).replace(/-(qat|instruct|it|gguf)$/i, '') : 'gemma-4'
|
const modelLabel = model ? (model.split('/').pop() ?? model).replace(/-(qat|instruct|it|gguf)$/i, '') : 'gemma-4'
|
||||||
const [text, setText] = useState('')
|
const [text, setText] = useState('')
|
||||||
@@ -28,7 +28,7 @@ export function ChatPanel({ onOpenDirectives, offline, onApplyChange }: ChatPane
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const el = scrollRef.current
|
const el = scrollRef.current
|
||||||
if (el) el.scrollTop = el.scrollHeight
|
if (el) el.scrollTop = el.scrollHeight
|
||||||
}, [msgs, thinking])
|
}, [msgs, thinking, streaming])
|
||||||
|
|
||||||
const send = () => {
|
const send = () => {
|
||||||
const t = text.trim()
|
const t = text.trim()
|
||||||
@@ -98,7 +98,14 @@ export function ChatPanel({ onOpenDirectives, offline, onApplyChange }: ChatPane
|
|||||||
The model is away from its desk. Reads still work; writes will wait their turn.
|
The model is away from its desk. Reads still work; writes will wait their turn.
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
{thinking ? <div style={{ font: 'var(--text-agent)', color: 'var(--ink-3)' }}>considering…</div> : null}
|
{streaming ? (
|
||||||
|
<div style={{ font: 'var(--text-agent)', color: 'var(--ink-1)', lineHeight: 1.55 }}>
|
||||||
|
{streaming}
|
||||||
|
<span style={{ opacity: 0.5 }}>▊</span>
|
||||||
|
</div>
|
||||||
|
) : thinking ? (
|
||||||
|
<div style={{ font: 'var(--text-agent)', color: 'var(--ink-3)' }}>considering…</div>
|
||||||
|
) : null}
|
||||||
{!thinking && steps.length ? (
|
{!thinking && steps.length ? (
|
||||||
<div style={{ font: 'var(--text-caption)', color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 5 }}>
|
<div style={{ font: 'var(--text-caption)', color: 'var(--ink-3)', display: 'flex', alignItems: 'center', gap: 5 }}>
|
||||||
<Icon name="eye" size={11} /> consulted {Array.from(new Set(steps.map((s) => s.replace('query_project', 'the project').replace('propose_change', 'the labels').replace('record_directive', 'the directive ledger')))).join(', ')}
|
<Icon name="eye" size={11} /> consulted {Array.from(new Set(steps.map((s) => s.replace('query_project', 'the project').replace('propose_change', 'the labels').replace('record_directive', 'the directive ledger')))).join(', ')}
|
||||||
|
|||||||
@@ -315,6 +315,8 @@ export interface RunwayMilestone {
|
|||||||
spread: number
|
spread: number
|
||||||
tone: 'ok' | 'warn'
|
tone: 'ok' | 'warn'
|
||||||
note: string
|
note: string
|
||||||
|
/** gitea milestone id, for the drill-in (absent on the demo fixture). */
|
||||||
|
id?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export const RUNWAY: RunwayMilestone[] = [
|
export const RUNWAY: RunwayMilestone[] = [
|
||||||
|
|||||||
2
apps/desktop/src/renderer/src/global.d.ts
vendored
2
apps/desktop/src/renderer/src/global.d.ts
vendored
@@ -68,6 +68,8 @@ export interface ModelBridge {
|
|||||||
status(): Promise<{ configured: boolean; model: string | null }>
|
status(): Promise<{ configured: boolean; model: string | null }>
|
||||||
chat(messages: ChatMessage[]): Promise<ChatResult>
|
chat(messages: ChatMessage[]): Promise<ChatResult>
|
||||||
capture(braindump: string): Promise<CaptureResult>
|
capture(braindump: string): Promise<CaptureResult>
|
||||||
|
/** Subscribe to streamed prose tokens; returns an unsubscribe fn. */
|
||||||
|
onToken(cb: (delta: string) => void): () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The result of reading the directive ledger. */
|
/** The result of reading the directive ledger. */
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
fitCalibration,
|
fitCalibration,
|
||||||
forecast,
|
forecast,
|
||||||
type GiteaIssue,
|
type GiteaIssue,
|
||||||
|
type GiteaMilestone,
|
||||||
inferLifecycle,
|
inferLifecycle,
|
||||||
type LifecycleColumn,
|
type LifecycleColumn,
|
||||||
type LifecycleEvent,
|
type LifecycleEvent,
|
||||||
@@ -16,10 +17,17 @@ import {
|
|||||||
type ScheduledItem,
|
type ScheduledItem,
|
||||||
selectFocus,
|
selectFocus,
|
||||||
toDurationModel,
|
toDurationModel,
|
||||||
|
workingDaysBetween,
|
||||||
} from '@commitea/core'
|
} from '@commitea/core'
|
||||||
|
|
||||||
import { type BoardColumn, type BoardIssue, type CalibrationData, type FocusIssue } from '../data/fixtures.js'
|
import {
|
||||||
import { type BurnUpData, buildBurnUpData } from './dates.js'
|
type BoardColumn,
|
||||||
|
type BoardIssue,
|
||||||
|
type CalibrationData,
|
||||||
|
type FocusIssue,
|
||||||
|
type RunwayMilestone,
|
||||||
|
} from '../data/fixtures.js'
|
||||||
|
import { addWorkingDays, type BurnUpData, buildBurnUpData, formatRange, formatShort } from './dates.js'
|
||||||
|
|
||||||
type Timelines = Record<number, LifecycleEvent[]>
|
type Timelines = Record<number, LifecycleEvent[]>
|
||||||
|
|
||||||
@@ -232,3 +240,133 @@ export function scheduleFocus(
|
|||||||
later: toFocusIssue(f.later, inf),
|
later: toFocusIssue(f.later, inf),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-milestone Monte Carlo forecast for the Runway screen — each open milestone's
|
||||||
|
* open scope gets its own cone, and the p80 landing is compared to the milestone's
|
||||||
|
* due date (ok/at-risk). Ranges, never point dates. Milestones with no open scope
|
||||||
|
* (already shipped) are omitted. Falls back to the demo when there's nothing real.
|
||||||
|
*/
|
||||||
|
export function runwayView(
|
||||||
|
issues: GiteaIssue[],
|
||||||
|
milestones: GiteaMilestone[],
|
||||||
|
deps: DependencyEdge[],
|
||||||
|
today: Date = new Date(),
|
||||||
|
): RunwayMilestone[] {
|
||||||
|
const open = issues.filter((i) => i.state === 'open')
|
||||||
|
const rows = milestones
|
||||||
|
.filter((m) => m.state === 'open')
|
||||||
|
.map((m) => ({ m, scope: open.filter((i) => i.milestone?.id === m.id) }))
|
||||||
|
.filter((x) => x.scope.length > 0)
|
||||||
|
.map(({ m, scope }) => {
|
||||||
|
const f = forecast(
|
||||||
|
scope.map((i) => ({
|
||||||
|
number: i.number,
|
||||||
|
title: i.title,
|
||||||
|
labels: i.labels,
|
||||||
|
estimateDays: i.facts.estimateDays,
|
||||||
|
priority: i.facts.priority,
|
||||||
|
})),
|
||||||
|
deps,
|
||||||
|
)
|
||||||
|
const p90 = f.curve.length ? f.curve[f.curve.length - 1].p90Day : f.p95Day
|
||||||
|
const dueDay = m.dueOn ? workingDaysBetween(today, new Date(m.dueOn)) : null
|
||||||
|
return { m, p50: f.p50Day, p80: f.p80Day, p90, dueDay }
|
||||||
|
})
|
||||||
|
|
||||||
|
const horizon = Math.max(1, ...rows.map((r) => Math.max(r.p90, r.dueDay ?? 0)))
|
||||||
|
|
||||||
|
return rows.map(({ m, p50, p80, p90, dueDay }) => {
|
||||||
|
const onTrack = dueDay == null || p80 <= dueDay
|
||||||
|
return {
|
||||||
|
id: m.id,
|
||||||
|
name: m.title,
|
||||||
|
due: m.dueOn ? formatShort(new Date(m.dueOn)) : 'no date',
|
||||||
|
hard: false,
|
||||||
|
p80: formatRange(addWorkingDays(today, p50), addWorkingDays(today, p90)),
|
||||||
|
pos: p80 / horizon,
|
||||||
|
spread: Math.min(0.6, (p90 - p50) / horizon),
|
||||||
|
tone: onTrack ? ('ok' as const) : ('warn' as const),
|
||||||
|
note: dueDay == null ? `${Math.ceil(p80)}d of work` : onTrack ? 'on track' : 'at risk',
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MilestoneGroup {
|
||||||
|
label: string
|
||||||
|
issues: { id: number; title: string; labels: string[]; days?: string }[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MilestoneView {
|
||||||
|
name: string
|
||||||
|
due: string
|
||||||
|
soft: boolean
|
||||||
|
scopeCount: number
|
||||||
|
scopeEstDays: number
|
||||||
|
doneCount: number
|
||||||
|
donePct: number
|
||||||
|
/** p50..p90 landing range for the remaining open scope; null when nothing's open. */
|
||||||
|
forecastRange: string | null
|
||||||
|
cone: BurnUpData | null
|
||||||
|
groups: MilestoneGroup[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Milestone drill-in: real scope, done %, a Monte Carlo cone over the
|
||||||
|
* milestone's remaining open work, and its issues grouped by lifecycle column.
|
||||||
|
* Returns null for an unknown id — the screen then shows the demo fixture.
|
||||||
|
*/
|
||||||
|
export function milestoneView(
|
||||||
|
id: number,
|
||||||
|
issues: GiteaIssue[],
|
||||||
|
milestones: GiteaMilestone[],
|
||||||
|
deps: DependencyEdge[],
|
||||||
|
timelines: Timelines = {},
|
||||||
|
calibration?: CalibrationModel,
|
||||||
|
today: Date = new Date(),
|
||||||
|
): MilestoneView | null {
|
||||||
|
const m = milestones.find((x) => x.id === id)
|
||||||
|
if (!m) return null
|
||||||
|
const all = issues.filter((i) => i.milestone?.id === id)
|
||||||
|
const open = all.filter((i) => i.state === 'open')
|
||||||
|
const done = all.filter((i) => i.state === 'closed')
|
||||||
|
const scopeEstDays = all.reduce((sum, i) => sum + (i.facts.estimateDays ?? 2), 0)
|
||||||
|
|
||||||
|
const model = calibration ? toDurationModel(calibration) : undefined
|
||||||
|
const f = forecast(
|
||||||
|
open.map((i) => ({
|
||||||
|
number: i.number,
|
||||||
|
title: i.title,
|
||||||
|
labels: i.labels,
|
||||||
|
estimateDays: i.facts.estimateDays,
|
||||||
|
priority: i.facts.priority,
|
||||||
|
})),
|
||||||
|
deps,
|
||||||
|
model ? { model } : {},
|
||||||
|
)
|
||||||
|
const cone = buildBurnUpData(f, today)
|
||||||
|
|
||||||
|
const inf = inferAll(all, timelines, today)
|
||||||
|
const groups: MilestoneGroup[] = COLUMN_ORDER.map((key) => ({
|
||||||
|
label: COLUMN_LABELS[key],
|
||||||
|
issues: all
|
||||||
|
.filter((i) => inf.get(i.number)!.column === key)
|
||||||
|
.map((i) => {
|
||||||
|
const days = inf.get(i.number)!.steepingDays
|
||||||
|
return { id: i.number, title: i.title, labels: i.labels, days: days != null ? `${days}d` : undefined }
|
||||||
|
}),
|
||||||
|
})).filter((g) => g.issues.length > 0)
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: m.title,
|
||||||
|
due: m.dueOn ? formatShort(new Date(m.dueOn)) : 'no date',
|
||||||
|
soft: true,
|
||||||
|
scopeCount: all.length,
|
||||||
|
scopeEstDays,
|
||||||
|
doneCount: done.length,
|
||||||
|
donePct: all.length ? Math.round((done.length / all.length) * 100) : 0,
|
||||||
|
forecastRange: cone ? cone.rangeLabel : null,
|
||||||
|
cone,
|
||||||
|
groups,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ export interface ChatState {
|
|||||||
steps: string[]
|
steps: string[]
|
||||||
/** Changes Reginald has proposed and is awaiting approval on. */
|
/** Changes Reginald has proposed and is awaiting approval on. */
|
||||||
proposals: ChangeProposal[]
|
proposals: ChangeProposal[]
|
||||||
|
/** The in-flight streamed prose (grows token-by-token) before the turn finalizes. */
|
||||||
|
streaming: string
|
||||||
send: (text: string) => void
|
send: (text: string) => void
|
||||||
approve: (p: ChangeProposal) => void
|
approve: (p: ChangeProposal) => void
|
||||||
dismiss: (p: ChangeProposal) => void
|
dismiss: (p: ChangeProposal) => void
|
||||||
@@ -41,6 +43,7 @@ export function useChat(onApplyChange?: (change: IssueChange) => Promise<{ ok: b
|
|||||||
const [model, setModel] = useState<string | null>(null)
|
const [model, setModel] = useState<string | null>(null)
|
||||||
const [steps, setSteps] = useState<string[]>([])
|
const [steps, setSteps] = useState<string[]>([])
|
||||||
const [proposals, setProposals] = useState<ChangeProposal[]>([])
|
const [proposals, setProposals] = useState<ChangeProposal[]>([])
|
||||||
|
const [streaming, setStreaming] = useState('')
|
||||||
const convoRef = useRef(convo)
|
const convoRef = useRef(convo)
|
||||||
convoRef.current = convo
|
convoRef.current = convo
|
||||||
|
|
||||||
@@ -86,10 +89,17 @@ export function useChat(onApplyChange?: (change: IssueChange) => Promise<{ ok: b
|
|||||||
role: m.from === 'user' ? 'user' : 'assistant',
|
role: m.from === 'user' ? 'user' : 'assistant',
|
||||||
content: m.text,
|
content: m.text,
|
||||||
}))
|
}))
|
||||||
|
setStreaming('')
|
||||||
|
const unsubscribe = window.commitea.model.onToken((delta) => setStreaming((s) => s + delta))
|
||||||
|
const finish = () => {
|
||||||
|
unsubscribe()
|
||||||
|
setThinking(false)
|
||||||
|
setStreaming('')
|
||||||
|
}
|
||||||
window.commitea.model
|
window.commitea.model
|
||||||
.chat(wire)
|
.chat(wire)
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
setThinking(false)
|
finish()
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
setSteps(res.steps.map((s) => s.tool))
|
setSteps(res.steps.map((s) => s.tool))
|
||||||
setProposals(res.proposals)
|
setProposals(res.proposals)
|
||||||
@@ -105,7 +115,7 @@ export function useChat(onApplyChange?: (change: IssueChange) => Promise<{ ok: b
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
setThinking(false)
|
finish()
|
||||||
setConvo((c) => [...c, { from: 'agent', text: 'I could not reach the model.' }])
|
setConvo((c) => [...c, { from: 'agent', text: 'I could not reach the model.' }])
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
@@ -137,5 +147,5 @@ export function useChat(onApplyChange?: (change: IssueChange) => Promise<{ ok: b
|
|||||||
setConvo((c) => [...c, { from: 'agent', text: `Left #${p.change.issue} as it was.` }])
|
setConvo((c) => [...c, { from: 'agent', text: `Left #${p.change.issue} as it was.` }])
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
return { msgs: [...seed, ...convo], thinking, live, model, steps, proposals, send, approve, dismiss }
|
return { msgs: [...seed, ...convo], thinking, live, model, steps, proposals, streaming, send, approve, dismiss }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,18 +31,20 @@ function stringify(result: unknown): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function runAgentTurn(opts: {
|
export async function runAgentTurn(opts: {
|
||||||
complete: (messages: ChatMessage[], tools?: ToolDecl[]) => Promise<CompletionResult>
|
complete: (messages: ChatMessage[], tools?: ToolDecl[], onToken?: (delta: string) => void) => Promise<CompletionResult>
|
||||||
messages: ChatMessage[]
|
messages: ChatMessage[]
|
||||||
tools: ToolDecl[]
|
tools: ToolDecl[]
|
||||||
execute: ToolExecutor
|
execute: ToolExecutor
|
||||||
maxSteps?: number
|
maxSteps?: number
|
||||||
|
/** Streams content deltas as the model produces prose (final-answer streaming). */
|
||||||
|
onToken?: (delta: string) => void
|
||||||
}): Promise<AgentTurn> {
|
}): Promise<AgentTurn> {
|
||||||
const maxSteps = opts.maxSteps ?? DEFAULT_MAX_STEPS
|
const maxSteps = opts.maxSteps ?? DEFAULT_MAX_STEPS
|
||||||
const convo: ChatMessage[] = [...opts.messages]
|
const convo: ChatMessage[] = [...opts.messages]
|
||||||
const steps: AgentStep[] = []
|
const steps: AgentStep[] = []
|
||||||
|
|
||||||
for (let step = 0; step < maxSteps; step++) {
|
for (let step = 0; step < maxSteps; step++) {
|
||||||
const { content, toolCalls } = await opts.complete(convo, opts.tools)
|
const { content, toolCalls } = await opts.complete(convo, opts.tools, opts.onToken)
|
||||||
if (toolCalls.length === 0) {
|
if (toolCalls.length === 0) {
|
||||||
convo.push({ role: 'assistant', content })
|
convo.push({ role: 'assistant', content })
|
||||||
return { content, steps, messages: convo }
|
return { content, steps, messages: convo }
|
||||||
@@ -63,7 +65,7 @@ export async function runAgentTurn(opts: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Out of tool budget — force a final prose answer with tools withheld.
|
// Out of tool budget — force a final prose answer with tools withheld.
|
||||||
const final = await opts.complete(convo, [])
|
const final = await opts.complete(convo, [], opts.onToken)
|
||||||
convo.push({ role: 'assistant', content: final.content })
|
convo.push({ role: 'assistant', content: final.content })
|
||||||
return { content: final.content, steps, messages: convo }
|
return { content: final.content, steps, messages: convo }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,6 +25,48 @@ describe('createChatClient', () => {
|
|||||||
return { fetch, calls }
|
return { fetch, calls }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function sseStub(chunks: string[]) {
|
||||||
|
const calls: { url: string; body: unknown }[] = []
|
||||||
|
const fetch: FetchLike = (url, init) => {
|
||||||
|
calls.push({ url, body: init?.body ? JSON.parse(init.body) : undefined })
|
||||||
|
const enc = new TextEncoder()
|
||||||
|
const body = new ReadableStream<Uint8Array>({
|
||||||
|
start(c) {
|
||||||
|
for (const ch of chunks) c.enqueue(enc.encode(ch))
|
||||||
|
c.close()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return Promise.resolve({ ok: true, status: 200, body, json: () => Promise.resolve({}), text: () => Promise.resolve('') })
|
||||||
|
}
|
||||||
|
return { fetch, calls }
|
||||||
|
}
|
||||||
|
|
||||||
|
it('streams content deltas via onToken and returns the assembled result', async () => {
|
||||||
|
const { fetch, calls } = sseStub([
|
||||||
|
'data: {"choices":[{"delta":{"content":"Right "}}]}\n\n',
|
||||||
|
'data: {"choices":[{"delta":{"content":"now: #2."}}]}\n\n',
|
||||||
|
'data: [DONE]\n\n',
|
||||||
|
])
|
||||||
|
const client = createChatClient({ baseUrl: 'http://x/v1', model: 'm' }, fetch)
|
||||||
|
const tokens: string[] = []
|
||||||
|
const res = await client.complete([{ role: 'user', content: 'now?' }], undefined, (d) => tokens.push(d))
|
||||||
|
|
||||||
|
expect(tokens).toEqual(['Right ', 'now: #2.'])
|
||||||
|
expect(res.content).toBe('Right now: #2.')
|
||||||
|
expect((calls[0].body as { stream?: boolean }).stream).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('assembles a streamed tool call from argument deltas', async () => {
|
||||||
|
const { fetch } = sseStub([
|
||||||
|
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","function":{"name":"query_project","arguments":"{\\"view\\""}}]}}]}\n\n',
|
||||||
|
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":":\\"focus\\"}"}}]}}]}\n\n',
|
||||||
|
'data: [DONE]\n\n',
|
||||||
|
])
|
||||||
|
const client = createChatClient({ baseUrl: 'http://x/v1', model: 'm' }, fetch)
|
||||||
|
const res = await client.complete([{ role: 'user', content: 'x' }], [{ name: 'query_project', description: '', parameters: {} }], () => {})
|
||||||
|
expect(res.toolCalls).toEqual([{ id: 'c1', name: 'query_project', arguments: '{"view":"focus"}' }])
|
||||||
|
})
|
||||||
|
|
||||||
it('POSTs to /chat/completions and parses content', async () => {
|
it('POSTs to /chat/completions and parses content', async () => {
|
||||||
const { fetch, calls } = stub({ choices: [{ message: { content: 'the focus is #2' } }] })
|
const { fetch, calls } = stub({ choices: [{ message: { content: 'the focus is #2' } }] })
|
||||||
const client = createChatClient({ baseUrl: 'http://localhost:1234/v1', model: 'gemma' }, fetch)
|
const client = createChatClient({ baseUrl: 'http://localhost:1234/v1', model: 'gemma' }, fetch)
|
||||||
|
|||||||
@@ -48,8 +48,12 @@ export interface CompletionResult {
|
|||||||
toolCalls: ToolCall[]
|
toolCalls: ToolCall[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Called with each streamed content delta (final-prose streaming). */
|
||||||
|
export type OnToken = (delta: string) => void
|
||||||
|
|
||||||
export interface ChatClient {
|
export interface ChatClient {
|
||||||
complete(messages: ChatMessage[], tools?: ToolDecl[]): Promise<CompletionResult>
|
/** When `onToken` is given, the response streams (SSE) and each content delta is emitted. */
|
||||||
|
complete(messages: ChatMessage[], tools?: ToolDecl[], onToken?: OnToken): Promise<CompletionResult>
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Map our message shape to the OpenAI wire shape. */
|
/** Map our message shape to the OpenAI wire shape. */
|
||||||
@@ -85,7 +89,7 @@ export function createChatClient(config: ModelConfig, fetchImpl: FetchLike): Cha
|
|||||||
const url = `${config.baseUrl.replace(/\/+$/, '')}/chat/completions`
|
const url = `${config.baseUrl.replace(/\/+$/, '')}/chat/completions`
|
||||||
|
|
||||||
return {
|
return {
|
||||||
async complete(messages, tools) {
|
async complete(messages, tools, onToken) {
|
||||||
const body: Record<string, unknown> = {
|
const body: Record<string, unknown> = {
|
||||||
model: config.model,
|
model: config.model,
|
||||||
messages: messages.map(toWireMessage),
|
messages: messages.map(toWireMessage),
|
||||||
@@ -95,11 +99,13 @@ export function createChatClient(config: ModelConfig, fetchImpl: FetchLike): Cha
|
|||||||
body.tools = tools.map(toWireTool)
|
body.tools = tools.map(toWireTool)
|
||||||
body.tool_choice = 'auto'
|
body.tool_choice = 'auto'
|
||||||
}
|
}
|
||||||
|
const stream = !!onToken
|
||||||
|
if (stream) body.stream = true
|
||||||
const res = await fetchImpl(url, {
|
const res = await fetchImpl(url, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
Accept: 'application/json',
|
Accept: stream ? 'text/event-stream' : 'application/json',
|
||||||
...(config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}),
|
...(config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}),
|
||||||
},
|
},
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
@@ -108,6 +114,8 @@ export function createChatClient(config: ModelConfig, fetchImpl: FetchLike): Cha
|
|||||||
const text = await res.text().catch(() => '')
|
const text = await res.text().catch(() => '')
|
||||||
throw new Error(`model completion failed (${res.status}): ${text.slice(0, 200)}`)
|
throw new Error(`model completion failed (${res.status}): ${text.slice(0, 200)}`)
|
||||||
}
|
}
|
||||||
|
if (stream && res.body) return readStream(res.body, onToken!)
|
||||||
|
|
||||||
const json = (await res.json()) as { choices?: { message: RawChoiceMessage }[] }
|
const json = (await res.json()) as { choices?: { message: RawChoiceMessage }[] }
|
||||||
const msg = json.choices?.[0]?.message
|
const msg = json.choices?.[0]?.message
|
||||||
return {
|
return {
|
||||||
@@ -121,3 +129,56 @@ export function createChatClient(config: ModelConfig, fetchImpl: FetchLike): Cha
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Streamed tool-call delta: name arrives first, arguments accumulate across chunks. */
|
||||||
|
interface RawToolDelta {
|
||||||
|
index: number
|
||||||
|
id?: string
|
||||||
|
function?: { name?: string; arguments?: string }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse an OpenAI SSE stream: emit content deltas via onToken, accumulate the final result. */
|
||||||
|
async function readStream(body: ReadableStream<Uint8Array>, onToken: OnToken): Promise<CompletionResult> {
|
||||||
|
const reader = body.getReader()
|
||||||
|
const decoder = new TextDecoder()
|
||||||
|
let buffer = ''
|
||||||
|
let content = ''
|
||||||
|
const toolAcc: { id: string; name: string; arguments: string }[] = []
|
||||||
|
|
||||||
|
const handle = (data: string) => {
|
||||||
|
if (data === '[DONE]') return
|
||||||
|
let chunk: { choices?: { delta?: { content?: string; tool_calls?: RawToolDelta[] } }[] }
|
||||||
|
try {
|
||||||
|
chunk = JSON.parse(data)
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const delta = chunk.choices?.[0]?.delta
|
||||||
|
if (!delta) return
|
||||||
|
if (delta.content) {
|
||||||
|
content += delta.content
|
||||||
|
onToken(delta.content)
|
||||||
|
}
|
||||||
|
for (const tc of delta.tool_calls ?? []) {
|
||||||
|
const slot = (toolAcc[tc.index] ??= { id: '', name: '', arguments: '' })
|
||||||
|
if (tc.id) slot.id = tc.id
|
||||||
|
if (tc.function?.name) slot.name = tc.function.name
|
||||||
|
if (tc.function?.arguments) slot.arguments += tc.function.arguments
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
const { done, value } = await reader.read()
|
||||||
|
if (done) break
|
||||||
|
buffer += decoder.decode(value, { stream: true })
|
||||||
|
const lines = buffer.split('\n')
|
||||||
|
buffer = lines.pop() ?? ''
|
||||||
|
for (const line of lines) {
|
||||||
|
const t = line.trim()
|
||||||
|
if (t.startsWith('data:')) handle(t.slice(5).trim())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (buffer.trim().startsWith('data:')) handle(buffer.trim().slice(5).trim())
|
||||||
|
|
||||||
|
return { content, toolCalls: toolAcc.filter((t) => t.name).map((t) => ({ id: t.id, name: t.name, arguments: t.arguments })) }
|
||||||
|
}
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ export interface GiteaHttpResponse {
|
|||||||
status: number
|
status: number
|
||||||
json(): Promise<unknown>
|
json(): Promise<unknown>
|
||||||
text(): Promise<string>
|
text(): Promise<string>
|
||||||
|
/** Present on the real fetch Response; used for SSE streaming (chat). */
|
||||||
|
body?: ReadableStream<Uint8Array> | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export type FetchLike = (url: string, init?: GiteaRequestInit) => Promise<GiteaHttpResponse>
|
export type FetchLike = (url: string, init?: GiteaRequestInit) => Promise<GiteaHttpResponse>
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ export type {
|
|||||||
} from './calibration/calibration-v0.js'
|
} from './calibration/calibration-v0.js'
|
||||||
|
|
||||||
export { createChatClient } from './agent/chat-client.js'
|
export { createChatClient } from './agent/chat-client.js'
|
||||||
export type { ChatClient, ChatMessage, CompletionResult, ModelConfig, ToolCall, ToolDecl } from './agent/chat-client.js'
|
export type { ChatClient, ChatMessage, CompletionResult, ModelConfig, OnToken, ToolCall, ToolDecl } from './agent/chat-client.js'
|
||||||
export { pickModel } from './agent/model-router.js'
|
export { pickModel } from './agent/model-router.js'
|
||||||
export type { ModelRouter, TaskKind } from './agent/model-router.js'
|
export type { ModelRouter, TaskKind } from './agent/model-router.js'
|
||||||
export { runAgentTurn } from './agent/agent-loop.js'
|
export { runAgentTurn } from './agent/agent-loop.js'
|
||||||
|
|||||||
Reference in New Issue
Block a user