Add thread archiving and settings navigation (#1359)

Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
shivamandJulius Marminge authored and GitHub committed 2026-03-28 10:48:34 -07:00
1 parent 48196e67a7
commit f0cdaf94c2
53 files changed
+2899 -1799

No files matched your search

+2
View File
@@ -1141,6 +1141,7 @@ function registerIpcHandlers(): void {
id: item.id,
label: item.label,
destructive: item.destructive === true,
disabled: item.disabled === true,
}));
if (normalizedItems.length === 0) {
return null;
@@ -1171,6 +1172,7 @@ function registerIpcHandlers(): void {
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
click: () => resolve(item.id),
};
if (item.destructive) {
@@ -61,6 +61,7 @@ function makeSnapshot(input: {
},
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
activities: [],
@@ -120,6 +120,73 @@ describe("OrchestrationEngine", () => {
await system.dispose();
});
it("archives and unarchives threads through orchestration commands", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
const createdAt = now();
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe("cmd-project-archive-create"),
projectId: asProjectId("project-archive"),
title: "Project Archive",
workspaceRoot: "/tmp/project-archive",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
}),
);
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-archive-create"),
threadId: ThreadId.makeUnsafe("thread-archive"),
projectId: asProjectId("project-archive"),
title: "Archive me",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
}),
);
await system.run(
engine.dispatch({
type: "thread.archive",
commandId: CommandId.makeUnsafe("cmd-thread-archive"),
threadId: ThreadId.makeUnsafe("thread-archive"),
}),
);
expect(
(await system.run(engine.getReadModel())).threads.find(
(thread) => thread.id === "thread-archive",
)?.archivedAt,
).not.toBeNull();
await system.run(
engine.dispatch({
type: "thread.unarchive",
commandId: CommandId.makeUnsafe("cmd-thread-unarchive"),
threadId: ThreadId.makeUnsafe("thread-archive"),
}),
);
expect(
(await system.run(engine.getReadModel())).threads.find(
(thread) => thread.id === "thread-archive",
)?.archivedAt,
).toBeNull();
await system.dispose();
});
it("replays append-only events from sequence", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
@@ -428,10 +428,41 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
latestTurnId: null,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
archivedAt: null,
deletedAt: null,
});
return;
case "thread.archived": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
archivedAt: event.payload.archivedAt,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.unarchived": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
archivedAt: null,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.meta-updated": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
@@ -279,6 +279,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
},
createdAt: "2026-02-24T00:00:02.000Z",
updatedAt: "2026-02-24T00:00:03.000Z",
archivedAt: null,
deletedAt: null,
messages: [
{
@@ -174,6 +174,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
deleted_at AS "deletedAt"
FROM projection_threads
ORDER BY created_at ASC, thread_id ASC
@@ -560,6 +561,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
+4
View File
@@ -3,10 +3,12 @@ import {
ProjectMetaUpdatedPayload as ContractsProjectMetaUpdatedPayloadSchema,
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema,
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -26,10 +28,12 @@ export const ProjectMetaUpdatedPayload = ContractsProjectMetaUpdatedPayloadSchem
export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
export const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema;
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
export const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
@@ -66,6 +66,7 @@ const readModel: OrchestrationReadModel = {
worktreePath: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
latestTurn: null,
messages: [],
session: null,
@@ -88,6 +89,7 @@ const readModel: OrchestrationReadModel = {
worktreePath: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
latestTurn: null,
messages: [],
session: null,
@@ -88,6 +88,44 @@ export function requireThread(input: {
);
}
export function requireThreadArchived(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly threadId: ThreadId;
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
return requireThread(input).pipe(
Effect.flatMap((thread) =>
thread.archivedAt !== null
? Effect.succeed(thread)
: Effect.fail(
invariantError(
input.command.type,
`Thread '${input.threadId}' is not archived for command '${input.command.type}'.`,
),
),
),
);
}
export function requireThreadNotArchived(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
readonly threadId: ThreadId;
}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {
return requireThread(input).pipe(
Effect.flatMap((thread) =>
thread.archivedAt === null
? Effect.succeed(thread)
: Effect.fail(
invariantError(
input.command.type,
`Thread '${input.threadId}' is already archived and cannot handle command '${input.command.type}'.`,
),
),
),
);
}
export function requireThreadAbsent(input: {
readonly readModel: OrchestrationReadModel;
readonly command: OrchestrationCommand;
+47
View File
@@ -10,7 +10,9 @@ import {
requireProject,
requireProjectAbsent,
requireThread,
requireThreadArchived,
requireThreadAbsent,
requireThreadNotArchived,
} from "./commandInvariants.ts";
const nowIso = () => new Date().toISOString();
@@ -190,6 +192,51 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.archive": {
yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = nowIso();
return {
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
}),
type: "thread.archived",
payload: {
threadId: command.threadId,
archivedAt: occurredAt,
updatedAt: occurredAt,
},
};
}
case "thread.unarchive": {
yield* requireThreadArchived({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = nowIso();
return {
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
}),
type: "thread.unarchived",
payload: {
threadId: command.threadId,
updatedAt: occurredAt,
},
};
}
case "thread.meta.update": {
yield* requireThread({
readModel,
@@ -87,6 +87,7 @@ describe("orchestration projector", () => {
latestTurn: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -131,6 +132,78 @@ describe("orchestration projector", () => {
).rejects.toBeDefined();
});
it("applies thread.archived and thread.unarchived events", async () => {
const now = new Date().toISOString();
const later = new Date(Date.parse(now) + 1_000).toISOString();
const created = await Effect.runPromise(
projectEvent(
createEmptyReadModel(now),
makeEvent({
sequence: 1,
type: "thread.created",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: now,
commandId: "cmd-thread-create",
payload: {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
),
);
const archived = await Effect.runPromise(
projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.archived",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: later,
commandId: "cmd-thread-archive",
payload: {
threadId: "thread-1",
archivedAt: later,
updatedAt: later,
},
}),
),
);
expect(archived.threads[0]?.archivedAt).toBe(later);
const unarchived = await Effect.runPromise(
projectEvent(
archived,
makeEvent({
sequence: 3,
type: "thread.unarchived",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: later,
commandId: "cmd-thread-unarchive",
payload: {
threadId: "thread-1",
updatedAt: later,
},
}),
),
);
expect(unarchived.threads[0]?.archivedAt).toBeNull();
});
it("keeps projector forward-compatible for unhandled event types", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
@@ -14,12 +14,14 @@ import {
ProjectDeletedPayload,
ProjectMetaUpdatedPayload,
ThreadActivityAppendedPayload,
ThreadArchivedPayload,
ThreadCreatedPayload,
ThreadDeletedPayload,
ThreadInteractionModeSetPayload,
ThreadMetaUpdatedPayload,
ThreadProposedPlanUpsertedPayload,
ThreadRuntimeModeSetPayload,
ThreadUnarchivedPayload,
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
@@ -260,6 +262,7 @@ export function projectEvent(
latestTurn: null,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
archivedAt: null,
deletedAt: null,
messages: [],
activities: [],
@@ -289,6 +292,28 @@ export function projectEvent(
})),
);
case "thread.archived":
return decodeForEvent(ThreadArchivedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
archivedAt: payload.archivedAt,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.unarchived":
return decodeForEvent(ThreadUnarchivedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
archivedAt: null,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.meta-updated":
return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
@@ -87,6 +87,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
latestTurnId: null,
createdAt: "2026-03-24T00:00:00.000Z",
updatedAt: "2026-03-24T00:00:00.000Z",
archivedAt: null,
deletedAt: null,
});
@@ -39,6 +39,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
latest_turn_id,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES (
@@ -53,6 +54,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.latestTurnId},
${row.createdAt},
${row.updatedAt},
${row.archivedAt},
${row.deletedAt}
)
ON CONFLICT (thread_id)
@@ -67,6 +69,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
latest_turn_id = excluded.latest_turn_id,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
archived_at = excluded.archived_at,
deleted_at = excluded.deleted_at
`,
});
@@ -88,6 +91,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE thread_id = ${threadId}
@@ -111,6 +115,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE project_id = ${projectId}
@@ -29,6 +29,8 @@ import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
/**
* Migration loader with all migrations defined inline.
@@ -57,6 +59,8 @@ export const migrationEntries = [
[14, "ProjectionThreadProposedPlanImplementation", Migration0014],
[15, "ProjectionTurnsSourceProposedPlan", Migration0015],
[16, "CanonicalizeModelSelections", Migration0016],
[17, "ProjectionThreadsArchivedAt", Migration0017],
[18, "ProjectionThreadsArchivedAtIndex", Migration0018],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -128,6 +128,20 @@ layer("016_CanonicalizeModelSelections", (it) => {
'{"projectId":"project-2","title":"Fallback Project","workspaceRoot":"/tmp/project-2","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"low"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-project-created-null-model',
'project',
'project-3',
1,
'project.created',
'2026-01-01T00:00:00.000Z',
'command-project-created-null-model',
NULL,
'correlation-project-created-null-model',
'user',
'{"projectId":"project-3","title":"Null Model Project","workspaceRoot":"/tmp/project-3","defaultModel":null,"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-thread-created',
'thread',
@@ -284,6 +298,16 @@ layer("016_CanonicalizeModelSelections", (it) => {
});
assert.deepStrictEqual(JSON.parse(eventRows[2]!.payloadJson), {
projectId: "project-3",
title: "Null Model Project",
workspaceRoot: "/tmp/project-3",
defaultModelSelection: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), {
threadId: "thread-1",
projectId: "project-1",
title: "Thread",
@@ -303,7 +327,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), {
assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
threadId: "thread-2",
projectId: "project-1",
title: "Fallback Thread",
@@ -322,7 +346,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
threadId: "thread-1",
turnId: "turn-1",
input: "hi",
@@ -336,7 +360,7 @@ layer("016_CanonicalizeModelSelections", (it) => {
deliveryMode: "buffered",
});
assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
assert.deepStrictEqual(JSON.parse(eventRows[6]!.payloadJson), {
threadId: "thread-3",
projectId: "project-1",
title: "Ancient Thread",
@@ -0,0 +1,18 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (columns.some((column) => column.name === "archived_at")) {
return;
}
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN archived_at TEXT
`;
});
@@ -0,0 +1,11 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_project_archived_at
ON projection_threads(project_id, archived_at)
`;
});
@@ -32,6 +32,7 @@ export const ProjectionThread = Schema.Struct({
latestTurnId: Schema.NullOr(TurnId),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
archivedAt: Schema.NullOr(IsoDateTime),
deletedAt: Schema.NullOr(IsoDateTime),
});
export type ProjectionThread = typeof ProjectionThread.Type;
@@ -672,9 +672,9 @@ describe("TerminalManager", () => {
).toBe(true);
} else {
expect(
ptyAdapter.spawnInputs.some((input) =>
["/bin/zsh", "/bin/bash", "/bin/sh", "zsh", "bash", "sh"].includes(input.shell),
),
ptyAdapter.spawnInputs
.slice(1)
.some((input) => input.shell !== "/definitely/missing-shell"),
).toBe(true);
}
@@ -0,0 +1,49 @@
import { useEffect, type ReactNode } from "react";
import { useNavigate } from "@tanstack/react-router";
import ThreadSidebar from "./Sidebar";
import { Sidebar, SidebarProvider, SidebarRail } from "./ui/sidebar";
const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width";
const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16;
const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16;
export function AppSidebarLayout({ children }: { children: ReactNode }) {
const navigate = useNavigate();
useEffect(() => {
const onMenuAction = window.desktopBridge?.onMenuAction;
if (typeof onMenuAction !== "function") {
return;
}
const unsubscribe = onMenuAction((action) => {
if (action !== "open-settings") return;
void navigate({ to: "/settings" });
});
return () => {
unsubscribe?.();
};
}, [navigate]);
return (
<SidebarProvider defaultOpen>
<Sidebar
side="left"
collapsible="offcanvas"
className="border-r border-border bg-card text-foreground"
resizable={{
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
shouldAcceptWidth: ({ nextWidth, wrapper }) =>
wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
}}
>
<ThreadSidebar />
<SidebarRail />
</Sidebar>
{children}
</SidebarProvider>
);
}
@@ -258,6 +258,7 @@ function createSnapshotForTargetUser(options: {
latestTurn: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
archivedAt: null,
deletedAt: null,
messages,
activities: [],
@@ -315,6 +316,7 @@ function addThreadToSnapshot(
latestTurn: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
archivedAt: null,
deletedAt: null,
messages: [],
activities: [],
@@ -32,6 +32,7 @@ export function buildLocalDraftThread(
messages: [],
error,
createdAt: draftThread.createdAt,
archivedAt: null,
latestTurn: null,
lastVisitedAt: draftThread.createdAt,
branch: draftThread.branch,
@@ -102,6 +102,7 @@ function createMinimalSnapshot(): OrchestrationReadModel {
latestTurn: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
archivedAt: null,
deletedAt: null,
messages: [
{
@@ -0,0 +1,49 @@
import { FolderIcon } from "lucide-react";
import { useState } from "react";
function getServerHttpOrigin(): string {
const bridgeUrl = window.desktopBridge?.getWsUrl();
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
const wsUrl =
bridgeUrl && bridgeUrl.length > 0
? bridgeUrl
: envUrl && envUrl.length > 0
? envUrl
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`;
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
try {
return new URL(httpUrl).origin;
} catch {
return httpUrl;
}
}
const serverHttpOrigin = getServerHttpOrigin();
const loadedProjectFaviconSrcs = new Set<string>();
export function ProjectFavicon({ cwd, className }: { cwd: string; className?: string }) {
const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading",
);
return (
<>
{status !== "loaded" ? (
<FolderIcon className={`size-3.5 shrink-0 text-muted-foreground/50 ${className ?? ""}`} />
) : null}
<img
src={src}
alt=""
className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loaded" ? "" : "hidden"} ${className ?? ""}`}
onLoad={() => {
loadedProjectFaviconSrcs.add(src);
setStatus("loaded");
}}
onError={() => setStatus("error")}
/>
</>
);
}
@@ -380,6 +380,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
proposedPlans: [],
error: null,
createdAt: "2026-03-09T10:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-09T10:00:00.000Z",
latestTurn: null,
branch: null,
@@ -697,6 +698,43 @@ describe("sortProjectsForSidebar", () => {
]);
});
it("ignores archived threads when sorting projects", () => {
const sorted = sortProjectsForSidebar(
[
makeProject({
id: ProjectId.makeUnsafe("project-1"),
name: "Visible project",
updatedAt: "2026-03-09T10:01:00.000Z",
}),
makeProject({
id: ProjectId.makeUnsafe("project-2"),
name: "Archived-only project",
updatedAt: "2026-03-09T10:00:00.000Z",
}),
],
[
makeThread({
id: ThreadId.makeUnsafe("thread-visible"),
projectId: ProjectId.makeUnsafe("project-1"),
updatedAt: "2026-03-09T10:02:00.000Z",
archivedAt: null,
}),
makeThread({
id: ThreadId.makeUnsafe("thread-archived"),
projectId: ProjectId.makeUnsafe("project-2"),
updatedAt: "2026-03-09T10:10:00.000Z",
archivedAt: "2026-03-09T10:11:00.000Z",
}),
].filter((thread) => thread.archivedAt === null),
"updated_at",
);
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-2"),
]);
});
it("returns the project timestamp when no threads are present", () => {
const timestamp = getProjectSortTimestamp(
makeProject({ updatedAt: "2026-03-09T10:10:00.000Z" }),
+336 -408
View File
@@ -1,5 +1,5 @@
import {
ArrowLeftIcon,
ArchiveIcon,
ArrowUpDownIcon,
ChevronRightIcon,
FolderIcon,
@@ -11,6 +11,7 @@ import {
TerminalIcon,
TriangleAlertIcon,
} from "lucide-react";
import { ProjectFavicon } from "./ProjectFavicon";
import { autoAnimate } from "@formkit/auto-animate";
import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import {
@@ -36,7 +37,7 @@ import {
type GitStatusResult,
type ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
import { useQueries, useQuery } from "@tanstack/react-query";
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
import {
type SidebarProjectSortOrder,
@@ -48,13 +49,16 @@ import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../l
import { useStore } from "../store";
import { shortcutLabelForCommand } from "../keybindings";
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
import { gitStatusQueryOptions } from "../lib/gitReactQuery";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useThreadActions } from "../hooks/useThreadActions";
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
import { toastManager } from "./ui/toast";
import { formatRelativeTimeLabel } from "../timestampFormat";
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
import {
getArm64IntelBuildWarningDescription,
getDesktopUpdateActionError,
@@ -87,10 +91,8 @@ import {
SidebarTrigger,
} from "./ui/sidebar";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { isNonEmpty as isNonEmptyString } from "effect/String";
import {
getFallbackThreadIdAfterDelete,
getVisibleThreadsForProject,
resolveProjectStatusIndicator,
resolveSidebarNewThreadEnvMode,
@@ -118,18 +120,6 @@ const SIDEBAR_LIST_ANIMATION_OPTIONS = {
duration: 180,
easing: "ease-out",
} as const;
const loadedProjectFaviconSrcs = new Set<string>();
function formatRelativeTime(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
const minutes = Math.floor(diff / 60_000);
if (minutes < 1) return "just now";
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}
interface TerminalStatusIndicator {
label: "Terminal process running";
colorClass: string;
@@ -204,54 +194,6 @@ function T3Wordmark() {
);
}
/**
* Derives the server's HTTP origin (scheme + host + port) from the same
* sources WsTransport uses, converting ws(s) to http(s).
*/
function getServerHttpOrigin(): string {
const bridgeUrl = window.desktopBridge?.getWsUrl();
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
const wsUrl =
bridgeUrl && bridgeUrl.length > 0
? bridgeUrl
: envUrl && envUrl.length > 0
? envUrl
: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.hostname}:${window.location.port}`;
// Parse to extract just the origin, dropping path/query (e.g. ?token=…)
const httpUrl = wsUrl.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
try {
return new URL(httpUrl).origin;
} catch {
return httpUrl;
}
}
const serverHttpOrigin = getServerHttpOrigin();
function ProjectFavicon({ cwd }: { cwd: string }) {
const src = `${serverHttpOrigin}/api/project-favicon?cwd=${encodeURIComponent(cwd)}`;
const [status, setStatus] = useState<"loading" | "loaded" | "error">(() =>
loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading",
);
if (status === "error") {
return <FolderIcon className="size-3.5 shrink-0 text-muted-foreground/50" />;
}
return (
<img
src={src}
alt=""
className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loading" ? "hidden" : ""}`}
onLoad={() => {
loadedProjectFaviconSrcs.add(src);
setStatus("loaded");
}}
onError={() => setStatus("error")}
/>
);
}
type SortableProjectHandleProps = Pick<
ReturnType<typeof useSortable>,
"attributes" | "listeners" | "setActivatorNodeRef"
@@ -372,18 +314,16 @@ export default function Sidebar() {
(store) => store.getDraftThreadByProjectId,
);
const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
const clearProjectDraftThreadId = useComposerDraftStore(
(store) => store.clearProjectDraftThreadId,
);
const clearProjectDraftThreadById = useComposerDraftStore(
(store) => store.clearProjectDraftThreadById,
);
const navigate = useNavigate();
const isOnSettings = useLocation({ select: (loc) => loc.pathname === "/settings" });
const pathname = useLocation({ select: (loc) => loc.pathname });
const isOnSettings = pathname.startsWith("/settings");
const appSettings = useSettings();
const { updateSettings } = useUpdateSettings();
const { handleNewThread } = useHandleNewThread();
const { archiveThread, deleteThread } = useThreadActions();
const routeThreadId = useParams({
strict: false,
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
@@ -392,8 +332,6 @@ export default function Sidebar() {
...serverConfigQueryOptions(),
select: (config) => config.keybindings,
});
const queryClient = useQueryClient();
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
const [addingProject, setAddingProject] = useState(false);
const [newCwd, setNewCwd] = useState("");
const [isPickingFolder, setIsPickingFolder] = useState(false);
@@ -402,6 +340,8 @@ export default function Sidebar() {
const addProjectInputRef = useRef<HTMLInputElement | null>(null);
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
const [renamingTitle, setRenamingTitle] = useState("");
const [hoveredThreadId, setHoveredThreadId] = useState<ThreadId | null>(null);
const [confirmingArchiveThreadId, setConfirmingArchiveThreadId] = useState<ThreadId | null>(null);
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
ReadonlySet<ProjectId>
>(() => new Set());
@@ -493,10 +433,25 @@ export default function Sidebar() {
});
}, []);
const attemptArchiveThread = useCallback(
async (threadId: ThreadId) => {
try {
await archiveThread(threadId);
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to archive thread",
description: error instanceof Error ? error.message : "An error occurred.",
});
}
},
[archiveThread],
);
const focusMostRecentThreadForProject = useCallback(
(projectId: ProjectId) => {
const latestThread = sortThreadsForSidebar(
threads.filter((thread) => thread.projectId === projectId),
threads.filter((thread) => thread.projectId === projectId && thread.archivedAt === null),
appSettings.sidebarThreadSortOrder,
)[0];
if (!latestThread) return;
@@ -627,7 +582,10 @@ export default function Sidebar() {
const trimmed = newTitle.trim();
if (trimmed.length === 0) {
toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
toastManager.add({
type: "warning",
title: "Thread title cannot be empty",
});
finishRename();
return;
}
@@ -659,129 +617,9 @@ export default function Sidebar() {
[],
);
/**
* Delete a single thread: stop session, close terminal, dispatch delete,
* clean up drafts/state, and optionally remove orphaned worktree.
* Callers handle thread-level confirmation; this still prompts for worktree removal.
*/
const deleteThread = useCallback(
async (
threadId: ThreadId,
opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {},
): Promise<void> => {
const api = readNativeApi();
if (!api) return;
const thread = threads.find((t) => t.id === threadId);
if (!thread) return;
const threadProject = projects.find((project) => project.id === thread.projectId);
// When bulk-deleting, exclude the other threads being deleted so
// getOrphanedWorktreePathForThread correctly detects that no surviving
// threads will reference this worktree.
const deletedIds = opts.deletedThreadIds;
const survivingThreads =
deletedIds && deletedIds.size > 0
? threads.filter((t) => t.id === threadId || !deletedIds.has(t.id))
: threads;
const orphanedWorktreePath = getOrphanedWorktreePathForThread(survivingThreads, threadId);
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
const shouldDeleteWorktree =
canDeleteWorktree &&
(await api.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
"",
"Delete the worktree too?",
].join("\n"),
));
if (thread.session && thread.session.status !== "closed") {
await api.orchestration
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
}
try {
await api.terminal.close({ threadId, deleteHistory: true });
} catch {
// Terminal may already be closed
}
const allDeletedIds = deletedIds ?? new Set<ThreadId>();
const shouldNavigateToFallback = routeThreadId === threadId;
const fallbackThreadId = getFallbackThreadIdAfterDelete({
threads,
deletedThreadId: threadId,
deletedThreadIds: allDeletedIds,
sortOrder: appSettings.sidebarThreadSortOrder,
});
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId,
});
clearComposerDraftForThread(threadId);
clearProjectDraftThreadById(thread.projectId, thread.id);
clearTerminalState(threadId);
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
void navigate({
to: "/$threadId",
params: { threadId: fallbackThreadId },
replace: true,
});
} else {
void navigate({ to: "/", replace: true });
}
}
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
return;
}
try {
await removeWorktreeMutation.mutateAsync({
cwd: threadProject.cwd,
path: orphanedWorktreePath,
force: true,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
console.error("Failed to remove orphaned worktree after thread deletion", {
threadId,
projectCwd: threadProject.cwd,
worktreePath: orphanedWorktreePath,
error,
});
toastManager.add({
type: "error",
title: "Thread deleted, but worktree removal failed",
description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
});
}
},
[
appSettings.sidebarThreadSortOrder,
clearComposerDraftForThread,
clearProjectDraftThreadById,
clearTerminalState,
navigate,
projects,
removeWorktreeMutation,
routeThreadId,
threads,
],
);
const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{
threadId: ThreadId;
}>({
onCopy: (ctx) => {
toastManager.add({
type: "success",
@@ -797,7 +635,9 @@ export default function Sidebar() {
});
},
});
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{
path: string;
}>({
onCopy: (ctx) => {
toastManager.add({
type: "success",
@@ -1098,9 +938,13 @@ export default function Sidebar() {
suppressProjectClickAfterDragRef.current = false;
}, []);
const visibleThreads = useMemo(
() => threads.filter((thread) => thread.archivedAt === null),
[threads],
);
const sortedProjects = useMemo(
() => sortProjectsForSidebar(projects, threads, appSettings.sidebarProjectSortOrder),
[appSettings.sidebarProjectSortOrder, projects, threads],
() => sortProjectsForSidebar(projects, visibleThreads, appSettings.sidebarProjectSortOrder),
[appSettings.sidebarProjectSortOrder, projects, visibleThreads],
);
const isManualProjectSorting = appSettings.sidebarProjectSortOrder === "manual";
@@ -1109,7 +953,7 @@ export default function Sidebar() {
dragHandleProps: SortableProjectHandleProps | null,
) {
const projectThreads = sortThreadsForSidebar(
threads.filter((thread) => thread.projectId === project.id),
visibleThreads.filter((thread) => thread.projectId === project.id),
appSettings.sidebarThreadSortOrder,
);
const projectStatus = resolveProjectStatusIndicator(
@@ -1128,18 +972,22 @@ export default function Sidebar() {
? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null)
: null;
const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null;
const { hasHiddenThreads, visibleThreads } = getVisibleThreadsForProject({
threads: projectThreads,
activeThreadId,
isThreadListExpanded,
previewLimit: THREAD_PREVIEW_LIMIT,
});
const { hasHiddenThreads, visibleThreads: visibleProjectThreads } = getVisibleThreadsForProject(
{
threads: projectThreads,
activeThreadId,
isThreadListExpanded,
previewLimit: THREAD_PREVIEW_LIMIT,
},
);
const orderedProjectThreadIds = projectThreads.map((thread) => thread.id);
const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : visibleThreads;
const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : visibleProjectThreads;
const renderThreadRow = (thread: (typeof projectThreads)[number]) => {
const isActive = routeThreadId === thread.id;
const isSelected = selectedThreadIds.has(thread.id);
const isHighlighted = isActive || isSelected;
const isThreadRunning =
thread.session?.status === "running" && thread.session.activeTurnId != null;
const threadStatus = resolveThreadStatusPill({
thread,
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
@@ -1151,15 +999,26 @@ export default function Sidebar() {
);
return (
<SidebarMenuSubItem key={thread.id} className="w-full" data-thread-item>
<SidebarMenuSubItem
key={thread.id}
className="w-full"
data-thread-item
onMouseEnter={() => {
setHoveredThreadId(thread.id);
}}
onMouseLeave={() => {
setHoveredThreadId((current) => (current === thread.id ? null : current));
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
}}
>
<SidebarMenuSubButton
render={<div role="button" tabIndex={0} />}
size="sm"
isActive={isActive}
className={resolveThreadRowClassName({
className={`${resolveThreadRowClassName({
isActive,
isSelected,
})}
})} relative`}
onClick={(event) => {
handleThreadClick(event, thread.id, orderedProjectThreadIds);
}}
@@ -1177,6 +1036,7 @@ export default function Sidebar() {
}}
onContextMenu={(event) => {
event.preventDefault();
setHoveredThreadId((current) => (current === thread.id ? null : current));
if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) {
void handleMultiSelectContextMenu({
x: event.clientX,
@@ -1273,15 +1133,86 @@ export default function Sidebar() {
/>
</span>
)}
<span
className={`text-[10px] ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/40"
}`}
>
{formatRelativeTime(thread.updatedAt ?? thread.createdAt)}
</span>
<div className="flex min-w-12 justify-end">
{confirmingArchiveThreadId === thread.id && !isThreadRunning ? (
<button
type="button"
data-thread-selection-safe
aria-label={`Confirm archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex h-5 -translate-y-1/2 cursor-pointer items-center rounded-full bg-destructive/12 px-2 text-[10px] font-medium text-destructive transition-colors hover:bg-destructive/18 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-destructive/40"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setConfirmingArchiveThreadId((current) =>
current === thread.id ? null : current,
);
setHoveredThreadId((current) => (current === thread.id ? null : current));
void attemptArchiveThread(thread.id);
}}
>
Confirm
</button>
) : hoveredThreadId === thread.id && !isThreadRunning ? (
appSettings.confirmThreadArchive ? (
<button
type="button"
data-thread-selection-safe
aria-label={`Archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setConfirmingArchiveThreadId(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
) : (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
data-thread-selection-safe
aria-label={`Archive ${thread.title}`}
className="absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
onPointerDown={(event) => {
event.stopPropagation();
}}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setHoveredThreadId((current) =>
current === thread.id ? null : current,
);
void attemptArchiveThread(thread.id);
}}
>
<ArchiveIcon className="size-3.5" />
</button>
}
/>
<TooltipPopup side="top">Archive</TooltipPopup>
</Tooltip>
)
) : (
<span
className={`text-[10px] ${
isHighlighted
? "text-foreground/72 dark:text-foreground/82"
: "text-muted-foreground/40"
}`}
>
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
</span>
)}
</div>
</div>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
@@ -1349,7 +1280,7 @@ export default function Sidebar() {
/>
}
showOnHover
className="top-1 right-1 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground"
className="top-1 right-1.5 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground"
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
@@ -1658,202 +1589,199 @@ export default function Sidebar() {
</SidebarHeader>
)}
<SidebarContent className="gap-0">
{showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? (
<SidebarGroup className="px-2 pt-2 pb-0">
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8">
<TriangleAlertIcon />
<AlertTitle>Intel build on Apple Silicon</AlertTitle>
<AlertDescription>{arm64IntelBuildWarningDescription}</AlertDescription>
{desktopUpdateButtonAction !== "none" ? (
<AlertAction>
<Button
size="xs"
variant="outline"
disabled={desktopUpdateButtonDisabled}
onClick={handleDesktopUpdateButtonClick}
>
{desktopUpdateButtonAction === "download"
? "Download ARM build"
: "Install ARM build"}
</Button>
</AlertAction>
) : null}
</Alert>
</SidebarGroup>
) : null}
<SidebarGroup className="px-2 py-2">
<div className="mb-1 flex items-center justify-between px-2">
<span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">
Projects
</span>
<div className="flex items-center gap-1">
<ProjectSortMenu
projectSortOrder={appSettings.sidebarProjectSortOrder}
threadSortOrder={appSettings.sidebarThreadSortOrder}
onProjectSortOrderChange={(sortOrder) => {
updateSettings({ sidebarProjectSortOrder: sortOrder });
}}
onThreadSortOrderChange={(sortOrder) => {
updateSettings({ sidebarThreadSortOrder: sortOrder });
}}
/>
<Tooltip>
<TooltipTrigger
render={
{isOnSettings ? (
<SettingsSidebarNav pathname={pathname} />
) : (
<>
<SidebarContent className="gap-0">
{showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? (
<SidebarGroup className="px-2 pt-2 pb-0">
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8">
<TriangleAlertIcon />
<AlertTitle>Intel build on Apple Silicon</AlertTitle>
<AlertDescription>{arm64IntelBuildWarningDescription}</AlertDescription>
{desktopUpdateButtonAction !== "none" ? (
<AlertAction>
<Button
size="xs"
variant="outline"
disabled={desktopUpdateButtonDisabled}
onClick={handleDesktopUpdateButtonClick}
>
{desktopUpdateButtonAction === "download"
? "Download ARM build"
: "Install ARM build"}
</Button>
</AlertAction>
) : null}
</Alert>
</SidebarGroup>
) : null}
<SidebarGroup className="px-2 py-2">
<div className="mb-1 flex items-center justify-between pl-2 pr-1.5">
<span className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">
Projects
</span>
<div className="flex items-center gap-1">
<ProjectSortMenu
projectSortOrder={appSettings.sidebarProjectSortOrder}
threadSortOrder={appSettings.sidebarThreadSortOrder}
onProjectSortOrderChange={(sortOrder) => {
updateSettings({ sidebarProjectSortOrder: sortOrder });
}}
onThreadSortOrderChange={(sortOrder) => {
updateSettings({ sidebarThreadSortOrder: sortOrder });
}}
/>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={
shouldShowProjectPathEntry ? "Cancel add project" : "Add project"
}
aria-pressed={shouldShowProjectPathEntry}
className="inline-flex size-5 cursor-pointer items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
onClick={handleStartAddProject}
/>
}
>
<PlusIcon
className={`size-3.5 transition-transform duration-150 ${
shouldShowProjectPathEntry ? "rotate-45" : "rotate-0"
}`}
/>
</TooltipTrigger>
<TooltipPopup side="right">
{shouldShowProjectPathEntry ? "Cancel add project" : "Add project"}
</TooltipPopup>
</Tooltip>
</div>
</div>
{shouldShowProjectPathEntry && (
<div className="mb-2 px-1">
{isElectron && (
<button
type="button"
aria-label={shouldShowProjectPathEntry ? "Cancel add project" : "Add project"}
aria-pressed={shouldShowProjectPathEntry}
className="inline-flex size-5 cursor-pointer items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
onClick={handleStartAddProject}
className="mb-1.5 flex w-full items-center justify-center gap-2 rounded-md border border-border bg-secondary py-1.5 text-xs text-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => void handlePickFolder()}
disabled={isPickingFolder || isAddingProject}
>
<FolderIcon className="size-3.5" />
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
</button>
)}
<div className="flex gap-1.5">
<input
ref={addProjectInputRef}
className={`min-w-0 flex-1 rounded-md border bg-secondary px-2 py-1 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:outline-none ${
addProjectError
? "border-red-500/70 focus:border-red-500"
: "border-border focus:border-ring"
}`}
placeholder="/path/to/project"
value={newCwd}
onChange={(event) => {
setNewCwd(event.target.value);
setAddProjectError(null);
}}
onKeyDown={(event) => {
if (event.key === "Enter") handleAddProject();
if (event.key === "Escape") {
setAddingProject(false);
setAddProjectError(null);
}
}}
autoFocus
/>
}
>
<PlusIcon
className={`size-3.5 transition-transform duration-150 ${
shouldShowProjectPathEntry ? "rotate-45" : "rotate-0"
}`}
/>
</TooltipTrigger>
<TooltipPopup side="right">
{shouldShowProjectPathEntry ? "Cancel add project" : "Add project"}
</TooltipPopup>
</Tooltip>
</div>
</div>
{shouldShowProjectPathEntry && (
<div className="mb-2 px-1">
{isElectron && (
<button
type="button"
className="mb-1.5 flex w-full items-center justify-center gap-2 rounded-md border border-border bg-secondary py-1.5 text-xs text-foreground/80 transition-colors duration-150 hover:bg-accent hover:text-foreground disabled:cursor-not-allowed disabled:opacity-60"
onClick={() => void handlePickFolder()}
disabled={isPickingFolder || isAddingProject}
>
<FolderIcon className="size-3.5" />
{isPickingFolder ? "Picking folder..." : "Browse for folder"}
</button>
<button
type="button"
className="shrink-0 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90 disabled:opacity-60"
onClick={handleAddProject}
disabled={!canAddProject}
>
{isAddingProject ? "Adding..." : "Add"}
</button>
</div>
{addProjectError && (
<p className="mt-1 px-0.5 text-[11px] leading-tight text-red-400">
{addProjectError}
</p>
)}
<div className="mt-1.5 px-0.5">
<button
type="button"
className="text-[11px] text-muted-foreground/50 transition-colors hover:text-muted-foreground"
onClick={() => {
setAddingProject(false);
setAddProjectError(null);
}}
>
Cancel
</button>
</div>
</div>
)}
<div className="flex gap-1.5">
<input
ref={addProjectInputRef}
className={`min-w-0 flex-1 rounded-md border bg-secondary px-2 py-1 font-mono text-xs text-foreground placeholder:text-muted-foreground/40 focus:outline-none ${
addProjectError
? "border-red-500/70 focus:border-red-500"
: "border-border focus:border-ring"
}`}
placeholder="/path/to/project"
value={newCwd}
onChange={(event) => {
setNewCwd(event.target.value);
setAddProjectError(null);
}}
onKeyDown={(event) => {
if (event.key === "Enter") handleAddProject();
if (event.key === "Escape") {
setAddingProject(false);
setAddProjectError(null);
}
}}
autoFocus
/>
<button
type="button"
className="shrink-0 rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground transition-colors duration-150 hover:bg-primary/90 disabled:opacity-60"
onClick={handleAddProject}
disabled={!canAddProject}
>
{isAddingProject ? "Adding..." : "Add"}
</button>
</div>
{addProjectError && (
<p className="mt-1 px-0.5 text-[11px] leading-tight text-red-400">
{addProjectError}
</p>
)}
<div className="mt-1.5 px-0.5">
<button
type="button"
className="text-[11px] text-muted-foreground/50 transition-colors hover:text-muted-foreground"
onClick={() => {
setAddingProject(false);
setAddProjectError(null);
}}
>
Cancel
</button>
</div>
</div>
)}
{isManualProjectSorting ? (
<DndContext
sensors={projectDnDSensors}
collisionDetection={projectCollisionDetection}
modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}
onDragStart={handleProjectDragStart}
onDragEnd={handleProjectDragEnd}
onDragCancel={handleProjectDragCancel}
>
<SidebarMenu>
<SortableContext
items={sortedProjects.map((project) => project.id)}
strategy={verticalListSortingStrategy}
{isManualProjectSorting ? (
<DndContext
sensors={projectDnDSensors}
collisionDetection={projectCollisionDetection}
modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}
onDragStart={handleProjectDragStart}
onDragEnd={handleProjectDragEnd}
onDragCancel={handleProjectDragCancel}
>
<SidebarMenu>
<SortableContext
items={sortedProjects.map((project) => project.id)}
strategy={verticalListSortingStrategy}
>
{sortedProjects.map((project) => (
<SortableProjectItem key={project.id} projectId={project.id}>
{(dragHandleProps) => renderProjectItem(project, dragHandleProps)}
</SortableProjectItem>
))}
</SortableContext>
</SidebarMenu>
</DndContext>
) : (
<SidebarMenu ref={attachProjectListAutoAnimateRef}>
{sortedProjects.map((project) => (
<SortableProjectItem key={project.id} projectId={project.id}>
{(dragHandleProps) => renderProjectItem(project, dragHandleProps)}
</SortableProjectItem>
<SidebarMenuItem key={project.id} className="rounded-md">
{renderProjectItem(project, null)}
</SidebarMenuItem>
))}
</SortableContext>
</SidebarMenu>
</DndContext>
) : (
<SidebarMenu ref={attachProjectListAutoAnimateRef}>
{sortedProjects.map((project) => (
<SidebarMenuItem key={project.id} className="rounded-md">
{renderProjectItem(project, null)}
</SidebarMenuItem>
))}
</SidebarMenu>
)}
{projects.length === 0 && !shouldShowProjectPathEntry && (
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
No projects yet
</div>
)}
</SidebarGroup>
</SidebarContent>
<SidebarSeparator />
<SidebarFooter className="p-2">
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
onClick={() => void navigate({ to: "/settings" })}
>
<SettingsIcon className="size-3.5" />
<span className="text-xs">Settings</span>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
)}
{projects.length === 0 && !shouldShowProjectPathEntry && (
<div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">
No projects yet
</div>
)}
</SidebarGroup>
</SidebarContent>
<SidebarSeparator />
<SidebarFooter className="p-2">
<SidebarMenu>
<SidebarMenuItem>
{isOnSettings ? (
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
onClick={() => window.history.back()}
>
<ArrowLeftIcon className="size-3.5" />
<span className="text-xs">Back</span>
</SidebarMenuButton>
) : (
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-1.5 text-muted-foreground/70 hover:bg-accent hover:text-foreground"
onClick={() => void navigate({ to: "/settings" })}
>
<SettingsIcon className="size-3.5" />
<span className="text-xs">Settings</span>
</SidebarMenuButton>
)}
</SidebarMenuItem>
</SidebarMenu>
</SidebarFooter>
</SidebarFooter>
</>
)}
</>
);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,82 @@
import type { ComponentType } from "react";
import { ArchiveIcon, ArrowLeftIcon, Settings2Icon } from "lucide-react";
import { useNavigate } from "@tanstack/react-router";
import {
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarSeparator,
} from "../ui/sidebar";
export type SettingsSectionPath = "/settings/general" | "/settings/archived";
export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
label: string;
to: SettingsSectionPath;
icon: ComponentType<{ className?: string }>;
}> = [
{ label: "General", to: "/settings/general", icon: Settings2Icon },
{ label: "Archived threads", to: "/settings/archived", icon: ArchiveIcon },
];
export function SettingsSidebarNav({ pathname }: { pathname: string }) {
const navigate = useNavigate();
return (
<>
<SidebarContent className="overflow-x-hidden">
<SidebarGroup className="px-2 py-3">
<SidebarMenu>
{SETTINGS_NAV_ITEMS.map((item) => {
const Icon = item.icon;
const isActive = pathname === item.to;
return (
<SidebarMenuItem key={item.to}>
<SidebarMenuButton
size="sm"
isActive={isActive}
className={
isActive
? "gap-2 px-2 py-2 text-left text-sm text-foreground"
: "gap-2 px-2 py-2 text-left text-sm text-muted-foreground hover:text-foreground/80"
}
onClick={() => void navigate({ to: item.to, replace: true })}
>
<Icon
className={
isActive
? "size-4 shrink-0 text-foreground"
: "size-4 shrink-0 text-muted-foreground"
}
/>
<span className="truncate">{item.label}</span>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
</SidebarMenu>
</SidebarGroup>
</SidebarContent>
<SidebarSeparator />
<SidebarFooter className="p-2">
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
size="sm"
className="gap-2 px-2 py-2 text-sm text-muted-foreground hover:bg-accent hover:text-foreground"
onClick={() => window.history.back()}
>
<ArrowLeftIcon className="size-4" />
<span>Back</span>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarFooter>
</>
);
}
+10 -4
View File
@@ -44,10 +44,16 @@ export function showContextMenuFallback<T extends string>(
btn.type = "button";
btn.textContent = item.label;
const isDestructiveAction = item.destructive === true || item.id === "delete";
btn.className = isDestructiveAction
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
btn.addEventListener("click", () => cleanup(item.id));
const isDisabled = item.disabled === true;
btn.disabled = isDisabled;
btn.className = isDisabled
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-muted-foreground/60 cursor-not-allowed"
: isDestructiveAction
? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default"
: "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default";
if (!isDisabled) {
btn.addEventListener("click", () => cleanup(item.id));
}
menu.appendChild(btn);
}
+16
View File
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";
import { buildLegacyClientSettingsMigrationPatch } from "./useSettings";
describe("buildLegacyClientSettingsMigrationPatch", () => {
it("migrates archive confirmation from legacy local settings", () => {
expect(
buildLegacyClientSettingsMigrationPatch({
confirmThreadArchive: true,
confirmThreadDelete: false,
}),
).toEqual({
confirmThreadArchive: true,
confirmThreadDelete: false,
});
});
});
+4
View File
@@ -202,6 +202,10 @@ export function buildLegacyClientSettingsMigrationPatch(
): Partial<DeepMutable<ClientSettings>> {
const patch: Partial<DeepMutable<ClientSettings>> = {};
if (Predicate.isBoolean(legacySettings.confirmThreadArchive)) {
patch.confirmThreadArchive = legacySettings.confirmThreadArchive;
}
if (Predicate.isBoolean(legacySettings.confirmThreadDelete)) {
patch.confirmThreadDelete = legacySettings.confirmThreadDelete;
}
+211
View File
@@ -0,0 +1,211 @@
import { ThreadId } from "@t3tools/contracts";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useCallback } from "react";
import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "./useHandleNewThread";
import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
import { newCommandId } from "../lib/utils";
import { readNativeApi } from "../nativeApi";
import { useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
import { toastManager } from "../components/ui/toast";
import { useSettings } from "./useSettings";
export function useThreadActions() {
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const appSettings = useSettings();
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
const clearProjectDraftThreadById = useComposerDraftStore(
(store) => store.clearProjectDraftThreadById,
);
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
const routeThreadId = useParams({
strict: false,
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
});
const navigate = useNavigate();
const { handleNewThread } = useHandleNewThread();
const queryClient = useQueryClient();
const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
const archiveThread = useCallback(
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
const thread = threads.find((entry) => entry.id === threadId);
if (!thread) return;
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
throw new Error("Cannot archive a running thread.");
}
await api.orchestration.dispatchCommand({
type: "thread.archive",
commandId: newCommandId(),
threadId,
});
if (routeThreadId === threadId) {
await handleNewThread(thread.projectId);
}
},
[handleNewThread, routeThreadId, threads],
);
const unarchiveThread = useCallback(async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
await api.orchestration.dispatchCommand({
type: "thread.unarchive",
commandId: newCommandId(),
threadId,
});
}, []);
const deleteThread = useCallback(
async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {}) => {
const api = readNativeApi();
if (!api) return;
const thread = threads.find((entry) => entry.id === threadId);
if (!thread) return;
const threadProject = projects.find((project) => project.id === thread.projectId);
const deletedIds = opts.deletedThreadIds;
const survivingThreads =
deletedIds && deletedIds.size > 0
? threads.filter((entry) => entry.id === threadId || !deletedIds.has(entry.id))
: threads;
const orphanedWorktreePath = getOrphanedWorktreePathForThread(survivingThreads, threadId);
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
const shouldDeleteWorktree =
canDeleteWorktree &&
(await api.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
"",
"Delete the worktree too?",
].join("\n"),
));
if (thread.session && thread.session.status !== "closed") {
await api.orchestration
.dispatchCommand({
type: "thread.session.stop",
commandId: newCommandId(),
threadId,
createdAt: new Date().toISOString(),
})
.catch(() => undefined);
}
try {
await api.terminal.close({ threadId, deleteHistory: true });
} catch {
// Terminal may already be closed.
}
const deletedThreadIds = opts.deletedThreadIds ?? new Set<ThreadId>();
const shouldNavigateToFallback = routeThreadId === threadId;
const fallbackThreadId = getFallbackThreadIdAfterDelete({
threads,
deletedThreadId: threadId,
deletedThreadIds,
sortOrder: appSettings.sidebarThreadSortOrder,
});
await api.orchestration.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId,
});
clearComposerDraftForThread(threadId);
clearProjectDraftThreadById(thread.projectId, thread.id);
clearTerminalState(threadId);
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
await navigate({
to: "/$threadId",
params: { threadId: fallbackThreadId },
replace: true,
});
} else {
await navigate({ to: "/", replace: true });
}
}
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
return;
}
try {
await removeWorktreeMutation.mutateAsync({
cwd: threadProject.cwd,
path: orphanedWorktreePath,
force: true,
});
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
console.error("Failed to remove orphaned worktree after thread deletion", {
threadId,
projectCwd: threadProject.cwd,
worktreePath: orphanedWorktreePath,
error,
});
toastManager.add({
type: "error",
title: "Thread deleted, but worktree removal failed",
description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
});
}
},
[
clearComposerDraftForThread,
clearProjectDraftThreadById,
clearTerminalState,
appSettings.sidebarThreadSortOrder,
navigate,
projects,
removeWorktreeMutation,
routeThreadId,
threads,
],
);
const confirmAndDeleteThread = useCallback(
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
const thread = threads.find((entry) => entry.id === threadId);
if (!thread) return;
if (appSettings.confirmThreadDelete) {
const confirmed = await api.dialogs.confirm(
[
`Delete thread "${thread.title}"?`,
"This permanently clears conversation history for this thread.",
].join("\n"),
);
if (!confirmed) {
return;
}
}
await deleteThread(threadId);
},
[appSettings.confirmThreadDelete, deleteThread, threads],
);
return {
archiveThread,
unarchiveThread,
deleteThread,
confirmAndDeleteThread,
};
}
+21 -4
View File
@@ -23,25 +23,42 @@ export function createMemoryStorage(): StateStorage {
};
}
export function isStateStorage(
storage: Partial<StateStorage> | null | undefined,
): storage is StateStorage {
return (
storage !== null &&
storage !== undefined &&
typeof storage.getItem === "function" &&
typeof storage.setItem === "function" &&
typeof storage.removeItem === "function"
);
}
export function resolveStorage(storage: Partial<StateStorage> | null | undefined): StateStorage {
return isStateStorage(storage) ? storage : createMemoryStorage();
}
export function createDebouncedStorage(
baseStorage: StateStorage,
baseStorage: Partial<StateStorage> | null | undefined,
debounceMs: number = 300,
): DebouncedStorage {
const resolvedStorage = resolveStorage(baseStorage);
const debouncedSetItem = new Debouncer(
(name: string, value: string) => {
baseStorage.setItem(name, value);
resolvedStorage.setItem(name, value);
},
{ wait: debounceMs },
);
return {
getItem: (name) => baseStorage.getItem(name),
getItem: (name) => resolvedStorage.getItem(name),
setItem: (name, value) => {
debouncedSetItem.maybeExecute(name, value);
},
removeItem: (name) => {
debouncedSetItem.cancel();
baseStorage.removeItem(name);
resolvedStorage.removeItem(name);
},
flush: () => {
debouncedSetItem.flush();
+82 -19
View File
@@ -9,11 +9,18 @@
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root'
import { Route as SettingsRouteImport } from './routes/settings'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as ChatSettingsRouteImport } from './routes/_chat.settings'
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as ChatThreadIdRouteImport } from './routes/_chat.$threadId'
const SettingsRoute = SettingsRouteImport.update({
id: '/settings',
path: '/settings',
getParentRoute: () => rootRouteImport,
} as any)
const ChatRoute = ChatRouteImport.update({
id: '/_chat',
getParentRoute: () => rootRouteImport,
@@ -23,10 +30,15 @@ const ChatIndexRoute = ChatIndexRouteImport.update({
path: '/',
getParentRoute: () => ChatRoute,
} as any)
const ChatSettingsRoute = ChatSettingsRouteImport.update({
id: '/settings',
path: '/settings',
getParentRoute: () => ChatRoute,
const SettingsGeneralRoute = SettingsGeneralRouteImport.update({
id: '/general',
path: '/general',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
id: '/archived',
path: '/archived',
getParentRoute: () => SettingsRoute,
} as any)
const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
id: '/$threadId',
@@ -36,35 +48,66 @@ const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
export interface FileRoutesByFullPath {
'/': typeof ChatIndexRoute
'/settings': typeof SettingsRouteWithChildren
'/$threadId': typeof ChatThreadIdRoute
'/settings': typeof ChatSettingsRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/general': typeof SettingsGeneralRoute
}
export interface FileRoutesByTo {
'/settings': typeof SettingsRouteWithChildren
'/$threadId': typeof ChatThreadIdRoute
'/settings': typeof ChatSettingsRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/general': typeof SettingsGeneralRoute
'/': typeof ChatIndexRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/_chat': typeof ChatRouteWithChildren
'/settings': typeof SettingsRouteWithChildren
'/_chat/$threadId': typeof ChatThreadIdRoute
'/_chat/settings': typeof ChatSettingsRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/general': typeof SettingsGeneralRoute
'/_chat/': typeof ChatIndexRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/$threadId' | '/settings'
fullPaths:
| '/'
| '/settings'
| '/$threadId'
| '/settings/archived'
| '/settings/general'
fileRoutesByTo: FileRoutesByTo
to: '/$threadId' | '/settings' | '/'
id: '__root__' | '/_chat' | '/_chat/$threadId' | '/_chat/settings' | '/_chat/'
to:
| '/settings'
| '/$threadId'
| '/settings/archived'
| '/settings/general'
| '/'
id:
| '__root__'
| '/_chat'
| '/settings'
| '/_chat/$threadId'
| '/settings/archived'
| '/settings/general'
| '/_chat/'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
ChatRoute: typeof ChatRouteWithChildren
SettingsRoute: typeof SettingsRouteWithChildren
}
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/settings': {
id: '/settings'
path: '/settings'
fullPath: '/settings'
preLoaderRoute: typeof SettingsRouteImport
parentRoute: typeof rootRouteImport
}
'/_chat': {
id: '/_chat'
path: ''
@@ -79,12 +122,19 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ChatIndexRouteImport
parentRoute: typeof ChatRoute
}
'/_chat/settings': {
id: '/_chat/settings'
path: '/settings'
fullPath: '/settings'
preLoaderRoute: typeof ChatSettingsRouteImport
parentRoute: typeof ChatRoute
'/settings/general': {
id: '/settings/general'
path: '/general'
fullPath: '/settings/general'
preLoaderRoute: typeof SettingsGeneralRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/archived': {
id: '/settings/archived'
path: '/archived'
fullPath: '/settings/archived'
preLoaderRoute: typeof SettingsArchivedRouteImport
parentRoute: typeof SettingsRoute
}
'/_chat/$threadId': {
id: '/_chat/$threadId'
@@ -98,20 +148,33 @@ declare module '@tanstack/react-router' {
interface ChatRouteChildren {
ChatThreadIdRoute: typeof ChatThreadIdRoute
ChatSettingsRoute: typeof ChatSettingsRoute
ChatIndexRoute: typeof ChatIndexRoute
}
const ChatRouteChildren: ChatRouteChildren = {
ChatThreadIdRoute: ChatThreadIdRoute,
ChatSettingsRoute: ChatSettingsRoute,
ChatIndexRoute: ChatIndexRoute,
}
const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
interface SettingsRouteChildren {
SettingsArchivedRoute: typeof SettingsArchivedRoute
SettingsGeneralRoute: typeof SettingsGeneralRoute
}
const SettingsRouteChildren: SettingsRouteChildren = {
SettingsArchivedRoute: SettingsArchivedRoute,
SettingsGeneralRoute: SettingsGeneralRoute,
}
const SettingsRouteWithChildren = SettingsRoute._addFileChildren(
SettingsRouteChildren,
)
const rootRouteChildren: RootRouteChildren = {
ChatRoute: ChatRouteWithChildren,
SettingsRoute: SettingsRouteWithChildren,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
+4 -1
View File
@@ -11,6 +11,7 @@ import { QueryClient, useQueryClient } from "@tanstack/react-query";
import { Throttler } from "@tanstack/react-pacer";
import { APP_DISPLAY_NAME } from "../branding";
import { AppSidebarLayout } from "../components/AppSidebarLayout";
import { Button } from "../components/ui/button";
import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast";
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
@@ -54,7 +55,9 @@ function RootRouteView() {
<AnchoredToastProvider>
<EventRouter />
<DesktopProjectBootstrap />
<Outlet />
<AppSidebarLayout>
<Outlet />
</AppSidebarLayout>
</AnchoredToastProvider>
</ToastProvider>
);
File diff suppressed because it is too large. Load diff
+3 -40
View File
@@ -1,9 +1,8 @@
import { type ResolvedKeybindingsConfig } from "@t3tools/contracts";
import { useQuery } from "@tanstack/react-query";
import { Outlet, createFileRoute, useNavigate } from "@tanstack/react-router";
import { Outlet, createFileRoute } from "@tanstack/react-router";
import { useEffect } from "react";
import ThreadSidebar from "../components/Sidebar";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { isTerminalFocused } from "../lib/terminalFocus";
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
@@ -12,12 +11,8 @@ import { selectThreadTerminalState, useTerminalStateStore } from "../terminalSta
import { useThreadSelectionStore } from "../threadSelectionStore";
import { resolveSidebarNewThreadEnvMode } from "~/components/Sidebar.logic";
import { useSettings } from "~/hooks/useSettings";
import { Sidebar, SidebarProvider, SidebarRail } from "~/components/ui/sidebar";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width";
const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16;
const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16;
function ChatRouteGlobalShortcuts() {
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
@@ -94,43 +89,11 @@ function ChatRouteGlobalShortcuts() {
}
function ChatRouteLayout() {
const navigate = useNavigate();
useEffect(() => {
const onMenuAction = window.desktopBridge?.onMenuAction;
if (typeof onMenuAction !== "function") {
return;
}
const unsubscribe = onMenuAction((action) => {
if (action !== "open-settings") return;
void navigate({ to: "/settings" });
});
return () => {
unsubscribe?.();
};
}, [navigate]);
return (
<SidebarProvider defaultOpen>
<>
<ChatRouteGlobalShortcuts />
<Sidebar
side="left"
collapsible="offcanvas"
className="border-r border-border bg-card text-foreground"
resizable={{
minWidth: THREAD_SIDEBAR_MIN_WIDTH,
shouldAcceptWidth: ({ nextWidth, wrapper }) =>
wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
}}
>
<ThreadSidebar />
<SidebarRail />
</Sidebar>
<Outlet />
</SidebarProvider>
</>
);
}
@@ -0,0 +1,7 @@
import { createFileRoute } from "@tanstack/react-router";
import { ArchivedThreadsPanel } from "../components/settings/SettingsPanels";
export const Route = createFileRoute("/settings/archived")({
component: ArchivedThreadsPanel,
});
+7
View File
@@ -0,0 +1,7 @@
import { createFileRoute } from "@tanstack/react-router";
import { GeneralSettingsPanel } from "../components/settings/SettingsPanels";
export const Route = createFileRoute("/settings/general")({
component: GeneralSettingsPanel,
});
+77
View File
@@ -0,0 +1,77 @@
import { RotateCcwIcon } from "lucide-react";
import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";
import { useState } from "react";
import { useSettingsRestore } from "../components/settings/SettingsPanels";
import { Button } from "../components/ui/button";
import { SidebarInset, SidebarTrigger } from "../components/ui/sidebar";
import { isElectron } from "../env";
function SettingsContentLayout() {
const [restoreSignal, setRestoreSignal] = useState(0);
const { changedSettingLabels, restoreDefaults } = useSettingsRestore(() =>
setRestoreSignal((value) => value + 1),
);
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
{!isElectron && (
<header className="border-b border-border px-3 py-2 sm:px-5">
<div className="flex items-center gap-2">
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
<span className="text-sm font-medium text-foreground">Settings</span>
<div className="ms-auto flex items-center gap-2">
<Button
size="xs"
variant="outline"
disabled={changedSettingLabels.length === 0}
onClick={() => void restoreDefaults()}
>
<RotateCcwIcon className="size-3.5" />
Restore defaults
</Button>
</div>
</div>
</header>
)}
{isElectron && (
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5">
<span className="text-xs font-medium tracking-wide text-muted-foreground/70">
Settings
</span>
<div className="ms-auto flex items-center gap-2">
<Button
size="xs"
variant="outline"
disabled={changedSettingLabels.length === 0}
onClick={() => void restoreDefaults()}
>
<RotateCcwIcon className="size-3.5" />
Restore defaults
</Button>
</div>
</div>
)}
<div key={restoreSignal} className="min-h-0 flex flex-1 flex-col">
<Outlet />
</div>
</div>
</SidebarInset>
);
}
function SettingsRouteLayout() {
return <SettingsContentLayout />;
}
export const Route = createFileRoute("/settings")({
beforeLoad: ({ location }) => {
if (location.pathname === "/settings") {
throw redirect({ to: "/settings/general", replace: true });
}
},
component: SettingsRouteLayout,
});
+17
View File
@@ -29,6 +29,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
proposedPlans: [],
error: null,
createdAt: "2026-02-13T00:00:00.000Z",
archivedAt: null,
latestTurn: null,
branch: null,
worktreePath: null,
@@ -72,6 +73,7 @@ function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"
latestTurn: null,
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
activities: [],
@@ -270,6 +272,21 @@ describe("store read model sync", () => {
expect(next.threads[0]?.updatedAt).toBe("2026-02-27T00:05:00.000Z");
});
it("maps archivedAt from the read model", () => {
const initialState = makeState(makeThread());
const archivedAt = "2026-02-28T00:00:00.000Z";
const next = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
archivedAt,
}),
),
);
expect(next.threads[0]?.archivedAt).toBe(archivedAt);
});
it("preserves the current project order when syncing incoming read model updates", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
+1
View File
@@ -299,6 +299,7 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea
})),
error: thread.session?.lastError ?? null,
createdAt: thread.createdAt,
archivedAt: thread.archivedAt,
updatedAt: thread.updatedAt,
latestTurn: thread.latestTurn,
lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt,
+1 -3
View File
@@ -7,9 +7,7 @@ const THREAD_ID = ThreadId.makeUnsafe("thread-1");
describe("terminalStateStore actions", () => {
beforeEach(() => {
if (typeof localStorage !== "undefined") {
localStorage.clear();
}
useTerminalStateStore.persist.clearStorage();
useTerminalStateStore.setState({ terminalStateByThreadId: {} });
});
+6 -1
View File
@@ -8,6 +8,7 @@
import type { ThreadId } from "@t3tools/contracts";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { resolveStorage } from "./lib/storage";
import {
DEFAULT_THREAD_TERMINAL_HEIGHT,
DEFAULT_THREAD_TERMINAL_ID,
@@ -27,6 +28,10 @@ interface ThreadTerminalState {
const TERMINAL_STATE_STORAGE_KEY = "t3code:terminal-state:v1";
function createTerminalStateStorage() {
return resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined);
}
function normalizeTerminalIds(terminalIds: string[]): string[] {
const ids = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
return ids.length > 0 ? ids : [DEFAULT_THREAD_TERMINAL_ID];
@@ -542,7 +547,7 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
{
name: TERMINAL_STATE_STORAGE_KEY,
version: 1,
storage: createJSONStorage(() => localStorage),
storage: createJSONStorage(createTerminalStateStorage),
partialize: (state) => ({
terminalStateByThreadId: state.terminalStateByThreadId,
}),
+5
View File
@@ -66,3 +66,8 @@ export function formatRelativeTime(isoDate: string): { value: string; suffix: st
const days = Math.floor(hours / 24);
return { value: `${days}d`, suffix: "ago" };
}
export function formatRelativeTimeLabel(isoDate: string) {
const relative = formatRelativeTime(isoDate);
return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
}
+1
View File
@@ -101,6 +101,7 @@ export interface Thread {
proposedPlans: ProposedPlan[];
error: string | null;
createdAt: string;
archivedAt: string | null;
updatedAt?: string | undefined;
latestTurn: OrchestrationLatestTurn | null;
lastVisitedAt?: string | undefined;
+1
View File
@@ -23,6 +23,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
proposedPlans: [],
error: null,
createdAt: "2026-02-13T00:00:00.000Z",
archivedAt: null,
latestTurn: null,
branch: null,
worktreePath: null,
+1
View File
@@ -57,6 +57,7 @@ export interface ContextMenuItem<T extends string = string> {
id: T;
label: string;
destructive?: boolean;
disabled?: boolean;
}
export type DesktopUpdateStatus =
@@ -5,6 +5,8 @@ import { Effect, Schema } from "effect";
import {
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
OrchestrationCommand,
OrchestrationEvent,
OrchestrationGetTurnDiffInput,
OrchestrationLatestTurn,
ProjectCreatedPayload,
@@ -32,6 +34,8 @@ const decodeOrchestrationLatestTurn = Schema.decodeUnknownEffect(OrchestrationLa
const decodeOrchestrationProposedPlan = Schema.decodeUnknownEffect(OrchestrationProposedPlan);
const decodeOrchestrationSession = Schema.decodeUnknownEffect(OrchestrationSession);
const decodeThreadCreatedPayload = Schema.decodeUnknownEffect(ThreadCreatedPayload);
const decodeOrchestrationCommand = Schema.decodeUnknownEffect(OrchestrationCommand);
const decodeOrchestrationEvent = Schema.decodeUnknownEffect(OrchestrationEvent);
const decodeThreadMetaUpdatedPayload = Schema.decodeUnknownEffect(ThreadMetaUpdatedPayload);
it.effect("parses turn diff input when fromTurnCount <= toTurnCount", () =>
@@ -227,6 +231,66 @@ it.effect("decodes thread.meta-updated payloads with explicit provider", () =>
}),
);
it.effect("decodes thread archive and unarchive commands", () =>
Effect.gen(function* () {
const archive = yield* decodeOrchestrationCommand({
type: "thread.archive",
commandId: "cmd-archive-1",
threadId: "thread-1",
});
const unarchive = yield* decodeOrchestrationCommand({
type: "thread.unarchive",
commandId: "cmd-unarchive-1",
threadId: "thread-1",
});
assert.strictEqual(archive.type, "thread.archive");
assert.strictEqual(unarchive.type, "thread.unarchive");
}),
);
it.effect("decodes thread archived and unarchived events", () =>
Effect.gen(function* () {
const archived = yield* decodeOrchestrationEvent({
sequence: 1,
eventId: "event-archive-1",
aggregateKind: "thread",
aggregateId: "thread-1",
type: "thread.archived",
occurredAt: "2026-01-01T00:00:00.000Z",
commandId: "cmd-archive-1",
causationEventId: null,
correlationId: "cmd-archive-1",
metadata: {},
payload: {
threadId: "thread-1",
archivedAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
},
});
const unarchived = yield* decodeOrchestrationEvent({
sequence: 2,
eventId: "event-unarchive-1",
aggregateKind: "thread",
aggregateId: "thread-1",
type: "thread.unarchived",
occurredAt: "2026-01-02T00:00:00.000Z",
commandId: "cmd-unarchive-1",
causationEventId: null,
correlationId: "cmd-unarchive-1",
metadata: {},
payload: {
threadId: "thread-1",
updatedAt: "2026-01-02T00:00:00.000Z",
},
});
assert.strictEqual(archived.type, "thread.archived");
assert.strictEqual(archived.payload.archivedAt, "2026-01-01T00:00:00.000Z");
assert.strictEqual(unarchived.type, "thread.unarchived");
}),
);
it.effect("accepts provider-scoped model options in thread.turn.start", () =>
Effect.gen(function* () {
const parsed = yield* decodeThreadTurnStartCommand({
+40
View File
@@ -283,6 +283,7 @@ export const OrchestrationThread = Schema.Struct({
latestTurn: Schema.NullOr(OrchestrationLatestTurn),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(() => null)),
deletedAt: Schema.NullOr(IsoDateTime),
messages: Schema.Array(OrchestrationMessage),
proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(Schema.withDecodingDefault(() => [])),
@@ -348,6 +349,18 @@ const ThreadDeleteCommand = Schema.Struct({
threadId: ThreadId,
});
const ThreadArchiveCommand = Schema.Struct({
type: Schema.Literal("thread.archive"),
commandId: CommandId,
threadId: ThreadId,
});
const ThreadUnarchiveCommand = Schema.Struct({
type: Schema.Literal("thread.unarchive"),
commandId: CommandId,
threadId: ThreadId,
});
const ThreadMetaUpdateCommand = Schema.Struct({
type: Schema.Literal("thread.meta.update"),
commandId: CommandId,
@@ -457,6 +470,8 @@ const DispatchableClientOrchestrationCommand = Schema.Union([
ProjectDeleteCommand,
ThreadCreateCommand,
ThreadDeleteCommand,
ThreadArchiveCommand,
ThreadUnarchiveCommand,
ThreadMetaUpdateCommand,
ThreadRuntimeModeSetCommand,
ThreadInteractionModeSetCommand,
@@ -476,6 +491,8 @@ export const ClientOrchestrationCommand = Schema.Union([
ProjectDeleteCommand,
ThreadCreateCommand,
ThreadDeleteCommand,
ThreadArchiveCommand,
ThreadUnarchiveCommand,
ThreadMetaUpdateCommand,
ThreadRuntimeModeSetCommand,
ThreadInteractionModeSetCommand,
@@ -576,6 +593,8 @@ export const OrchestrationEventType = Schema.Literals([
"project.deleted",
"thread.created",
"thread.deleted",
"thread.archived",
"thread.unarchived",
"thread.meta-updated",
"thread.runtime-mode-set",
"thread.interaction-mode-set",
@@ -642,6 +661,17 @@ export const ThreadDeletedPayload = Schema.Struct({
deletedAt: IsoDateTime,
});
export const ThreadArchivedPayload = Schema.Struct({
threadId: ThreadId,
archivedAt: IsoDateTime,
updatedAt: IsoDateTime,
});
export const ThreadUnarchivedPayload = Schema.Struct({
threadId: ThreadId,
updatedAt: IsoDateTime,
});
export const ThreadMetaUpdatedPayload = Schema.Struct({
threadId: ThreadId,
title: Schema.optional(TrimmedNonEmptyString),
@@ -799,6 +829,16 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("thread.deleted"),
payload: ThreadDeletedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.archived"),
payload: ThreadArchivedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.unarchived"),
payload: ThreadUnarchivedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.meta-updated"),
+8
View File
@@ -0,0 +1,8 @@
import { describe, expect, it } from "vitest";
import { DEFAULT_CLIENT_SETTINGS } from "./settings";
describe("DEFAULT_CLIENT_SETTINGS", () => {
it("includes archive confirmation with a false default", () => {
expect(DEFAULT_CLIENT_SETTINGS.confirmThreadArchive).toBe(false);
});
});
+1
View File
@@ -24,6 +24,7 @@ export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
export const ClientSettingsSchema = Schema.Struct({
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(