Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
Move approval derivation and thread visit tracking into core session log
Julius Marminge052314b65fcb
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 38d95b899..3497b3bc5 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -4,7 +4,6 @@ import {PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,type ProviderSendTurnAttachmentInput,type ProviderApprovalDecision,- type ProviderEvent,} from "@t3tools/contracts";import {type ClipboardEvent,@@ -30,6 +29,7 @@ import {resolveModelSlug,} from "../model-logic";import {+ derivePendingApprovals,derivePhase,deriveTimelineEntries,deriveWorkLogEntries,@@ -74,13 +74,6 @@ function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {return "text-muted-foreground/40";}-interface PendingApprovalCard {- requestId: string;- requestKind: "command" | "file-change";- createdAt: string;- detail?: string;-}-type SessionContinuityState = "resumed" | "new" | "fallback_new";interface EnsuredSessionInfo {@@ -99,57 +92,6 @@ interface ExpandedImagePreview {name: string;}-function asRecord(value: unknown): Record<string, unknown> | undefined {- if (!value || typeof value !== "object") return undefined;- return value as Record<string, unknown>;-}--function asString(value: unknown): string | undefined {- return typeof value === "string" ? value : undefined;-}--function approvalDetail(event: ProviderEvent): string | undefined {- const payload = asRecord(event.payload);- const command = asString(payload?.command);- if (command) return command;- return asString(payload?.reason);-}--function derivePendingApprovals(events: ProviderEvent[]): PendingApprovalCard[] {- const pending = new Map<string, PendingApprovalCard>();- const ordered = [...events].toReversed();-- for (const event of ordered) {- if (event.method === "session/closed" || event.method === "session/exited") {- pending.clear();- continue;- }-- const requestId = event.requestId ?? asString(asRecord(event.payload)?.requestId);- if (!requestId) continue;-- if (- event.kind === "request" &&- (event.requestKind === "command" || event.requestKind === "file-change")- ) {- const detail = approvalDetail(event);- pending.set(requestId, {- requestId,- requestKind: event.requestKind,- createdAt: event.createdAt,- ...(detail ? { detail } : {}),- });- continue;- }-- if (event.method === "item/requestApproval/decision") {- pending.delete(requestId);- }- }-- return Array.from(pending.values());-}-function readFileAsDataUrl(file: File): Promise<string> {return new Promise((resolve, reject) => {const reader = new FileReader();@@ -305,9 +247,6 @@ export default function ChatView() {(activeThread.messages.length > 0 ||(activeThread.session !== null && activeThread.session.status !== "closed")),);- const terminalShortcutHint = navigator.platform.includes("Mac")- ? "\u2318J"- : "Ctrl+J";const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {for (const image of images) {if (!image.previewUrl) continue;diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex 4fec0637e..f08f09907 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -1,10 +1,11 @@import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";-import { useCallback, useEffect, useState } from "react";+import { useCallback, useEffect, useMemo, useState } from "react";import { isElectron } from "../env";import { useTheme } from "../hooks/useTheme";import { DEFAULT_MODEL } from "../model-logic";+import { derivePendingApprovals } from "../session-logic";import { useStore } from "../store";-import { DEFAULT_THREAD_TERMINAL_HEIGHT, type Project } from "../types";+import { DEFAULT_THREAD_TERMINAL_HEIGHT, type Project, type Thread } from "../types";import { useNativeApi } from "../hooks/useNativeApi";const THEME_CYCLE = { system: "light", light: "dark", dark: "system" } as const;@@ -25,11 +26,61 @@ function inferProjectName(cwd: string): string {return last && last.length > 0 ? last : "project";}-function threadStatusLabel(- status: "connecting" | "ready" | "running" | "error" | "closed" | undefined,-): "Working" | "Connecting" | null {- if (status === "running") return "Working";- if (status === "connecting") return "Connecting";+interface ThreadStatusPill {+ label: "Working" | "Connecting" | "Completed" | "Awaiting response";+ colorClass: string;+ dotClass: string;+ pulse: boolean;+}++function hasUnseenCompletion(thread: Thread): boolean {+ if (!thread.latestTurnCompletedAt) return false;+ const completedAt = Date.parse(thread.latestTurnCompletedAt);+ if (Number.isNaN(completedAt)) return false;+ if (!thread.lastVisitedAt) return true;++ const lastVisitedAt = Date.parse(thread.lastVisitedAt);+ if (Number.isNaN(lastVisitedAt)) return true;+ return completedAt > lastVisitedAt;+}++function threadStatusPill(thread: Thread, hasPendingApprovals: boolean): ThreadStatusPill | null {+ if (hasPendingApprovals) {+ return {+ label: "Awaiting response",+ colorClass: "text-amber-600 dark:text-amber-300/90",+ dotClass: "bg-amber-500 dark:bg-amber-300/90",+ pulse: false,+ };+ }++ if (thread.session?.status === "running") {+ return {+ label: "Working",+ colorClass: "text-sky-600 dark:text-sky-300/80",+ dotClass: "bg-sky-500 dark:bg-sky-300/80",+ pulse: true,+ };+ }++ if (thread.session?.status === "connecting") {+ return {+ label: "Connecting",+ colorClass: "text-sky-600 dark:text-sky-300/80",+ dotClass: "bg-sky-500 dark:bg-sky-300/80",+ pulse: true,+ };+ }++ if (hasUnseenCompletion(thread)) {+ return {+ label: "Completed",+ colorClass: "text-emerald-600 dark:text-emerald-300/90",+ dotClass: "bg-emerald-500 dark:bg-emerald-300/90",+ pulse: false,+ };+ }+return null;}@@ -41,6 +92,13 @@ export default function Sidebar() {const [newCwd, setNewCwd] = useState("");const [isPickingFolder, setIsPickingFolder] = useState(false);const [isAddingProject, setIsAddingProject] = useState(false);+ const pendingApprovalByThreadId = useMemo(() => {+ const map = new Map<string, boolean>();+ for (const thread of state.threads) {+ map.set(thread.id, derivePendingApprovals(thread.events).length > 0);+ }+ return map;+ }, [state.threads]);const handleNewThread = useCallback((projectId: string) => {@@ -312,7 +370,10 @@ export default function Sidebar() {<div className="ml-2 border-l border-border/80 pl-2">{threads.map((thread) => {const isActive = state.activeThreadId === thread.id;- const threadStatus = threadStatusLabel(thread.session?.status);+ const threadStatus = threadStatusPill(+ thread,+ pendingApprovalByThreadId.get(thread.id) === true,+ );return (<buttonkey={thread.id}@@ -338,9 +399,15 @@ export default function Sidebar() {><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-sky-600 dark:text-sky-300/80">- <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-sky-500 dark:bg-sky-300/80" />- <span className="hidden xl:inline">{threadStatus}</span>+ <span+ className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}+ >+ <span+ className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${+ threadStatus.pulse ? "animate-pulse" : ""+ }`}+ />+ <span className="hidden xl:inline">{threadStatus.label}</span></span>)}<span className="min-w-0 flex-1 truncate text-xs">{thread.title}</span>diff --git a/apps/web/src/persistenceSchema.test.ts b/apps/web/src/persistenceSchema.test.tsindex a72f7eaea..0081ef90b 100644--- a/apps/web/src/persistenceSchema.test.ts+++ b/apps/web/src/persistenceSchema.test.ts@@ -141,6 +141,7 @@ describe("hydratePersistedState", () => {terminalHeight: 360,messages: [],createdAt: "2026-02-08T10:00:00.000Z",+ lastVisitedAt: "2026-02-08T10:01:00.000Z",},],activeThreadId: "t-1",@@ -149,6 +150,7 @@ describe("hydratePersistedState", () => {const hydrated = hydratePersistedState(payload, false);expect(hydrated?.threads[0]?.terminalOpen).toBe(true);expect(hydrated?.threads[0]?.terminalHeight).toBe(360);+ expect(hydrated?.threads[0]?.lastVisitedAt).toBe("2026-02-08T10:01:00.000Z");});it("defaults terminalHeight when hydrating v5 payloads", () => {@@ -217,6 +219,7 @@ describe("toPersistedState", () => {events: [],error: "boom",createdAt: "2026-02-08T10:00:00.000Z",+ lastVisitedAt: "2026-02-08T10:02:00.000Z",branch: null,worktreePath: null,};@@ -265,6 +268,7 @@ describe("toPersistedState", () => {},],createdAt: thread.createdAt,+ lastVisitedAt: thread.lastVisitedAt,branch: null,worktreePath: null,});diff --git a/apps/web/src/persistenceSchema.ts b/apps/web/src/persistenceSchema.tsindex 31d108ba9..112d2e3c6 100644--- a/apps/web/src/persistenceSchema.ts+++ b/apps/web/src/persistenceSchema.ts@@ -50,6 +50,7 @@ const persistedThreadSchema = z.object({),messages: z.array(persistedMessageSchema),createdAt: z.string().min(1),+ lastVisitedAt: z.string().min(1).optional(),branch: z.string().min(1).nullable().optional(),worktreePath: z.string().min(1).nullable().optional(),});@@ -153,6 +154,7 @@ function hydrateThread(events: [],error: null,createdAt: thread.createdAt,+ lastVisitedAt: thread.lastVisitedAt,branch: thread.branch ?? null,worktreePath: thread.worktreePath ?? null,};@@ -228,6 +230,7 @@ export function toPersistedState(streaming: message.streaming,})),createdAt: thread.createdAt,+ ...(thread.lastVisitedAt ? { lastVisitedAt: thread.lastVisitedAt } : {}),branch: thread.branch,worktreePath: thread.worktreePath,})),diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.tsindex 40fea5d77..d488a0557 100644--- a/apps/web/src/session-logic.test.ts+++ b/apps/web/src/session-logic.test.ts@@ -4,6 +4,7 @@ import type { ProviderEvent, ProviderSession } from "@t3tools/contracts";import {type WorkLogEntry,applyEventToMessages,+ derivePendingApprovals,deriveTimelineEntries,deriveWorkLogEntries,evolveSession,@@ -392,6 +393,73 @@ describe("deriveWorkLogEntries", () => {});});+describe("derivePendingApprovals", () => {+ it("returns pending command/file-change approvals", () => {+ const approvals = derivePendingApprovals([+ makeEvent({+ id: "evt-request",+ kind: "request",+ method: "item/commandExecution/requestApproval",+ requestId: "req-1",+ requestKind: "command",+ createdAt: "2026-02-08T10:00:00.000Z",+ payload: { command: "git commit -m 'msg'" },+ }),+ ]);++ expect(approvals).toEqual([+ {+ requestId: "req-1",+ requestKind: "command",+ createdAt: "2026-02-08T10:00:00.000Z",+ detail: "git commit -m 'msg'",+ },+ ]);+ });++ it("removes approvals after a decision event", () => {+ const approvals = derivePendingApprovals([+ makeEvent({+ id: "evt-decision",+ method: "item/requestApproval/decision",+ requestId: "req-1",+ createdAt: "2026-02-08T10:00:01.000Z",+ }),+ makeEvent({+ id: "evt-request",+ kind: "request",+ method: "item/fileChange/requestApproval",+ requestId: "req-1",+ requestKind: "file-change",+ createdAt: "2026-02-08T10:00:00.000Z",+ }),+ ]);++ expect(approvals).toHaveLength(0);+ });++ it("clears pending approvals after turn completion", () => {+ const approvals = derivePendingApprovals([+ makeEvent({+ id: "evt-turn-complete",+ method: "turn/completed",+ createdAt: "2026-02-08T10:00:01.000Z",+ payload: { turn: { id: "turn-1", status: "completed" } },+ }),+ makeEvent({+ id: "evt-request",+ kind: "request",+ method: "item/commandExecution/requestApproval",+ requestId: "req-1",+ requestKind: "command",+ createdAt: "2026-02-08T10:00:00.000Z",+ }),+ ]);++ expect(approvals).toHaveLength(0);+ });+});+describe("evolveSession", () => {it("updates thread id when thread starts", () => {const previous = makeSession();diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.tsindex 7622864db..538186e05 100644--- a/apps/web/src/session-logic.ts+++ b/apps/web/src/session-logic.ts@@ -78,6 +78,13 @@ export interface WorkLogEntry {tone: "thinking" | "tool" | "info" | "error";}+export interface PendingApproval {+ requestId: string;+ requestKind: "command" | "file-change";+ createdAt: string;+ detail?: string;+}+export type TimelineEntry =| {id: string;@@ -98,6 +105,52 @@ function normalizeDetail(value: string | undefined): string | undefined {return trimmed.length > 0 ? trimmed : undefined;}+function approvalDetail(event: ProviderEvent): string | undefined {+ const payload = asObject(event.payload);+ const command = asString(payload?.command);+ if (command) return command;+ return asString(payload?.reason);+}++export function derivePendingApprovals(events: ProviderEvent[]): PendingApproval[] {+ const pending = new Map<string, PendingApproval>();+ const ordered = [...events].toReversed();++ for (const event of ordered) {+ if (+ event.method === "session/closed" ||+ event.method === "session/exited" ||+ event.method === "turn/completed"+ ) {+ pending.clear();+ continue;+ }++ const requestId = event.requestId ?? asString(asObject(event.payload)?.requestId);+ if (!requestId) continue;++ if (+ event.kind === "request" &&+ (event.requestKind === "command" || event.requestKind === "file-change")+ ) {+ const detail = approvalDetail(event);+ pending.set(requestId, {+ requestId,+ requestKind: event.requestKind,+ createdAt: event.createdAt,+ ...(detail ? { detail } : {}),+ });+ continue;+ }++ if (event.method === "item/requestApproval/decision") {+ pending.delete(requestId);+ }+ }++ return Array.from(pending.values());+}+function normalizeItemType(raw: string | undefined): string {if (!raw) return "item";return rawdiff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.tsindex 3d9b566c8..c33f1c077 100644--- a/apps/web/src/store.test.ts+++ b/apps/web/src/store.test.ts@@ -219,4 +219,48 @@ describe("store reducer thread continuity", () => {expect(next.threads[0]?.projectId).toBe("project-new-a");expect(next.activeThreadId).toBe("thread-a");});++ it("marks the active thread as visited when selected", () => {+ const state = makeState(+ makeThread({+ lastVisitedAt: "2000-01-01T00:00:00.000Z",+ }),+ );++ const next = reducer(state, {+ type: "SET_ACTIVE_THREAD",+ threadId: "thread-local-1",+ });++ expect(next.activeThreadId).toBe("thread-local-1");+ expect(next.threads[0]?.lastVisitedAt).toBeDefined();+ expect(next.threads[0]?.lastVisitedAt).not.toBe("2000-01-01T00:00:00.000Z");+ });++ it("marks completion as seen immediately for the active thread", () => {+ const state = makeState(+ makeThread({+ session: makeSession({+ status: "running",+ activeTurnId: "turn-1",+ }),+ lastVisitedAt: "2026-02-08T10:00:00.000Z",+ }),+ );++ const completedAt = "2026-02-08T10:00:10.000Z";+ const next = reducer(state, {+ type: "APPLY_EVENT",+ event: makeEvent({+ method: "turn/completed",+ turnId: "turn-1",+ createdAt: completedAt,+ payload: { turn: { id: "turn-1", status: "completed" } },+ }),+ activeAssistantItemRef: { current: null },+ });++ expect(next.threads[0]?.latestTurnCompletedAt).toBe(completedAt);+ expect(next.threads[0]?.lastVisitedAt).toBe(completedAt);+ });});diff --git a/apps/web/src/store.ts b/apps/web/src/store.tsindex 6d2946b6e..c8b457bb1 100644--- a/apps/web/src/store.ts+++ b/apps/web/src/store.ts@@ -293,13 +293,23 @@ export function reducer(state: AppState, action: Action): AppState {{...action.thread,model: resolveModelSlug(action.thread.model),+ lastVisitedAt: action.thread.lastVisitedAt ?? action.thread.createdAt,},],activeThreadId: action.thread.id,};- case "SET_ACTIVE_THREAD":- return { ...state, activeThreadId: action.threadId };+ case "SET_ACTIVE_THREAD": {+ const visitedAt = new Date().toISOString();+ return {+ ...state,+ activeThreadId: action.threadId,+ threads: updateThread(state.threads, action.threadId, (t) => ({+ ...t,+ lastVisitedAt: visitedAt,+ })),+ };+ }case "TOGGLE_THREAD_TERMINAL":return {@@ -356,6 +366,9 @@ export function reducer(state: AppState, action: Action): AppState {messages: applyEventToMessages(t.messages, event, activeAssistantItemRef),events: [event, ...t.events],...updateTurnFields(t, event),+ ...(event.method === "turn/completed" && t.id === state.activeThreadId+ ? { lastVisitedAt: event.createdAt }+ : {}),})),};}diff --git a/apps/web/src/types.ts b/apps/web/src/types.tsindex d3f0539ba..16a51fc87 100644--- a/apps/web/src/types.ts+++ b/apps/web/src/types.ts@@ -50,6 +50,7 @@ export interface Thread {latestTurnStartedAt?: string | undefined;latestTurnCompletedAt?: string | undefined;latestTurnDurationMs?: number | undefined;+ lastVisitedAt?: string | undefined;branch: string | null;worktreePath: string | null;}