TypeScript
feat(threads): persist manual active thread order (#9729)
Julius Marminge2d645df474f0
diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.tsindex 141aa405af2..a674a25c1ec 100644--- a/apps/server/src/environment/ServerEnvironment.test.ts+++ b/apps/server/src/environment/ServerEnvironment.test.ts@@ -167,6 +167,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {expect(second.capabilities.fileAttachments).toEqual({ maxUploadBytes: 50 * 1024 * 1024 });expect(second.capabilities.pullRequests).toBe(true);expect(second.capabilities.usagePriceOverrides).toBe(true);+ expect(second.capabilities.threadActiveReorder).toBe(true);expect(second.capabilities.threadTitleRegeneration).toBe(true);expect(second.capabilities.threadPullRequestLinking).toBe(true);expect(second.capabilities.agentActivityPublishing).toBe(false);diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.tsindex eab723d7909..0b7f1761cf7 100644--- a/apps/server/src/environment/ServerEnvironment.ts+++ b/apps/server/src/environment/ServerEnvironment.ts@@ -226,6 +226,7 @@ export const make = Effect.gen(function* () {usagePriceOverrides: true,threadPinning: true,threadPinReorder: true,+ threadActiveReorder: true,threadTitleRegeneration: true,threadPullRequestLinking: true,environmentIcon: true,diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.tsindex f619f6a9391..1a989958f50 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts@@ -488,6 +488,48 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {yield* sql`DROP TRIGGER count_thread_shell_updates`;yield* sql`DROP TABLE thread_shell_updates`;+ // Replayed order events must survive later lifecycle upserts, whose+ // complete SQL row writes otherwise risk dropping the placement.+ const orderUpdatedAt = "2026-01-01T00:00:00.200Z";+ const orderEvents = [+ { type: "thread.meta-updated", payload: { activeOrderKey: "gm" } },+ { type: "thread.pinned", payload: { pinnedAt: now, pinOrderKey: "m" } },+ {+ type: "thread.snoozed",+ payload: { snoozedAt: now, snoozedUntil: "2026-01-02T00:00:00.000Z" },+ },+ { type: "thread.unsnoozed", payload: { reason: "user" } },+ { type: "thread.unpinned", payload: {} },+ { type: "thread.meta-updated", payload: { title: "Renamed" } },+ ] as const;+ for (const [index, event] of orderEvents.entries()) {+ yield* eventStore.append({+ type: event.type,+ eventId: EventId.make(`evt-active-order-${index}`),+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ occurredAt: "2026-01-01T00:00:00.500Z",+ commandId: CommandId.make(`cmd-active-order-${index}`),+ causationEventId: null,+ correlationId: null,+ metadata: {},+ payload: {+ ...event.payload,+ threadId: ThreadId.make("thread-1"),+ updatedAt: orderUpdatedAt,+ },+ });+ yield* projectionPipeline.bootstrap;+ const rows = yield* sql<{+ readonly activeOrderKey: string | null;+ readonly updatedAt: string;+ }>`+ SELECT active_order_key AS "activeOrderKey", updated_at AS "updatedAt"+ FROM projection_threads WHERE thread_id = 'thread-1'+ `;+ assert.deepEqual(rows, [{ activeOrderKey: "gm", updatedAt: orderUpdatedAt }]);+ }+// Settled lifecycle through the DB pipeline: thread.settled writes the// override + timestamp, thread.unsettled(user) flips to the active pin.yield* eventStore.append({@@ -512,16 +554,23 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {readonly settledOverride: string | null;readonly settledAt: string | null;readonly unsettledAt: string | null;+ readonly activeOrderKey: string | null;}>`SELECTsettled_override AS "settledOverride",settled_at AS "settledAt",- unsettled_at AS "unsettledAt"+ unsettled_at AS "unsettledAt",+ active_order_key AS "activeOrderKey"FROM projection_threadsWHERE thread_id = 'thread-1'`;assert.deepEqual(settledRows, [- { settledOverride: "settled", settledAt: "2026-01-01T00:00:01.000Z", unsettledAt: null },+ {+ settledOverride: "settled",+ settledAt: "2026-01-01T00:00:01.000Z",+ unsettledAt: null,+ activeOrderKey: null,+ },]);yield* eventStore.append({@@ -546,11 +595,13 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {readonly settledOverride: string | null;readonly settledAt: string | null;readonly unsettledAt: string | null;+ readonly activeOrderKey: string | null;}>`SELECTsettled_override AS "settledOverride",settled_at AS "settledAt",- unsettled_at AS "unsettledAt"+ unsettled_at AS "unsettledAt",+ active_order_key AS "activeOrderKey"FROM projection_threadsWHERE thread_id = 'thread-1'`;@@ -561,6 +612,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {settledOverride: "active",settledAt: null,unsettledAt: "2026-01-01T00:00:02.000Z",+ activeOrderKey: null,},]);}),diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex bcef68170a4..050ad1a902a 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -617,6 +617,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectisnoozedAt: null,pinnedAt: null,pinOrderKey: null,+ activeOrderKey: null,titleRegenerationRequestId: null,titleRegenerationStartedAt: null,latestUserMessageAt: null,@@ -671,6 +672,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectisettledOverride: "settled",settledAt: event.payload.settledAt,unsettledAt: null,+ activeOrderKey: null,updatedAt: event.payload.updatedAt,});return;@@ -790,6 +792,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectiyield* projectionThreadRepository.upsert({...existingRow.value,...(event.payload.title !== undefined ? { title: event.payload.title } : {}),+ ...(event.payload.activeOrderKey !== undefined+ ? { activeOrderKey: event.payload.activeOrderKey }+ : {}),...(event.payload.titleRegeneration !== undefined? {titleRegenerationRequestId: event.payload.titleRegeneration?.requestId ?? null,diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.tsindex 08a07c0be75..e262bce34aa 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts@@ -110,6 +110,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {has_actionable_proposed_plan,pinned_at,pin_order_key,+ active_order_key,created_at,updated_at,deleted_at@@ -132,6 +133,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {0,'2026-02-24T00:00:01.000Z','gm',+ 'hq','2026-02-24T00:00:02.000Z','2026-02-24T00:00:03.000Z',NULL@@ -358,6 +360,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {snoozedAt: null,pinnedAt: "2026-02-24T00:00:01.000Z",pinOrderKey: "gm",+ activeOrderKey: "hq",titleRegeneration: null,deletedAt: null,messages: [@@ -487,6 +490,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {snoozedAt: null,pinnedAt: "2026-02-24T00:00:01.000Z",pinOrderKey: "gm",+ activeOrderKey: "hq",titleRegeneration: null,session: {threadId: ThreadId.make("thread-1"),@@ -513,6 +517,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {}const commandSnapshot = yield* snapshotQuery.getCommandReadModel();+ assert.equal(commandSnapshot.threads[0]?.activeOrderKey, "hq");assert.deepEqual(commandSnapshot.threads[0]?.branchPullRequest, branchPullRequest);const threadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));assert.equal(threadShell._tag, "Some");@@ -560,6 +565,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {);assert.equal(detailWithoutActivities._tag, "Some");if (detailWithoutActivities._tag === "Some") {+ assert.equal(detailWithoutActivities.value.activeOrderKey, "hq");assert.deepEqual(detailWithoutActivities.value.activities, []);assert.deepEqual(detailWithoutActivities.value.messages, snapshot.threads[0]?.messages);assert.deepEqual(diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.tsindex b15b72ee567..5f82a26e2a3 100644--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts@@ -513,6 +513,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {snoozed_at AS "snoozedAt",pinned_at AS "pinnedAt",pin_order_key AS "pinOrderKey",+ active_order_key AS "activeOrderKey",title_regeneration_request_id AS "titleRegenerationRequestId",title_regeneration_started_at AS "titleRegenerationStartedAt",latest_user_message_at AS "latestUserMessageAt",@@ -552,6 +553,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {snoozed_at AS "snoozedAt",pinned_at AS "pinnedAt",pin_order_key AS "pinOrderKey",+ active_order_key AS "activeOrderKey",title_regeneration_request_id AS "titleRegenerationRequestId",title_regeneration_started_at AS "titleRegenerationStartedAt",latest_user_message_at AS "latestUserMessageAt",@@ -593,6 +595,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {snoozed_at AS "snoozedAt",pinned_at AS "pinnedAt",pin_order_key AS "pinOrderKey",+ active_order_key AS "activeOrderKey",title_regeneration_request_id AS "titleRegenerationRequestId",title_regeneration_started_at AS "titleRegenerationStartedAt",latest_user_message_at AS "latestUserMessageAt",@@ -1083,6 +1086,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {snoozed_at AS "snoozedAt",pinned_at AS "pinnedAt",pin_order_key AS "pinOrderKey",+ active_order_key AS "activeOrderKey",title_regeneration_request_id AS "titleRegenerationRequestId",title_regeneration_started_at AS "titleRegenerationStartedAt",latest_user_message_at AS "latestUserMessageAt",@@ -2082,6 +2086,7 @@ pending_approval_requests AS (snoozedAt: row.snoozedAt,pinnedAt: row.pinnedAt,pinOrderKey: row.pinOrderKey ?? null,+ activeOrderKey: row.activeOrderKey ?? null,titleRegeneration: mapTitleRegeneration(row),deletedAt: row.deletedAt,messages: messagesByThread.get(row.threadId) ?? [],@@ -2296,6 +2301,7 @@ pending_approval_requests AS (snoozedAt: row.snoozedAt,pinnedAt: row.pinnedAt,pinOrderKey: row.pinOrderKey ?? null,+ activeOrderKey: row.activeOrderKey ?? null,titleRegeneration: mapTitleRegeneration(row),deletedAt: row.deletedAt,messages: [],@@ -2437,6 +2443,7 @@ pending_approval_requests AS (snoozedAt: row.snoozedAt,pinnedAt: row.pinnedAt,pinOrderKey: row.pinOrderKey ?? null,+ activeOrderKey: row.activeOrderKey ?? null,titleRegeneration: mapTitleRegeneration(row),session: sessionByThread.get(row.threadId) ?? null,latestUserMessageAt: row.latestUserMessageAt,@@ -2586,6 +2593,7 @@ pending_approval_requests AS (snoozedAt: row.snoozedAt,pinnedAt: row.pinnedAt,pinOrderKey: row.pinOrderKey ?? null,+ activeOrderKey: row.activeOrderKey ?? null,titleRegeneration: mapTitleRegeneration(row),session: sessionByThread.get(row.threadId) ?? null,latestUserMessageAt: row.latestUserMessageAt,@@ -2908,6 +2916,7 @@ pending_approval_requests AS (snoozedAt: threadRow.value.snoozedAt,pinnedAt: threadRow.value.pinnedAt,pinOrderKey: threadRow.value.pinOrderKey ?? null,+ activeOrderKey: threadRow.value.activeOrderKey ?? null,titleRegeneration: mapTitleRegeneration(threadRow.value),session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,latestUserMessageAt: threadRow.value.latestUserMessageAt,@@ -3190,6 +3199,7 @@ pending_approval_requests AS (snoozedAt: threadRow.value.snoozedAt,pinnedAt: threadRow.value.pinnedAt,pinOrderKey: threadRow.value.pinOrderKey ?? null,+ activeOrderKey: threadRow.value.activeOrderKey ?? null,titleRegeneration: mapTitleRegeneration(threadRow.value),deletedAt: null,messages: messageRows.map((row) => {diff --git a/apps/server/src/orchestration/decider.active-order.test.ts b/apps/server/src/orchestration/decider.active-order.test.tsnew file mode 100644index 00000000000..58a7f5c054e--- /dev/null+++ b/apps/server/src/orchestration/decider.active-order.test.ts@@ -0,0 +1,200 @@+import {+ CommandId,+ ProjectId,+ ProviderInstanceId,+ ThreadId,+ type OrchestrationCommand,+ type OrchestrationReadModel,+ type OrchestrationThread,+} from "@t3tools/contracts";+import * as NodeServices from "@effect/platform-node/NodeServices";+import { expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";++import { decideOrchestrationCommand } from "./decider.ts";+import { projectEvent } from "./projector.ts";++const NOW = "2026-01-01T00:00:00.000Z";+// The Effect test clock starts at the epoch.+const BEFORE_NOW = "1969-12-30T00:00:00.000Z";+const SNOOZED_AT = "1969-12-31T00:00:00.000Z";+const FUTURE_WAKE = "1970-01-02T00:00:00.000Z";+const THREAD_ID = ThreadId.make("thread-1");++function makeReadModel(overrides: Partial<OrchestrationThread> = {}): OrchestrationReadModel {+ return {+ snapshotSequence: 0,+ projects: [],+ threads: [+ {+ id: THREAD_ID,+ projectId: ProjectId.make("project-1"),+ title: "Thread",+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ latestTurn: null,+ createdAt: NOW,+ updatedAt: NOW,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ unsettledAt: null,+ activeOrderKey: null,+ snoozedUntil: null,+ snoozedAt: null,+ pinnedAt: null,+ pinOrderKey: null,+ deletedAt: null,+ messages: [],+ proposedPlans: [],+ activities: [],+ checkpoints: [],+ session: null,+ ...overrides,+ },+ ],+ updatedAt: NOW,+ };+}++const reorderCommand = {+ type: "thread.active.reorder",+ commandId: CommandId.make("cmd-active-reorder"),+ threadId: THREAD_ID,+ orderKey: "m",+} as const;++it.layer(NodeServices.layer)("active thread ordering", (it) => {+ it.effect("persists changed and repeated slots without changing thread activity timestamps", () =>+ Effect.gen(function* () {+ let readModel = makeReadModel({ unsettledAt: BEFORE_NOW });+ for (const orderKey of ["m", "m", "g"]) {+ const decided = yield* decideOrchestrationCommand({+ command: { ...reorderCommand, orderKey },+ readModel,+ });+ const events = Array.isArray(decided) ? decided : [decided];+ expect(events).toHaveLength(1);+ expect(events[0]).toMatchObject({+ type: "thread.meta-updated",+ payload: { threadId: THREAD_ID, activeOrderKey: orderKey, updatedAt: NOW },+ });+ for (const event of events) {+ readModel = yield* projectEvent(readModel, {+ ...event,+ sequence: readModel.snapshotSequence + 1,+ });+ }+ expect(readModel.threads[0]).toMatchObject({+ activeOrderKey: orderKey,+ updatedAt: NOW,+ createdAt: NOW,+ unsettledAt: BEFORE_NOW,+ });+ }+ }),+ );++ for (const [label, overrides] of [+ ["archived", { archivedAt: NOW }],+ ["deleted", { deletedAt: NOW }],+ ["pinned", { pinnedAt: NOW }],+ ["settled", { settledOverride: "settled", settledAt: NOW }],+ ] satisfies ReadonlyArray<readonly [string, Partial<OrchestrationThread>]>) {+ it.effect(`rejects reordering a ${label} thread`, () =>+ Effect.gen(function* () {+ const error = yield* decideOrchestrationCommand({+ command: reorderCommand,+ readModel: makeReadModel(overrides),+ }).pipe(Effect.flip);+ expect(error._tag).toBe("OrchestrationCommandInvariantError");+ }),+ );+ }++ it.effect("reorders a running thread without affecting its session", () =>+ Effect.gen(function* () {+ const readModel = makeReadModel({+ session: {+ threadId: THREAD_ID,+ status: "running",+ providerName: "codex",+ runtimeMode: "full-access",+ activeTurnId: null,+ lastError: null,+ updatedAt: NOW,+ },+ });+ const decided = yield* decideOrchestrationCommand({ command: reorderCommand, readModel });+ const events = Array.isArray(decided) ? decided : [decided];+ expect(events).toHaveLength(1);+ for (const event of events) {+ const projected = yield* projectEvent(readModel, { ...event, sequence: 1 });+ expect(projected.threads[0]).toEqual({ ...readModel.threads[0], activeOrderKey: "m" });+ }+ }),+ );++ it.effect(+ "changes a snoozed thread's retained slot without waking it or changing timestamps",+ () =>+ Effect.gen(function* () {+ const readModel = makeReadModel({+ activeOrderKey: "g",+ snoozedAt: SNOOZED_AT,+ snoozedUntil: FUTURE_WAKE,+ unsettledAt: BEFORE_NOW,+ });+ const decided = yield* decideOrchestrationCommand({ command: reorderCommand, readModel });+ const events = Array.isArray(decided) ? decided : [decided];+ expect(events).toHaveLength(1);+ for (const event of events) {+ const projected = yield* projectEvent(readModel, { ...event, sequence: 1 });+ expect(projected.threads[0]).toEqual({ ...readModel.threads[0], activeOrderKey: "m" });+ }+ }),+ );++ it.effect("keeps placement through metadata, pin and snooze, then resets it on settlement", () =>+ Effect.gen(function* () {+ let readModel = makeReadModel();+ const steps = [+ [reorderCommand, "m"],+ [{ type: "thread.meta.update", title: "Renamed" }, "m"],+ [{ type: "thread.pin", orderKey: "g" }, "m"],+ [{ type: "thread.snooze", snoozedUntil: FUTURE_WAKE }, "m"],+ [{ type: "thread.unsnooze", reason: "user" }, "m"],+ [{ type: "thread.unpin" }, "m"],+ [{ type: "thread.settle" }, null],+ [{ type: "thread.unsettle", reason: "user" }, null],+ [{ type: "thread.active.reorder", orderKey: "s" }, "s"],+ ] as const;+ for (const [index, [step, expectedKey]] of steps.entries()) {+ const command: OrchestrationCommand = {+ ...step,+ commandId: CommandId.make(`lifecycle-${index}`),+ threadId: THREAD_ID,+ };+ const decided = yield* decideOrchestrationCommand({ command, readModel });+ const events = Array.isArray(decided) ? decided : [decided];+ for (const event of events) {+ readModel = yield* projectEvent(readModel, {+ ...event,+ sequence: readModel.snapshotSequence + 1,+ });+ }+ expect(readModel.threads[0]?.activeOrderKey, command.type).toBe(expectedKey);+ }+ expect(readModel.threads[0]).toMatchObject({+ title: "Renamed",+ settledOverride: "active",+ settledAt: null,+ snoozedUntil: null,+ pinnedAt: null,+ });+ }),+ );+});diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.tsindex a20dba468c6..9dc55e1194c 100644--- a/apps/server/src/orchestration/decider.ts+++ b/apps/server/src/orchestration/decider.ts@@ -788,6 +788,42 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"};}+ case "thread.active.reorder": {+ const thread = yield* requireThreadNotArchived({+ readModel,+ command,+ threadId: command.threadId,+ });+ const occurredAt = yield* nowIso;+ // Snooze retains this slot. Changing it cannot wake the thread, and+ // accepting it handles races with snooze and retained wake timestamps.+ if (+ thread.deletedAt !== null ||+ thread.pinnedAt != null ||+ thread.settledOverride === "settled"+ ) {+ return yield* new OrchestrationCommandInvariantError({+ commandType: command.type,+ detail: `thread ${command.threadId} is not active and cannot be reordered`,+ });+ }+ return {+ ...(yield* withEventBase({+ aggregateKind: "thread",+ aggregateId: command.threadId,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "thread.meta-updated",+ payload: {+ threadId: command.threadId,+ activeOrderKey: command.orderKey,+ // Arranging the list is not thread activity or a lifecycle transition.+ updatedAt: thread.updatedAt,+ },+ };+ }+case "thread.meta.update": {const thread = yield* requireThread({readModel,diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.tsindex d4e1213b2ab..e973b523275 100644--- a/apps/server/src/orchestration/projector.test.ts+++ b/apps/server/src/orchestration/projector.test.ts@@ -91,6 +91,7 @@ describe("orchestration projector", () => {createdAt: now,updatedAt: now,archivedAt: null,+ activeOrderKey: null,settledOverride: null,settledAt: null,unsettledAt: null,diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.tsindex 58c4876905e..c048247f412 100644--- a/apps/server/src/orchestration/projector.ts+++ b/apps/server/src/orchestration/projector.ts@@ -344,6 +344,7 @@ export function projectEvent(settledOverride: null,settledAt: null,unsettledAt: null,+ activeOrderKey: null,snoozedUntil: null,snoozedAt: null,deletedAt: null,@@ -406,6 +407,7 @@ export function projectEvent(settledOverride: "settled",settledAt: payload.settledAt,unsettledAt: null,+ activeOrderKey: null,updatedAt: payload.updatedAt,}),})),@@ -500,6 +502,9 @@ export function projectEvent(...nextBase,threads: updateThread(nextBase.threads, payload.threadId, {...(payload.title !== undefined ? { title: payload.title } : {}),+ ...(payload.activeOrderKey !== undefined+ ? { activeOrderKey: payload.activeOrderKey }+ : {}),...(payload.titleRegeneration !== undefined? { titleRegeneration: payload.titleRegeneration }: {}),diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.tsindex 79938684541..6406e8237bc 100644--- a/apps/server/src/persistence/Layers/ProjectionThreads.ts+++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts@@ -54,6 +54,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {snoozed_at,pinned_at,pin_order_key,+ active_order_key,title_regeneration_request_id,title_regeneration_started_at,latest_user_message_at,@@ -84,6 +85,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {${row.snoozedAt},${row.pinnedAt},${row.pinOrderKey ?? null},+ ${row.activeOrderKey ?? null},${row.titleRegenerationRequestId ?? null},${row.titleRegenerationStartedAt ?? null},${row.latestUserMessageAt},@@ -114,6 +116,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {snoozed_at = excluded.snoozed_at,pinned_at = excluded.pinned_at,pin_order_key = excluded.pin_order_key,+ active_order_key = excluded.active_order_key,title_regeneration_request_id = excluded.title_regeneration_request_id,title_regeneration_started_at = excluded.title_regeneration_started_at,latest_user_message_at = excluded.latest_user_message_at,@@ -151,6 +154,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {snoozed_at AS "snoozedAt",pinned_at AS "pinnedAt",pin_order_key AS "pinOrderKey",+ active_order_key AS "activeOrderKey",title_regeneration_request_id AS "titleRegenerationRequestId",title_regeneration_started_at AS "titleRegenerationStartedAt",latest_user_message_at AS "latestUserMessageAt",@@ -190,6 +194,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {snoozed_at AS "snoozedAt",pinned_at AS "pinnedAt",pin_order_key AS "pinOrderKey",+ active_order_key AS "activeOrderKey",title_regeneration_request_id AS "titleRegenerationRequestId",title_regeneration_started_at AS "titleRegenerationStartedAt",latest_user_message_at AS "latestUserMessageAt",diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.tsindex 7f89170d29f..c95f746d364 100644--- a/apps/server/src/persistence/Migrations.ts+++ b/apps/server/src/persistence/Migrations.ts@@ -60,6 +60,7 @@ import Migration0045 from "./Migrations/045_ProjectionProjectsAutoPull.ts";import Migration0046 from "./Migrations/046_RepairAutomaticSettlementTimestamps.ts";import Migration0047 from "./Migrations/047_ProjectionProjectIcon.ts";import Migration0048 from "./Migrations/048_ProjectionThreadBranchPullRequest.ts";+import Migration0049 from "./Migrations/049_ProjectionThreadsActiveOrderKey.ts";/*** Migration loader with all migrations defined inline.@@ -120,6 +121,7 @@ export const migrationEntries = [[46, "RepairAutomaticSettlementTimestamps", Migration0046],[47, "ProjectionProjectIcon", Migration0047],[48, "ProjectionThreadBranchPullRequest", Migration0048],+ [49, "ProjectionThreadsActiveOrderKey", Migration0049],] as const;export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);diff --git a/apps/server/src/persistence/Migrations/049_ProjectionThreadsActiveOrderKey.test.ts b/apps/server/src/persistence/Migrations/049_ProjectionThreadsActiveOrderKey.test.tsnew file mode 100644index 00000000000..138d25754d7--- /dev/null+++ b/apps/server/src/persistence/Migrations/049_ProjectionThreadsActiveOrderKey.test.ts@@ -0,0 +1,44 @@+import { assert, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as SqlClient from "effect/unstable/sql/SqlClient";+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";++import { runMigrations } from "../Migrations.ts";+import migrateActiveOrderKey from "./049_ProjectionThreadsActiveOrderKey.ts";++it.layer(NodeSqliteClient.layerMemory())("049_ProjectionThreadsActiveOrderKey", (it) => {+ it.effect("migrates old threads without changing their timestamps or assigning an order", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ yield* runMigrations({ toMigrationInclusive: 48 });+ const now = "2026-01-01T00:00:00.000Z";+ yield* sql`+ INSERT INTO projection_threads (+ thread_id, project_id, title, model_selection_json, runtime_mode,+ created_at, updated_at+ ) VALUES (+ 'thread-1', 'project-1', 'Existing thread',+ '{"instanceId":"codex","model":"gpt-5.4"}', 'full-access', ${now}, ${now}+ )+ `;+ yield* runMigrations({ toMigrationInclusive: 49 });+ const migrated = yield* sql<{ readonly activeOrderKey: string | null }>`+ SELECT active_order_key AS "activeOrderKey" FROM projection_threads WHERE thread_id = 'thread-1'+ `;+ assert.deepEqual(migrated, [{ activeOrderKey: null }]);+ // Recovery may run the same migration against a database that already+ // has the column, including a placement written after the upgrade.+ yield* sql`UPDATE projection_threads SET active_order_key = 'gm' WHERE thread_id = 'thread-1'`;+ yield* migrateActiveOrderKey;+ const rows = yield* sql<{+ readonly activeOrderKey: string | null;+ readonly createdAt: string;+ readonly updatedAt: string;+ }>`+ SELECT active_order_key AS "activeOrderKey", created_at AS "createdAt", updated_at AS "updatedAt"+ FROM projection_threads WHERE thread_id = 'thread-1'+ `;+ assert.deepEqual(rows, [{ activeOrderKey: "gm", createdAt: now, updatedAt: now }]);+ }),+ );+});diff --git a/apps/server/src/persistence/Migrations/049_ProjectionThreadsActiveOrderKey.ts b/apps/server/src/persistence/Migrations/049_ProjectionThreadsActiveOrderKey.tsnew file mode 100644index 00000000000..6f40ec38d08--- /dev/null+++ b/apps/server/src/persistence/Migrations/049_ProjectionThreadsActiveOrderKey.ts@@ -0,0 +1,15 @@+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 === "active_order_key")) {+ yield* sql`+ ALTER TABLE projection_threads+ ADD COLUMN active_order_key TEXT+ `;+ }+});diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.tsindex ee442624be5..0a8b2e31c5a 100644--- a/apps/server/src/persistence/Services/ProjectionThreads.ts+++ b/apps/server/src/persistence/Services/ProjectionThreads.ts@@ -47,6 +47,7 @@ export const ProjectionThread = Schema.Struct({snoozedAt: Schema.NullOr(IsoDateTime),pinnedAt: Schema.NullOr(IsoDateTime),pinOrderKey: Schema.optional(Schema.NullOr(Schema.String)),+ activeOrderKey: Schema.optional(Schema.NullOr(Schema.String)),titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)),titleRegenerationStartedAt: Schema.optional(Schema.NullOr(IsoDateTime)),latestUserMessageAt: Schema.NullOr(IsoDateTime),diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.tsindex 36bc6a7b296..5cc17586471 100644--- a/packages/client-runtime/src/operations/commands.test.ts+++ b/packages/client-runtime/src/operations/commands.test.ts@@ -24,6 +24,7 @@ import type { WsRpcProtocolClient } from "../rpc/protocol.ts";import {archiveThread,createProject,+ reorderActiveThread,settleThread,stopThreadSession,unsettleThread,@@ -172,4 +173,24 @@ describe("environment commands", () => {]);}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),);++ it.effect("sends an active order key without changing activity timestamps", () =>+ Effect.gen(function* () {+ const dispatched: ClientOrchestrationCommand[] = [];+ const supervisor = yield* makeSupervisor(dispatched);+ yield* reorderActiveThread({+ commandId: CommandId.make("reorder-command"),+ threadId: ThreadId.make("thread-1"),+ orderKey: "mf",+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));+ expect(dispatched).toEqual([+ {+ type: "thread.active.reorder",+ commandId: "reorder-command",+ threadId: "thread-1",+ orderKey: "mf",+ },+ ]);+ }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),+ );});diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.tsindex cb74f117b77..9bf75c838a9 100644--- a/packages/client-runtime/src/operations/commands.ts+++ b/packages/client-runtime/src/operations/commands.ts@@ -42,6 +42,7 @@ export type UnsnoozeThreadInput = CommandInput<"thread.unsnooze">;export type PinThreadInput = CommandInput<"thread.pin">;export type UnpinThreadInput = CommandInput<"thread.unpin">;export type ReorderPinnedThreadInput = CommandInput<"thread.pin.reorder">;+export type ReorderActiveThreadInput = CommandInput<"thread.active.reorder">;export type UpdateThreadMetadataInput = CommandInput<"thread.meta.update">;export type SetThreadRuntimeModeInput = CommandInput<"thread.runtime-mode.set">;export type SetThreadInteractionModeInput = CommandInput<"thread.interaction-mode.set">;@@ -230,6 +231,16 @@ export const reorderPinnedThread: (input: ReorderPinnedThreadInput) => CommandEf});});+export const reorderActiveThread: (input: ReorderActiveThreadInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.reorderActiveThread",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "thread.active.reorder",+ commandId: yield* commandId(input),+ });+});+export const updateThreadMetadata: (input: UpdateThreadMetadataInput) => CommandEffect = Effect.fn("EnvironmentCommands.updateThreadMetadata",)(function* (input) {diff --git a/packages/client-runtime/src/state/entities.test.ts b/packages/client-runtime/src/state/entities.test.tsindex d02f63c0b69..b8d2aef4069 100644--- a/packages/client-runtime/src/state/entities.test.ts+++ b/packages/client-runtime/src/state/entities.test.ts@@ -208,6 +208,8 @@ describe("environment entity projections", () => {title: "Cached thread",branch: "stale-branch",worktreePath: "/repo/stale-worktree",+ activeOrderKey: "t",+ unsettledAt: "2026-03-09T10:00:00.000Z",deletedAt: null,messages,proposedPlans: [],@@ -220,6 +222,8 @@ describe("environment entity projections", () => {title: "Current thread",branch: "current-branch",worktreePath: "/repo/current-worktree",+ activeOrderKey: "f",+ unsettledAt: "2026-03-09T12:00:00.000Z",};const merged = mergeEnvironmentThread(detail, shell);@@ -228,6 +232,8 @@ describe("environment entity projections", () => {title: "Current thread",branch: "current-branch",worktreePath: "/repo/current-worktree",+ activeOrderKey: "f",+ unsettledAt: "2026-03-09T12:00:00.000Z",});expect(merged?.messages).toBe(messages);});diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.tsindex c540644289d..83881f7ec15 100644--- a/packages/client-runtime/src/state/threadCommands.ts+++ b/packages/client-runtime/src/state/threadCommands.ts@@ -19,6 +19,7 @@ import {type SetThreadRuntimeModeInput,type PinThreadInput,type ReorderPinnedThreadInput,+ type ReorderActiveThreadInput,type SettleThreadInput,type SnoozeThreadInput,type StartThreadTurnInput,@@ -39,6 +40,7 @@ import {setThreadRuntimeMode,pinThread,reorderPinnedThread,+ reorderActiveThread,settleThread,snoozeThread,startThreadTurn,@@ -63,6 +65,7 @@ export type {SetThreadRuntimeModeInput,PinThreadInput,ReorderPinnedThreadInput,+ ReorderActiveThreadInput,SettleThreadInput,SnoozeThreadInput,StartThreadTurnInput,@@ -150,6 +153,12 @@ export function createThreadEnvironmentAtoms<R, E>(scheduler,concurrency,}),+ reorderActive: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:thread:reorder-active",+ execute: (input: ReorderActiveThreadInput) => reorderActiveThread(input),+ scheduler,+ concurrency,+ }),updateMetadata: createEnvironmentCommand(runtime, {label: "environment-data:commands:thread:update-metadata",execute: (input: UpdateThreadMetadataInput) => updateThreadMetadata(input),diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.tsindex 0233cee0e22..379985b7124 100644--- a/packages/client-runtime/src/state/threadDetail.ts+++ b/packages/client-runtime/src/state/threadDetail.ts@@ -58,6 +58,8 @@ export function mergeEnvironmentThread(archivedAt: shell.archivedAt,settledOverride: shell.settledOverride,settledAt: shell.settledAt,+ unsettledAt: shell.unsettledAt,+ activeOrderKey: shell.activeOrderKey,snoozedUntil: shell.snoozedUntil,snoozedAt: shell.snoozedAt,pinnedAt: shell.pinnedAt,diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.tsindex 59b3cb0551e..38afce2d5cb 100644--- a/packages/client-runtime/src/state/threadReducer.test.ts+++ b/packages/client-runtime/src/state/threadReducer.test.ts@@ -178,24 +178,28 @@ describe("applyThreadDetailEvent", () => {describe("thread.settled / thread.unsettled", () => {it("sets the settled override and timestamp", () => {const settledAt = "2026-04-01T05:00:00.000Z";- const result = applyThreadDetailEvent(baseThread, {- ...baseEventFields,- sequence: 5,- occurredAt: settledAt,- aggregateKind: "thread",- aggregateId: ThreadId.make("thread-1"),- type: "thread.settled",- payload: {- threadId: ThreadId.make("thread-1"),- settledAt,- updatedAt: settledAt,+ const result = applyThreadDetailEvent(+ { ...baseThread, activeOrderKey: "m" },+ {+ ...baseEventFields,+ sequence: 5,+ occurredAt: settledAt,+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ type: "thread.settled",+ payload: {+ threadId: ThreadId.make("thread-1"),+ settledAt,+ updatedAt: settledAt,+ },},- });+ );expect(result.kind).toBe("updated");if (result.kind === "updated") {expect(result.thread.settledOverride).toBe("settled");expect(result.thread.settledAt).toBe(settledAt);+ expect(result.thread.activeOrderKey).toBeNull();}});@@ -234,23 +238,27 @@ describe("applyThreadDetailEvent", () => {describe("thread.pinned / thread.unpinned", () => {it("sets pinnedAt", () => {const pinnedAt = "2026-04-01T05:00:00.000Z";- const result = applyThreadDetailEvent(baseThread, {- ...baseEventFields,- sequence: 5,- occurredAt: pinnedAt,- aggregateKind: "thread",- aggregateId: ThreadId.make("thread-1"),- type: "thread.pinned",- payload: {- threadId: ThreadId.make("thread-1"),- pinnedAt,- updatedAt: pinnedAt,+ const result = applyThreadDetailEvent(+ { ...baseThread, activeOrderKey: "m" },+ {+ ...baseEventFields,+ sequence: 5,+ occurredAt: pinnedAt,+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ type: "thread.pinned",+ payload: {+ threadId: ThreadId.make("thread-1"),+ pinnedAt,+ updatedAt: pinnedAt,+ },},- });+ );expect(result.kind).toBe("updated");if (result.kind === "updated") {expect(result.thread.pinnedAt).toBe(pinnedAt);+ expect(result.thread.activeOrderKey).toBe("m");}});@@ -281,26 +289,57 @@ describe("applyThreadDetailEvent", () => {});describe("thread.meta-updated", () => {+ it.each(["f", null] as const)(+ "updates the active key to %s without activity",+ (activeOrderKey) => {+ const result = applyThreadDetailEvent(+ { ...baseThread, activeOrderKey: "m" },+ {+ ...baseEventFields,+ sequence: 5,+ occurredAt: "2026-04-01T05:00:00.000Z",+ aggregateKind: "thread",+ aggregateId: baseThread.id,+ type: "thread.meta-updated",+ payload: {+ threadId: baseThread.id,+ activeOrderKey,+ updatedAt: baseThread.updatedAt,+ },+ },+ );+ expect(result.kind).toBe("updated");+ if (result.kind === "updated") {+ expect(result.thread.activeOrderKey).toBe(activeOrderKey);+ expect(result.thread.updatedAt).toBe(baseThread.updatedAt);+ }+ },+ );+it("patches title and branch", () => {- const result = applyThreadDetailEvent(baseThread, {- ...baseEventFields,- sequence: 5,- occurredAt: "2026-04-01T05:00:00.000Z",- aggregateKind: "thread",- aggregateId: ThreadId.make("thread-1"),- type: "thread.meta-updated",- payload: {- threadId: ThreadId.make("thread-1"),- title: "Updated Title",- branch: "feature/demo",- updatedAt: "2026-04-01T05:00:00.000Z",+ const result = applyThreadDetailEvent(+ { ...baseThread, activeOrderKey: "m" },+ {+ ...baseEventFields,+ sequence: 5,+ occurredAt: "2026-04-01T05:00:00.000Z",+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ type: "thread.meta-updated",+ payload: {+ threadId: ThreadId.make("thread-1"),+ title: "Updated Title",+ branch: "feature/demo",+ updatedAt: "2026-04-01T05:00:00.000Z",+ },},- });+ );expect(result.kind).toBe("updated");if (result.kind === "updated") {expect(result.thread.title).toBe("Updated Title");expect(result.thread.branch).toBe("feature/demo");+ expect(result.thread.activeOrderKey).toBe("m");// Model selection should be unchanged since it wasn't in the payloadexpect(result.thread.modelSelection).toEqual(baseThread.modelSelection);}diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.tsindex 09272cd065c..a3481fdc729 100644--- a/packages/client-runtime/src/state/threadReducer.ts+++ b/packages/client-runtime/src/state/threadReducer.ts@@ -105,6 +105,7 @@ export function applyThreadDetailEvent(settledOverride: null,settledAt: null,unsettledAt: null,+ activeOrderKey: null,snoozedUntil: null,snoozedAt: null,deletedAt: null,@@ -144,6 +145,7 @@ export function applyThreadDetailEvent(settledOverride: "settled",settledAt: event.payload.settledAt,unsettledAt: null,+ activeOrderKey: null,updatedAt: event.payload.updatedAt,},};@@ -244,6 +246,9 @@ export function applyThreadDetailEvent(...(event.payload.branchPullRequest !== undefined? { branchPullRequest: event.payload.branchPullRequest }: {}),+ ...(event.payload.activeOrderKey !== undefined+ ? { activeOrderKey: event.payload.activeOrderKey }+ : {}),updatedAt: event.payload.updatedAt,},};diff --git a/packages/client-runtime/src/state/threadSort.test.ts b/packages/client-runtime/src/state/threadSort.test.tsindex a51d4cfed09..d9a2c124ee7 100644--- a/packages/client-runtime/src/state/threadSort.test.ts+++ b/packages/client-runtime/src/state/threadSort.test.ts@@ -1,8 +1,12 @@import { describe, expect, it } from "vite-plus/test";import {+ generateSpreadPinOrderKeys,+ pinOrderKeyBetween,planPinnedMove,+ planPinnedReorder,resolveSettledThreadTimestamp,+ sortActiveThreadsByOrderKey,sortPinnedThreadsByOrderKey,sortThreads,type ThreadSortInput,@@ -108,6 +112,44 @@ describe("sortThreads", () => {});});+describe("planPinnedReorder with hidden rows", () => {+ it("keeps hidden slots available when inserting between visible neighbors", () => {+ const midpoint = pinOrderKeyBetween("f", "t")!;+ const keysById = new Map([+ ["a", "f"],+ ["b", "t"],+ ["moved", "z"],+ ["snoozed", midpoint],+ ]);+ const assignments = planPinnedReorder({+ orderedIds: ["a", "moved", "b"],+ keysById,+ movedId: "moved",+ });+ expect(assignments).toHaveLength(1);+ const key = assignments[0]!.orderKey;+ expect(key > "f" && key < "t").toBe(true);+ expect(key).not.toBe(midpoint);+ expect(assignments[0]!.id).toBe("moved");+ });++ it("materializes keyless rows without overwriting hidden slots", () => {+ const reserved = generateSpreadPinOrderKeys(6);+ const keysById = new Map<string, string | null>([+ ["a", null],+ ["b", null],+ ["c", null],+ ...reserved.map((key, i) => [`hidden-${i}`, key] as const),+ ]);+ const assignments = planPinnedReorder({ orderedIds: ["c", "a", "b"], keysById, movedId: "c" });+ expect(assignments.map(({ id }) => id)).toEqual(["c", "a", "b"]);+ const keys = assignments.map(({ orderKey }) => orderKey);+ expect(keys).toEqual([...keys].sort());+ expect(new Set(keys).size).toBe(3);+ expect(keys.every((key) => !reserved.includes(key))).toBe(true);+ });+});+describe("planPinnedMove", () => {it("moves a thread up with a single key write", () => {const assignments = planPinnedMove({@@ -173,3 +215,137 @@ describe("sortPinnedThreadsByOrderKey", () => {expect(sorted.map((thread) => thread.environmentId)).toEqual(["env-a", "env-b"]);});});++describe("generateSpreadPinOrderKeys", () => {+ it.each([0, 1, 650, 675, 676, 1_001, 2_000])(+ "leaves unique, insertable keys for %i threads",+ (count) => {+ const keys = generateSpreadPinOrderKeys(count);+ expect(keys).toHaveLength(count);+ expect(new Set(keys).size).toBe(count);+ expect([...keys].sort()).toEqual(keys);+ for (let index = 0; index < keys.length; index += 1) {+ const before = keys[index - 1] ?? null;+ const after = keys[index]!;+ expect(after).toMatch(/^[a-z]*[b-z]$/);+ const between = pinOrderKeyBetween(before, after);+ expect(between).not.toBeNull();+ expect(between! < after).toBe(true);+ if (before !== null) expect(between! > before).toBe(true);+ }+ },+ );+});++describe("sortActiveThreadsByOrderKey", () => {+ it("keeps new and reopened threads ahead of the saved order", () => {+ const sorted = sortActiveThreadsByOrderKey([+ {+ id: "arranged-first",+ createdAt: "2026-03-09T09:00:00.000Z",+ activeOrderKey: "f",+ },+ {+ id: "new",+ createdAt: "2026-03-09T11:00:00.000Z",+ activeOrderKey: null,+ },+ {+ id: "arranged-last",+ createdAt: "2026-03-09T12:00:00.000Z",+ unsettledAt: "2026-03-09T13:00:00.000Z",+ activeOrderKey: "t",+ },+ {+ id: "reopened",+ createdAt: "2026-03-01T09:00:00.000Z",+ unsettledAt: "2026-03-09T12:00:00.000Z",+ },+ ]);+ expect(sorted.map((thread) => thread.id)).toEqual([+ "reopened",+ "new",+ "arranged-first",+ "arranged-last",+ ]);+ });++ it("breaks equal order keys and timestamps by thread then environment", () => {+ for (const activeOrderKey of [null, "m"]) {+ const threads = [+ { id: "thread-b", environmentId: "env-a" },+ { id: "thread-a", environmentId: "env-b" },+ { id: "thread-a", environmentId: "env-a" },+ ].map((thread) => ({+ ...thread,+ createdAt: "2026-03-09T10:00:00.000Z",+ activeOrderKey,+ }));+ expect(+ sortActiveThreadsByOrderKey(threads).map(+ (thread) => `${thread.id}:${thread.environmentId}`,+ ),+ ).toEqual(["thread-a:env-a", "thread-a:env-b", "thread-b:env-a"]);+ }+ });++ it("applies every move across a mixed keyless and keyed section", () => {+ const threads = Array.from({ length: 6 }, (_, index) => ({+ id: String(index),+ createdAt: `2026-03-09T0${6 - index}:00:00.000Z`,+ activeOrderKey: index < 3 ? null : ["f", "m", "t"][index - 3]!,+ }));+ const ids = threads.map((thread) => thread.id);+ const keysById = new Map(threads.map((thread) => [thread.id, thread.activeOrderKey]));+ for (const movedId of ids) {+ for (let targetIndex = 0; targetIndex < ids.length; targetIndex += 1) {+ const desired = ids.filter((id) => id !== movedId);+ desired.splice(targetIndex, 0, movedId);+ const assignments = planPinnedReorder({ orderedIds: desired, keysById, movedId });+ const nextKeys = new Map(+ assignments.map((assignment) => [assignment.id, assignment.orderKey]),+ );+ const updated = threads.map((thread) => ({+ ...thread,+ activeOrderKey: nextKeys.get(thread.id) ?? thread.activeOrderKey,+ }));+ expect(sortActiveThreadsByOrderKey(updated).map((thread) => thread.id)).toEqual(desired);+ }+ }+ });++ it("moves a keyless thread into the arranged run with one write", () => {+ const assignments = planPinnedMove({+ orderedIds: ["new", "reopened", "first", "last"],+ keysById: new Map([+ ["new", null],+ ["reopened", null],+ ["first", "f"],+ ["last", "t"],+ ]),+ movedId: "reopened",+ direction: "down",+ });+ expect(assignments).toHaveLength(1);+ expect(assignments![0]!.id).toBe("reopened");+ expect(assignments![0]!.orderKey > "f").toBe(true);+ expect(assignments![0]!.orderKey < "t").toBe(true);+ });++ it("materializes a large active list without changing the requested order", () => {+ const threads = Array.from({ length: 1_200 }, (_, index) => ({+ id: String(index),+ createdAt: "2026-03-09T10:00:00.000Z",+ activeOrderKey: null as string | null,+ }));+ const orderedIds = threads.map((thread) => thread.id).toReversed();+ const assignments = planPinnedReorder({+ orderedIds,+ movedId: orderedIds[0]!,+ keysById: new Map(threads.map((thread) => [thread.id, thread.activeOrderKey])),+ });+ const keys = new Map(assignments.map((assignment) => [assignment.id, assignment.orderKey]));+ const updated = threads.map((thread) => ({ ...thread, activeOrderKey: keys.get(thread.id) }));+ expect(sortActiveThreadsByOrderKey(updated).map((thread) => thread.id)).toEqual(orderedIds);+ });+});diff --git a/packages/client-runtime/src/state/threadSort.ts b/packages/client-runtime/src/state/threadSort.tsindex cf89d4a21ac..f06c9591955 100644--- a/packages/client-runtime/src/state/threadSort.ts+++ b/packages/client-runtime/src/state/threadSort.ts@@ -205,25 +205,27 @@ export function pinOrderKeyBetween(before: string | null, after: string | null):return pinOrderMidpoint(a, b);}-/** Evenly spaced keys for rewriting a whole pinned section (used when a- drop lands next to keyless threads, so single-key insertion has nothing- to anchor on). Two base-26 digits give 675 slots — far beyond any real- pinned section — with monotonicity enforced as a belt-and-braces. */-function generateSpreadPinOrderKeys(count: number): string[] {- const space = PIN_ORDER_DIGITS.length * PIN_ORDER_DIGITS.length;+/** Evenly spaced keys for materializing an order. Wider keys keep a large+ active list from exhausting the space between two-digit keys. */+export function generateSpreadPinOrderKeys(count: number): string[] {+ let width = 2;+ let space = PIN_ORDER_DIGITS.length ** width;+ while (space <= (count + 1) * 2) {+ width += 1;+ space *= PIN_ORDER_DIGITS.length;+ }const step = space / (count + 1);const keys: string[] = [];- let previous = 0;for (let i = 0; i < count; i += 1) {- let value = Math.max(Math.round(step * (i + 1)), previous + 1);+ let value = Math.round(step * (i + 1));// Skip values whose low digit is the minimum (a trailing "a" key).if (value % PIN_ORDER_DIGITS.length === 0) value += 1;- value = Math.min(value, space - 1);- previous = value;- keys.push(- PIN_ORDER_DIGITS.charAt(Math.floor(value / PIN_ORDER_DIGITS.length)) +- PIN_ORDER_DIGITS.charAt(value % PIN_ORDER_DIGITS.length),- );+ let key = "";+ for (let digit = 0; digit < width; digit += 1) {+ key = PIN_ORDER_DIGITS.charAt(value % PIN_ORDER_DIGITS.length) + key;+ value = Math.floor(value / PIN_ORDER_DIGITS.length);+ }+ keys.push(key);}return keys;}@@ -233,15 +235,21 @@ function generateSpreadPinOrderKeys(count: number): string[] {* sits between two keyed (or absent) neighbors, this is a single write to* the moved thread. When a neighbor is keyless (threads pinned before* reordering shipped), the whole section gets fresh spread keys — a- * one-time materialization; every move after that is single-write.+ * one-time materialization; every move after that is single-write. Active+ * reordering uses the same planner with activeOrderKey values.*/export function planPinnedReorder(input: {/** Thread ids in the desired visual order (after the move). */readonly orderedIds: readonly string[];+ /** Include retained keys from hidden rows; only orderedIds receive writes. */readonly keysById: ReadonlyMap<string, string | null | undefined>;readonly movedId: string;}): ReadonlyArray<{ readonly id: string; readonly orderKey: string }> {const { orderedIds, keysById, movedId } = input;+ const visibleIds = new Set(orderedIds);+ const reservedKeys = new Set(+ [...keysById].flatMap(([id, key]) => (!visibleIds.has(id) && key != null ? [key] : [])),+ );const movedIndex = orderedIds.indexOf(movedId);if (movedIndex === -1) return [];const beforeId = movedIndex > 0 ? orderedIds[movedIndex - 1] : null;@@ -251,11 +259,14 @@ export function planPinnedReorder(input: {const beforeUsable = beforeId === null || beforeKey != null;const afterUsable = afterId === null || afterKey != null;if (beforeUsable && afterUsable) {- const key = pinOrderKeyBetween(beforeKey, afterKey);+ let key = pinOrderKeyBetween(beforeKey, afterKey);+ while (key !== null && reservedKeys.has(key)) key = pinOrderKeyBetween(key, afterKey);if (key !== null) return [{ id: movedId, orderKey: key }];}// Keyless neighbor (or corrupt keys): rewrite the section in the new order.- const keys = generateSpreadPinOrderKeys(orderedIds.length);+ const keys = generateSpreadPinOrderKeys(orderedIds.length + reservedKeys.size)+ .filter((key) => !reservedKeys.has(key))+ .slice(0, orderedIds.length);return orderedIds.flatMap((id, index) => {const key = keys[index]!;return keysById.get(id) === key ? [] : [{ id, orderKey: key }];@@ -303,6 +314,36 @@ export function sortPinnedThreadsByOrderKey<return [...keyed, ...keyless];}+/** New and reopened threads lead the active list. Arranged threads follow+ their saved keys; activity leaves both groups in place. */+export function sortActiveThreadsByOrderKey<+ T extends {+ readonly id: string;+ readonly createdAt: string;+ readonly unsettledAt?: string | null | undefined;+ readonly activeOrderKey?: string | null | undefined;+ readonly environmentId?: string | undefined;+ },+>(threads: readonly T[]): T[] {+ return [...threads].sort((left, right) => {+ const leftKey = left.activeOrderKey;+ const rightKey = right.activeOrderKey;+ if (leftKey == null && rightKey != null) return -1;+ if (leftKey != null && rightKey == null) return 1;+ let order = 0;+ if (leftKey != null && rightKey != null) {+ order = leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0;+ } else {+ order = activeThreadAnchorTimestampMs(right) - activeThreadAnchorTimestampMs(left);+ }+ return (+ order ||+ left.id.localeCompare(right.id) ||+ (left.environmentId ?? "").localeCompare(right.environmentId ?? "")+ );+ });+}+/*** planPinnedReorder specialized for mobile's Move up / Move down menu* actions: swap the moved thread with its displayed neighbor. Null when thediff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 6b815591ff2..94d7c608125 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -116,6 +116,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({/** Server understands thread.pin.reorder (and orderKey on thread.pin).Same version-skew contract as threadSettlement. */threadPinReorder: Schema.optionalKey(Schema.Boolean),+ /** Server persists manual Active order through thread.active.reorder. */+ threadActiveReorder: Schema.optionalKey(Schema.Boolean),/** Server understands regenerateTitle on thread.meta.update. Absent onolder servers, so clients hide the action instead of sending it. */threadTitleRegeneration: Schema.optionalKey(Schema.Boolean),diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.tsindex 61dbdb9a551..b3dbc4188c2 100644--- a/packages/contracts/src/orchestration.test.ts+++ b/packages/contracts/src/orchestration.test.ts@@ -784,6 +784,61 @@ it.effect("accepts a title seed in thread.turn.start", () =>}),);+it.effect("decodes active reorder commands through client and orchestration boundaries", () =>+ Effect.gen(function* () {+ const input = {+ type: "thread.active.reorder",+ commandId: "cmd-active-reorder",+ threadId: "thread-1",+ orderKey: "gm",+ };+ const clientCommand = yield* decodeClientOrchestrationCommand(input);+ const command = yield* decodeOrchestrationCommand(input);+ for (const decoded of [clientCommand, command]) {+ assert.strictEqual(decoded.type, "thread.active.reorder");+ if (decoded.type === "thread.active.reorder") {+ assert.strictEqual(decoded.threadId, "thread-1");+ assert.strictEqual(decoded.orderKey, "gm");+ }+ }+ const emptyKey = yield* Effect.exit(+ decodeClientOrchestrationCommand({ ...input, orderKey: " " }),+ );+ assert.isTrue(Exit.isFailure(emptyKey));+ }),+);++it.effect("decodes active placement on existing metadata events while accepting old payloads", () =>+ Effect.gen(function* () {+ const payload = { threadId: "thread-1", updatedAt: "2026-01-01T00:00:00.000Z" };+ const oldPayload = yield* decodeThreadMetaUpdatedPayload(payload);+ assert.strictEqual(oldPayload.activeOrderKey, undefined);+ const resetPayload = yield* decodeThreadMetaUpdatedPayload({+ ...payload,+ activeOrderKey: null,+ });+ assert.strictEqual(resetPayload.activeOrderKey, null);+ const event = yield* decodeOrchestrationEvent({+ type: "thread.meta-updated",+ sequence: 1,+ eventId: "event-active-reorder",+ aggregateKind: "thread",+ aggregateId: "thread-1",+ occurredAt: "2026-01-02T00:00:00.000Z",+ commandId: "cmd-active-reorder",+ causationEventId: null,+ correlationId: null,+ metadata: {},+ payload: { ...payload, activeOrderKey: "gm" },+ });+ assert.strictEqual(event.type, "thread.meta-updated");+ if (event.type === "thread.meta-updated") {+ assert.strictEqual(event.payload.activeOrderKey, "gm");+ assert.strictEqual(event.payload.updatedAt, payload.updatedAt);+ }+ }),+);+it.effect("accepts a title regeneration intent in thread.meta.update", () =>Effect.gen(function* () {const parsed = yield* decodeOrchestrationCommand({diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex 47501e32344..37f5476fecc 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -523,6 +523,9 @@ export const OrchestrationThread = Schema.Struct({// servers never need each other's threads to agree on the merged list.// Optional so payloads from pre-reorder servers still decode.pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),+ // Manual Active placement. Keyless threads retain their creation/re-entry+ // order above the arranged run. Settling clears this slot.+ activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),// Pending-only state. Optional so older servers remain compatible.titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),deletedAt: Schema.NullOr(IsoDateTime),@@ -588,6 +591,7 @@ export const OrchestrationThreadShell = Schema.Struct({snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),+ activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),session: Schema.NullOr(OrchestrationSession),latestUserMessageAt: Schema.NullOr(IsoDateTime),@@ -895,6 +899,13 @@ const ThreadPinReorderCommand = Schema.Struct({orderKey: TrimmedNonEmptyString,});+const ThreadActiveReorderCommand = Schema.Struct({+ type: Schema.Literal("thread.active.reorder"),+ commandId: CommandId,+ threadId: ThreadId,+ orderKey: TrimmedNonEmptyString,+});+const ThreadMetaUpdateCommand = Schema.Struct({type: Schema.Literal("thread.meta.update"),commandId: CommandId,@@ -1058,6 +1069,7 @@ const DispatchableClientOrchestrationCommand = Schema.Union([ThreadPinCommand,ThreadUnpinCommand,ThreadPinReorderCommand,+ ThreadActiveReorderCommand,ThreadMetaUpdateCommand,ThreadRuntimeModeSetCommand,ThreadInteractionModeSetCommand,@@ -1086,6 +1098,7 @@ export const ClientOrchestrationCommand = Schema.Union([ThreadPinCommand,ThreadUnpinCommand,ThreadPinReorderCommand,+ ThreadActiveReorderCommand,ThreadMetaUpdateCommand,ThreadRuntimeModeSetCommand,ThreadInteractionModeSetCommand,@@ -1375,6 +1388,9 @@ export const ThreadPinReorderedPayload = Schema.Struct({export const ThreadMetaUpdatedPayload = Schema.Struct({threadId: ThreadId,+ // Order updates use this existing event so older clients can ignore the+ // new field while continuing to decode the event stream.+ activeOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),title: Schema.optional(TrimmedNonEmptyString),/** Intent marker consumed by the title-generation reactor. Keeping this onthe existing event lets older clients safely ignore the new field. */