progress
This commit is contained in:
16 files changed
+695
-458
No files matched your search
@@ -1,6 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { classifyCodexStderrLine } from "./codexAppServerManager";
|
||||
import {
|
||||
classifyCodexStderrLine,
|
||||
normalizeCodexModelSlug,
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
describe("classifyCodexStderrLine", () => {
|
||||
it("ignores empty lines", () => {
|
||||
@@ -34,3 +37,21 @@ describe("classifyCodexStderrLine", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeCodexModelSlug", () => {
|
||||
it("maps 5.3 aliases to gpt-5.3-codex", () => {
|
||||
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
|
||||
expect(normalizeCodexModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
|
||||
});
|
||||
|
||||
it("prefers codex id when model differs", () => {
|
||||
expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe(
|
||||
"gpt-5.3-codex",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps non-aliased models as-is", () => {
|
||||
expect(normalizeCodexModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
|
||||
expect(normalizeCodexModelSlug("gpt-5.2")).toBe("gpt-5.2");
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,6 @@ import readline from "node:readline";
|
||||
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderModel,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
ProviderSessionStartInput,
|
||||
@@ -60,6 +59,34 @@ const BENIGN_ERROR_LOG_SNIPPETS = [
|
||||
"state db missing rollout path for thread",
|
||||
"state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
|
||||
];
|
||||
const MODEL_SLUG_ALIASES: Record<string, string> = {
|
||||
"5.3": "gpt-5.3-codex",
|
||||
"gpt-5.3": "gpt-5.3-codex",
|
||||
};
|
||||
|
||||
export function normalizeCodexModelSlug(
|
||||
model: string | undefined | null,
|
||||
preferredId?: string,
|
||||
): string | undefined {
|
||||
if (typeof model !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const trimmed = model.trim();
|
||||
if (!trimmed) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (
|
||||
preferredId &&
|
||||
preferredId.endsWith("-codex") &&
|
||||
preferredId !== trimmed
|
||||
) {
|
||||
return preferredId;
|
||||
}
|
||||
|
||||
return MODEL_SLUG_ALIASES[trimmed] ?? trimmed;
|
||||
}
|
||||
|
||||
export function classifyCodexStderrLine(
|
||||
rawLine: string,
|
||||
@@ -104,7 +131,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
sessionId,
|
||||
provider: "codex",
|
||||
status: "connecting",
|
||||
model: input.model,
|
||||
model: normalizeCodexModelSlug(input.model),
|
||||
cwd: input.cwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -150,7 +177,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
this.writeMessage(context, { method: "initialized" });
|
||||
|
||||
const threadStart = await this.sendRequest(context, "thread/start", {
|
||||
model: input.model ?? null,
|
||||
model: null,
|
||||
cwd: input.cwd ?? null,
|
||||
approvalPolicy: input.approvalPolicy,
|
||||
sandbox: input.sandboxMode,
|
||||
@@ -202,6 +229,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
threadId: string;
|
||||
input: Array<{ type: "text"; text: string; text_elements: [] }>;
|
||||
model?: string;
|
||||
effort?: string;
|
||||
} = {
|
||||
threadId: context.session.threadId,
|
||||
input: [
|
||||
@@ -212,8 +240,12 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
},
|
||||
],
|
||||
};
|
||||
if (input.model) {
|
||||
turnStartParams.model = input.model;
|
||||
const normalizedModel = normalizeCodexModelSlug(input.model);
|
||||
if (normalizedModel) {
|
||||
turnStartParams.model = normalizedModel;
|
||||
}
|
||||
if (input.effort) {
|
||||
turnStartParams.effort = input.effort;
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(
|
||||
@@ -239,177 +271,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
};
|
||||
}
|
||||
|
||||
async listModels(cwd?: string): Promise<ProviderModel[]> {
|
||||
const child = spawn("codex", ["app-server"], {
|
||||
cwd,
|
||||
env: process.env,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
const pending = new Map<PendingRequestKey, PendingRequest>();
|
||||
let nextRequestId = 1;
|
||||
let exited = false;
|
||||
let exitError: Error | null = null;
|
||||
|
||||
const cleanup = () => {
|
||||
for (const request of pending.values()) {
|
||||
clearTimeout(request.timeout);
|
||||
}
|
||||
pending.clear();
|
||||
output.close();
|
||||
if (!child.killed) {
|
||||
child.kill();
|
||||
}
|
||||
};
|
||||
|
||||
const writeMessage = (message: unknown) => {
|
||||
if (!child.stdin.writable) {
|
||||
throw new Error("Cannot write to codex app-server stdin.");
|
||||
}
|
||||
child.stdin.write(`${JSON.stringify(message)}\n`);
|
||||
};
|
||||
|
||||
const sendRequest = async <TResponse>(
|
||||
method: string,
|
||||
params: unknown,
|
||||
timeoutMs = 20_000,
|
||||
): Promise<TResponse> => {
|
||||
if (exited) {
|
||||
throw (
|
||||
exitError ??
|
||||
new Error("codex app-server exited before request could be sent.")
|
||||
);
|
||||
}
|
||||
|
||||
const id = nextRequestId;
|
||||
nextRequestId += 1;
|
||||
|
||||
const result = await new Promise<unknown>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
pending.delete(String(id));
|
||||
reject(new Error(`Timed out waiting for ${method}.`));
|
||||
}, timeoutMs);
|
||||
|
||||
pending.set(String(id), {
|
||||
timeout,
|
||||
resolve,
|
||||
reject,
|
||||
method,
|
||||
});
|
||||
writeMessage({ id, method, params });
|
||||
});
|
||||
|
||||
return result as TResponse;
|
||||
};
|
||||
|
||||
output.on("line", (line) => {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isResponse(parsed)) {
|
||||
const key = String(parsed.id);
|
||||
const request = pending.get(key);
|
||||
if (!request) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearTimeout(request.timeout);
|
||||
pending.delete(key);
|
||||
|
||||
if (parsed.error?.message) {
|
||||
request.reject(
|
||||
new Error(
|
||||
`${request.method} failed: ${String(parsed.error.message)}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
request.resolve(parsed.result);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.isServerRequest(parsed)) {
|
||||
writeMessage({
|
||||
id: parsed.id,
|
||||
error: {
|
||||
code: -32601,
|
||||
message: `Unsupported server request: ${parsed.method}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
exited = true;
|
||||
exitError = error;
|
||||
for (const request of pending.values()) {
|
||||
clearTimeout(request.timeout);
|
||||
request.reject(error);
|
||||
}
|
||||
pending.clear();
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
exited = true;
|
||||
if (!exitError && code !== 0) {
|
||||
exitError = new Error(
|
||||
`codex app-server exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
|
||||
);
|
||||
}
|
||||
for (const request of pending.values()) {
|
||||
clearTimeout(request.timeout);
|
||||
request.reject(
|
||||
exitError ??
|
||||
new Error("codex app-server exited before request completed."),
|
||||
);
|
||||
}
|
||||
pending.clear();
|
||||
});
|
||||
|
||||
try {
|
||||
await sendRequest("initialize", {
|
||||
clientInfo: {
|
||||
name: "codething_desktop",
|
||||
title: "CodeThing Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: false,
|
||||
},
|
||||
});
|
||||
|
||||
writeMessage({ method: "initialized" });
|
||||
|
||||
const deduped = new Map<string, ProviderModel>();
|
||||
let cursor: string | null = null;
|
||||
|
||||
while (true) {
|
||||
const response = await sendRequest<unknown>("model/list", {
|
||||
cursor,
|
||||
limit: 100,
|
||||
});
|
||||
const parsed = this.parseModelListResponse(response);
|
||||
for (const model of parsed.models) {
|
||||
deduped.set(model.model, model);
|
||||
}
|
||||
|
||||
if (!parsed.nextCursor) {
|
||||
break;
|
||||
}
|
||||
cursor = parsed.nextCursor;
|
||||
}
|
||||
|
||||
return Array.from(deduped.values());
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
async interruptTurn(sessionId: string, turnId?: string): Promise<void> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const effectiveTurnId = turnId ?? context.session.activeTurnId;
|
||||
@@ -807,66 +668,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
};
|
||||
}
|
||||
|
||||
private parseModelListResponse(response: unknown): {
|
||||
models: ProviderModel[];
|
||||
nextCursor: string | null;
|
||||
} {
|
||||
const object = this.readObject(response);
|
||||
if (!object) {
|
||||
throw new Error("model/list response was not an object.");
|
||||
}
|
||||
|
||||
const data = object.data;
|
||||
if (!Array.isArray(data)) {
|
||||
throw new Error("model/list response missing data array.");
|
||||
}
|
||||
|
||||
const models: ProviderModel[] = [];
|
||||
for (const entry of data) {
|
||||
const item = this.readObject(entry);
|
||||
if (!item) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const model = this.readString(item, "model");
|
||||
if (!model) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const id = this.readString(item, "id") ?? model;
|
||||
const displayName = this.readString(item, "displayName") ?? model;
|
||||
const description = this.readString(item, "description");
|
||||
const isDefault =
|
||||
typeof item.isDefault === "boolean" ? item.isDefault : undefined;
|
||||
const rawUpgrade = item.upgrade;
|
||||
const upgrade =
|
||||
typeof rawUpgrade === "string"
|
||||
? rawUpgrade
|
||||
: rawUpgrade === null
|
||||
? null
|
||||
: undefined;
|
||||
|
||||
models.push({
|
||||
id,
|
||||
model,
|
||||
displayName,
|
||||
...(description ? { description } : {}),
|
||||
...(isDefault === undefined ? {} : { isDefault }),
|
||||
...(upgrade === undefined ? {} : { upgrade }),
|
||||
});
|
||||
}
|
||||
|
||||
const rawCursor = object.nextCursor;
|
||||
const nextCursor =
|
||||
typeof rawCursor === "string"
|
||||
? rawCursor
|
||||
: rawCursor === null || rawCursor === undefined
|
||||
? null
|
||||
: null;
|
||||
|
||||
return { models, nextCursor };
|
||||
}
|
||||
|
||||
private isServerRequest(value: unknown): value is JsonRpcRequest {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
|
||||
@@ -139,15 +139,6 @@ function registerIpcHandlers(): void {
|
||||
ipcMain.handle(IPC_CHANNELS.providerSessionList, async () => {
|
||||
return providerManager.listSessions();
|
||||
});
|
||||
|
||||
ipcMain.handle(
|
||||
IPC_CHANNELS.providerModelList,
|
||||
async (_event, payload: unknown) => {
|
||||
return providerManager.listModels(
|
||||
payload as Parameters<typeof providerManager.listModels>[0],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function runTerminalCommand(
|
||||
|
||||
@@ -41,8 +41,6 @@ const nativeApi: NativeApi = {
|
||||
stopSession: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerSessionStop, input),
|
||||
listSessions: () => ipcRenderer.invoke(IPC_CHANNELS.providerSessionList),
|
||||
listModels: (input) =>
|
||||
ipcRenderer.invoke(IPC_CHANNELS.providerModelList, input),
|
||||
onEvent: (callback) => {
|
||||
const listener = (_event: Electron.IpcRendererEvent, payload: unknown) =>
|
||||
callback(payload as Parameters<typeof callback>[0]);
|
||||
|
||||
@@ -3,15 +3,12 @@ import { EventEmitter } from "node:events";
|
||||
import {
|
||||
type ProviderEvent,
|
||||
type ProviderInterruptTurnInput,
|
||||
type ProviderListModelsInput,
|
||||
type ProviderModel,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderStopSessionInput,
|
||||
type ProviderTurnStartResult,
|
||||
providerInterruptTurnInputSchema,
|
||||
providerListModelsInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
providerStopSessionInputSchema,
|
||||
@@ -66,17 +63,6 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
return this.codex.listSessions();
|
||||
}
|
||||
|
||||
async listModels(
|
||||
raw: ProviderListModelsInput = {},
|
||||
): Promise<ProviderModel[]> {
|
||||
const input = providerListModelsInputSchema.parse(raw);
|
||||
if (input.provider !== "codex") {
|
||||
throw new Error(`Provider '${input.provider}' is not implemented yet.`);
|
||||
}
|
||||
|
||||
return this.codex.listModels(input.cwd);
|
||||
}
|
||||
|
||||
stopAll(): void {
|
||||
this.codex.stopAll();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { ProviderModel } from "@acme/contracts";
|
||||
import {
|
||||
type FormEvent,
|
||||
type KeyboardEvent,
|
||||
@@ -8,10 +7,40 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
import { derivePhase, formatTimestamp, readNativeApi } from "../session-logic";
|
||||
import {
|
||||
derivePhase,
|
||||
deriveWorkLogEntries,
|
||||
formatElapsed,
|
||||
formatTimestamp,
|
||||
readNativeApi,
|
||||
} from "../session-logic";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_REASONING,
|
||||
MODEL_OPTIONS,
|
||||
REASONING_OPTIONS,
|
||||
resolveModelSlug,
|
||||
} from "../model-logic";
|
||||
import { useStore } from "../store";
|
||||
|
||||
const DEFAULT_MODEL = "gpt-5.2-codex";
|
||||
function formatMessageMeta(createdAt: string, duration: string | null): string {
|
||||
if (!duration) return formatTimestamp(createdAt);
|
||||
return `${formatTimestamp(createdAt)} • ${duration}`;
|
||||
}
|
||||
|
||||
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 === "thinking") return "text-sky-100";
|
||||
if (tone === "tool") return "text-emerald-100";
|
||||
if (tone === "error") return "text-rose-100";
|
||||
return "text-[#d8d8d8]";
|
||||
}
|
||||
|
||||
export default function ChatView() {
|
||||
const { state, dispatch } = useStore();
|
||||
@@ -20,9 +49,10 @@ export default function ChatView() {
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const [isModelMenuOpen, setIsModelMenuOpen] = useState(false);
|
||||
const [isLoadingModels, setIsLoadingModels] = useState(false);
|
||||
const [modelLoadError, setModelLoadError] = useState<string | null>(null);
|
||||
const [availableModels, setAvailableModels] = useState<ProviderModel[]>([]);
|
||||
const [selectedEffort, setSelectedEffort] = useState<string>(
|
||||
DEFAULT_REASONING,
|
||||
);
|
||||
const [nowTick, setNowTick] = useState(() => Date.now());
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const modelMenuRef = useRef<HTMLDivElement>(null);
|
||||
@@ -31,31 +61,42 @@ export default function ChatView() {
|
||||
const activeProject = state.projects.find(
|
||||
(p) => p.id === activeThread?.projectId,
|
||||
);
|
||||
const selectedModel =
|
||||
activeThread?.model || activeProject?.model || DEFAULT_MODEL;
|
||||
const selectedModel = resolveModelSlug(
|
||||
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
||||
);
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const modelOptions = useMemo(() => {
|
||||
const deduped = new Map<string, ProviderModel>();
|
||||
for (const model of availableModels) {
|
||||
deduped.set(model.model, model);
|
||||
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],
|
||||
);
|
||||
const assistantCompletionByItemId = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
const ordered = [...(activeThread?.events ?? [])].reverse();
|
||||
for (const event of ordered) {
|
||||
if (event.method !== "item/completed") continue;
|
||||
if (!event.itemId) continue;
|
||||
map.set(event.itemId, event.createdAt);
|
||||
}
|
||||
if (!deduped.has(selectedModel)) {
|
||||
deduped.set(selectedModel, {
|
||||
id: selectedModel,
|
||||
model: selectedModel,
|
||||
displayName: selectedModel,
|
||||
description: "Current model for this thread.",
|
||||
});
|
||||
}
|
||||
return Array.from(deduped.values());
|
||||
}, [availableModels, selectedModel]);
|
||||
return map;
|
||||
}, [activeThread?.events]);
|
||||
const recentWorkLogEntries = workLogEntries.slice(-12);
|
||||
|
||||
// Auto-scroll on new messages
|
||||
const messageCount = activeThread?.messages.length ?? 0;
|
||||
const workLogCount = recentWorkLogEntries.length;
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: trigger on message count change
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [messageCount]);
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: auto-scroll while active work-log events stream in
|
||||
useEffect(() => {
|
||||
if (phase !== "running") return;
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [phase, workLogCount]);
|
||||
|
||||
// Auto-resize textarea
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: trigger on prompt change
|
||||
@@ -66,6 +107,16 @@ export default function ChatView() {
|
||||
ta.style.height = `${Math.min(ta.scrollHeight, 200)}px`;
|
||||
}, [prompt]);
|
||||
|
||||
useEffect(() => {
|
||||
if (phase !== "running") return;
|
||||
const timer = window.setInterval(() => {
|
||||
setNowTick(Date.now());
|
||||
}, 250);
|
||||
return () => {
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [phase]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isModelMenuOpen) return;
|
||||
|
||||
@@ -85,48 +136,6 @@ export default function ChatView() {
|
||||
};
|
||||
}, [isModelMenuOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!api || !state.activeThreadId) return;
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const loadModels = async () => {
|
||||
setIsLoadingModels(true);
|
||||
setModelLoadError(null);
|
||||
try {
|
||||
const models = await api.providers.listModels(
|
||||
activeProject?.cwd ? { cwd: activeProject.cwd } : undefined,
|
||||
);
|
||||
if (cancelled) return;
|
||||
|
||||
const sorted = [...models].sort((a, b) => {
|
||||
if ((a.isDefault ?? false) && !(b.isDefault ?? false)) return -1;
|
||||
if ((b.isDefault ?? false) && !(a.isDefault ?? false)) return 1;
|
||||
return a.displayName.localeCompare(b.displayName);
|
||||
});
|
||||
setAvailableModels(sorted);
|
||||
} catch (err) {
|
||||
if (cancelled) return;
|
||||
setAvailableModels([]);
|
||||
setModelLoadError(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Could not load available models from Codex.",
|
||||
);
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setIsLoadingModels(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void loadModels();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [api, activeProject?.cwd, state.activeThreadId]);
|
||||
|
||||
const ensureSession = async (): Promise<string | null> => {
|
||||
if (!api || !activeThread || !activeProject) return null;
|
||||
if (activeThread.session && activeThread.session.status !== "closed") {
|
||||
@@ -197,6 +206,7 @@ export default function ChatView() {
|
||||
sessionId,
|
||||
input: trimmed,
|
||||
model: selectedModel || undefined,
|
||||
effort: selectedEffort || undefined,
|
||||
});
|
||||
} catch (err) {
|
||||
dispatch({
|
||||
@@ -222,7 +232,7 @@ export default function ChatView() {
|
||||
dispatch({
|
||||
type: "SET_THREAD_MODEL",
|
||||
threadId: activeThread.id,
|
||||
model,
|
||||
model: resolveModelSlug(model),
|
||||
});
|
||||
setIsModelMenuOpen(false);
|
||||
};
|
||||
@@ -266,19 +276,38 @@ export default function ChatView() {
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Status indicator */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div
|
||||
className={`h-2 w-2 rounded-full ${
|
||||
phase === "running"
|
||||
? "animate-pulse bg-emerald-400"
|
||||
<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"
|
||||
? "bg-emerald-400"
|
||||
? "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"
|
||||
? "animate-pulse bg-amber-400"
|
||||
: "bg-[#a0a0a0]/30"
|
||||
}`}
|
||||
/>
|
||||
<span className="text-[10px] text-[#a0a0a0]/50">{phase}</span>
|
||||
? "bg-amber-200"
|
||||
: phase === "ready"
|
||||
? "bg-emerald-200"
|
||||
: "bg-[#a0a0a0]/40"
|
||||
}`}
|
||||
/>
|
||||
</span>
|
||||
<span>{statusLabel(phase)}</span>
|
||||
</div>
|
||||
{/* Diff toggle */}
|
||||
<button
|
||||
@@ -304,7 +333,7 @@ export default function ChatView() {
|
||||
|
||||
{/* Messages */}
|
||||
<div className="flex-1 overflow-y-auto px-5 py-4">
|
||||
{activeThread.messages.length === 0 ? (
|
||||
{activeThread.messages.length === 0 && !isWorking ? (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-sm text-[#a0a0a0]/30">
|
||||
Send a message to start the conversation.
|
||||
@@ -312,6 +341,53 @@ export default function ChatView() {
|
||||
</div>
|
||||
) : (
|
||||
<div className="mx-auto max-w-3xl space-y-4">
|
||||
{isWorking && (
|
||||
<div className="rounded-2xl border border-sky-400/20 bg-sky-500/[0.06] px-3 py-2.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="inline-flex items-center gap-2 text-xs text-sky-100">
|
||||
<span className="relative inline-flex h-2.5 w-2.5">
|
||||
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-sky-300/70" />
|
||||
<span className="relative inline-flex h-2.5 w-2.5 rounded-full bg-sky-200" />
|
||||
</span>
|
||||
<span>Model is working</span>
|
||||
</div>
|
||||
<span className="text-[10px] text-sky-100/70">
|
||||
{recentWorkLogEntries.length} event
|
||||
{recentWorkLogEntries.length === 1 ? "" : "s"}
|
||||
</span>
|
||||
</div>
|
||||
{recentWorkLogEntries.length === 0 ? (
|
||||
<p className="pt-2 text-[11px] text-sky-100/70">
|
||||
Waiting for tool/preamble updates...
|
||||
</p>
|
||||
) : (
|
||||
<div className="mt-2 max-h-48 space-y-1.5 overflow-y-auto pr-1">
|
||||
{recentWorkLogEntries.map((entry) => (
|
||||
<div
|
||||
key={entry.id}
|
||||
className="rounded-lg border border-white/[0.08] bg-black/20 px-2 py-1.5"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<p
|
||||
className={`text-[11px] ${workToneClass(entry.tone)}`}
|
||||
>
|
||||
{entry.label}
|
||||
</p>
|
||||
<span className="shrink-0 text-[10px] text-[#a0a0a0]/60">
|
||||
{formatTimestamp(entry.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
{entry.detail && (
|
||||
<p className="pt-0.5 font-mono text-[11px] text-[#d0d0d0]/75">
|
||||
{entry.detail}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{activeThread.messages.map((msg) => (
|
||||
<div key={msg.id}>
|
||||
{msg.role === "user" ? (
|
||||
@@ -331,17 +407,28 @@ export default function ChatView() {
|
||||
{msg.text || (msg.streaming ? "" : "(empty response)")}
|
||||
</pre>
|
||||
{msg.streaming && (
|
||||
<span className="inline-flex gap-1 pt-1">
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-white/50" />
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-white/50 [animation-delay:150ms]" />
|
||||
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-white/50 [animation-delay:300ms]" />
|
||||
</span>
|
||||
)}
|
||||
{!msg.streaming && (
|
||||
<p className="mt-1.5 text-[10px] text-[#a0a0a0]/30">
|
||||
{formatTimestamp(msg.createdAt)}
|
||||
</p>
|
||||
<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(
|
||||
msg.createdAt,
|
||||
msg.streaming
|
||||
? formatElapsed(msg.createdAt, nowIso)
|
||||
: formatElapsed(
|
||||
msg.createdAt,
|
||||
assistantCompletionByItemId.get(msg.id),
|
||||
),
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -373,70 +460,71 @@ export default function ChatView() {
|
||||
disabled={isSending || isConnecting}
|
||||
/>
|
||||
<div className="mt-2 flex items-center justify-between gap-2">
|
||||
<div className="relative" ref={modelMenuRef}>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center gap-2 rounded-full border border-white/[0.1] bg-white/[0.04] px-3 py-1.5 text-xs text-[#d8d8d8] transition-colors duration-150 hover:bg-white/[0.08]"
|
||||
onClick={() => setIsModelMenuOpen((open) => !open)}
|
||||
>
|
||||
<span className="max-w-[180px] truncate">
|
||||
{selectedModel}
|
||||
</span>
|
||||
<span className="text-[10px] text-[#a0a0a0]/70">▼</span>
|
||||
</button>
|
||||
{isModelMenuOpen && (
|
||||
<div className="absolute bottom-full left-0 z-20 mb-2 w-[340px] rounded-2xl border border-white/[0.1] bg-[#1b1b1d]/95 p-2 shadow-[0_16px_40px_rgba(0,0,0,0.55)] backdrop-blur">
|
||||
<p className="px-2 py-1 text-[11px] text-[#a0a0a0]/70">
|
||||
Select model
|
||||
</p>
|
||||
<div className="max-h-72 overflow-y-auto">
|
||||
{modelOptions.map((model) => {
|
||||
const isSelected = model.model === selectedModel;
|
||||
return (
|
||||
<button
|
||||
key={model.id}
|
||||
type="button"
|
||||
className={`mb-0.5 flex w-full items-start justify-between gap-2 rounded-xl px-2 py-2 text-left transition-colors duration-150 ${
|
||||
isSelected
|
||||
? "bg-white/[0.08] text-white"
|
||||
: "text-[#d4d4d4] hover:bg-white/[0.05]"
|
||||
}`}
|
||||
onClick={() => onModelSelect(model.model)}
|
||||
>
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-sm">
|
||||
{model.displayName}
|
||||
</span>
|
||||
{model.description && (
|
||||
<span className="block pt-0.5 text-[10px] text-[#a0a0a0]/65">
|
||||
{model.description}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span
|
||||
className={`pt-0.5 text-sm ${
|
||||
isSelected ? "text-white" : "text-transparent"
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative" ref={modelMenuRef}>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center gap-2 rounded-full border border-white/[0.1] bg-white/[0.04] px-3 py-1.5 text-xs text-[#d8d8d8] transition-colors duration-150 hover:bg-white/[0.08]"
|
||||
onClick={() => setIsModelMenuOpen((open) => !open)}
|
||||
>
|
||||
<span className="max-w-[180px] truncate font-mono">
|
||||
{selectedModel}
|
||||
</span>
|
||||
<span className="text-[10px] text-[#a0a0a0]/70">▼</span>
|
||||
</button>
|
||||
{isModelMenuOpen && (
|
||||
<div className="absolute bottom-full left-0 z-20 mb-2 w-[320px] rounded-2xl border border-white/[0.1] bg-[#1b1b1d]/95 p-2 shadow-[0_16px_40px_rgba(0,0,0,0.55)] backdrop-blur">
|
||||
<p className="px-2 py-1 text-[11px] text-[#a0a0a0]/70">
|
||||
Select model
|
||||
</p>
|
||||
<div className="max-h-72 overflow-y-auto">
|
||||
{modelOptions.map((model) => {
|
||||
const isSelected = model === selectedModel;
|
||||
return (
|
||||
<button
|
||||
key={model}
|
||||
type="button"
|
||||
className={`mb-0.5 flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left font-mono text-sm transition-colors duration-150 ${
|
||||
isSelected
|
||||
? "bg-white/[0.08] text-white"
|
||||
: "text-[#d4d4d4] hover:bg-white/[0.05]"
|
||||
}`}
|
||||
onClick={() => onModelSelect(model)}
|
||||
>
|
||||
✓
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
<span className="truncate">{model}</span>
|
||||
<span
|
||||
className={`pt-0.5 text-sm ${
|
||||
isSelected ? "text-white" : "text-transparent"
|
||||
}`}
|
||||
>
|
||||
✓
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{isLoadingModels && (
|
||||
<p className="px-2 pt-2 text-[10px] text-[#a0a0a0]/60">
|
||||
Refreshing available models...
|
||||
</p>
|
||||
)}
|
||||
{modelLoadError && (
|
||||
<p className="px-2 pt-2 text-[10px] text-amber-200/80">
|
||||
Could not load full model list from Codex:{" "}
|
||||
{modelLoadError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
</div>
|
||||
<label
|
||||
className="inline-flex items-center gap-2 rounded-full border border-white/[0.1] bg-white/[0.04] px-3 py-1.5 text-xs text-[#d8d8d8]"
|
||||
htmlFor="reasoning-effort"
|
||||
>
|
||||
<span>Reasoning</span>
|
||||
<select
|
||||
id="reasoning-effort"
|
||||
className="bg-transparent font-mono text-xs text-[#d8d8d8] outline-none"
|
||||
value={selectedEffort}
|
||||
onChange={(event) => setSelectedEffort(event.target.value)}
|
||||
>
|
||||
{REASONING_OPTIONS.map((effort) => (
|
||||
<option key={effort} value={effort} className="bg-[#1b1b1d]">
|
||||
{effort}
|
||||
{effort === DEFAULT_REASONING ? " (default)" : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{activeProject && (
|
||||
<span className="text-[10px] text-[#a0a0a0]/35">
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useState } from "react";
|
||||
import { DEFAULT_MODEL, MODEL_OPTIONS, resolveModelSlug } from "../model-logic";
|
||||
import { useStore } from "../store";
|
||||
import type { Project } from "../types";
|
||||
|
||||
const DEFAULT_MODEL = "gpt-5.2-codex";
|
||||
|
||||
function formatRelativeTime(iso: string): string {
|
||||
const diff = Date.now() - new Date(iso).getTime();
|
||||
const minutes = Math.floor(diff / 60_000);
|
||||
@@ -24,11 +23,12 @@ export default function Sidebar() {
|
||||
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: newModel.trim() || DEFAULT_MODEL,
|
||||
model: normalizedModel,
|
||||
expanded: true,
|
||||
};
|
||||
dispatch({ type: "ADD_PROJECT", project });
|
||||
@@ -186,16 +186,21 @@ export default function Sidebar() {
|
||||
if (e.key === "Escape") setAddingProject(false);
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
<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"
|
||||
placeholder={`model (default: ${DEFAULT_MODEL})`}
|
||||
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"
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DEFAULT_MODEL, normalizeModelSlug, resolveModelSlug } from "./model-logic";
|
||||
|
||||
describe("normalizeModelSlug", () => {
|
||||
it("maps 5.3 aliases to canonical codex slug", () => {
|
||||
expect(normalizeModelSlug("5.3")).toBe("gpt-5.3-codex");
|
||||
expect(normalizeModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
|
||||
});
|
||||
|
||||
it("preserves non-aliased slugs", () => {
|
||||
expect(normalizeModelSlug("gpt-5.3-codex")).toBe("gpt-5.3-codex");
|
||||
expect(normalizeModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
|
||||
});
|
||||
|
||||
it("returns null for empty input", () => {
|
||||
expect(normalizeModelSlug("")).toBeNull();
|
||||
expect(normalizeModelSlug(" ")).toBeNull();
|
||||
expect(normalizeModelSlug(null)).toBeNull();
|
||||
expect(normalizeModelSlug(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveModelSlug", () => {
|
||||
it("falls back to default for unknown models", () => {
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL);
|
||||
});
|
||||
|
||||
it("resolves supported hard-coded models", () => {
|
||||
expect(resolveModelSlug("gpt-5.3-codex")).toBe("gpt-5.3-codex");
|
||||
expect(resolveModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
|
||||
expect(resolveModelSlug("gpt-5.2")).toBe("gpt-5.2");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
export const MODEL_OPTIONS = [
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.2-codex",
|
||||
"gpt-5.2",
|
||||
] as const;
|
||||
|
||||
export const DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
|
||||
export const REASONING_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
||||
export const DEFAULT_REASONING = "high";
|
||||
|
||||
const MODEL_SLUG_ALIASES: Record<string, string> = {
|
||||
"5.3": "gpt-5.3-codex",
|
||||
"gpt-5.3": "gpt-5.3-codex",
|
||||
};
|
||||
|
||||
export function normalizeModelSlug(model: string | null | undefined): string | null {
|
||||
if (typeof model !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const trimmed = model.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return MODEL_SLUG_ALIASES[trimmed] ?? trimmed;
|
||||
}
|
||||
|
||||
export function resolveModelSlug(model: string | null | undefined): string {
|
||||
const normalized = normalizeModelSlug(model);
|
||||
if (!normalized) {
|
||||
return DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
return MODEL_OPTIONS.includes(normalized as (typeof MODEL_OPTIONS)[number])
|
||||
? normalized
|
||||
: DEFAULT_MODEL;
|
||||
}
|
||||
@@ -36,6 +36,247 @@ export function formatTimestamp(isoDate: string): string {
|
||||
}).format(new Date(isoDate));
|
||||
}
|
||||
|
||||
export function formatDuration(durationMs: number): string {
|
||||
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
|
||||
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
|
||||
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
|
||||
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
|
||||
|
||||
const minutes = Math.floor(durationMs / 60_000);
|
||||
const seconds = Math.round((durationMs % 60_000) / 1_000);
|
||||
if (seconds === 0) return `${minutes}m`;
|
||||
if (seconds === 60) return `${minutes + 1}m`;
|
||||
return `${minutes}m ${seconds}s`;
|
||||
}
|
||||
|
||||
export function formatElapsed(
|
||||
startIso: string,
|
||||
endIso: string | undefined,
|
||||
): string | null {
|
||||
if (!endIso) return null;
|
||||
|
||||
const startedAt = Date.parse(startIso);
|
||||
const endedAt = Date.parse(endIso);
|
||||
if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return formatDuration(endedAt - startedAt);
|
||||
}
|
||||
|
||||
export interface WorkLogEntry {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
label: string;
|
||||
detail?: string;
|
||||
tone: "thinking" | "tool" | "info" | "error";
|
||||
}
|
||||
|
||||
function truncateLine(value: string, limit = 140): string {
|
||||
if (value.length <= limit) return value;
|
||||
return `${value.slice(0, limit - 1)}…`;
|
||||
}
|
||||
|
||||
function normalizeItemType(raw: string | undefined): string {
|
||||
if (!raw) return "item";
|
||||
return raw.replace(/[_-]/g, " ").replace(/\s+/g, " ").trim().toLowerCase();
|
||||
}
|
||||
|
||||
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("tool") ||
|
||||
type.includes("command") ||
|
||||
type.includes("file change")
|
||||
) {
|
||||
return { label: "Tool call", tone: "tool" };
|
||||
}
|
||||
if (type.includes("agent message")) {
|
||||
return { label: "Drafting response", tone: "thinking" };
|
||||
}
|
||||
return { label: "Work item", tone: "info" };
|
||||
}
|
||||
|
||||
function extractDetail(
|
||||
payload: Record<string, unknown> | undefined,
|
||||
item: Record<string, unknown> | undefined,
|
||||
): string | undefined {
|
||||
const candidates = [
|
||||
asString(item?.title),
|
||||
asString(item?.summary),
|
||||
asString(item?.text),
|
||||
asString(item?.command),
|
||||
asString(payload?.message),
|
||||
asString(payload?.prompt),
|
||||
asString(payload?.command),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (candidate && candidate.trim().length > 0) {
|
||||
return truncateLine(candidate.trim());
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function entryFromItemLifecycle(event: ProviderEvent): WorkLogEntry | null {
|
||||
const payload = asObject(event.payload);
|
||||
const item = asObject(payload?.item);
|
||||
const normalizedType = normalizeItemType(asString(item?.type));
|
||||
const meta = itemTypeMeta(normalizedType);
|
||||
const isStarted = event.method === "item/started";
|
||||
const isCompleted = event.method === "item/completed";
|
||||
if (!isStarted && !isCompleted) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const label = isCompleted ? `${meta.label} complete` : meta.label;
|
||||
const detail = extractDetail(payload, item);
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label,
|
||||
...(detail ? { detail } : {}),
|
||||
tone: meta.tone,
|
||||
};
|
||||
}
|
||||
|
||||
function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
|
||||
if (event.kind !== "request") return null;
|
||||
|
||||
if (event.method.includes("commandExecution")) {
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: "Command approval requested",
|
||||
tone: "tool",
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method.includes("fileChange")) {
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: "File-change approval requested",
|
||||
tone: "tool",
|
||||
};
|
||||
}
|
||||
|
||||
if (event.method.includes("requestUserInput")) {
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: "Tool requested user input",
|
||||
tone: "tool",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: `Request: ${event.method}`,
|
||||
tone: "info",
|
||||
};
|
||||
}
|
||||
|
||||
function entryFromNotification(event: ProviderEvent): WorkLogEntry | null {
|
||||
if (event.kind !== "notification") return null;
|
||||
if (event.method === "item/agentMessage/delta") return null;
|
||||
if (event.method === "turn/started" || event.method === "turn/completed") {
|
||||
return null;
|
||||
}
|
||||
if (event.method === "thread/started") return null;
|
||||
|
||||
const lifecycleEntry = entryFromItemLifecycle(event);
|
||||
if (lifecycleEntry) return lifecycleEntry;
|
||||
|
||||
if (event.method.startsWith("item/")) {
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: `Event: ${event.method.replace(/^item\//, "")}`,
|
||||
tone: "info",
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function entryFromError(event: ProviderEvent): WorkLogEntry | null {
|
||||
if (event.kind !== "error") return null;
|
||||
|
||||
return {
|
||||
id: event.id,
|
||||
createdAt: event.createdAt,
|
||||
label: "Runtime error",
|
||||
...(event.message ? { detail: truncateLine(event.message) } : {}),
|
||||
tone: "error",
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveWorkLogEntries(
|
||||
events: ProviderEvent[],
|
||||
turnId: string | undefined,
|
||||
): WorkLogEntry[] {
|
||||
const ordered = [...events].reverse();
|
||||
const entries: WorkLogEntry[] = [];
|
||||
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;
|
||||
})?.createdAt
|
||||
: undefined;
|
||||
const turnStartedAt = turnStartedAtIso
|
||||
? Date.parse(turnStartedAtIso)
|
||||
: Number.NaN;
|
||||
|
||||
for (const event of ordered) {
|
||||
if (turnId) {
|
||||
if (event.turnId && event.turnId !== turnId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!event.turnId && !Number.isNaN(turnStartedAt)) {
|
||||
const eventAt = Date.parse(event.createdAt);
|
||||
if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const fromRequest = entryFromRequest(event);
|
||||
if (fromRequest) {
|
||||
entries.push(fromRequest);
|
||||
continue;
|
||||
}
|
||||
|
||||
const fromNotification = entryFromNotification(event);
|
||||
if (fromNotification) {
|
||||
entries.push(fromNotification);
|
||||
continue;
|
||||
}
|
||||
|
||||
const fromError = entryFromError(event);
|
||||
if (fromError) {
|
||||
entries.push(fromError);
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
export function derivePhase(session: ProviderSession | null): SessionPhase {
|
||||
if (!session || session.status === "closed") return "disconnected";
|
||||
if (session.status === "connecting") return "connecting";
|
||||
|
||||
+49
-11
@@ -9,6 +9,7 @@ import {
|
||||
} from "react";
|
||||
|
||||
import type { ProviderEvent, ProviderSession } from "@acme/contracts";
|
||||
import { DEFAULT_MODEL, resolveModelSlug } from "./model-logic";
|
||||
import { applyEventToMessages, evolveSession } from "./session-logic";
|
||||
import type { Project, Thread } from "./types";
|
||||
|
||||
@@ -40,7 +41,9 @@ export interface AppState {
|
||||
diffOpen: boolean;
|
||||
}
|
||||
|
||||
const PERSISTED_STATE_KEY = "codething:renderer-state:v1";
|
||||
const PERSISTED_STATE_KEY = "codething:renderer-state:v2";
|
||||
const LEGACY_PERSISTED_STATE_KEY = "codething:renderer-state:v1";
|
||||
const LEGACY_DEFAULT_MODEL = "gpt-5.2-codex";
|
||||
|
||||
const initialState: AppState = {
|
||||
projects: [],
|
||||
@@ -86,7 +89,8 @@ function sanitizeProjects(input: unknown): Project[] {
|
||||
const id = asString(project.id);
|
||||
const name = asString(project.name);
|
||||
const cwd = asString(project.cwd);
|
||||
const model = asString(project.model);
|
||||
const rawModel = asString(project.model);
|
||||
const model = resolveModelSlug(rawModel);
|
||||
const expanded = project.expanded;
|
||||
if (!id || !name || !cwd || !model || !isBoolean(expanded)) return null;
|
||||
|
||||
@@ -101,6 +105,10 @@ function sanitizeProjects(input: unknown): Project[] {
|
||||
.filter((project): project is Project => project !== null);
|
||||
}
|
||||
|
||||
function migrateLegacyDefaultModel(model: string): string {
|
||||
return model === LEGACY_DEFAULT_MODEL ? DEFAULT_MODEL : model;
|
||||
}
|
||||
|
||||
function sanitizeMessages(input: unknown): Thread["messages"] {
|
||||
if (!Array.isArray(input)) return [];
|
||||
|
||||
@@ -149,7 +157,8 @@ function sanitizeThreads(input: unknown): AppState["threads"] {
|
||||
const id = asString(thread.id);
|
||||
const projectId = asString(thread.projectId);
|
||||
const title = asString(thread.title);
|
||||
const model = asString(thread.model);
|
||||
const rawModel = asString(thread.model);
|
||||
const model = resolveModelSlug(rawModel);
|
||||
const createdAt = asString(thread.createdAt);
|
||||
if (!id || !projectId || !title || !model || !createdAt) return null;
|
||||
|
||||
@@ -173,17 +182,30 @@ function readPersistedState(): AppState {
|
||||
if (typeof window === "undefined") return initialState;
|
||||
|
||||
try {
|
||||
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
|
||||
const rawCurrent = window.localStorage.getItem(PERSISTED_STATE_KEY);
|
||||
const rawLegacy = window.localStorage.getItem(LEGACY_PERSISTED_STATE_KEY);
|
||||
const raw = rawCurrent ?? rawLegacy;
|
||||
if (!raw) return initialState;
|
||||
const isLegacyPayload = !rawCurrent && Boolean(rawLegacy);
|
||||
|
||||
const parsed = asObject(JSON.parse(raw));
|
||||
if (!parsed) return initialState;
|
||||
|
||||
const projects = sanitizeProjects(parsed.projects);
|
||||
const projects = sanitizeProjects(parsed.projects).map((project) => ({
|
||||
...project,
|
||||
model: isLegacyPayload
|
||||
? migrateLegacyDefaultModel(project.model)
|
||||
: project.model,
|
||||
}));
|
||||
const projectIds = new Set(projects.map((project) => project.id));
|
||||
const threads = sanitizeThreads(parsed.threads).filter((thread) =>
|
||||
projectIds.has(thread.projectId),
|
||||
);
|
||||
const threads = sanitizeThreads(parsed.threads)
|
||||
.map((thread) => ({
|
||||
...thread,
|
||||
model: isLegacyPayload
|
||||
? migrateLegacyDefaultModel(thread.model)
|
||||
: thread.model,
|
||||
}))
|
||||
.filter((thread) => projectIds.has(thread.projectId));
|
||||
const activeThreadId = asString(parsed.activeThreadId);
|
||||
const hasActiveThread = Boolean(
|
||||
activeThreadId && threads.some((thread) => thread.id === activeThreadId),
|
||||
@@ -227,6 +249,7 @@ function persistState(state: AppState): void {
|
||||
PERSISTED_STATE_KEY,
|
||||
JSON.stringify(toPersistedState(state)),
|
||||
);
|
||||
window.localStorage.removeItem(LEGACY_PERSISTED_STATE_KEY);
|
||||
} catch {
|
||||
// Ignore quota/storage errors to avoid breaking chat UX.
|
||||
}
|
||||
@@ -252,7 +275,16 @@ function findThreadBySessionId(
|
||||
function reducer(state: AppState, action: Action): AppState {
|
||||
switch (action.type) {
|
||||
case "ADD_PROJECT":
|
||||
return { ...state, projects: [...state.projects, action.project] };
|
||||
return {
|
||||
...state,
|
||||
projects: [
|
||||
...state.projects,
|
||||
{
|
||||
...action.project,
|
||||
model: resolveModelSlug(action.project.model),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
case "TOGGLE_PROJECT":
|
||||
return {
|
||||
@@ -265,7 +297,13 @@ function reducer(state: AppState, action: Action): AppState {
|
||||
case "ADD_THREAD":
|
||||
return {
|
||||
...state,
|
||||
threads: [...state.threads, action.thread],
|
||||
threads: [
|
||||
...state.threads,
|
||||
{
|
||||
...action.thread,
|
||||
model: resolveModelSlug(action.thread.model),
|
||||
},
|
||||
],
|
||||
activeThreadId: action.thread.id,
|
||||
};
|
||||
|
||||
@@ -349,7 +387,7 @@ function reducer(state: AppState, action: Action): AppState {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => ({
|
||||
...t,
|
||||
model: action.model,
|
||||
model: resolveModelSlug(action.model),
|
||||
})),
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user