Merge origin/main and resolve conflicts
Keep open-in-editor dropdown, accept main's removal of status indicator from header. Co-Authored-By: Claude Opus 4.6 <[email protected]>
This commit is contained in:
commit
36314bb3bb
9 files changed
+720
-239
No files matched your search
@@ -1,9 +1,6 @@
|
||||
## TODO
|
||||
|
||||
- [ ] Fix sort order for threads (newest first)
|
||||
- [ ] Indicate in thread list which threads are currently working
|
||||
- [ ] Logs should be per-thread, not a single events.txt
|
||||
- [ ] Audit the logs to identify which events are (and aren't) worth showing to the user, i.e. drop "preamble" and "work" events
|
||||
- [ ] Make the "end message" stand out from the work done prior (maybe just a bar between the two that says "worked for 10 minutes 31 seconds" or however long it was)
|
||||
- [ ] Better logging of "time to complete" (I want this more than the timestamps tbh)
|
||||
- [ ] Remove the left bars on messages to make UI feel "flatter"
|
||||
- [x] Remove model picker from new project menu
|
||||
- [x] CMD+Shift+O to create new thread in current project
|
||||
- [x] Remove project title pill from input box and topnav
|
||||
- [x] Remove connection status from topnav
|
||||
@@ -3,20 +3,43 @@ import { describe, expect, it } from "vitest";
|
||||
import { ProviderManager } from "./providerManager";
|
||||
|
||||
describe("ProviderManager", () => {
|
||||
it("detaches provider event listener and ends log stream on dispose", () => {
|
||||
it("detaches provider event listener and ends thread log streams on dispose", () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: { listenerCount: (event: string) => number };
|
||||
logStream: { writableEnded: boolean; destroyed: boolean };
|
||||
onCodexEvent: (event: {
|
||||
id: string;
|
||||
kind: "notification";
|
||||
provider: "codex";
|
||||
sessionId: string;
|
||||
createdAt: string;
|
||||
method: string;
|
||||
threadId: string;
|
||||
}) => void;
|
||||
threadLogStreams: Map<
|
||||
string,
|
||||
{ writableEnded: boolean; destroyed: boolean }
|
||||
>;
|
||||
};
|
||||
internals.onCodexEvent({
|
||||
id: "evt-1",
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
sessionId: "sess-1",
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "thread/started",
|
||||
threadId: "thread-1",
|
||||
});
|
||||
const stream = internals.threadLogStreams.get("thread-1");
|
||||
expect(stream).toBeDefined();
|
||||
if (!stream) return;
|
||||
|
||||
expect(internals.codex.listenerCount("event")).toBe(1);
|
||||
manager.dispose();
|
||||
|
||||
expect(internals.codex.listenerCount("event")).toBe(0);
|
||||
expect(
|
||||
internals.logStream.writableEnded || internals.logStream.destroyed,
|
||||
).toBe(true);
|
||||
expect(stream.writableEnded || stream.destroyed).toBe(true);
|
||||
expect(internals.threadLogStreams.size).toBe(0);
|
||||
});
|
||||
|
||||
it("allows multiple dispose calls", () => {
|
||||
|
||||
@@ -23,14 +23,17 @@ export interface ProviderManagerEvents {
|
||||
|
||||
export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
private readonly codex = new CodexAppServerManager();
|
||||
private readonly logStream: fs.WriteStream;
|
||||
private readonly threadLogsDir: string;
|
||||
private readonly threadLogStreams = new Map<string, fs.WriteStream>();
|
||||
private readonly sessionThreadIds = new Map<string, string>();
|
||||
private readonly pendingEventsBySession = new Map<string, ProviderEvent[]>();
|
||||
private disposed = false;
|
||||
private readonly onCodexEvent = (event: ProviderEvent) => {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logStream.write(`${JSON.stringify(event)}\n`);
|
||||
this.routeEventToThreadLog(event);
|
||||
this.emit("event", event);
|
||||
};
|
||||
|
||||
@@ -38,10 +41,8 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
super();
|
||||
|
||||
const logsDir = path.resolve(process.cwd(), ".logs");
|
||||
fs.mkdirSync(logsDir, { recursive: true });
|
||||
this.logStream = fs.createWriteStream(path.join(logsDir, "events.txt"), {
|
||||
flags: "a",
|
||||
});
|
||||
this.threadLogsDir = path.join(logsDir, "threads");
|
||||
fs.mkdirSync(this.threadLogsDir, { recursive: true });
|
||||
|
||||
this.codex.on("event", this.onCodexEvent);
|
||||
}
|
||||
@@ -52,7 +53,12 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
throw new Error(`Provider '${input.provider}' is not implemented yet.`);
|
||||
}
|
||||
|
||||
return this.codex.startSession(input);
|
||||
const session = await this.codex.startSession(input);
|
||||
if (session.threadId) {
|
||||
this.sessionThreadIds.set(session.sessionId, session.threadId);
|
||||
this.flushPendingSessionEvents(session.sessionId, session.threadId);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
async sendTurn(raw: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
@@ -76,6 +82,8 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
stopSession(raw: ProviderStopSessionInput): void {
|
||||
const input = providerStopSessionInputSchema.parse(raw);
|
||||
this.codex.stopSession(input.sessionId);
|
||||
this.sessionThreadIds.delete(input.sessionId);
|
||||
this.pendingEventsBySession.delete(input.sessionId);
|
||||
}
|
||||
|
||||
listSessions(): ProviderSession[] {
|
||||
@@ -93,6 +101,94 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
|
||||
this.disposed = true;
|
||||
this.codex.off("event", this.onCodexEvent);
|
||||
this.logStream.end();
|
||||
for (const stream of this.threadLogStreams.values()) {
|
||||
stream.end();
|
||||
}
|
||||
this.threadLogStreams.clear();
|
||||
this.sessionThreadIds.clear();
|
||||
this.pendingEventsBySession.clear();
|
||||
}
|
||||
|
||||
private routeEventToThreadLog(event: ProviderEvent): void {
|
||||
const threadId = this.resolveThreadId(event);
|
||||
if (!threadId) {
|
||||
const pending = this.pendingEventsBySession.get(event.sessionId) ?? [];
|
||||
pending.push(event);
|
||||
this.pendingEventsBySession.set(event.sessionId, pending.slice(-100));
|
||||
return;
|
||||
}
|
||||
|
||||
this.flushPendingSessionEvents(event.sessionId, threadId);
|
||||
this.writeThreadEvent(threadId, event);
|
||||
}
|
||||
|
||||
private flushPendingSessionEvents(sessionId: string, threadId: string): void {
|
||||
const pending = this.pendingEventsBySession.get(sessionId);
|
||||
if (!pending || pending.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const event of pending) {
|
||||
this.writeThreadEvent(threadId, event);
|
||||
}
|
||||
this.pendingEventsBySession.delete(sessionId);
|
||||
}
|
||||
|
||||
private resolveThreadId(event: ProviderEvent): string | undefined {
|
||||
const fromPayload = this.readThreadIdFromPayload(event.payload);
|
||||
const threadId =
|
||||
event.threadId ??
|
||||
fromPayload ??
|
||||
this.sessionThreadIds.get(event.sessionId);
|
||||
|
||||
if (threadId) {
|
||||
this.sessionThreadIds.set(event.sessionId, threadId);
|
||||
}
|
||||
|
||||
return threadId;
|
||||
}
|
||||
|
||||
private readThreadIdFromPayload(payload: unknown): string | undefined {
|
||||
if (!payload || typeof payload !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const record = payload as Record<string, unknown>;
|
||||
const direct = record.threadId;
|
||||
if (typeof direct === "string" && direct.length > 0) {
|
||||
return direct;
|
||||
}
|
||||
|
||||
const thread = record.thread;
|
||||
if (!thread || typeof thread !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const nested = (thread as Record<string, unknown>).id;
|
||||
if (typeof nested === "string" && nested.length > 0) {
|
||||
return nested;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private writeThreadEvent(threadId: string, event: ProviderEvent): void {
|
||||
const stream = this.getOrCreateThreadLogStream(threadId);
|
||||
stream.write(`${JSON.stringify(event)}\n`);
|
||||
}
|
||||
|
||||
private getOrCreateThreadLogStream(threadId: string): fs.WriteStream {
|
||||
const cached = this.threadLogStreams.get(threadId);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const safeThreadId = threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
const stream = fs.createWriteStream(
|
||||
path.join(this.threadLogsDir, `${safeThreadId}.events.ndjson`),
|
||||
{ flags: "a" },
|
||||
);
|
||||
this.threadLogStreams.set(threadId, stream);
|
||||
return stream;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
type FormEvent,
|
||||
Fragment,
|
||||
type KeyboardEvent,
|
||||
useEffect,
|
||||
useMemo,
|
||||
@@ -19,6 +20,7 @@ import {
|
||||
derivePhase,
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
formatDuration,
|
||||
formatElapsed,
|
||||
formatTimestamp,
|
||||
readNativeApi,
|
||||
@@ -43,13 +45,6 @@ function editorLabel(editor: (typeof EDITORS)[number]): string {
|
||||
|
||||
const LAST_EDITOR_KEY = "codething:last-editor";
|
||||
|
||||
function statusLabel(phase: string): string {
|
||||
if (phase === "running") return "Thinking / working";
|
||||
if (phase === "connecting") return "Connecting";
|
||||
if (phase === "ready") return "Ready";
|
||||
return "Disconnected";
|
||||
}
|
||||
|
||||
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
|
||||
if (tone === "error") return "text-rose-300/50";
|
||||
if (tone === "tool") return "text-[#8a8a8a]";
|
||||
@@ -88,12 +83,11 @@ export default function ChatView() {
|
||||
);
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const isWorking = phase === "running" || isSending || isConnecting;
|
||||
const activeTurnId = activeThread?.session?.activeTurnId;
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const modelOptions = MODEL_OPTIONS;
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(activeThread?.events ?? [], activeTurnId),
|
||||
[activeThread?.events, activeTurnId],
|
||||
() => deriveWorkLogEntries(activeThread?.events ?? [], undefined),
|
||||
[activeThread?.events],
|
||||
);
|
||||
const assistantCompletionByItemId = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
@@ -106,13 +100,54 @@ export default function ChatView() {
|
||||
return map;
|
||||
}, [activeThread?.events]);
|
||||
const timelineEntries = useMemo(
|
||||
() =>
|
||||
deriveTimelineEntries(
|
||||
activeThread?.messages ?? [],
|
||||
isWorking ? workLogEntries : [],
|
||||
),
|
||||
[activeThread?.messages, isWorking, workLogEntries],
|
||||
() => deriveTimelineEntries(activeThread?.messages ?? [], workLogEntries),
|
||||
[activeThread?.messages, workLogEntries],
|
||||
);
|
||||
const completionSummary = useMemo(() => {
|
||||
if (!activeThread?.latestTurnStartedAt) return null;
|
||||
if (!activeThread.latestTurnCompletedAt) return null;
|
||||
if (workLogEntries.length === 0) return null;
|
||||
|
||||
if (
|
||||
typeof activeThread.latestTurnDurationMs === "number" &&
|
||||
Number.isFinite(activeThread.latestTurnDurationMs) &&
|
||||
activeThread.latestTurnDurationMs >= 0
|
||||
) {
|
||||
return `Worked for ${formatDuration(activeThread.latestTurnDurationMs)}`;
|
||||
}
|
||||
|
||||
const elapsed = formatElapsed(
|
||||
activeThread.latestTurnStartedAt,
|
||||
activeThread.latestTurnCompletedAt,
|
||||
);
|
||||
return elapsed ? `Worked for ${elapsed}` : null;
|
||||
}, [
|
||||
activeThread?.latestTurnStartedAt,
|
||||
activeThread?.latestTurnCompletedAt,
|
||||
activeThread?.latestTurnDurationMs,
|
||||
workLogEntries.length,
|
||||
]);
|
||||
const completionDividerBeforeEntryId = useMemo(() => {
|
||||
if (!activeThread?.latestTurnStartedAt) return null;
|
||||
if (!activeThread.latestTurnCompletedAt) return null;
|
||||
if (workLogEntries.length === 0) return null;
|
||||
|
||||
const turnStartedAt = Date.parse(activeThread.latestTurnStartedAt);
|
||||
if (Number.isNaN(turnStartedAt)) return null;
|
||||
|
||||
const entry = timelineEntries.find((timelineEntry) => {
|
||||
if (timelineEntry.kind !== "message") return false;
|
||||
if (timelineEntry.message.role !== "assistant") return false;
|
||||
const messageAt = Date.parse(timelineEntry.message.createdAt);
|
||||
return !Number.isNaN(messageAt) && messageAt >= turnStartedAt;
|
||||
});
|
||||
return entry?.id ?? null;
|
||||
}, [
|
||||
activeThread?.latestTurnStartedAt,
|
||||
activeThread?.latestTurnCompletedAt,
|
||||
timelineEntries,
|
||||
workLogEntries.length,
|
||||
]);
|
||||
|
||||
// Auto-scroll on new messages
|
||||
const messageCount = activeThread?.messages.length ?? 0;
|
||||
@@ -338,47 +373,8 @@ export default function ChatView() {
|
||||
<h2 className="text-sm font-medium text-[#e0e0e0]">
|
||||
{activeThread.title}
|
||||
</h2>
|
||||
{activeProject && (
|
||||
<span className="rounded-full bg-white/[0.06] px-2 py-0.5 text-[10px] text-[#a0a0a0]/50">
|
||||
{activeProject.name}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Status indicator */}
|
||||
<div
|
||||
className={`inline-flex items-center gap-2 rounded-full border px-2.5 py-1 text-[10px] ${
|
||||
phase === "running"
|
||||
? "border-sky-400/35 bg-sky-500/[0.08] text-sky-100"
|
||||
: phase === "connecting"
|
||||
? "border-amber-400/35 bg-amber-500/[0.08] text-amber-100"
|
||||
: phase === "ready"
|
||||
? "border-emerald-400/35 bg-emerald-500/[0.08] text-emerald-100"
|
||||
: "border-white/[0.08] bg-white/[0.04] text-[#a0a0a0]/70"
|
||||
}`}
|
||||
>
|
||||
<span className="relative inline-flex h-2.5 w-2.5">
|
||||
{(phase === "running" || phase === "connecting") && (
|
||||
<span
|
||||
className={`absolute inline-flex h-full w-full animate-ping rounded-full ${
|
||||
phase === "running" ? "bg-sky-300/70" : "bg-amber-300/70"
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
<span
|
||||
className={`relative inline-flex h-2.5 w-2.5 rounded-full ${
|
||||
phase === "running"
|
||||
? "bg-sky-200"
|
||||
: phase === "connecting"
|
||||
? "bg-amber-200"
|
||||
: phase === "ready"
|
||||
? "bg-emerald-200"
|
||||
: "bg-[#a0a0a0]/40"
|
||||
}`}
|
||||
/>
|
||||
</span>
|
||||
<span>{statusLabel(phase)}</span>
|
||||
</div>
|
||||
{/* Open in editor */}
|
||||
{activeProject && (
|
||||
<div className="relative" ref={editorMenuRef}>
|
||||
@@ -444,85 +440,99 @@ export default function ChatView() {
|
||||
</div>
|
||||
) : (
|
||||
<div className="mx-auto max-w-3xl space-y-4">
|
||||
{timelineEntries.map((timelineEntry) =>
|
||||
timelineEntry.kind === "work" ? (
|
||||
<div
|
||||
key={timelineEntry.id}
|
||||
className="border-l-2 border-white/[0.05] pl-4 py-1"
|
||||
>
|
||||
<p
|
||||
className={`py-[2px] text-[12px] leading-relaxed ${workToneClass(timelineEntry.entry.tone)}`}
|
||||
>
|
||||
{timelineEntry.entry.detail ? (
|
||||
<>
|
||||
{timelineEntry.entry.label}
|
||||
<span className="ml-1.5 font-mono text-[11px] opacity-60">
|
||||
{timelineEntry.entry.detail}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
timelineEntry.entry.label
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div key={timelineEntry.id}>
|
||||
{timelineEntry.message.role === "user" ? (
|
||||
<div className="flex justify-end">
|
||||
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-white/[0.08] bg-white/[0.05] px-4 py-3">
|
||||
<pre className="whitespace-pre-wrap break-words font-mono text-sm leading-relaxed text-[#e0e0e0]">
|
||||
{timelineEntry.message.text}
|
||||
</pre>
|
||||
<p className="mt-1.5 text-right text-[10px] text-[#a0a0a0]/30">
|
||||
{formatTimestamp(timelineEntry.message.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="border-l-2 border-white/[0.15] pl-4">
|
||||
<ChatMarkdown
|
||||
text={
|
||||
timelineEntry.message.text ||
|
||||
(timelineEntry.message.streaming
|
||||
? ""
|
||||
: "(empty response)")
|
||||
}
|
||||
/>
|
||||
{timelineEntry.message.streaming && (
|
||||
<div className="pt-1.5">
|
||||
<span className="inline-flex items-center gap-2 rounded-full border border-sky-400/25 bg-sky-500/[0.08] px-2 py-0.5 text-[10px] text-sky-100/90">
|
||||
<span className="inline-flex gap-1">
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80" />
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80 [animation-delay:150ms]" />
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80 [animation-delay:300ms]" />
|
||||
</span>
|
||||
<span>Thinking</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<p className="mt-1.5 text-[10px] text-[#a0a0a0]/30">
|
||||
{formatMessageMeta(
|
||||
timelineEntry.message.createdAt,
|
||||
timelineEntry.message.streaming
|
||||
? formatElapsed(
|
||||
timelineEntry.message.createdAt,
|
||||
nowIso,
|
||||
)
|
||||
: formatElapsed(
|
||||
timelineEntry.message.createdAt,
|
||||
assistantCompletionByItemId.get(
|
||||
timelineEntry.message.id,
|
||||
),
|
||||
),
|
||||
)}
|
||||
</p>
|
||||
{timelineEntries.map((timelineEntry, index) => (
|
||||
<Fragment key={timelineEntry.id}>
|
||||
{timelineEntry.kind === "message" &&
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
(completionDividerBeforeEntryId === timelineEntry.id ||
|
||||
timelineEntries[index - 1]?.kind === "work") && (
|
||||
<div className="my-3 flex items-center gap-3">
|
||||
<span className="h-px flex-1 bg-white/[0.1]" />
|
||||
<span className="rounded-full border border-white/[0.12] bg-[#121212] px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-[#9a9a9a]/80">
|
||||
{completionSummary
|
||||
? `Response • ${completionSummary}`
|
||||
: "Response"}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-white/[0.1]" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
{timelineEntry.kind === "work" ? (
|
||||
<div className="flex items-start gap-2 py-0.5 pl-1.5">
|
||||
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-white/[0.18]" />
|
||||
<p
|
||||
className={`py-[2px] text-[11px] leading-relaxed ${workToneClass(timelineEntry.entry.tone)}`}
|
||||
>
|
||||
{timelineEntry.entry.detail ? (
|
||||
<>
|
||||
{timelineEntry.entry.label}
|
||||
<span
|
||||
className="ml-1.5 inline-block max-w-[70ch] truncate align-bottom font-mono text-[11px] opacity-60"
|
||||
title={timelineEntry.entry.detail}
|
||||
>
|
||||
{timelineEntry.entry.detail}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
timelineEntry.entry.label
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
) : timelineEntry.message.role === "user" ? (
|
||||
<div className="flex justify-end">
|
||||
<div className="max-w-[80%] rounded-2xl rounded-br-sm border border-white/[0.08] bg-white/[0.05] px-4 py-3">
|
||||
<pre className="whitespace-pre-wrap break-words font-mono text-sm leading-relaxed text-[#e0e0e0]">
|
||||
{timelineEntry.message.text}
|
||||
</pre>
|
||||
<p className="mt-1.5 text-right text-[10px] text-[#a0a0a0]/30">
|
||||
{formatTimestamp(timelineEntry.message.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="px-1 py-0.5">
|
||||
<ChatMarkdown
|
||||
text={
|
||||
timelineEntry.message.text ||
|
||||
(timelineEntry.message.streaming
|
||||
? ""
|
||||
: "(empty response)")
|
||||
}
|
||||
/>
|
||||
{timelineEntry.message.streaming && (
|
||||
<div className="pt-1.5">
|
||||
<span className="inline-flex items-center gap-2 rounded-full border border-sky-400/25 bg-sky-500/[0.08] px-2 py-0.5 text-[10px] text-sky-100/90">
|
||||
<span className="inline-flex gap-1">
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80" />
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80 [animation-delay:150ms]" />
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-100/80 [animation-delay:300ms]" />
|
||||
</span>
|
||||
<span>Thinking</span>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<p className="mt-1.5 text-[10px] text-[#a0a0a0]/30">
|
||||
{formatMessageMeta(
|
||||
timelineEntry.message.createdAt,
|
||||
timelineEntry.message.streaming
|
||||
? formatElapsed(
|
||||
timelineEntry.message.createdAt,
|
||||
nowIso,
|
||||
)
|
||||
: formatElapsed(
|
||||
timelineEntry.message.createdAt,
|
||||
assistantCompletionByItemId.get(
|
||||
timelineEntry.message.id,
|
||||
),
|
||||
),
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
{isWorking && (
|
||||
<div className="border-l-2 border-white/[0.05] pl-4 py-1">
|
||||
<div className="flex items-center gap-2 py-0.5 pl-1.5">
|
||||
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-white/[0.18]" />
|
||||
<div className="flex items-center pt-1">
|
||||
<span className="inline-flex items-center gap-[3px]">
|
||||
<span className="h-1 w-1 rounded-full bg-white/20 animate-pulse" />
|
||||
@@ -674,11 +684,6 @@ export default function ChatView() {
|
||||
|
||||
{/* Right side: send / stop button */}
|
||||
<div className="flex items-center gap-2">
|
||||
{activeProject && (
|
||||
<span className="text-[11px] text-[#a0a0a0]/25">
|
||||
{activeProject.name}
|
||||
</span>
|
||||
)}
|
||||
{phase === "running" ? (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { DEFAULT_MODEL, MODEL_OPTIONS, resolveModelSlug } from "../model-logic";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { DEFAULT_MODEL } from "../model-logic";
|
||||
import { readNativeApi } from "../session-logic";
|
||||
import { useStore } from "../store";
|
||||
import type { Project } from "../types";
|
||||
@@ -14,50 +14,58 @@ function formatRelativeTime(iso: string): string {
|
||||
return `${Math.floor(hours / 24)}d ago`;
|
||||
}
|
||||
|
||||
function threadStatusLabel(
|
||||
status: "connecting" | "ready" | "running" | "error" | "closed" | undefined,
|
||||
): "Working" | "Connecting" | null {
|
||||
if (status === "running") return "Working";
|
||||
if (status === "connecting") return "Connecting";
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function Sidebar() {
|
||||
const { state, dispatch } = useStore();
|
||||
const api = useMemo(() => readNativeApi(), []);
|
||||
const [addingProject, setAddingProject] = useState(false);
|
||||
const [newCwd, setNewCwd] = useState("");
|
||||
const [newModel, setNewModel] = useState(DEFAULT_MODEL);
|
||||
const [isPickingFolder, setIsPickingFolder] = useState(false);
|
||||
|
||||
const handleAddProject = () => {
|
||||
const cwd = newCwd.trim();
|
||||
if (!cwd) return;
|
||||
const name = cwd.split("/").filter(Boolean).pop() ?? "project";
|
||||
const normalizedModel = resolveModelSlug(newModel);
|
||||
const project: Project = {
|
||||
id: crypto.randomUUID(),
|
||||
name,
|
||||
cwd,
|
||||
model: normalizedModel,
|
||||
model: DEFAULT_MODEL,
|
||||
expanded: true,
|
||||
};
|
||||
dispatch({ type: "ADD_PROJECT", project });
|
||||
setNewCwd("");
|
||||
setNewModel(DEFAULT_MODEL);
|
||||
setAddingProject(false);
|
||||
};
|
||||
|
||||
const handleNewThread = (projectId: string) => {
|
||||
dispatch({
|
||||
type: "ADD_THREAD",
|
||||
thread: {
|
||||
id: crypto.randomUUID(),
|
||||
projectId,
|
||||
title: "New thread",
|
||||
model:
|
||||
state.projects.find((p) => p.id === projectId)?.model ??
|
||||
DEFAULT_MODEL,
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
};
|
||||
const handleNewThread = useCallback(
|
||||
(projectId: string) => {
|
||||
dispatch({
|
||||
type: "ADD_THREAD",
|
||||
thread: {
|
||||
id: crypto.randomUUID(),
|
||||
projectId,
|
||||
title: "New thread",
|
||||
model:
|
||||
state.projects.find((p) => p.id === projectId)?.model ??
|
||||
DEFAULT_MODEL,
|
||||
session: null,
|
||||
messages: [],
|
||||
events: [],
|
||||
error: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
},
|
||||
[dispatch, state.projects],
|
||||
);
|
||||
|
||||
const handlePickFolder = async () => {
|
||||
if (!api || isPickingFolder) return;
|
||||
@@ -71,6 +79,45 @@ export default function Sidebar() {
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
const isNewThreadShortcut =
|
||||
event.metaKey &&
|
||||
event.shiftKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.altKey &&
|
||||
event.key.toLowerCase() === "o";
|
||||
if (!isNewThreadShortcut) return;
|
||||
|
||||
const target = event.target;
|
||||
if (target instanceof HTMLElement) {
|
||||
const tagName = target.tagName;
|
||||
if (
|
||||
target.isContentEditable ||
|
||||
tagName === "INPUT" ||
|
||||
tagName === "TEXTAREA" ||
|
||||
tagName === "SELECT"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const activeThread = state.threads.find(
|
||||
(t) => t.id === state.activeThreadId,
|
||||
);
|
||||
const projectId = activeThread?.projectId ?? state.projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
|
||||
event.preventDefault();
|
||||
handleNewThread(projectId);
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown);
|
||||
};
|
||||
}, [handleNewThread, state.activeThreadId, state.projects, state.threads]);
|
||||
|
||||
return (
|
||||
<aside className="sidebar flex h-full w-[260px] shrink-0 flex-col border-r border-white/[0.08] bg-[#141414]">
|
||||
{/* Drag region / traffic light space */}
|
||||
@@ -107,9 +154,15 @@ export default function Sidebar() {
|
||||
{/* Project list */}
|
||||
<nav className="flex-1 overflow-y-auto px-2">
|
||||
{state.projects.map((project) => {
|
||||
const threads = state.threads.filter(
|
||||
(t) => t.projectId === project.id,
|
||||
);
|
||||
const threads = state.threads
|
||||
.filter((t) => t.projectId === project.id)
|
||||
.sort((a, b) => {
|
||||
const byDate =
|
||||
new Date(b.createdAt).getTime() -
|
||||
new Date(a.createdAt).getTime();
|
||||
if (byDate !== 0) return byDate;
|
||||
return b.id.localeCompare(a.id);
|
||||
});
|
||||
return (
|
||||
<div key={project.id} className="mb-1">
|
||||
{/* Project header */}
|
||||
@@ -136,6 +189,9 @@ export default function Sidebar() {
|
||||
<div className="ml-2 border-l border-white/[0.06] pl-2">
|
||||
{threads.map((thread) => {
|
||||
const isActive = state.activeThreadId === thread.id;
|
||||
const threadStatus = threadStatusLabel(
|
||||
thread.session?.status,
|
||||
);
|
||||
return (
|
||||
<button
|
||||
key={thread.id}
|
||||
@@ -152,9 +208,19 @@ export default function Sidebar() {
|
||||
})
|
||||
}
|
||||
>
|
||||
<span className="flex-1 truncate text-xs">
|
||||
{thread.title}
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
{threadStatus && (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] text-[#7ed8ff]/80">
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-300/80" />
|
||||
<span className="hidden xl:inline">
|
||||
{threadStatus}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate text-xs">
|
||||
{thread.title}
|
||||
</span>
|
||||
</div>
|
||||
<span className="shrink-0 text-[10px] text-[#a0a0a0]/30">
|
||||
{formatRelativeTime(thread.createdAt)}
|
||||
</span>
|
||||
@@ -211,21 +277,6 @@ export default function Sidebar() {
|
||||
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
|
||||
</button>
|
||||
)}
|
||||
<select
|
||||
className="mb-2 w-full rounded-md border border-white/[0.1] bg-white/[0.04] px-2 py-1.5 font-mono text-xs text-[#e0e0e0] placeholder:text-[#a0a0a0]/30 focus:border-white/30 focus:outline-none"
|
||||
value={newModel}
|
||||
onChange={(e) => setNewModel(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") handleAddProject();
|
||||
if (e.key === "Escape") setAddingProject(false);
|
||||
}}
|
||||
>
|
||||
{MODEL_OPTIONS.map((model) => (
|
||||
<option key={model} value={model} className="bg-[#141414]">
|
||||
{model}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type WorkLogEntry,
|
||||
applyEventToMessages,
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
evolveSession,
|
||||
} from "./session-logic";
|
||||
import type { ChatMessage } from "./types";
|
||||
@@ -105,6 +106,188 @@ describe("deriveTimelineEntries", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveWorkLogEntries", () => {
|
||||
it("drops preamble/work events from the visible work log", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-1",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
payload: { item: { type: "preamble", text: "thinking" } },
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-2",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: { item: { type: "work", text: "planning" } },
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-3",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: { item: { type: "tool_call", command: "ls -la" } },
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.label).toBe("Tool call");
|
||||
});
|
||||
|
||||
it("logs turn completion with elapsed time", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-complete",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:10.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries[0]?.label).toBe("Turn complete in 10s");
|
||||
});
|
||||
|
||||
it("hides reasoning and agent-message noise from the visible work log", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-turn-start",
|
||||
method: "turn/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-summary-part",
|
||||
method: "item/reasoning/summaryPartAdded",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-summary-delta",
|
||||
method: "item/reasoning/summaryTextDelta",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-agent-start",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:03.000Z",
|
||||
payload: {
|
||||
item: { id: "item-msg", type: "agentMessage", text: "Working..." },
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-agent-complete",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:04.000Z",
|
||||
payload: {
|
||||
item: {
|
||||
id: "item-msg",
|
||||
type: "agentMessage",
|
||||
text: "Done response",
|
||||
},
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-tool-start",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:05.000Z",
|
||||
payload: {
|
||||
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-tool-complete",
|
||||
method: "item/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:06.000Z",
|
||||
payload: {
|
||||
item: { id: "item-tool", type: "tool_call", command: "ls -la" },
|
||||
},
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-complete",
|
||||
method: "turn/completed",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:08.000Z",
|
||||
payload: { turn: { id: "turn-1", status: "completed" } },
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries.map((entry) => entry.label)).toEqual([
|
||||
"Turn complete in 8.0s",
|
||||
"Tool call complete",
|
||||
"Tool call",
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves full tool-call detail text without data truncation", () => {
|
||||
const longCommand =
|
||||
'node ./scripts/sync.js --project ct-round-5 --mode dry-run --include "very long argument with lots of detail and metadata to verify there is no hard truncation in session logic"';
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-tool-start",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:05.000Z",
|
||||
payload: {
|
||||
item: { id: "item-tool", type: "tool_call", command: longCommand },
|
||||
},
|
||||
}),
|
||||
],
|
||||
"turn-1",
|
||||
);
|
||||
|
||||
expect(entries[0]?.detail).toBe(longCommand);
|
||||
});
|
||||
|
||||
it("can derive work-log entries across all turns when not scoped", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeEvent({
|
||||
id: "evt-turn-1-tool",
|
||||
method: "item/started",
|
||||
turnId: "turn-1",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
payload: { item: { type: "tool_call", command: "ls -la" } },
|
||||
}),
|
||||
makeEvent({
|
||||
id: "evt-turn-2-tool",
|
||||
method: "item/started",
|
||||
turnId: "turn-2",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
payload: { item: { type: "tool_call", command: "pwd" } },
|
||||
}),
|
||||
],
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(2);
|
||||
expect(entries.map((entry) => entry.detail)).toEqual(["pwd", "ls -la"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("evolveSession", () => {
|
||||
it("updates thread id when thread starts", () => {
|
||||
const previous = makeSession();
|
||||
|
||||
@@ -86,37 +86,59 @@ export type TimelineEntry =
|
||||
entry: WorkLogEntry;
|
||||
};
|
||||
|
||||
function truncateLine(value: string, limit = 140): string {
|
||||
if (value.length <= limit) return value;
|
||||
return `${value.slice(0, limit - 1)}…`;
|
||||
function normalizeDetail(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function normalizeItemType(raw: string | undefined): string {
|
||||
if (!raw) return "item";
|
||||
return raw.replace(/[_-]/g, " ").replace(/\s+/g, " ").trim().toLowerCase();
|
||||
return raw
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.replace(/[._/-]/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function shouldDropItemType(type: string): boolean {
|
||||
if (
|
||||
type.includes("preamble") ||
|
||||
type.includes("reasoning") ||
|
||||
type.includes("thought")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return type === "work" || type.startsWith("work ");
|
||||
}
|
||||
|
||||
function shouldShowItemLifecycle(type: string): boolean {
|
||||
return (
|
||||
type.includes("tool") ||
|
||||
type.includes("command") ||
|
||||
type.includes("file change")
|
||||
);
|
||||
}
|
||||
|
||||
function shouldDropMethod(method: string): boolean {
|
||||
return /(^|\/)(preamble|work|reasoning|thought)(\/|$)/i.test(method);
|
||||
}
|
||||
|
||||
function itemTypeMeta(type: string): {
|
||||
label: string;
|
||||
tone: WorkLogEntry["tone"];
|
||||
} {
|
||||
if (
|
||||
type.includes("preamble") ||
|
||||
type.includes("reasoning") ||
|
||||
type.includes("thought")
|
||||
) {
|
||||
return { label: "Preamble", tone: "thinking" };
|
||||
if (type.includes("command")) {
|
||||
return { label: "Command run", tone: "tool" };
|
||||
}
|
||||
if (
|
||||
type.includes("tool") ||
|
||||
type.includes("command") ||
|
||||
type.includes("file change")
|
||||
) {
|
||||
if (type.includes("file change")) {
|
||||
return { label: "File change", tone: "tool" };
|
||||
}
|
||||
if (type.includes("tool")) {
|
||||
return { label: "Tool call", tone: "tool" };
|
||||
}
|
||||
if (type.includes("agent message")) {
|
||||
return { label: "Drafting response", tone: "thinking" };
|
||||
}
|
||||
return { label: "Work item", tone: "info" };
|
||||
}
|
||||
|
||||
@@ -135,9 +157,8 @@ function extractDetail(
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (candidate && candidate.trim().length > 0) {
|
||||
return truncateLine(candidate.trim());
|
||||
}
|
||||
const detail = normalizeDetail(candidate);
|
||||
if (detail) return detail;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -146,6 +167,13 @@ function entryFromItemLifecycle(event: ProviderEvent): WorkLogEntry | null {
|
||||
const payload = asObject(event.payload);
|
||||
const item = asObject(payload?.item);
|
||||
const normalizedType = normalizeItemType(asString(item?.type));
|
||||
if (shouldDropItemType(normalizedType) || shouldDropMethod(event.method)) {
|
||||
return null;
|
||||
}
|
||||
if (!shouldShowItemLifecycle(normalizedType)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const meta = itemTypeMeta(normalizedType);
|
||||
const isStarted = event.method === "item/started";
|
||||
const isCompleted = event.method === "item/completed";
|
||||
@@ -166,6 +194,7 @@ function entryFromItemLifecycle(event: ProviderEvent): WorkLogEntry | null {
|
||||
|
||||
function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
|
||||
if (event.kind !== "request") return null;
|
||||
if (shouldDropMethod(event.method)) return null;
|
||||
|
||||
if (event.method.includes("commandExecution")) {
|
||||
return {
|
||||
@@ -202,41 +231,75 @@ function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
|
||||
};
|
||||
}
|
||||
|
||||
function entryFromNotification(event: ProviderEvent): WorkLogEntry | null {
|
||||
function entryFromNotification(
|
||||
event: ProviderEvent,
|
||||
turnStartedAt: number,
|
||||
): WorkLogEntry | null {
|
||||
if (event.kind !== "notification") return null;
|
||||
if (shouldDropMethod(event.method)) return null;
|
||||
if (event.method === "item/agentMessage/delta") return null;
|
||||
if (event.method === "turn/started" || event.method === "turn/completed") {
|
||||
if (event.method === "turn/started") {
|
||||
return null;
|
||||
}
|
||||
if (event.method === "thread/started") return null;
|
||||
|
||||
const lifecycleEntry = entryFromItemLifecycle(event);
|
||||
if (lifecycleEntry) return lifecycleEntry;
|
||||
if (event.method === "turn/completed") {
|
||||
const payload = asObject(event.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
const status = asString(turn?.status);
|
||||
const turnError = asObject(turn?.error);
|
||||
const turnErrorMessage = asString(turnError?.message);
|
||||
const turnErrorDetail = normalizeDetail(turnErrorMessage);
|
||||
const eventAt = Date.parse(event.createdAt);
|
||||
const durationMs =
|
||||
Number.isNaN(turnStartedAt) ||
|
||||
Number.isNaN(eventAt) ||
|
||||
eventAt < turnStartedAt
|
||||
? undefined
|
||||
: eventAt - turnStartedAt;
|
||||
|
||||
if (event.method.startsWith("item/")) {
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: `Event: ${event.method.replace(/^item\//, "")}`,
|
||||
tone: "info",
|
||||
label:
|
||||
status === "failed"
|
||||
? "Turn failed"
|
||||
: durationMs !== undefined
|
||||
? `Turn complete in ${formatDuration(durationMs)}`
|
||||
: "Turn complete",
|
||||
...(turnErrorDetail ? { detail: turnErrorDetail } : {}),
|
||||
tone: status === "failed" ? "error" : "info",
|
||||
};
|
||||
}
|
||||
|
||||
const lifecycleEntry = entryFromItemLifecycle(event);
|
||||
if (lifecycleEntry) return lifecycleEntry;
|
||||
|
||||
if (event.method.startsWith("item/")) return null;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function entryFromError(event: ProviderEvent): WorkLogEntry | null {
|
||||
if (event.kind !== "error") return null;
|
||||
if (shouldDropMethod(event.method)) return null;
|
||||
const detail = normalizeDetail(event.message);
|
||||
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: "Runtime error",
|
||||
...(event.message ? { detail: truncateLine(event.message) } : {}),
|
||||
...(detail ? { detail } : {}),
|
||||
tone: "error",
|
||||
};
|
||||
}
|
||||
|
||||
function eventTurnId(event: ProviderEvent): string | undefined {
|
||||
const payload = asObject(event.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
return event.turnId ?? asString(turn?.id);
|
||||
}
|
||||
|
||||
export function deriveWorkLogEntries(
|
||||
events: ProviderEvent[],
|
||||
turnId: string | undefined,
|
||||
@@ -246,10 +309,7 @@ export function deriveWorkLogEntries(
|
||||
const turnStartedAtIso = turnId
|
||||
? ordered.find((event) => {
|
||||
if (event.method !== "turn/started") return false;
|
||||
const payload = asObject(event.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
const startedTurnId = event.turnId ?? asString(turn?.id);
|
||||
return startedTurnId === turnId;
|
||||
return eventTurnId(event) === turnId;
|
||||
})?.createdAt
|
||||
: undefined;
|
||||
const turnStartedAt = turnStartedAtIso
|
||||
@@ -258,11 +318,12 @@ export function deriveWorkLogEntries(
|
||||
|
||||
for (const event of ordered) {
|
||||
if (turnId) {
|
||||
if (event.turnId && event.turnId !== turnId) {
|
||||
const scopedTurnId = eventTurnId(event);
|
||||
if (scopedTurnId && scopedTurnId !== turnId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!event.turnId && !Number.isNaN(turnStartedAt)) {
|
||||
if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
|
||||
const eventAt = Date.parse(event.createdAt);
|
||||
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
|
||||
continue;
|
||||
@@ -276,7 +337,7 @@ export function deriveWorkLogEntries(
|
||||
continue;
|
||||
}
|
||||
|
||||
const fromNotification = entryFromNotification(event);
|
||||
const fromNotification = entryFromNotification(event, turnStartedAt);
|
||||
if (fromNotification) {
|
||||
entries.push(fromNotification);
|
||||
continue;
|
||||
|
||||
@@ -11,7 +11,12 @@ import {
|
||||
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { applyEventToMessages, evolveSession } from "./session-logic";
|
||||
import {
|
||||
applyEventToMessages,
|
||||
asObject,
|
||||
asString,
|
||||
evolveSession,
|
||||
} from "./session-logic";
|
||||
import type { Project, Thread } from "./types";
|
||||
|
||||
// ── Actions ──────────────────────────────────────────────────────────
|
||||
@@ -103,6 +108,57 @@ function findThreadBySessionId(
|
||||
return threads.find((t) => t.session?.sessionId === sessionId);
|
||||
}
|
||||
|
||||
function getEventTurnId(event: ProviderEvent): string | undefined {
|
||||
if (event.turnId) return event.turnId;
|
||||
const payload = asObject(event.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
return asString(turn?.id);
|
||||
}
|
||||
|
||||
function durationMs(startIso: string, endIso: string): number | undefined {
|
||||
const start = Date.parse(startIso);
|
||||
const end = Date.parse(endIso);
|
||||
if (Number.isNaN(start) || Number.isNaN(end) || end < start) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return end - start;
|
||||
}
|
||||
|
||||
function updateTurnFields(
|
||||
thread: Thread,
|
||||
event: ProviderEvent,
|
||||
): Partial<Thread> {
|
||||
if (event.method === "turn/started") {
|
||||
return {
|
||||
latestTurnId: getEventTurnId(event) ?? thread.latestTurnId,
|
||||
latestTurnStartedAt: event.createdAt,
|
||||
latestTurnCompletedAt: undefined,
|
||||
latestTurnDurationMs: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method === "turn/completed") {
|
||||
const completedTurnId = getEventTurnId(event) ?? thread.latestTurnId;
|
||||
const startedAt =
|
||||
completedTurnId && completedTurnId === thread.latestTurnId
|
||||
? thread.latestTurnStartedAt
|
||||
: undefined;
|
||||
const elapsed =
|
||||
startedAt && startedAt.length > 0
|
||||
? durationMs(startedAt, event.createdAt)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
latestTurnId: completedTurnId ?? thread.latestTurnId,
|
||||
latestTurnCompletedAt: event.createdAt,
|
||||
latestTurnDurationMs: elapsed,
|
||||
};
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
// ── Reducer ──────────────────────────────────────────────────────────
|
||||
|
||||
function reducer(state: AppState, action: Action): AppState {
|
||||
@@ -161,9 +217,10 @@ function reducer(state: AppState, action: Action): AppState {
|
||||
event,
|
||||
activeAssistantItemRef,
|
||||
),
|
||||
events: [event, ...t.events].slice(0, 200),
|
||||
events: [event, ...t.events],
|
||||
error:
|
||||
event.kind === "error" && event.message ? event.message : t.error,
|
||||
...updateTurnFields(t, event),
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -176,6 +233,10 @@ function reducer(state: AppState, action: Action): AppState {
|
||||
session: action.session,
|
||||
events: [],
|
||||
error: null,
|
||||
latestTurnId: undefined,
|
||||
latestTurnStartedAt: undefined,
|
||||
latestTurnCompletedAt: undefined,
|
||||
latestTurnDurationMs: undefined,
|
||||
})),
|
||||
};
|
||||
|
||||
|
||||
@@ -28,4 +28,8 @@ export interface Thread {
|
||||
events: ProviderEvent[];
|
||||
error: string | null;
|
||||
createdAt: string;
|
||||
latestTurnId?: string | undefined;
|
||||
latestTurnStartedAt?: string | undefined;
|
||||
latestTurnCompletedAt?: string | undefined;
|
||||
latestTurnDurationMs?: number | undefined;
|
||||
}
|
||||
Reference in new issue
Block a user