Files
ai-chess/apps/web/src/lib/components/Thoughts.svelte
T

196 lines
6.1 KiB
Svelte

<script lang="ts">
import { api } from '#lib/api.ts';
import type { LiveTurn, MoveDTO, ToolCallLog, TranscriptItem, TurnAttempt } from '#lib/types.ts';
import { fmtDuration, fmtTokens, fmtUsd, moveNo } from '#lib/fmt.ts';
let { gameId, ply, live = null, move = null, onclose }: { gameId: string; ply: number; live?: LiveTurn | null; move?: MoveDTO | null; onclose?: () => void } = $props();
let attempts = $state<TurnAttempt[] | null>(null);
let err = $state<string | null>(null);
$effect(() => {
const p = ply;
const isLive = !!live;
attempts = null;
err = null;
if (isLive && !move) return;
api
.get<{ turns: TurnAttempt[] }>(`/api/games/${gameId}/turns/${p}`)
.then((r) => (attempts = r.turns))
.catch((e) => (err = e.message));
});
const done = $derived(attempts?.find((a) => a.status === 'done') ?? attempts?.at(-1) ?? null);
const failed = $derived(attempts?.filter((a) => a.status === 'failed') ?? []);
/** live transcript built from streaming state */
const liveItems = $derived.by<TranscriptItem[]>(() => {
if (!live) return [];
const items: TranscriptItem[] = [];
if (live.thinking) items.push({ kind: 'thinking', text: live.thinking, at: live.startedAt });
for (const t of live.tools) items.push({ kind: 'tool', call: t, at: t.startedAt });
if (live.text) items.push({ kind: 'text', text: live.text, at: live.startedAt });
return items;
});
const items = $derived(live && !move ? liveItems : (done?.transcript ?? []));
const context = $derived(items.find((i) => i.kind === 'context') as Extract<TranscriptItem, { kind: 'context' }> | undefined);
const TOOL_RU: Record<string, string> = {
make_move: 'ход',
finish_turn: 'завершить ход',
resign: 'сдаться',
accept_draw: 'принять ничью',
get_move_history: 'история ходов',
python: 'python'
};
function argText(c: ToolCallLog) {
const a = c.args as any;
if (!a) return '';
if (c.name === 'python') return a.code ?? '';
if (c.name === 'make_move') return `${a.move ?? ''}${a.offer_draw ? ' + предложение ничьей' : ''}`;
if (c.name === 'finish_turn') return [a.phrase ? `«${a.phrase}»` : '', a.note_to_self ? `заметка себе: ${a.note_to_self}` : ''].filter(Boolean).join('\n');
return JSON.stringify(a);
}
</script>
<div class="thoughts">
<header>
<span class="label">💭 мысли · {moveNo(ply)} {move?.san ?? (live ? 'в эфире' : '')}</span>
<span class="spacer"></span>
{#if done?.usage}<span class="mono meta">{fmtTokens(done.usage.input + done.usage.output + done.usage.cacheRead)} ток · {fmtUsd(done.usage.cost, 3)}{#if move?.thinkMs} · {fmtDuration(move.thinkMs)}{/if}</span>{/if}
{#if onclose}<button class="x" onclick={onclose} aria-label="Закрыть">✕</button>{/if}
</header>
{#if err}<div class="error-box">{err}</div>{/if}
{#if !live && !attempts && !err}<div class="empty">Загружаю…</div>{/if}
{#if failed.length && move}
<div class="note mono">⟲ {failed.length} {failed.length === 1 ? 'попытка' : 'попытки'} упали (ошибка провайдера) — ход переигран с чистого листа</div>
{/if}
{#if context}
<details class="ctx">
<summary class="label">что агент видел на входе</summary>
<pre class="mono">{context.text}</pre>
</details>
{/if}
<div class="items">
{#each items as it, i (i)}
{#if it.kind === 'thinking'}
<div class="it thinking"><pre>{it.text}</pre></div>
{:else if it.kind === 'text'}
<div class="it text"><pre>{it.text}</pre></div>
{:else if it.kind === 'tool'}
<div class="it tool" class:err={it.call.isError}>
<div class="tool-head"><span class="chip outline mono">{it.call.name}</span><span class="muted">{TOOL_RU[it.call.name] ?? ''}</span>{#if !it.call.endedAt}<span class="live-dot"></span>{/if}</div>
{#if argText(it.call)}<pre class="mono args">{argText(it.call)}</pre>{/if}
{#if it.call.result && it.call.name !== 'finish_turn'}<pre class="mono res">{it.call.result}</pre>{/if}
</div>
{:else if it.kind === 'nudge'}
<div class="it nudge mono">арбитр: {it.text}</div>
{:else if it.kind === 'error'}
<div class="it nudge mono">ошибка: {it.text}</div>
{/if}
{/each}
{#if live && !move && !items.length}<div class="empty">Агент начал думать… (часть моделей не показывает рассуждения до конца хода)</div>{/if}
{#if !live && attempts && !items.filter((i) => i.kind !== 'context').length}<div class="empty">Модель не раскрыла рассуждения на этом ходу.</div>{/if}
</div>
</div>
<style>
.thoughts {
padding: 10px 12px 12px;
display: grid;
gap: 8px;
font-size: 13px;
}
header {
display: flex;
align-items: center;
gap: 8px;
}
.meta {
font-size: 11px;
color: var(--muted);
}
.x {
font-size: 13px;
padding: 2px 6px;
}
.note {
font-size: 11px;
color: var(--muted);
}
.ctx summary {
cursor: pointer;
color: var(--accent-text, var(--accent));
}
pre {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
font-family: inherit;
}
.ctx pre {
margin-top: 6px;
padding: 8px;
max-height: 340px;
overflow: auto;
font-size: 11px;
background: var(--surface);
border: var(--border-thin);
}
.items {
display: grid;
gap: 8px;
max-height: 520px;
overflow: auto;
}
.it.thinking pre {
font-style: italic;
color: var(--text-2);
line-height: 1.5;
border-left: 3px solid var(--muted);
padding-left: 10px;
}
.it.text pre {
border-left: 3px solid var(--accent);
padding-left: 10px;
}
.tool {
border: var(--border-thin);
background: var(--surface);
padding: 6px 8px;
display: grid;
gap: 4px;
}
.tool.err {
border-color: var(--danger);
}
.tool-head {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
}
.args {
font-size: 12px;
font-weight: 600;
}
.res {
font-size: 11px;
color: var(--text-2);
max-height: 200px;
overflow: auto;
border-top: 1px dashed var(--line);
padding-top: 4px;
}
.tool.err .res {
color: var(--danger);
}
.nudge {
font-size: 11px;
color: var(--danger);
}
</style>