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.
Add thread archiving and settings navigation (#1359)
shivamf0cdaf94c2b6
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 0bb3d20c4..c718a3127 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -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) {diff --git a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.tsindex daa6eb5f4..9fb2500ce 100644--- a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts+++ b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts@@ -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: [],diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.tsindex a1cbfa002..6aa889991 100644--- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts@@ -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;diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex ce68d654e..7d85d1e38 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -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,diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.tsindex 5080ea8c4..32143d751 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts@@ -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: [{diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.tsindex cc2f4f87e..f951c54b5 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts@@ -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_threadsORDER 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) ?? [],diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.tsindex c96385cad..f7ebf6934 100644--- a/apps/server/src/orchestration/Schemas.ts+++ b/apps/server/src/orchestration/Schemas.ts@@ -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 = ContractsProjectMetaUpdatedPayloadSchemexport 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;diff --git a/apps/server/src/orchestration/commandInvariants.test.ts b/apps/server/src/orchestration/commandInvariants.test.tsindex b07eb4234..43d665a2c 100644--- a/apps/server/src/orchestration/commandInvariants.test.ts+++ b/apps/server/src/orchestration/commandInvariants.test.ts@@ -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,diff --git a/apps/server/src/orchestration/commandInvariants.ts b/apps/server/src/orchestration/commandInvariants.tsindex 6acb9c82b..009fdb190 100644--- a/apps/server/src/orchestration/commandInvariants.ts+++ b/apps/server/src/orchestration/commandInvariants.ts@@ -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;diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.tsindex c4cfd2314..c70194bef 100644--- a/apps/server/src/orchestration/decider.ts+++ b/apps/server/src/orchestration/decider.ts@@ -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,diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.tsindex fd95d028d..3dcdd1925 100644--- a/apps/server/src/orchestration/projector.test.ts+++ b/apps/server/src/orchestration/projector.test.ts@@ -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);diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.tsindex 05a660f75..deb8a6d44 100644--- a/apps/server/src/orchestration/projector.ts+++ b/apps/server/src/orchestration/projector.ts@@ -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) => ({diff --git a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts b/apps/server/src/persistence/Layers/ProjectionRepositories.test.tsindex 0ca13f2e9..b0e177483 100644--- a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts+++ b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts@@ -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,});diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.tsindex 344f19909..48dd51fdc 100644--- a/apps/server/src/persistence/Layers/ProjectionThreads.ts+++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts@@ -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_threadsWHERE 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_threadsWHERE project_id = ${projectId}diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.tsindex 7ee45514e..c759665f0 100644--- a/apps/server/src/persistence/Migrations.ts+++ b/apps/server/src/persistence/Migrations.ts@@ -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) =>diff --git a/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts b/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.tsindex 039a63d60..d74e9fe08 100644--- a/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts+++ b/apps/server/src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts@@ -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",diff --git a/apps/server/src/persistence/Migrations/017_ProjectionThreadsArchivedAt.ts b/apps/server/src/persistence/Migrations/017_ProjectionThreadsArchivedAt.tsnew file mode 100644index 000000000..35d05f189--- /dev/null+++ b/apps/server/src/persistence/Migrations/017_ProjectionThreadsArchivedAt.ts@@ -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+ `;+});diff --git a/apps/server/src/persistence/Migrations/018_ProjectionThreadsArchivedAtIndex.ts b/apps/server/src/persistence/Migrations/018_ProjectionThreadsArchivedAtIndex.tsnew file mode 100644index 000000000..b12ab1bcf--- /dev/null+++ b/apps/server/src/persistence/Migrations/018_ProjectionThreadsArchivedAtIndex.ts@@ -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)+ `;+});diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.tsindex cf4bd55a8..59505c125 100644--- a/apps/server/src/persistence/Services/ProjectionThreads.ts+++ b/apps/server/src/persistence/Services/ProjectionThreads.ts@@ -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;diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.tsindex 53ee7d74f..5717fda39 100644--- a/apps/server/src/terminal/Layers/Manager.test.ts+++ b/apps/server/src/terminal/Layers/Manager.test.ts@@ -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);}diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsxnew file mode 100644index 000000000..a2b27bb1e--- /dev/null+++ b/apps/web/src/components/AppSidebarLayout.tsx@@ -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>+ );+}diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsxindex 7bf3ecf26..06cbf0efb 100644--- a/apps/web/src/components/ChatView.browser.tsx+++ b/apps/web/src/components/ChatView.browser.tsx@@ -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: [],diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex 0a9f242ed..0a27fb203 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -32,6 +32,7 @@ export function buildLocalDraftThread(messages: [],error,createdAt: draftThread.createdAt,+ archivedAt: null,latestTurn: null,lastVisitedAt: draftThread.createdAt,branch: draftThread.branch,diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsxindex e64a981ee..5d6ec94a5 100644--- a/apps/web/src/components/KeybindingsToast.browser.tsx+++ b/apps/web/src/components/KeybindingsToast.browser.tsx@@ -102,6 +102,7 @@ function createMinimalSnapshot(): OrchestrationReadModel {latestTurn: null,createdAt: NOW_ISO,updatedAt: NOW_ISO,+ archivedAt: null,deletedAt: null,messages: [{diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsxnew file mode 100644index 000000000..bc0118120--- /dev/null+++ b/apps/web/src/components/ProjectFavicon.tsx@@ -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")}+ />+ </>+ );+}diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.tsindex dcfe3f6b6..0824758ba 100644--- a/apps/web/src/components/Sidebar.logic.test.ts+++ b/apps/web/src/components/Sidebar.logic.test.ts@@ -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" }),diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex 6c531b1e7..af60ce7d2 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -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 "../limport { 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));+ }}+ ><SidebarMenuSubButtonrender={<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 && (<buttontype="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>+ <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>+ )}- {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}+ {isManualProjectSorting ? (+ <DndContext+ sensors={projectDnDSensors}+ collisionDetection={projectCollisionDetection}+ modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}+ onDragStart={handleProjectDragStart}+ onDragEnd={handleProjectDragEnd}+ onDragCancel={handleProjectDragCancel}>- <FolderIcon className="size-3.5" />- {isPickingFolder ? "Picking folder..." : "Browse for folder"}- </button>+ <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) => (+ <SidebarMenuItem key={project.id} className="rounded-md">+ {renderProjectItem(project, null)}+ </SidebarMenuItem>+ ))}+ </SidebarMenu>)}- <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>++ {projects.length === 0 && !shouldShowProjectPathEntry && (+ <div className="px-2 pt-4 text-center text-xs text-muted-foreground/60">+ No projects yet+ </div>)}- <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}+ </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" })}>- {sortedProjects.map((project) => (- <SortableProjectItem key={project.id} projectId={project.id}>- {(dragHandleProps) => renderProjectItem(project, dragHandleProps)}- </SortableProjectItem>- ))}- </SortableContext>- </SidebarMenu>- </DndContext>- ) : (- <SidebarMenu ref={attachProjectListAutoAnimateRef}>- {sortedProjects.map((project) => (- <SidebarMenuItem key={project.id} className="rounded-md">- {renderProjectItem(project, null)}- </SidebarMenuItem>- ))}+ <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>+ </>+ )}</>);}diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxnew file mode 100644index 000000000..bb149c00a--- /dev/null+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -0,0 +1,1390 @@+import {+ ArchiveIcon,+ ArchiveX,+ ChevronDownIcon,+ InfoIcon,+ LoaderIcon,+ PlusIcon,+ RefreshCwIcon,+ Undo2Icon,+ XIcon,+} from "lucide-react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";+import {+ PROVIDER_DISPLAY_NAMES,+ type ProviderKind,+ type ServerProvider,+ type ServerProviderModel,+ ThreadId,+} from "@t3tools/contracts";+import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";+import { normalizeModelSlug } from "@t3tools/shared/model";+import { Equal } from "effect";+import { APP_VERSION } from "../../branding";+import { ProviderModelPicker } from "../chat/ProviderModelPicker";+import { TraitsPicker } from "../chat/TraitsPicker";+import { resolveAndPersistPreferredEditor } from "../../editorPreferences";+import { useTheme } from "../../hooks/useTheme";+import { useSettings, useUpdateSettings } from "../../hooks/useSettings";+import { useThreadActions } from "../../hooks/useThreadActions";+import { serverConfigQueryOptions, serverQueryKeys } from "../../lib/serverReactQuery";+import {+ MAX_CUSTOM_MODEL_LENGTH,+ getCustomModelOptionsByProvider,+ resolveAppModelSelectionState,+} from "../../modelSelection";+import { ensureNativeApi, readNativeApi } from "../../nativeApi";+import { useStore } from "../../store";+import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat";+import { cn } from "../../lib/utils";+import { Button } from "../ui/button";+import { Collapsible, CollapsibleContent } from "../ui/collapsible";+import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";+import { Input } from "../ui/input";+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";+import { Switch } from "../ui/switch";+import { toastManager } from "../ui/toast";+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";+import { ProjectFavicon } from "../ProjectFavicon";++const THEME_OPTIONS = [+ {+ value: "system",+ label: "System",+ },+ {+ value: "light",+ label: "Light",+ },+ {+ value: "dark",+ label: "Dark",+ },+] as const;++const TIMESTAMP_FORMAT_LABELS = {+ locale: "System default",+ "12-hour": "12-hour",+ "24-hour": "24-hour",+} as const;++const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];++type InstallProviderSettings = {+ provider: ProviderKind;+ title: string;+ binaryPlaceholder: string;+ binaryDescription: ReactNode;+ homePathKey?: "codexHomePath";+ homePlaceholder?: string;+ homeDescription?: ReactNode;+};++const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [+ {+ provider: "codex",+ title: "Codex",+ binaryPlaceholder: "Codex binary path",+ binaryDescription: "Path to the Codex binary",+ homePathKey: "codexHomePath",+ homePlaceholder: "CODEX_HOME",+ homeDescription: "Optional custom Codex home and config directory.",+ },+ {+ provider: "claudeAgent",+ title: "Claude",+ binaryPlaceholder: "Claude binary path",+ binaryDescription: "Path to the Claude binary",+ },+] as const;++const PROVIDER_STATUS_STYLES = {+ disabled: {+ dot: "bg-amber-400",+ },+ error: {+ dot: "bg-destructive",+ },+ ready: {+ dot: "bg-success",+ },+ warning: {+ dot: "bg-warning",+ },+} as const;++function getProviderSummary(provider: ServerProvider | undefined) {+ if (!provider) {+ return {+ headline: "Checking provider status",+ detail: "Waiting for the server to report installation and authentication details.",+ };+ }+ if (!provider.enabled) {+ return {+ headline: "Disabled",+ detail:+ provider.message ?? "This provider is installed but disabled for new sessions in T3 Code.",+ };+ }+ if (!provider.installed) {+ return {+ headline: "Not found",+ detail: provider.message ?? "CLI not detected on PATH.",+ };+ }+ if (provider.authStatus === "authenticated") {+ return {+ headline: "Authenticated",+ detail: provider.message ?? null,+ };+ }+ if (provider.authStatus === "unauthenticated") {+ return {+ headline: "Not authenticated",+ detail: provider.message ?? null,+ };+ }+ if (provider.status === "warning") {+ return {+ headline: "Needs attention",+ detail:+ provider.message ?? "The provider is installed, but the server could not fully verify it.",+ };+ }+ if (provider.status === "error") {+ return {+ headline: "Unavailable",+ detail: provider.message ?? "The provider failed its startup checks.",+ };+ }+ return {+ headline: "Available",+ detail: provider.message ?? "Installed and ready, but authentication could not be verified.",+ };+}++function getProviderVersionLabel(version: string | null | undefined) {+ if (!version) return null;+ return version.startsWith("v") ? version : `v${version}`;+}++function useRelativeTimeTick(intervalMs = 1_000) {+ const [tick, setTick] = useState(() => Date.now());+ useEffect(() => {+ const id = setInterval(() => setTick(Date.now()), intervalMs);+ return () => clearInterval(id);+ }, [intervalMs]);+ return tick;+}++function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {+ useRelativeTimeTick();+ const lastCheckedRelative = lastCheckedAt ? formatRelativeTime(lastCheckedAt) : null;++ if (!lastCheckedRelative) {+ return null;+ }++ return (+ <span className="text-[11px] text-muted-foreground/60">+ {lastCheckedRelative.suffix ? (+ <>+ Checked <span className="font-mono tabular-nums">{lastCheckedRelative.value}</span>{" "}+ {lastCheckedRelative.suffix}+ </>+ ) : (+ <>Checked {lastCheckedRelative.value}</>+ )}+ </span>+ );+}++function SettingsSection({+ title,+ icon,+ headerAction,+ children,+}: {+ title: string;+ icon?: ReactNode;+ headerAction?: ReactNode;+ children: ReactNode;+}) {+ return (+ <section className="space-y-3">+ <div className="flex items-center justify-between">+ <h2 className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground">+ {icon}+ {title}+ </h2>+ {headerAction}+ </div>+ <div className="relative overflow-hidden rounded-2xl border bg-card text-card-foreground shadow-xs/5 not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]">+ {children}+ </div>+ </section>+ );+}++function SettingsRow({+ title,+ description,+ status,+ resetAction,+ control,+ children,+}: {+ title: string;+ description: string;+ status?: ReactNode;+ resetAction?: ReactNode;+ control?: ReactNode;+ children?: ReactNode;+}) {+ return (+ <div className="border-t border-border px-4 py-4 first:border-t-0 sm:px-5">+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <div className="min-w-0 flex-1 space-y-1">+ <div className="flex min-h-5 items-center gap-1.5">+ <h3 className="text-sm font-medium text-foreground">{title}</h3>+ <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">+ {resetAction}+ </span>+ </div>+ <p className="text-xs text-muted-foreground">{description}</p>+ {status ? <div className="pt-1 text-[11px] text-muted-foreground">{status}</div> : null}+ </div>+ {control ? (+ <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">+ {control}+ </div>+ ) : null}+ </div>+ {children}+ </div>+ );+}++function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) {+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ size="icon-xs"+ variant="ghost"+ aria-label={`Reset ${label} to default`}+ className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"+ onClick={(event) => {+ event.stopPropagation();+ onClick();+ }}+ >+ <Undo2Icon className="size-3" />+ </Button>+ }+ />+ <TooltipPopup side="top">Reset to default</TooltipPopup>+ </Tooltip>+ );+}++function SettingsPageContainer({ children }: { children: ReactNode }) {+ return (+ <div className="flex-1 overflow-y-auto p-6">+ <div className="mx-auto flex w-full max-w-4xl flex-col gap-6">{children}</div>+ </div>+ );+}++export function useSettingsRestore(onRestored?: () => void) {+ const { theme, setTheme } = useTheme();+ const settings = useSettings();+ const { resetSettings } = useUpdateSettings();++ const isGitWritingModelDirty = !Equal.equals(+ settings.textGenerationModelSelection ?? null,+ DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,+ );+ const areProviderSettingsDirty = PROVIDER_SETTINGS.some((providerSettings) => {+ const currentSettings = settings.providers[providerSettings.provider];+ const defaultSettings = DEFAULT_UNIFIED_SETTINGS.providers[providerSettings.provider];+ return !Equal.equals(currentSettings, defaultSettings);+ });++ const changedSettingLabels = useMemo(+ () => [+ ...(theme !== "system" ? ["Theme"] : []),+ ...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat+ ? ["Time format"]+ : []),+ ...(settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap+ ? ["Diff line wrapping"]+ : []),+ ...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming+ ? ["Assistant output"]+ : []),+ ...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode+ ? ["New thread mode"]+ : []),+ ...(settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive+ ? ["Archive confirmation"]+ : []),+ ...(settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete+ ? ["Delete confirmation"]+ : []),+ ...(isGitWritingModelDirty ? ["Git writing model"] : []),+ ...(areProviderSettingsDirty ? ["Providers"] : []),+ ],+ [+ areProviderSettingsDirty,+ isGitWritingModelDirty,+ settings.confirmThreadArchive,+ settings.confirmThreadDelete,+ settings.defaultThreadEnvMode,+ settings.diffWordWrap,+ settings.enableAssistantStreaming,+ settings.timestampFormat,+ theme,+ ],+ );++ const restoreDefaults = useCallback(async () => {+ if (changedSettingLabels.length === 0) return;+ const api = readNativeApi();+ const confirmed = await (api ?? ensureNativeApi()).dialogs.confirm(+ ["Restore default settings?", `This will reset: ${changedSettingLabels.join(", ")}.`].join(+ "\n",+ ),+ );+ if (!confirmed) return;++ setTheme("system");+ resetSettings();+ onRestored?.();+ }, [changedSettingLabels, onRestored, resetSettings, setTheme]);++ return {+ changedSettingLabels,+ restoreDefaults,+ };+}++export function GeneralSettingsPanel() {+ const { theme, setTheme } = useTheme();+ const settings = useSettings();+ const { updateSettings } = useUpdateSettings();+ const serverConfigQuery = useQuery(serverConfigQueryOptions());+ const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);+ const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);+ const [openProviderDetails, setOpenProviderDetails] = useState<Record<ProviderKind, boolean>>({+ codex: Boolean(+ settings.providers.codex.binaryPath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.binaryPath ||+ settings.providers.codex.homePath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.homePath ||+ settings.providers.codex.customModels.length > 0,+ ),+ claudeAgent: Boolean(+ settings.providers.claudeAgent.binaryPath !==+ DEFAULT_UNIFIED_SETTINGS.providers.claudeAgent.binaryPath ||+ settings.providers.claudeAgent.customModels.length > 0,+ ),+ });+ const [customModelInputByProvider, setCustomModelInputByProvider] = useState<+ Record<ProviderKind, string>+ >({+ codex: "",+ claudeAgent: "",+ });+ const [customModelErrorByProvider, setCustomModelErrorByProvider] = useState<+ Partial<Record<ProviderKind, string | null>>+ >({});+ const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);+ const refreshingRef = useRef(false);+ const queryClient = useQueryClient();+ const modelListRefs = useRef<Partial<Record<ProviderKind, HTMLDivElement | null>>>({});+ const refreshProviders = useCallback(() => {+ if (refreshingRef.current) return;+ refreshingRef.current = true;+ setIsRefreshingProviders(true);+ void ensureNativeApi()+ .server.refreshProviders()+ .then(() => queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() }))+ .catch((error: unknown) => {+ console.warn("Failed to refresh providers", error);+ })+ .finally(() => {+ refreshingRef.current = false;+ setIsRefreshingProviders(false);+ });+ }, [queryClient]);++ const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;+ const availableEditors = serverConfigQuery.data?.availableEditors;+ const serverProviders = serverConfigQuery.data?.providers ?? EMPTY_SERVER_PROVIDERS;+ const codexHomePath = settings.providers.codex.homePath;++ const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);+ const textGenProvider = textGenerationModelSelection.provider;+ const textGenModel = textGenerationModelSelection.model;+ const textGenModelOptions = textGenerationModelSelection.options;+ const gitModelOptionsByProvider = getCustomModelOptionsByProvider(+ settings,+ serverProviders,+ textGenProvider,+ textGenModel,+ );+ const isGitWritingModelDirty = !Equal.equals(+ settings.textGenerationModelSelection ?? null,+ DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,+ );++ const openKeybindingsFile = useCallback(() => {+ if (!keybindingsConfigPath) return;+ setOpenKeybindingsError(null);+ setIsOpeningKeybindings(true);+ const editor = resolveAndPersistPreferredEditor(availableEditors ?? []);+ if (!editor) {+ setOpenKeybindingsError("No available editors found.");+ setIsOpeningKeybindings(false);+ return;+ }+ void ensureNativeApi()+ .shell.openInEditor(keybindingsConfigPath, editor)+ .catch((error) => {+ setOpenKeybindingsError(+ error instanceof Error ? error.message : "Unable to open keybindings file.",+ );+ })+ .finally(() => {+ setIsOpeningKeybindings(false);+ });+ }, [availableEditors, keybindingsConfigPath]);++ const addCustomModel = useCallback(+ (provider: ProviderKind) => {+ const customModelInput = customModelInputByProvider[provider];+ const customModels = settings.providers[provider].customModels;+ const normalized = normalizeModelSlug(customModelInput, provider);+ if (!normalized) {+ setCustomModelErrorByProvider((existing) => ({+ ...existing,+ [provider]: "Enter a model slug.",+ }));+ return;+ }+ if (+ serverProviders+ .find((candidate) => candidate.provider === provider)+ ?.models.some((option) => !option.isCustom && option.slug === normalized)+ ) {+ setCustomModelErrorByProvider((existing) => ({+ ...existing,+ [provider]: "That model is already built in.",+ }));+ return;+ }+ if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {+ setCustomModelErrorByProvider((existing) => ({+ ...existing,+ [provider]: `Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`,+ }));+ return;+ }+ if (customModels.includes(normalized)) {+ setCustomModelErrorByProvider((existing) => ({+ ...existing,+ [provider]: "That custom model is already saved.",+ }));+ return;+ }++ updateSettings({+ providers: {+ ...settings.providers,+ [provider]: {+ ...settings.providers[provider],+ customModels: [...customModels, normalized],+ },+ },+ });+ setCustomModelInputByProvider((existing) => ({+ ...existing,+ [provider]: "",+ }));+ setCustomModelErrorByProvider((existing) => ({+ ...existing,+ [provider]: null,+ }));++ const el = modelListRefs.current[provider];+ if (!el) return;+ const scrollToEnd = () => el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });+ requestAnimationFrame(scrollToEnd);+ const observer = new MutationObserver(() => {+ scrollToEnd();+ observer.disconnect();+ });+ observer.observe(el, { childList: true, subtree: true });+ setTimeout(() => observer.disconnect(), 2_000);+ },+ [customModelInputByProvider, serverProviders, settings, updateSettings],+ );++ const removeCustomModel = useCallback(+ (provider: ProviderKind, slug: string) => {+ updateSettings({+ providers: {+ ...settings.providers,+ [provider]: {+ ...settings.providers[provider],+ customModels: settings.providers[provider].customModels.filter(+ (model) => model !== slug,+ ),+ },+ },+ });+ setCustomModelErrorByProvider((existing) => ({+ ...existing,+ [provider]: null,+ }));+ },+ [settings, updateSettings],+ );++ const providerCards = PROVIDER_SETTINGS.map((providerSettings) => {+ const liveProvider = serverProviders.find(+ (candidate) => candidate.provider === providerSettings.provider,+ );+ const providerConfig = settings.providers[providerSettings.provider];+ const defaultProviderConfig = DEFAULT_UNIFIED_SETTINGS.providers[providerSettings.provider];+ const statusKey = liveProvider?.status ?? (providerConfig.enabled ? "warning" : "disabled");+ const summary = getProviderSummary(liveProvider);+ const models: ReadonlyArray<ServerProviderModel> =+ liveProvider?.models ??+ providerConfig.customModels.map((slug) => ({+ slug,+ name: slug,+ isCustom: true,+ capabilities: null,+ }));++ return {+ provider: providerSettings.provider,+ title: providerSettings.title,+ binaryPlaceholder: providerSettings.binaryPlaceholder,+ binaryDescription: providerSettings.binaryDescription,+ homePathKey: providerSettings.homePathKey,+ homePlaceholder: providerSettings.homePlaceholder,+ homeDescription: providerSettings.homeDescription,+ binaryPathValue: providerConfig.binaryPath,+ isDirty: !Equal.equals(providerConfig, defaultProviderConfig),+ liveProvider,+ models,+ providerConfig,+ statusStyle: PROVIDER_STATUS_STYLES[statusKey],+ summary,+ versionLabel: getProviderVersionLabel(liveProvider?.version),+ };+ });++ const lastCheckedAt =+ serverProviders.length > 0+ ? serverProviders.reduce(+ (latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest),+ serverProviders[0]!.checkedAt,+ )+ : null;+ return (+ <SettingsPageContainer>+ <SettingsSection title="General">+ <SettingsRow+ title="Theme"+ description="Choose how T3 Code looks across the app."+ resetAction={+ theme !== "system" ? (+ <SettingResetButton label="theme" onClick={() => setTheme("system")} />+ ) : null+ }+ control={+ <Select+ value={theme}+ onValueChange={(value) => {+ if (value === "system" || value === "light" || value === "dark") {+ setTheme(value);+ }+ }}+ >+ <SelectTrigger className="w-full sm:w-40" aria-label="Theme preference">+ <SelectValue>+ {THEME_OPTIONS.find((option) => option.value === theme)?.label ?? "System"}+ </SelectValue>+ </SelectTrigger>+ <SelectPopup align="end" alignItemWithTrigger={false}>+ {THEME_OPTIONS.map((option) => (+ <SelectItem hideIndicator key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ }+ />++ <SettingsRow+ title="Time format"+ description="System default follows your browser or OS clock preference."+ resetAction={+ settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? (+ <SettingResetButton+ label="time format"+ onClick={() =>+ updateSettings({+ timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,+ })+ }+ />+ ) : null+ }+ control={+ <Select+ value={settings.timestampFormat}+ onValueChange={(value) => {+ if (value === "locale" || value === "12-hour" || value === "24-hour") {+ updateSettings({ timestampFormat: value });+ }+ }}+ >+ <SelectTrigger className="w-full sm:w-40" aria-label="Timestamp format">+ <SelectValue>{TIMESTAMP_FORMAT_LABELS[settings.timestampFormat]}</SelectValue>+ </SelectTrigger>+ <SelectPopup align="end" alignItemWithTrigger={false}>+ <SelectItem hideIndicator value="locale">+ {TIMESTAMP_FORMAT_LABELS.locale}+ </SelectItem>+ <SelectItem hideIndicator value="12-hour">+ {TIMESTAMP_FORMAT_LABELS["12-hour"]}+ </SelectItem>+ <SelectItem hideIndicator value="24-hour">+ {TIMESTAMP_FORMAT_LABELS["24-hour"]}+ </SelectItem>+ </SelectPopup>+ </Select>+ }+ />++ <SettingsRow+ title="Diff line wrapping"+ description="Set the default wrap state when the diff panel opens."+ resetAction={+ settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap ? (+ <SettingResetButton+ label="diff line wrapping"+ onClick={() =>+ updateSettings({+ diffWordWrap: DEFAULT_UNIFIED_SETTINGS.diffWordWrap,+ })+ }+ />+ ) : null+ }+ control={+ <Switch+ checked={settings.diffWordWrap}+ onCheckedChange={(checked) => updateSettings({ diffWordWrap: Boolean(checked) })}+ aria-label="Wrap diff lines by default"+ />+ }+ />++ <SettingsRow+ title="Assistant output"+ description="Show token-by-token output while a response is in progress."+ resetAction={+ settings.enableAssistantStreaming !==+ DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? (+ <SettingResetButton+ label="assistant output"+ onClick={() =>+ updateSettings({+ enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,+ })+ }+ />+ ) : null+ }+ control={+ <Switch+ checked={settings.enableAssistantStreaming}+ onCheckedChange={(checked) =>+ updateSettings({ enableAssistantStreaming: Boolean(checked) })+ }+ aria-label="Stream assistant messages"+ />+ }+ />++ <SettingsRow+ title="New threads"+ description="Pick the default workspace mode for newly created draft threads."+ resetAction={+ settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ? (+ <SettingResetButton+ label="new threads"+ onClick={() =>+ updateSettings({+ defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,+ })+ }+ />+ ) : null+ }+ control={+ <Select+ value={settings.defaultThreadEnvMode}+ onValueChange={(value) => {+ if (value === "local" || value === "worktree") {+ updateSettings({ defaultThreadEnvMode: value });+ }+ }}+ >+ <SelectTrigger className="w-full sm:w-44" aria-label="Default thread mode">+ <SelectValue>+ {settings.defaultThreadEnvMode === "worktree" ? "New worktree" : "Local"}+ </SelectValue>+ </SelectTrigger>+ <SelectPopup align="end" alignItemWithTrigger={false}>+ <SelectItem hideIndicator value="local">+ Local+ </SelectItem>+ <SelectItem hideIndicator value="worktree">+ New worktree+ </SelectItem>+ </SelectPopup>+ </Select>+ }+ />++ <SettingsRow+ title="Archive confirmation"+ description="Require a second click on the inline archive action before a thread is archived."+ resetAction={+ settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive ? (+ <SettingResetButton+ label="archive confirmation"+ onClick={() =>+ updateSettings({+ confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,+ })+ }+ />+ ) : null+ }+ control={+ <Switch+ checked={settings.confirmThreadArchive}+ onCheckedChange={(checked) =>+ updateSettings({ confirmThreadArchive: Boolean(checked) })+ }+ aria-label="Confirm thread archiving"+ />+ }+ />++ <SettingsRow+ title="Delete confirmation"+ description="Ask before deleting a thread and its chat history."+ resetAction={+ settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete ? (+ <SettingResetButton+ label="delete confirmation"+ onClick={() =>+ updateSettings({+ confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete,+ })+ }+ />+ ) : null+ }+ control={+ <Switch+ checked={settings.confirmThreadDelete}+ onCheckedChange={(checked) =>+ updateSettings({ confirmThreadDelete: Boolean(checked) })+ }+ aria-label="Confirm thread deletion"+ />+ }+ />++ <SettingsRow+ title="Text generation model"+ description="Configure the model used for generated commit messages, PR titles, and similar Git text."+ resetAction={+ isGitWritingModelDirty ? (+ <SettingResetButton+ label="text generation model"+ onClick={() =>+ updateSettings({+ textGenerationModelSelection:+ DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,+ })+ }+ />+ ) : null+ }+ control={+ <div className="flex flex-wrap items-center justify-end gap-1.5">+ <ProviderModelPicker+ provider={textGenProvider}+ model={textGenModel}+ lockedProvider={null}+ providers={serverProviders}+ modelOptionsByProvider={gitModelOptionsByProvider}+ triggerVariant="outline"+ triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"+ onProviderModelChange={(provider, model) => {+ updateSettings({+ textGenerationModelSelection: resolveAppModelSelectionState(+ {+ ...settings,+ textGenerationModelSelection: { provider, model },+ },+ serverProviders,+ ),+ });+ }}+ />+ <TraitsPicker+ provider={textGenProvider}+ models={+ serverProviders.find((provider) => provider.provider === textGenProvider)+ ?.models ?? []+ }+ model={textGenModel}+ prompt=""+ onPromptChange={() => {}}+ modelOptions={textGenModelOptions}+ allowPromptInjectedEffort={false}+ triggerVariant="outline"+ triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"+ onModelOptionsChange={(nextOptions) => {+ updateSettings({+ textGenerationModelSelection: resolveAppModelSelectionState(+ {+ ...settings,+ textGenerationModelSelection: {+ provider: textGenProvider,+ model: textGenModel,+ ...(nextOptions ? { options: nextOptions } : {}),+ },+ },+ serverProviders,+ ),+ });+ }}+ />+ </div>+ }+ />+ </SettingsSection>++ <SettingsSection+ title="Providers"+ headerAction={+ <div className="flex items-center gap-1.5">+ <ProviderLastChecked lastCheckedAt={lastCheckedAt} />+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ size="icon-xs"+ variant="ghost"+ className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"+ disabled={isRefreshingProviders}+ onClick={() => void refreshProviders()}+ aria-label="Refresh provider status"+ >+ {isRefreshingProviders ? (+ <LoaderIcon className="size-3 animate-spin" />+ ) : (+ <RefreshCwIcon className="size-3" />+ )}+ </Button>+ }+ />+ <TooltipPopup side="top">Refresh provider status</TooltipPopup>+ </Tooltip>+ </div>+ }+ >+ {providerCards.map((providerCard) => {+ const customModelInput = customModelInputByProvider[providerCard.provider];+ const customModelError = customModelErrorByProvider[providerCard.provider] ?? null;+ const providerDisplayName =+ PROVIDER_DISPLAY_NAMES[providerCard.provider] ?? providerCard.title;++ return (+ <div key={providerCard.provider} className="border-t border-border first:border-t-0">+ <div className="px-4 py-4 sm:px-5">+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <div className="min-w-0 flex-1 space-y-1">+ <div className="flex min-h-5 items-center gap-1.5">+ <span+ className={cn("size-2 shrink-0 rounded-full", providerCard.statusStyle.dot)}+ />+ <h3 className="text-sm font-medium text-foreground">{providerDisplayName}</h3>+ {providerCard.versionLabel ? (+ <code className="text-xs text-muted-foreground">+ {providerCard.versionLabel}+ </code>+ ) : null}+ <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">+ {providerCard.isDirty ? (+ <SettingResetButton+ label={`${providerDisplayName} provider settings`}+ onClick={() => {+ updateSettings({+ providers: {+ ...settings.providers,+ [providerCard.provider]:+ DEFAULT_UNIFIED_SETTINGS.providers[providerCard.provider],+ },+ });+ setCustomModelErrorByProvider((existing) => ({+ ...existing,+ [providerCard.provider]: null,+ }));+ }}+ />+ ) : null}+ </span>+ </div>+ <p className="text-xs text-muted-foreground">+ {providerCard.summary.headline}+ {providerCard.summary.detail ? ` - ${providerCard.summary.detail}` : null}+ </p>+ </div>+ <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">+ <Button+ size="sm"+ variant="ghost"+ className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"+ onClick={() =>+ setOpenProviderDetails((existing) => ({+ ...existing,+ [providerCard.provider]: !existing[providerCard.provider],+ }))+ }+ aria-label={`Toggle ${providerDisplayName} details`}+ >+ <ChevronDownIcon+ className={cn(+ "size-3.5 transition-transform",+ openProviderDetails[providerCard.provider] && "rotate-180",+ )}+ />+ </Button>+ <Switch+ checked={providerCard.providerConfig.enabled}+ onCheckedChange={(checked) => {+ const isDisabling = !checked;+ const shouldClearModelSelection =+ isDisabling && textGenProvider === providerCard.provider;+ updateSettings({+ providers: {+ ...settings.providers,+ [providerCard.provider]: {+ ...settings.providers[providerCard.provider],+ enabled: Boolean(checked),+ },+ },+ ...(shouldClearModelSelection+ ? {+ textGenerationModelSelection:+ DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,+ }+ : {}),+ });+ }}+ aria-label={`Enable ${providerDisplayName}`}+ />+ </div>+ </div>+ </div>++ <Collapsible+ open={openProviderDetails[providerCard.provider]}+ onOpenChange={(open) =>+ setOpenProviderDetails((existing) => ({+ ...existing,+ [providerCard.provider]: open,+ }))+ }+ >+ <CollapsibleContent>+ <div className="space-y-0">+ <div className="border-t border-border/60 px-4 py-3 sm:px-5">+ <label+ htmlFor={`provider-install-${providerCard.provider}-binary-path`}+ className="block"+ >+ <span className="text-xs font-medium text-foreground">+ {providerDisplayName} binary path+ </span>+ <Input+ id={`provider-install-${providerCard.provider}-binary-path`}+ className="mt-1.5"+ value={providerCard.binaryPathValue}+ onChange={(event) =>+ updateSettings({+ providers: {+ ...settings.providers,+ [providerCard.provider]: {+ ...settings.providers[providerCard.provider],+ binaryPath: event.target.value,+ },+ },+ })+ }+ placeholder={providerCard.binaryPlaceholder}+ spellCheck={false}+ />+ <span className="mt-1 block text-xs text-muted-foreground">+ {providerCard.binaryDescription}+ </span>+ </label>+ </div>++ {providerCard.homePathKey ? (+ <div className="border-t border-border/60 px-4 py-3 sm:px-5">+ <label+ htmlFor={`provider-install-${providerCard.homePathKey}`}+ className="block"+ >+ <span className="text-xs font-medium text-foreground">+ CODEX_HOME path+ </span>+ <Input+ id={`provider-install-${providerCard.homePathKey}`}+ className="mt-1.5"+ value={codexHomePath}+ onChange={(event) =>+ updateSettings({+ providers: {+ ...settings.providers,+ codex: {+ ...settings.providers.codex,+ homePath: event.target.value,+ },+ },+ })+ }+ placeholder={providerCard.homePlaceholder}+ spellCheck={false}+ />+ {providerCard.homeDescription ? (+ <span className="mt-1 block text-xs text-muted-foreground">+ {providerCard.homeDescription}+ </span>+ ) : null}+ </label>+ </div>+ ) : null}++ <div className="border-t border-border/60 px-4 py-3 sm:px-5">+ <div className="text-xs font-medium text-foreground">Models</div>+ <div className="mt-1 text-xs text-muted-foreground">+ {providerCard.models.length} model+ {providerCard.models.length === 1 ? "" : "s"} available.+ </div>+ <div+ ref={(el) => {+ modelListRefs.current[providerCard.provider] = el;+ }}+ className="mt-2 max-h-40 overflow-y-auto pb-1"+ >+ {providerCard.models.map((model) => {+ const caps = model.capabilities;+ const capLabels: string[] = [];+ if (caps?.supportsFastMode) capLabels.push("Fast mode");+ if (caps?.supportsThinkingToggle) capLabels.push("Thinking");+ if (+ caps?.reasoningEffortLevels &&+ caps.reasoningEffortLevels.length > 0+ ) {+ capLabels.push("Reasoning");+ }+ const hasDetails = capLabels.length > 0 || model.name !== model.slug;++ return (+ <div+ key={`${providerCard.provider}:${model.slug}`}+ className="flex items-center gap-2 py-1"+ >+ <span className="min-w-0 truncate text-xs text-foreground/90">+ {model.name}+ </span>+ {hasDetails ? (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ className="shrink-0 text-muted-foreground/40 transition-colors hover:text-muted-foreground"+ aria-label={`Details for ${model.name}`}+ />+ }+ >+ <InfoIcon className="size-3" />+ </TooltipTrigger>+ <TooltipPopup side="top" className="max-w-56">+ <div className="space-y-1">+ <code className="block text-[11px] text-foreground">+ {model.slug}+ </code>+ {capLabels.length > 0 ? (+ <div className="flex flex-wrap gap-x-2 gap-y-0.5">+ {capLabels.map((label) => (+ <span+ key={label}+ className="text-[10px] text-muted-foreground"+ >+ {label}+ </span>+ ))}+ </div>+ ) : null}+ </div>+ </TooltipPopup>+ </Tooltip>+ ) : null}+ {model.isCustom ? (+ <div className="ml-auto flex shrink-0 items-center gap-1.5">+ <span className="text-[10px] text-muted-foreground">custom</span>+ <button+ type="button"+ className="text-muted-foreground transition-colors hover:text-foreground"+ aria-label={`Remove ${model.slug}`}+ onClick={() =>+ removeCustomModel(providerCard.provider, model.slug)+ }+ >+ <XIcon className="size-3" />+ </button>+ </div>+ ) : null}+ </div>+ );+ })}+ </div>++ <div className="mt-3 flex flex-col gap-2 sm:flex-row">+ <Input+ id={`custom-model-${providerCard.provider}`}+ value={customModelInput}+ onChange={(event) => {+ const value = event.target.value;+ setCustomModelInputByProvider((existing) => ({+ ...existing,+ [providerCard.provider]: value,+ }));+ if (customModelError) {+ setCustomModelErrorByProvider((existing) => ({+ ...existing,+ [providerCard.provider]: null,+ }));+ }+ }}+ onKeyDown={(event) => {+ if (event.key !== "Enter") return;+ event.preventDefault();+ addCustomModel(providerCard.provider);+ }}+ placeholder={+ providerCard.provider === "codex"+ ? "gpt-6.7-codex-ultra-preview"+ : "claude-sonnet-5-0"+ }+ spellCheck={false}+ />+ <Button+ className="shrink-0"+ variant="outline"+ onClick={() => addCustomModel(providerCard.provider)}+ >+ <PlusIcon className="size-3.5" />+ Add+ </Button>+ </div>++ {customModelError ? (+ <p className="mt-2 text-xs text-destructive">{customModelError}</p>+ ) : null}+ </div>+ </div>+ </CollapsibleContent>+ </Collapsible>+ </div>+ );+ })}+ </SettingsSection>++ <SettingsSection title="Advanced">+ <SettingsRow+ title="Keybindings"+ description="Open the persisted `keybindings.json` file to edit advanced bindings directly."+ status={+ <>+ <span className="block break-all font-mono text-[11px] text-foreground">+ {keybindingsConfigPath ?? "Resolving keybindings path..."}+ </span>+ {openKeybindingsError ? (+ <span className="mt-1 block text-destructive">{openKeybindingsError}</span>+ ) : (+ <span className="mt-1 block">Opens in your preferred editor.</span>+ )}+ </>+ }+ control={+ <Button+ size="xs"+ variant="outline"+ disabled={!keybindingsConfigPath || isOpeningKeybindings}+ onClick={openKeybindingsFile}+ >+ {isOpeningKeybindings ? "Opening..." : "Open file"}+ </Button>+ }+ />++ <SettingsRow+ title="Version"+ description="Current application version."+ control={<code className="text-xs font-medium text-muted-foreground">{APP_VERSION}</code>}+ />+ </SettingsSection>+ </SettingsPageContainer>+ );+}++export function ArchivedThreadsPanel() {+ const projects = useStore((store) => store.projects);+ const threads = useStore((store) => store.threads);+ const { unarchiveThread, confirmAndDeleteThread } = useThreadActions();+ const archivedGroups = useMemo(() => {+ const projectById = new Map(projects.map((project) => [project.id, project] as const));+ return [...projectById.values()]+ .map((project) => ({+ project,+ threads: threads+ .filter((thread) => thread.projectId === project.id && thread.archivedAt !== null)+ .toSorted((left, right) => {+ const leftKey = left.archivedAt ?? left.createdAt;+ const rightKey = right.archivedAt ?? right.createdAt;+ return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id);+ }),+ }))+ .filter((group) => group.threads.length > 0);+ }, [projects, threads]);++ const handleArchivedThreadContextMenu = useCallback(+ async (threadId: ThreadId, position: { x: number; y: number }) => {+ const api = readNativeApi();+ if (!api) return;+ const clicked = await api.contextMenu.show(+ [+ { id: "unarchive", label: "Unarchive" },+ { id: "delete", label: "Delete", destructive: true },+ ],+ position,+ );++ if (clicked === "unarchive") {+ try {+ await unarchiveThread(threadId);+ } catch (error) {+ toastManager.add({+ type: "error",+ title: "Failed to unarchive thread",+ description: error instanceof Error ? error.message : "An error occurred.",+ });+ }+ return;+ }++ if (clicked === "delete") {+ await confirmAndDeleteThread(threadId);+ }+ },+ [confirmAndDeleteThread, unarchiveThread],+ );++ return (+ <SettingsPageContainer>+ {archivedGroups.length === 0 ? (+ <SettingsSection title="Archived threads">+ <Empty className="min-h-[22rem]">+ <EmptyMedia variant="icon">+ <ArchiveIcon />+ </EmptyMedia>+ <EmptyHeader>+ <EmptyTitle>No archived threads</EmptyTitle>+ <EmptyDescription>Archived threads will appear here.</EmptyDescription>+ </EmptyHeader>+ </Empty>+ </SettingsSection>+ ) : (+ archivedGroups.map(({ project, threads: projectThreads }) => (+ <SettingsSection+ key={project.id}+ title={project.name}+ icon={<ProjectFavicon cwd={project.cwd} />}+ >+ {projectThreads.map((thread) => (+ <div+ key={thread.id}+ className="flex items-center justify-between gap-3 border-t border-border px-4 py-3 first:border-t-0 sm:px-5"+ onContextMenu={(event) => {+ event.preventDefault();+ void handleArchivedThreadContextMenu(thread.id, {+ x: event.clientX,+ y: event.clientY,+ });+ }}+ >+ <div className="min-w-0 flex-1">+ <h3 className="truncate text-sm font-medium text-foreground">{thread.title}</h3>+ <p className="text-xs text-muted-foreground">+ Archived {formatRelativeTimeLabel(thread.archivedAt ?? thread.createdAt)}+ {" \u00b7 Created "}+ {formatRelativeTimeLabel(thread.createdAt)}+ </p>+ </div>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="h-7 shrink-0 cursor-pointer gap-1.5 px-2.5"+ onClick={() =>+ void unarchiveThread(thread.id).catch((error) => {+ toastManager.add({+ type: "error",+ title: "Failed to unarchive thread",+ description: error instanceof Error ? error.message : "An error occurred.",+ });+ })+ }+ >+ <ArchiveX className="size-3.5" />+ <span>Unarchive</span>+ </Button>+ </div>+ ))}+ </SettingsSection>+ ))+ )}+ </SettingsPageContainer>+ );+}diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsxnew file mode 100644index 000000000..ffca1e209--- /dev/null+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx@@ -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>+ </>+ );+}diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.tsindex 63cdef848..9fd1a1295 100644--- a/apps/web/src/contextMenuFallback.ts+++ b/apps/web/src/contextMenuFallback.ts@@ -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);}diff --git a/apps/web/src/hooks/useSettings.test.ts b/apps/web/src/hooks/useSettings.test.tsnew file mode 100644index 000000000..832ee17f7--- /dev/null+++ b/apps/web/src/hooks/useSettings.test.ts@@ -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,+ });+ });+});diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.tsindex addf550e3..3f804bc48 100644--- a/apps/web/src/hooks/useSettings.ts+++ b/apps/web/src/hooks/useSettings.ts@@ -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;}diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.tsnew file mode 100644index 000000000..83cfe911f--- /dev/null+++ b/apps/web/src/hooks/useThreadActions.ts@@ -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,+ };+}diff --git a/apps/web/src/lib/storage.ts b/apps/web/src/lib/storage.tsindex eeb3a03a8..a37c67064 100644--- a/apps/web/src/lib/storage.ts+++ b/apps/web/src/lib/storage.ts@@ -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();diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.tsindex 880d5ef64..77b1b1584 100644--- a/apps/web/src/routeTree.gen.ts+++ b/apps/web/src/routeTree.gen.ts@@ -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 ChatIndexRouteImportparentRoute: 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 ChatSettingsRouteChatIndexRoute: 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)diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsxindex 5ebed20fb..e99ec5022 100644--- a/apps/web/src/routes/__root.tsx+++ b/apps/web/src/routes/__root.tsx@@ -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>);diff --git a/apps/web/src/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsxdeleted file mode 100644index 3e92891a5..000000000--- a/apps/web/src/routes/_chat.settings.tsx+++ /dev/null@@ -1,1313 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";-import { useQuery, useQueryClient } from "@tanstack/react-query";-import {- ChevronDownIcon,- InfoIcon,- LoaderIcon,- PlusIcon,- RefreshCwIcon,- RotateCcwIcon,- Undo2Icon,- XIcon,-} from "lucide-react";-import { type ReactNode, useCallback, useEffect, useRef, useState } from "react";-import {- PROVIDER_DISPLAY_NAMES,- type ProviderKind,- type ServerProvider,- type ServerProviderModel,-} from "@t3tools/contracts";-import { normalizeModelSlug } from "@t3tools/shared/model";-import { useSettings, useUpdateSettings } from "../hooks/useSettings";-import {- getCustomModelOptionsByProvider,- MAX_CUSTOM_MODEL_LENGTH,- resolveAppModelSelectionState,-} from "../modelSelection";-import { APP_VERSION } from "../branding";-import { Button } from "../components/ui/button";-import { Collapsible, CollapsibleContent } from "../components/ui/collapsible";-import { Input } from "../components/ui/input";-import {- Select,- SelectItem,- SelectPopup,- SelectTrigger,- SelectValue,-} from "../components/ui/select";-import { SidebarTrigger } from "../components/ui/sidebar";-import { Switch } from "../components/ui/switch";-import { ProviderModelPicker } from "../components/chat/ProviderModelPicker";-import { TraitsPicker } from "../components/chat/TraitsPicker";-import { SidebarInset } from "../components/ui/sidebar";-import { Tooltip, TooltipPopup, TooltipTrigger } from "../components/ui/tooltip";-import { resolveAndPersistPreferredEditor } from "../editorPreferences";-import { isElectron } from "../env";-import { useTheme } from "../hooks/useTheme";-import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";-import { cn } from "../lib/utils";-import { formatRelativeTime } from "../timestampFormat";-import { ensureNativeApi, readNativeApi } from "../nativeApi";-import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";-import { Equal } from "effect";--const THEME_OPTIONS = [- {- value: "system",- label: "System",- description: "Match your OS appearance setting.",- },- {- value: "light",- label: "Light",- description: "Always use the light theme.",- },- {- value: "dark",- label: "Dark",- description: "Always use the dark theme.",- },-] as const;--const TIMESTAMP_FORMAT_LABELS = {- locale: "System default",- "12-hour": "12-hour",- "24-hour": "24-hour",-} as const;--const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];--type InstallProviderSettings = {- provider: ProviderKind;- title: string;- binaryPlaceholder: string;- binaryDescription: ReactNode;- homePathKey?: "codexHomePath";- homePlaceholder?: string;- homeDescription?: ReactNode;-};--const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [- {- provider: "codex",- title: "Codex",- binaryPlaceholder: "Codex binary path",- binaryDescription: "Path to the Codex binary",- homePathKey: "codexHomePath",- homePlaceholder: "CODEX_HOME",- homeDescription: "Optional custom Codex home and config directory.",- },- {- provider: "claudeAgent",- title: "Claude",- binaryPlaceholder: "Claude binary path",- binaryDescription: "Path to the Claude binary",- },-];--const PROVIDER_STATUS_STYLES = {- disabled: {- dot: "bg-amber-400",- badge: "warning" as const,- },- error: {- dot: "bg-destructive",- badge: "error" as const,- },- ready: {- dot: "bg-success",- badge: "success" as const,- },- warning: {- dot: "bg-warning",- badge: "warning" as const,- },-} as const;--function getProviderSummary(provider: ServerProvider | undefined): {- readonly headline: string;- readonly detail: string | null;-} {- if (!provider) {- return {- headline: "Checking provider status",- detail: "Waiting for the server to report installation and authentication details.",- };- }- if (!provider.enabled) {- return {- headline: "Disabled",- detail:- provider.message ?? "This provider is installed but disabled for new sessions in T3 Code.",- };- }- if (!provider.installed) {- return {- headline: "Not found",- detail: provider.message ?? "CLI not detected on PATH.",- };- }- if (provider.authStatus === "authenticated") {- return {- headline: "Authenticated",- detail: provider.message ?? null,- };- }- if (provider.authStatus === "unauthenticated") {- return {- headline: "Not authenticated",- detail: provider.message ?? null,- };- }- if (provider.status === "warning") {- return {- headline: "Needs attention",- detail:- provider.message ?? "The provider is installed, but the server could not fully verify it.",- };- }- if (provider.status === "error") {- return {- headline: "Unavailable",- detail: provider.message ?? "The provider failed its startup checks.",- };- }- return {- headline: "Available",- detail: provider.message ?? "Installed and ready, but authentication could not be verified.",- };-}--function getProviderVersionLabel(version: string | null | undefined): string | null {- if (!version) return null;- return version.startsWith("v") ? version : `v${version}`;-}--/** Returns a timestamp that updates on an interval, forcing re-renders to keep relative times fresh. */-function useRelativeTimeTick(intervalMs = 1_000): number {- const [tick, setTick] = useState(() => Date.now());- useEffect(() => {- const id = setInterval(() => setTick(Date.now()), intervalMs);- return () => clearInterval(id);- }, [intervalMs]);- return tick;-}--function SettingsSection({- title,- headerAction,- children,-}: {- title: string;- headerAction?: ReactNode;- children: ReactNode;-}) {- return (- <section className="space-y-3">- <div className="flex items-center justify-between">- <h2 className="text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground">- {title}- </h2>- {headerAction}- </div>- <div className="relative overflow-hidden rounded-2xl border bg-card not-dark:bg-clip-padding text-card-foreground shadow-xs/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]">- {children}- </div>- </section>- );-}--function SettingsRow({- title,- description,- status,- resetAction,- control,- children,-}: {- title: string;- description: string;- status?: ReactNode;- resetAction?: ReactNode;- control?: ReactNode;- children?: ReactNode;-}) {- return (- <div- className="border-t border-border px-4 py-4 first:border-t-0 sm:px-5"- data-slot="settings-row"- >- <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">- <div className="min-w-0 flex-1 space-y-1">- <div className="flex min-h-5 items-center gap-1.5">- <h3 className="text-sm font-medium text-foreground">{title}</h3>- <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">- {resetAction}- </span>- </div>- <p className="text-xs text-muted-foreground">{description}</p>- {status ? <div className="pt-1 text-[11px] text-muted-foreground">{status}</div> : null}- </div>- {control ? (- <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">- {control}- </div>- ) : null}- </div>- {children}- </div>- );-}--function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) {- return (- <Tooltip>- <TooltipTrigger- render={- <Button- size="icon-xs"- variant="ghost"- aria-label={`Reset ${label} to default`}- className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"- onClick={(event) => {- event.stopPropagation();- onClick();- }}- >- <Undo2Icon className="size-3" />- </Button>- }- />- <TooltipPopup side="top">Reset to default</TooltipPopup>- </Tooltip>- );-}--function SettingsRouteView() {- const { theme, setTheme } = useTheme();- const settings = useSettings();- const { updateSettings, resetSettings } = useUpdateSettings();- const serverConfigQuery = useQuery(serverConfigQueryOptions());- const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);- const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);- const [openProviderDetails, setOpenProviderDetails] = useState<Record<ProviderKind, boolean>>({- codex: Boolean(- settings.providers.codex.binaryPath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.binaryPath ||- settings.providers.codex.homePath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.homePath ||- settings.providers.codex.customModels.length > 0,- ),- claudeAgent: Boolean(- settings.providers.claudeAgent.binaryPath !==- DEFAULT_UNIFIED_SETTINGS.providers.claudeAgent.binaryPath ||- settings.providers.claudeAgent.customModels.length > 0,- ),- });- const [customModelInputByProvider, setCustomModelInputByProvider] = useState<- Record<ProviderKind, string>- >({- codex: "",- claudeAgent: "",- });- const [customModelErrorByProvider, setCustomModelErrorByProvider] = useState<- Partial<Record<ProviderKind, string | null>>- >({});- const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);- const refreshingRef = useRef(false);- const queryClient = useQueryClient();- useRelativeTimeTick();-- const refreshProviders = useCallback(() => {- if (refreshingRef.current) return;- refreshingRef.current = true;- setIsRefreshingProviders(true);- const api = ensureNativeApi();- api.server- .refreshProviders()- .then(() => queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() }))- .catch((error: unknown) => {- console.warn("Failed to refresh providers", error);- })- .finally(() => {- refreshingRef.current = false;- setIsRefreshingProviders(false);- });- }, [queryClient]);-- const modelListRefs = useRef<Partial<Record<ProviderKind, HTMLDivElement | null>>>({});-- const codexHomePath = settings.providers.codex.homePath;- const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;- const availableEditors = serverConfigQuery.data?.availableEditors;- const serverProviders = serverConfigQuery.data?.providers ?? EMPTY_SERVER_PROVIDERS;-- const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);- const textGenProvider = textGenerationModelSelection.provider;- const textGenModel = textGenerationModelSelection.model;- const textGenModelOptions = textGenerationModelSelection.options;- const gitModelOptionsByProvider = getCustomModelOptionsByProvider(- settings,- serverProviders,- textGenProvider,- textGenModel,- );- const areProviderSettingsDirty = PROVIDER_SETTINGS.some((providerSettings) => {- const currentSettings = settings.providers[providerSettings.provider];- const defaultSettings = DEFAULT_UNIFIED_SETTINGS.providers[providerSettings.provider];- return !Equal.equals(currentSettings, defaultSettings);- });- const isGitWritingModelDirty = !Equal.equals(- settings.textGenerationModelSelection ?? null,- DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,- );- const changedSettingLabels = [- ...(theme !== "system" ? ["Theme"] : []),- ...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat- ? ["Time format"]- : []),- ...(settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap- ? ["Diff line wrapping"]- : []),- ...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming- ? ["Assistant output"]- : []),- ...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode- ? ["New thread mode"]- : []),- ...(settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete- ? ["Delete confirmation"]- : []),- ...(isGitWritingModelDirty ? ["Git writing model"] : []),- ...(areProviderSettingsDirty ? ["Providers"] : []),- ];-- const openKeybindingsFile = useCallback(() => {- if (!keybindingsConfigPath) return;- setOpenKeybindingsError(null);- setIsOpeningKeybindings(true);- const api = ensureNativeApi();- const editor = resolveAndPersistPreferredEditor(availableEditors ?? []);- if (!editor) {- setOpenKeybindingsError("No available editors found.");- setIsOpeningKeybindings(false);- return;- }- void api.shell- .openInEditor(keybindingsConfigPath, editor)- .catch((error) => {- setOpenKeybindingsError(- error instanceof Error ? error.message : "Unable to open keybindings file.",- );- })- .finally(() => {- setIsOpeningKeybindings(false);- });- }, [availableEditors, keybindingsConfigPath]);-- const addCustomModel = useCallback(- (provider: ProviderKind) => {- const customModelInput = customModelInputByProvider[provider];- const customModels = settings.providers[provider].customModels;- const normalized = normalizeModelSlug(customModelInput, provider);- if (!normalized) {- setCustomModelErrorByProvider((existing) => ({- ...existing,- [provider]: "Enter a model slug.",- }));- return;- }- if (- serverProviders- .find((candidate) => candidate.provider === provider)- ?.models.some((option) => !option.isCustom && option.slug === normalized)- ) {- setCustomModelErrorByProvider((existing) => ({- ...existing,- [provider]: "That model is already built in.",- }));- return;- }- if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) {- setCustomModelErrorByProvider((existing) => ({- ...existing,- [provider]: `Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`,- }));- return;- }- if (customModels.includes(normalized)) {- setCustomModelErrorByProvider((existing) => ({- ...existing,- [provider]: "That custom model is already saved.",- }));- return;- }-- updateSettings({- providers: {- ...settings.providers,- [provider]: {- ...settings.providers[provider],- customModels: [...customModels, normalized],- },- },- });- setCustomModelInputByProvider((existing) => ({- ...existing,- [provider]: "",- }));- setCustomModelErrorByProvider((existing) => ({- ...existing,- [provider]: null,- }));- // Watch for DOM changes (server may push updated model list) and scroll to bottom- const el = modelListRefs.current[provider];- if (el) {- const scrollToEnd = () => el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });- // Immediate scroll for the optimistic update- requestAnimationFrame(scrollToEnd);- // Also observe mutations for when the server pushes an updated list- const observer = new MutationObserver(() => {- scrollToEnd();- observer.disconnect();- });- observer.observe(el, { childList: true, subtree: true });- // Clean up observer after a reasonable window- setTimeout(() => observer.disconnect(), 2000);- }- },- [customModelInputByProvider, serverProviders, settings, updateSettings],- );-- const removeCustomModel = useCallback(- (provider: ProviderKind, slug: string) => {- const customModels = settings.providers[provider].customModels;- updateSettings({- providers: {- ...settings.providers,- [provider]: {- ...settings.providers[provider],- customModels: customModels.filter((model) => model !== slug),- },- },- });- setCustomModelErrorByProvider((existing) => ({- ...existing,- [provider]: null,- }));- },- [settings, updateSettings],- );-- const providerCards = PROVIDER_SETTINGS.map((providerSettings) => {- const liveProvider = serverProviders.find(- (candidate) => candidate.provider === providerSettings.provider,- );- const providerConfig = settings.providers[providerSettings.provider];- const defaultProviderConfig = DEFAULT_UNIFIED_SETTINGS.providers[providerSettings.provider];- const statusKey = liveProvider?.status ?? (providerConfig.enabled ? "warning" : "disabled");- const statusStyle = PROVIDER_STATUS_STYLES[statusKey];- const summary = getProviderSummary(liveProvider);- const models: ReadonlyArray<ServerProviderModel> =- liveProvider?.models ??- providerConfig.customModels.map((slug) => ({- slug,- name: slug,- isCustom: true,- capabilities: null,- }));- const binaryPathValue = providerConfig.binaryPath;- const isDirty = !Equal.equals(providerConfig, defaultProviderConfig);-- return {- provider: providerSettings.provider,- title: providerSettings.title,- binaryPlaceholder: providerSettings.binaryPlaceholder,- binaryDescription: providerSettings.binaryDescription,- homePathKey: providerSettings.homePathKey,- homePlaceholder: providerSettings.homePlaceholder,- homeDescription: providerSettings.homeDescription,- binaryPathValue,- isDirty,- liveProvider,- models,- providerConfig,- statusKey,- statusStyle,- summary,- versionLabel: getProviderVersionLabel(liveProvider?.version),- };- });-- async function restoreDefaults() {- if (changedSettingLabels.length === 0) return;-- const api = readNativeApi();- const confirmed = await (api ?? ensureNativeApi()).dialogs.confirm(- ["Restore default settings?", `This will reset: ${changedSettingLabels.join(", ")}.`].join(- "\n",- ),- );- if (!confirmed) return;-- setTheme("system");- resetSettings();- setOpenProviderDetails({- codex: false,- claudeAgent: false,- });- setCustomModelInputByProvider({- codex: "",- claudeAgent: "",- });- setCustomModelErrorByProvider({});- }-- 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 className="flex-1 overflow-y-auto p-6">- <div className="mx-auto flex w-full max-w-2xl flex-col gap-6">- <SettingsSection title="General">- <SettingsRow- title="Theme"- description="Choose how T3 Code looks across the app."- resetAction={- theme !== "system" ? (- <SettingResetButton label="theme" onClick={() => setTheme("system")} />- ) : null- }- control={- <Select- value={theme}- onValueChange={(value) => {- if (value !== "system" && value !== "light" && value !== "dark") return;- setTheme(value);- }}- >- <SelectTrigger className="w-full sm:w-40" aria-label="Theme preference">- <SelectValue>- {THEME_OPTIONS.find((option) => option.value === theme)?.label ?? "System"}- </SelectValue>- </SelectTrigger>- <SelectPopup align="end" alignItemWithTrigger={false}>- {THEME_OPTIONS.map((option) => (- <SelectItem hideIndicator key={option.value} value={option.value}>- {option.label}- </SelectItem>- ))}- </SelectPopup>- </Select>- }- />-- <SettingsRow- title="Time format"- description="System default follows your browser or OS clock preference."- resetAction={- settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? (- <SettingResetButton- label="time format"- onClick={() =>- updateSettings({- timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,- })- }- />- ) : null- }- control={- <Select- value={settings.timestampFormat}- onValueChange={(value) => {- if (value !== "locale" && value !== "12-hour" && value !== "24-hour") {- return;- }- updateSettings({- timestampFormat: value,- });- }}- >- <SelectTrigger className="w-full sm:w-40" aria-label="Timestamp format">- <SelectValue>{TIMESTAMP_FORMAT_LABELS[settings.timestampFormat]}</SelectValue>- </SelectTrigger>- <SelectPopup align="end" alignItemWithTrigger={false}>- <SelectItem hideIndicator value="locale">- {TIMESTAMP_FORMAT_LABELS.locale}- </SelectItem>- <SelectItem hideIndicator value="12-hour">- {TIMESTAMP_FORMAT_LABELS["12-hour"]}- </SelectItem>- <SelectItem hideIndicator value="24-hour">- {TIMESTAMP_FORMAT_LABELS["24-hour"]}- </SelectItem>- </SelectPopup>- </Select>- }- />-- <SettingsRow- title="Diff line wrapping"- description="Set the default wrap state when the diff panel opens. The in-panel wrap toggle only affects the current diff session."- resetAction={- settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap ? (- <SettingResetButton- label="diff line wrapping"- onClick={() =>- updateSettings({- diffWordWrap: DEFAULT_UNIFIED_SETTINGS.diffWordWrap,- })- }- />- ) : null- }- control={- <Switch- checked={settings.diffWordWrap}- onCheckedChange={(checked) =>- updateSettings({- diffWordWrap: Boolean(checked),- })- }- aria-label="Wrap diff lines by default"- />- }- />-- <SettingsRow- title="Assistant output"- description="Show token-by-token output while a response is in progress."- resetAction={- settings.enableAssistantStreaming !==- DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? (- <SettingResetButton- label="assistant output"- onClick={() =>- updateSettings({- enableAssistantStreaming:- DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,- })- }- />- ) : null- }- control={- <Switch- checked={settings.enableAssistantStreaming}- onCheckedChange={(checked) =>- updateSettings({- enableAssistantStreaming: Boolean(checked),- })- }- aria-label="Stream assistant messages"- />- }- />-- <SettingsRow- title="New threads"- description="Pick the default workspace mode for newly created draft threads."- resetAction={- settings.defaultThreadEnvMode !==- DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ? (- <SettingResetButton- label="new threads"- onClick={() =>- updateSettings({- defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode,- })- }- />- ) : null- }- control={- <Select- value={settings.defaultThreadEnvMode}- onValueChange={(value) => {- if (value !== "local" && value !== "worktree") return;- updateSettings({- defaultThreadEnvMode: value,- });- }}- >- <SelectTrigger className="w-full sm:w-44" aria-label="Default thread mode">- <SelectValue>- {settings.defaultThreadEnvMode === "worktree" ? "New worktree" : "Local"}- </SelectValue>- </SelectTrigger>- <SelectPopup align="end" alignItemWithTrigger={false}>- <SelectItem hideIndicator value="local">- Local- </SelectItem>- <SelectItem hideIndicator value="worktree">- New worktree- </SelectItem>- </SelectPopup>- </Select>- }- />-- <SettingsRow- title="Delete confirmation"- description="Ask before deleting a thread and its chat history."- resetAction={- settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete ? (- <SettingResetButton- label="delete confirmation"- onClick={() =>- updateSettings({- confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete,- })- }- />- ) : null- }- control={- <Switch- checked={settings.confirmThreadDelete}- onCheckedChange={(checked) =>- updateSettings({- confirmThreadDelete: Boolean(checked),- })- }- aria-label="Confirm thread deletion"- />- }- />- <SettingsRow- title="Text generation model"- description="Configure the model used for text generation (commit messages, PR content etc.)"- resetAction={- JSON.stringify(settings.textGenerationModelSelection ?? null) !==- JSON.stringify(DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null) ? (- <SettingResetButton- label="text generation model"- onClick={() => {- updateSettings({- textGenerationModelSelection:- DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,- });- }}- />- ) : null- }- control={- <div className="flex flex-wrap items-center justify-end gap-1.5">- <ProviderModelPicker- provider={textGenProvider}- model={textGenModel}- lockedProvider={null}- providers={serverProviders}- modelOptionsByProvider={gitModelOptionsByProvider}- triggerVariant="outline"- triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"- onProviderModelChange={(provider, model) => {- updateSettings({- textGenerationModelSelection: resolveAppModelSelectionState(- {- ...settings,- textGenerationModelSelection: { provider, model },- },- serverProviders,- ),- });- }}- />- <TraitsPicker- provider={textGenProvider}- models={- serverProviders.find((provider) => provider.provider === textGenProvider)- ?.models ?? []- }- model={textGenModel}- prompt=""- onPromptChange={() => {}}- modelOptions={textGenModelOptions}- allowPromptInjectedEffort={false}- triggerVariant="outline"- triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"- onModelOptionsChange={(nextOptions) => {- updateSettings({- textGenerationModelSelection: resolveAppModelSelectionState(- {- ...settings,- textGenerationModelSelection: {- provider: textGenProvider,- model: textGenModel,- ...(nextOptions ? { options: nextOptions } : {}),- },- },- serverProviders,- ),- });- }}- />- </div>- }- />- </SettingsSection>-- <SettingsSection- title="Providers"- headerAction={- <div className="flex items-center gap-1.5">- {serverProviders.length > 0 ? (- <span className="text-[11px] text-muted-foreground/60">- {(() => {- const rel = formatRelativeTime(- serverProviders.reduce(- (latest, provider) =>- provider.checkedAt > latest ? provider.checkedAt : latest,- serverProviders[0]!.checkedAt,- ),- );- return rel.suffix ? (- <>- Checked <span className="font-mono tabular-nums">{rel.value}</span>{" "}- {rel.suffix}- </>- ) : (- <>Checked {rel.value}</>- );- })()}- </span>- ) : null}- <Tooltip>- <TooltipTrigger- render={- <Button- size="icon-xs"- variant="ghost"- className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"- disabled={isRefreshingProviders}- onClick={() => void refreshProviders()}- aria-label="Refresh provider status"- >- {isRefreshingProviders ? (- <LoaderIcon className="size-3 animate-spin" />- ) : (- <RefreshCwIcon className="size-3" />- )}- </Button>- }- />- <TooltipPopup side="top">Refresh provider status</TooltipPopup>- </Tooltip>- </div>- }- >- {providerCards.map((providerCard) => {- const customModelInput = customModelInputByProvider[providerCard.provider];- const customModelError = customModelErrorByProvider[providerCard.provider] ?? null;- const providerDisplayName =- PROVIDER_DISPLAY_NAMES[providerCard.provider] ?? providerCard.title;-- return (- <div- key={providerCard.provider}- className="border-t border-border first:border-t-0"- data-slot="settings-row"- >- <div className="px-4 py-4 sm:px-5">- <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">- <div className="min-w-0 flex-1 space-y-1">- <div className="flex min-h-5 items-center gap-1.5">- <span- className={cn(- "size-2 shrink-0 rounded-full",- providerCard.statusStyle.dot,- )}- />- <h3 className="text-sm font-medium text-foreground">- {providerDisplayName}- </h3>- {providerCard.versionLabel ? (- <code className="text-xs text-muted-foreground">- {providerCard.versionLabel}- </code>- ) : null}- <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">- {providerCard.isDirty ? (- <SettingResetButton- label={`${providerDisplayName} provider settings`}- onClick={() => {- updateSettings({- providers: {- ...settings.providers,- [providerCard.provider]:- DEFAULT_UNIFIED_SETTINGS.providers[providerCard.provider],- },- });- setCustomModelErrorByProvider((existing) => ({- ...existing,- [providerCard.provider]: null,- }));- }}- />- ) : null}- </span>- </div>- <p className="text-xs text-muted-foreground">- {providerCard.summary.headline}- {providerCard.summary.detail- ? ` — ${providerCard.summary.detail}`- : null}- </p>- </div>- <div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">- <Button- size="sm"- variant="ghost"- className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"- onClick={() =>- setOpenProviderDetails((existing) => ({- ...existing,- [providerCard.provider]: !existing[providerCard.provider],- }))- }- aria-label={`Toggle ${providerDisplayName} details`}- >- <ChevronDownIcon- className={cn(- "size-3.5 transition-transform",- openProviderDetails[providerCard.provider] && "rotate-180",- )}- />- </Button>- <Switch- checked={providerCard.providerConfig.enabled}- onCheckedChange={(checked) => {- const isDisabling = !checked;- // The resolved provider accounts for both explicit- // selection and the implicit default (codex).- const resolvedProvider = textGenProvider;- // When disabling the provider that's currently used for- // text generation, clear the selection so it falls back to- // the next available provider's default model.- const shouldClearModelSelection =- isDisabling && resolvedProvider === providerCard.provider;- updateSettings({- providers: {- ...settings.providers,- [providerCard.provider]: {- ...settings.providers[providerCard.provider],- enabled: Boolean(checked),- },- },- ...(shouldClearModelSelection- ? {- textGenerationModelSelection:- DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,- }- : {}),- });- }}- aria-label={`Enable ${providerDisplayName}`}- />- </div>- </div>- </div>-- <Collapsible- open={openProviderDetails[providerCard.provider]}- onOpenChange={(open) =>- setOpenProviderDetails((existing) => ({- ...existing,- [providerCard.provider]: open,- }))- }- >- <CollapsibleContent>- <div className="space-y-0">- {/* Binary path */}- <div className="border-t border-border/60 px-4 py-3 sm:px-5">- <label- htmlFor={`provider-install-${providerCard.provider}-binary-path`}- className="block"- >- <span className="text-xs font-medium text-foreground">- {providerDisplayName} binary path- </span>- <Input- id={`provider-install-${providerCard.provider}-binary-path`}- className="mt-1.5"- value={providerCard.binaryPathValue}- onChange={(event) =>- updateSettings({- providers: {- ...settings.providers,- [providerCard.provider]: {- ...settings.providers[providerCard.provider],- binaryPath: event.target.value,- },- },- })- }- placeholder={providerCard.binaryPlaceholder}- spellCheck={false}- />- <span className="mt-1 block text-xs text-muted-foreground">- {providerCard.binaryDescription}- </span>- </label>- </div>-- {/* Home path (Codex only) */}- {providerCard.homePathKey ? (- <div className="border-t border-border/60 px-4 py-3 sm:px-5">- <label- htmlFor={`provider-install-${providerCard.homePathKey}`}- className="block"- >- <span className="text-xs font-medium text-foreground">- CODEX_HOME path- </span>- <Input- id={`provider-install-${providerCard.homePathKey}`}- className="mt-1.5"- value={codexHomePath}- onChange={(event) =>- updateSettings({- providers: {- ...settings.providers,- codex: {- ...settings.providers.codex,- homePath: event.target.value,- },- },- })- }- placeholder={providerCard.homePlaceholder}- spellCheck={false}- />- {providerCard.homeDescription ? (- <span className="mt-1 block text-xs text-muted-foreground">- {providerCard.homeDescription}- </span>- ) : null}- </label>- </div>- ) : null}-- {/* Models */}- <div className="border-t border-border/60 px-4 py-3 sm:px-5">- <div className="text-xs font-medium text-foreground">Models</div>- <div className="mt-1 text-xs text-muted-foreground">- {providerCard.models.length} model- {providerCard.models.length === 1 ? "" : "s"} available.- </div>- <div- ref={(el) => {- modelListRefs.current[providerCard.provider] = el;- }}- className="mt-2 max-h-40 overflow-y-auto pb-1"- >- {providerCard.models.map((model) => {- const caps = model.capabilities;- const capLabels: string[] = [];- if (caps?.supportsFastMode) capLabels.push("Fast mode");- if (caps?.supportsThinkingToggle) capLabels.push("Thinking");- if (- caps?.reasoningEffortLevels &&- caps.reasoningEffortLevels.length > 0- )- capLabels.push("Reasoning");- const hasDetails =- capLabels.length > 0 || model.name !== model.slug;-- return (- <div- key={`${providerCard.provider}:${model.slug}`}- className="flex items-center gap-2 py-1"- >- <span className="min-w-0 truncate text-xs text-foreground/90">- {model.name}- </span>- {hasDetails ? (- <Tooltip>- <TooltipTrigger- render={- <button- type="button"- className="shrink-0 text-muted-foreground/40 transition-colors hover:text-muted-foreground"- aria-label={`Details for ${model.name}`}- />- }- >- <InfoIcon className="size-3" />- </TooltipTrigger>- <TooltipPopup side="top" className="max-w-56">- <div className="space-y-1">- <code className="block text-[11px] text-foreground">- {model.slug}- </code>- {capLabels.length > 0 ? (- <div className="flex flex-wrap gap-x-2 gap-y-0.5">- {capLabels.map((label) => (- <span- key={label}- className="text-[10px] text-muted-foreground"- >- {label}- </span>- ))}- </div>- ) : null}- </div>- </TooltipPopup>- </Tooltip>- ) : null}- {model.isCustom ? (- <div className="ml-auto flex shrink-0 items-center gap-1.5">- <span className="text-[10px] text-muted-foreground">- custom- </span>- <button- type="button"- className="text-muted-foreground transition-colors hover:text-foreground"- aria-label={`Remove ${model.slug}`}- onClick={() =>- removeCustomModel(providerCard.provider, model.slug)- }- >- <XIcon className="size-3" />- </button>- </div>- ) : null}- </div>- );- })}- </div>- <div className="mt-3 flex flex-col gap-2 sm:flex-row">- <Input- id={`custom-model-${providerCard.provider}`}- value={customModelInput}- onChange={(event) => {- const value = event.target.value;- setCustomModelInputByProvider((existing) => ({- ...existing,- [providerCard.provider]: value,- }));- if (customModelError) {- setCustomModelErrorByProvider((existing) => ({- ...existing,- [providerCard.provider]: null,- }));- }- }}- onKeyDown={(event) => {- if (event.key !== "Enter") return;- event.preventDefault();- addCustomModel(providerCard.provider);- }}- placeholder={- providerCard.provider === "codex"- ? "gpt-6.7-codex-ultra-preview"- : "claude-sonnet-5-0"- }- spellCheck={false}- />- <Button- className="shrink-0"- variant="outline"- onClick={() => addCustomModel(providerCard.provider)}- >- <PlusIcon className="size-3.5" />- Add- </Button>- </div>- {customModelError ? (- <p className="mt-2 text-xs text-destructive">{customModelError}</p>- ) : null}- </div>- </div>- </CollapsibleContent>- </Collapsible>- </div>- );- })}- </SettingsSection>-- <SettingsSection title="Advanced">- <SettingsRow- title="Keybindings"- description="Open the persisted `keybindings.json` file to edit advanced bindings directly."- status={- <>- <span className="block break-all font-mono text-[11px] text-foreground">- {keybindingsConfigPath ?? "Resolving keybindings path..."}- </span>- {openKeybindingsError ? (- <span className="mt-1 block text-destructive">{openKeybindingsError}</span>- ) : (- <span className="mt-1 block">Opens in your preferred editor.</span>- )}- </>- }- control={- <Button- size="xs"- variant="outline"- disabled={!keybindingsConfigPath || isOpeningKeybindings}- onClick={openKeybindingsFile}- >- {isOpeningKeybindings ? "Opening..." : "Open file"}- </Button>- }- />-- <SettingsRow- title="Version"- description="Current application version."- control={- <code className="text-xs font-medium text-muted-foreground">{APP_VERSION}</code>- }- />- </SettingsSection>- </div>- </div>- </div>- </SidebarInset>- );-}--export const Route = createFileRoute("/_chat/settings")({- component: SettingsRouteView,-});diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsxindex 80525f556..3c86ab42f 100644--- a/apps/web/src/routes/_chat.tsx+++ b/apps/web/src/routes/_chat.tsx@@ -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 "../terminalStaimport { 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>+ </>);}diff --git a/apps/web/src/routes/settings.archived.tsx b/apps/web/src/routes/settings.archived.tsxnew file mode 100644index 000000000..3ad690afc--- /dev/null+++ b/apps/web/src/routes/settings.archived.tsx@@ -0,0 +1,7 @@+import { createFileRoute } from "@tanstack/react-router";++import { ArchivedThreadsPanel } from "../components/settings/SettingsPanels";++export const Route = createFileRoute("/settings/archived")({+ component: ArchivedThreadsPanel,+});diff --git a/apps/web/src/routes/settings.general.tsx b/apps/web/src/routes/settings.general.tsxnew file mode 100644index 000000000..7fb503e0a--- /dev/null+++ b/apps/web/src/routes/settings.general.tsx@@ -0,0 +1,7 @@+import { createFileRoute } from "@tanstack/react-router";++import { GeneralSettingsPanel } from "../components/settings/SettingsPanels";++export const Route = createFileRoute("/settings/general")({+ component: GeneralSettingsPanel,+});diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsxnew file mode 100644index 000000000..edee42673--- /dev/null+++ b/apps/web/src/routes/settings.tsx@@ -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,+});diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.tsindex 4da4f23c8..db62bad52 100644--- a/apps/web/src/store.test.ts+++ b/apps/web/src/store.test.ts@@ -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");diff --git a/apps/web/src/store.ts b/apps/web/src/store.tsindex 4590b2886..a5beb5b1b 100644--- a/apps/web/src/store.ts+++ b/apps/web/src/store.ts@@ -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,diff --git a/apps/web/src/terminalStateStore.test.ts b/apps/web/src/terminalStateStore.test.tsindex e7e240cf2..d61827568 100644--- a/apps/web/src/terminalStateStore.test.ts+++ b/apps/web/src/terminalStateStore.test.ts@@ -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: {} });});diff --git a/apps/web/src/terminalStateStore.ts b/apps/web/src/terminalStateStore.tsindex b2cea6d56..4f51e2ed8 100644--- a/apps/web/src/terminalStateStore.ts+++ b/apps/web/src/terminalStateStore.ts@@ -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,}),diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.tsindex a75ab2101..453c07016 100644--- a/apps/web/src/timestampFormat.ts+++ b/apps/web/src/timestampFormat.ts@@ -66,3 +66,8 @@ export function formatRelativeTime(isoDate: string): { value: string; suffix: stconst 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;+}diff --git a/apps/web/src/types.ts b/apps/web/src/types.tsindex de06f9553..e6cb1efea 100644--- a/apps/web/src/types.ts+++ b/apps/web/src/types.ts@@ -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;diff --git a/apps/web/src/worktreeCleanup.test.ts b/apps/web/src/worktreeCleanup.test.tsindex 574675ae1..723661ccb 100644--- a/apps/web/src/worktreeCleanup.test.ts+++ b/apps/web/src/worktreeCleanup.test.ts@@ -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,diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.tsindex 1d282ae72..0443128dd 100644--- a/packages/contracts/src/ipc.ts+++ b/packages/contracts/src/ipc.ts@@ -57,6 +57,7 @@ export interface ContextMenuItem<T extends string = string> {id: T;label: string;destructive?: boolean;+ disabled?: boolean;}export type DesktopUpdateStatus =diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.tsindex 19cef5a39..59c023e62 100644--- a/packages/contracts/src/orchestration.test.ts+++ b/packages/contracts/src/orchestration.test.ts@@ -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(OrchestrationLaconst 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({diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex 0b40bb6fd..31631666e 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -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"),diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.tsnew file mode 100644index 000000000..e7f638c7f--- /dev/null+++ b/packages/contracts/src/settings.test.ts@@ -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);+ });+});diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex 8ce01f630..9cd8a5f25 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -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(