fix: repair rerere-damaged files and reconcile main's round-3 features with v2

Post-rebase reconciliation sweep:
- Sidebar: main's folded Sidebar.tsx/Sidebar.logic.ts adapted to v2 shells
  (latestRun/runtime naming, waiting status instead of monitoring), with
  subagent-thread filtering and main's pinned-reorder helpers re-exported
- Pinned drag reorder (#5581) ported into v2: thread.pin orderKey +
  thread.pin.reorder command, thread.pin-reordered event, Orchestrator fold,
  ProjectionStore/Maintenance, client-runtime commands and shell mapping
- Project favicon (#4849-era) and defaultThreadEnvMode flowed through v2
  contracts (OrchestrationProjectShell, application event payloads)
- ChatView: main's #5592 header props, pull-request right-panel surfaces,
  liveAgentCount badge (#5745) wired into the v2 panel layout
- enableAssistantStreaming -> enableLegacyTokenStreaming rename applied to
  v2 RunExecutionService and replay testkit
- Removed v1 zombies resurrected by the rebase (provider service/reaper/
  ingestion + v1 layer tests, server.test.ts, integration harness)
- routeTree: main's tree + branch's /settings/scheduled-tasks route
- Misc marker-sweep syntax repairs (rpc.ts, entities.ts, localApi.test.ts,
  rightPanelStore.test.ts, GitManager.test.ts, mobile model menu helpers)

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 committed 2026-08-14 11:23:51 +02:00
1 parent 931cc7c440
commit d256570669
62 files changed
+1303 -28448

No files matched your search

@@ -1071,50 +1071,15 @@ export function HomeScreen(props: HomeScreenProps) {
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
variant="plain"
/>
<<<<<<< HEAD
<<<<<<< HEAD
{emptyState.loading ? (
=======
{emptyState.loading && !shouldShowConnectionStatus ? (
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
<View className="mt-4 items-center">
<ActivityIndicator color={accentColor} />
</View>
) : null}
<<<<<<< HEAD
</View>
</View>
);
}
=======
) : !hasResults ? (
<EmptyState
title="No threads yet"
detail="Create a task to start a new coding runtime."
/>
) : (
projectGroups.map((group) => {
const isExpanded = expandedProjects.has(group.key);
const visibleThreads = isExpanded
? group.threads
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover)
=======
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View className="mt-4">
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
variant="sidebar"
/>
</View>
) : null}
</View>
{connectionStatus}
</View>
);
}
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
const listHeader = Platform.OS === "ios" ? null : <HomeTopContentSpacer />;
+51
View File
@@ -1,3 +1,4 @@
import type { MenuAction } from "@react-native-menu/menu";
import type {
ModelCapabilities,
ModelSelection,
@@ -187,3 +188,53 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr
models: group.models,
}));
}
function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
return {
id: `model:${option.key}`,
title: option.label,
state:
option.selection.instanceId === selectedModel?.instanceId &&
option.selection.model === selectedModel.model
? "on"
: undefined,
};
}
export function buildModelMenuActions(
groups: ReadonlyArray<ProviderGroup>,
selectedModel: ModelSelection | null,
): MenuAction[] {
return groups.flatMap((group) => {
const currentModels = group.models.filter((model) => !model.isLegacy);
const legacyModels = group.models.filter((model) => model.isLegacy);
const selected = group.models.find(
(model) =>
model.selection.instanceId === selectedModel?.instanceId &&
model.selection.model === selectedModel.model,
);
return [
...(currentModels.length > 0
? [
{
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: selected && !selected.isLegacy ? selected.label : undefined,
subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
...(legacyModels.length > 0
? [
{
id: `legacy-models:${group.providerKey}`,
title: `${group.providerLabel} legacy models`,
subtitle: selected?.isLegacy ? selected.label : undefined,
subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
];
});
}
@@ -79,3 +79,13 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
createdAt: spec.createdAt,
};
}
export function deriveThreadTitleFromPrompt(value: string): string {
const trimmed = value.trim();
if (trimmed.length === 0) {
return "New thread";
}
const compact = trimmed.replace(/\s+/g, " ");
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
}
-17
View File
@@ -145,24 +145,7 @@ function resolvePendingUserInputAnswer(
draft: PendingUserInputDraftAnswer | undefined,
): string | null {
return (
<<<<<<< HEAD
normalized.includes("file not found") ||
normalized.includes("no files found") ||
normalized.includes("enoent") ||
normalized.includes("no such file or directory") ||
normalized.includes("no such file") ||
normalized.includes("commandnotfoundexception") ||
normalized.includes("command not found") ||
(normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||
(normalized.includes("is not recognized") && normalized.includes("the term '")) ||
normalized.includes("is not recognized as the name of a cmdlet") ||
normalized.includes("a parameter cannot be found that matches parameter name") ||
/<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
=======
normalizeDraftAnswer(draft?.customAnswer) ?? normalizeDraftAnswer(draft?.selectedOptionLabel)
>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover)
);
}
@@ -1,386 +0,0 @@
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../src/provider/Layers/ProviderEventLoggers.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import * as ServerConfig from "../src/config.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "../src/persistence/ProviderSessionRuntime.ts";
import {
makeTestProviderAdapterHarness,
type TestProviderAdapterHarness,
type TestTurnResponse,
} from "./TestProviderAdapter.integration.ts";
import {
codexTurnApprovalFixture,
codexTurnToolFixture,
codexTurnTextFixture,
} from "./fixtures/providerRuntime.ts";
const codexInstanceId = ProviderInstanceId.make("codex");
const makeWorkspaceDirectory = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const cwd = yield* fs.makeTempDirectory();
yield* fs.writeFileString(pathService.join(cwd, "README.md"), "v1\n");
return cwd;
}).pipe(Effect.provide(NodeServices.layer));
interface IntegrationFixture {
readonly cwd: string;
readonly harness: TestProviderAdapterHarness;
readonly layer: Layer.Layer<ProviderService, unknown, never>;
}
interface RecordedAnalyticsEvent {
readonly event: string;
readonly properties: Readonly<Record<string, unknown>> | undefined;
}
/**
* Analytics layer that keeps captured events in memory so tests can assert on
* telemetry payloads. `AnalyticsService.layerTest` discards them.
*/
const makeRecordingAnalytics = Effect.gen(function* () {
const recorded = yield* Ref.make<ReadonlyArray<RecordedAnalyticsEvent>>([]);
const layer = Layer.succeed(
AnalyticsService,
AnalyticsService.of({
record: (event, properties) =>
Ref.update(recorded, (current) => [...current, { event, properties }]),
flush: Effect.void,
}),
);
return { layer, get: Ref.get(recorded) } as const;
});
const makeIntegrationFixture = (options?: { readonly analytics?: Layer.Layer<AnalyticsService> }) =>
Effect.gen(function* () {
const cwd = yield* makeWorkspaceDirectory;
const harness = yield* makeTestProviderAdapterHarness();
const registry = makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: harness.adapter,
});
const directoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntime.layer),
);
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
ServerConfig.layerTest(cwd, cwd).pipe(Layer.provide(NodeServices.layer)),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
options?.analytics ?? AnalyticsService.layerTest,
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
return {
cwd,
harness,
layer,
} satisfies IntegrationFixture;
});
const collectEventsDuring = <A, E, R>(
stream: Stream.Stream<ProviderRuntimeEvent>,
count: number,
action: Effect.Effect<A, E, R>,
) =>
Effect.gen(function* () {
const queue = yield* Queue.unbounded<ProviderRuntimeEvent>();
yield* Stream.runForEach(stream, (event) => Queue.offer(queue, event).pipe(Effect.asVoid)).pipe(
Effect.forkScoped,
);
yield* Effect.sleep("50 millis");
yield* action;
return yield* Effect.forEach(
Array.from({ length: count }, () => undefined),
() => Queue.take(queue),
{ discard: false },
);
});
const runTurn = (input: {
readonly provider: ProviderServiceShape;
readonly harness: TestProviderAdapterHarness;
readonly threadId: ThreadId;
readonly userText: string;
readonly response: TestTurnResponse;
}) =>
Effect.gen(function* () {
yield* input.harness.queueTurnResponse(input.threadId, input.response);
return yield* collectEventsDuring(
input.provider.streamEvents,
input.response.events.length,
input.provider.sendTurn({
threadId: input.threadId,
input: input.userText,
attachments: [],
}),
);
});
it.live("replays typed runtime fixture events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture();
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
threadId: ThreadId.make("thread-integration-typed"),
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
assert.equal((session.threadId ?? "").length > 0, true);
const observedEvents = yield* runTurn({
provider,
harness: fixture.harness,
threadId: session.threadId,
userText: "hello",
response: { events: codexTurnTextFixture },
});
assert.deepEqual(
observedEvents.map((event) => event.type),
codexTurnTextFixture.map((event) => event.type),
);
assert.deepEqual(
observedEvents.map((event) => event.providerInstanceId),
codexTurnTextFixture.map(() => codexInstanceId),
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("replays file-changing fixture turn events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture();
const { join } = yield* Path.Path;
const { writeFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
threadId: ThreadId.make("thread-integration-tools"),
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
assert.equal((session.threadId ?? "").length > 0, true);
const observedEvents = yield* runTurn({
provider,
harness: fixture.harness,
threadId: session.threadId,
userText: "make a small change",
response: {
events: codexTurnToolFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
},
});
assert.deepEqual(
observedEvents.map((event) => event.type),
codexTurnToolFixture.map((event) => event.type),
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("runs multi-turn tool/approval flow", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture();
const { join } = yield* Path.Path;
const { writeFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
threadId: ThreadId.make("thread-integration-multi"),
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
assert.equal((session.threadId ?? "").length > 0, true);
const firstTurnEvents = yield* runTurn({
provider,
harness: fixture.harness,
threadId: session.threadId,
userText: "turn 1",
response: {
events: codexTurnToolFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
},
});
assert.deepEqual(
firstTurnEvents.map((event) => event.type),
codexTurnToolFixture.map((event) => event.type),
);
const secondTurnEvents = yield* runTurn({
provider,
harness: fixture.harness,
threadId: session.threadId,
userText: "turn 2 approval",
response: {
events: codexTurnApprovalFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore),
},
});
assert.deepEqual(
secondTurnEvents.map((event) => event.type),
codexTurnApprovalFixture.map((event) => event.type),
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("rolls back provider conversation state only", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture();
const { join } = yield* Path.Path;
const { writeFileString, readFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
threadId: ThreadId.make("thread-integration-rollback"),
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
assert.equal((session.threadId ?? "").length > 0, true);
yield* runTurn({
provider,
harness: fixture.harness,
threadId: session.threadId,
userText: "turn 1",
response: {
events: codexTurnToolFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
},
});
yield* runTurn({
provider,
harness: fixture.harness,
threadId: session.threadId,
userText: "turn 2 approval",
response: {
events: codexTurnApprovalFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore),
},
});
yield* provider.rollbackConversation({
threadId: session.threadId,
numTurns: 1,
});
const rollbackCalls = fixture.harness.getRollbackCalls(session.threadId);
assert.deepEqual(rollbackCalls, [1]);
const readme = yield* readFileString(join(fixture.cwd, "README.md"));
assert.equal(readme, "v3\n");
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("reports runtime mode per turn and on mode transitions", () =>
Effect.gen(function* () {
const analytics = yield* makeRecordingAnalytics;
const fixture = yield* makeIntegrationFixture({ analytics: analytics.layer });
const threadId = ThreadId.make("thread-integration-runtime-mode");
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const startSession = (runtimeMode: "approval-required" | "full-access") =>
provider.startSession(threadId, {
threadId,
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode,
});
yield* startSession("approval-required");
yield* runTurn({
provider,
harness: fixture.harness,
threadId,
userText: "supervised turn",
response: { events: codexTurnTextFixture },
});
// Toggling the mode restarts the session, which is the only place the
// transition is observable.
yield* startSession("full-access");
yield* runTurn({
provider,
harness: fixture.harness,
threadId,
userText: "full access turn",
response: { events: codexTurnTextFixture },
});
const recorded = yield* analytics.get;
assert.deepEqual(
recorded
.filter((entry) => entry.event === "provider.turn.sent")
.map((entry) => entry.properties?.runtimeMode),
["approval-required", "full-access"],
);
assert.deepEqual(
recorded
.filter((entry) => entry.event === "provider.runtime_mode.changed")
.map((entry) => [entry.properties?.from, entry.properties?.to]),
[["approval-required", "full-access"]],
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
-2
View File
@@ -1018,8 +1018,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(Duration.toMillis(GitManager.prLookupFailureTtl(20))).toBe(900_000);
});
it.effect(
effect(
it.effect(
"status ignores unrelated fork PRs when the current branch tracks the same repository",
() =>
@@ -197,6 +197,7 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId {
case "thread.unsnooze":
case "thread.pin":
case "thread.unpin":
case "thread.pin.reorder":
case "thread.visit":
case "thread.mark-unread":
case "thread.metadata.update":
@@ -1346,6 +1347,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
| "thread.unsnooze"
| "thread.pin"
| "thread.unpin"
| "thread.pin.reorder"
| "thread.visit"
| "thread.mark-unread"
| "thread.metadata.update"
@@ -1407,7 +1409,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
command.type === "thread.snooze" ||
command.type === "thread.unsnooze" ||
command.type === "thread.pin" ||
command.type === "thread.unpin") &&
command.type === "thread.unpin" ||
command.type === "thread.pin.reorder") &&
thread.archivedAt !== null
) {
return yield* new OrchestratorDispatchError({
@@ -1416,6 +1419,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
cause: `Thread ${command.threadId} is archived.`,
});
}
// Only pinned threads have a slot in the arranged order. Rejecting
// (rather than silently pinning) keeps a raced reorder-after-unpin from
// resurrecting a pin the user just cleared.
if (command.type === "thread.pin.reorder" && thread.pinnedAt == null) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Thread ${command.threadId} is not pinned and cannot be reordered.`,
});
}
if (
command.type === "thread.settle" &&
(projection.runs.some((run) =>
@@ -1530,6 +1543,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
settledOverride: "settled",
settledAt: alreadySettled ? thread.settledAt : now,
pinnedAt: null,
pinOrderKey: null,
updatedAt: alreadySettled ? thread.updatedAt : now,
};
}
@@ -1573,6 +1587,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return {
...thread,
pinnedAt: alreadyPinned ? thread.pinnedAt : now,
// A fresh pin takes the client's slot in the arranged order; on a
// re-pin the existing key wins so raced duplicates cannot move a
// thread the user already placed.
...(alreadyPinned || command.orderKey === undefined
? {}
: { pinOrderKey: command.orderKey }),
settledOverride:
thread.settledOverride === "settled" ? "active" : thread.settledOverride,
settledAt: thread.settledOverride === "settled" ? null : thread.settledAt,
@@ -1586,9 +1606,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return {
...thread,
pinnedAt: null,
// Unpin clears the slot: re-pinning is "pin again", not "restore
// an ancient position".
pinOrderKey: null,
updatedAt: alreadyUnpinned ? thread.updatedAt : now,
};
}
case "thread.pin.reorder": {
// Idempotent by re-emission (see thread.settle): a duplicate drop on
// the same slot keeps the existing updatedAt so it projects as a
// no-op.
const keyUnchanged = thread.pinOrderKey === command.orderKey;
return {
...thread,
pinOrderKey: command.orderKey,
updatedAt: keyUnchanged ? thread.updatedAt : now,
};
}
// Visited tracking records read state only; it must not bump updatedAt,
// otherwise viewing a thread would count as activity (and re-trigger the
// clients that dispatch thread.visit whenever updatedAt advances).
@@ -1660,6 +1694,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return "thread.pinned" as const;
case "thread.unpin":
return "thread.unpinned" as const;
case "thread.pin.reorder":
return "thread.pin-reordered" as const;
case "thread.visit":
return "thread.visited" as const;
case "thread.mark-unread":
@@ -6692,6 +6728,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
case "thread.unsnooze":
case "thread.pin":
case "thread.unpin":
case "thread.pin.reorder":
case "thread.visit":
case "thread.mark-unread":
case "thread.metadata.update":
@@ -232,6 +232,7 @@ export const layer: Layer.Layer<
"thread.unsnoozed",
"thread.pinned",
"thread.unpinned",
"thread.pin-reordered",
"thread.metadata-updated",
"thread.runtime-mode-updated",
"thread.interaction-mode-updated",
@@ -209,6 +209,7 @@ export function applyToProjection(
case "thread.unsnoozed":
case "thread.pinned":
case "thread.unpinned":
case "thread.pin-reordered":
case "thread.metadata-updated":
case "thread.runtime-mode-updated":
case "thread.interaction-mode-updated":
@@ -914,6 +915,7 @@ export function threadShellFromProjection(
snoozedUntil: projection.thread.snoozedUntil ?? null,
snoozedAt: projection.thread.snoozedAt ?? null,
pinnedAt: projection.thread.pinnedAt ?? null,
pinOrderKey: projection.thread.pinOrderKey ?? null,
lastVisitedAt: projection.thread.lastVisitedAt,
titleRegeneration: projection.thread.titleRegeneration ?? null,
deletedAt: projection.thread.deletedAt,
@@ -1098,6 +1100,7 @@ function shellFromState(input: {
snoozedUntil: input.state.thread.snoozedUntil ?? null,
snoozedAt: input.state.thread.snoozedAt ?? null,
pinnedAt: input.state.thread.pinnedAt ?? null,
pinOrderKey: input.state.thread.pinOrderKey ?? null,
lastVisitedAt: input.state.thread.lastVisitedAt,
titleRegeneration: input.state.thread.titleRegeneration ?? null,
deletedAt: input.state.thread.deletedAt,
@@ -1122,6 +1125,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
case "thread.unsnoozed":
case "thread.pinned":
case "thread.unpinned":
case "thread.pin-reordered":
case "thread.visited":
case "thread.marked-unread":
case "thread.metadata-updated":
@@ -1923,6 +1927,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
event.type !== "thread.unsnoozed" &&
event.type !== "thread.pinned" &&
event.type !== "thread.unpinned" &&
event.type !== "thread.pin-reordered" &&
event.type !== "thread.visited" &&
event.type !== "thread.marked-unread" &&
event.type !== "thread.metadata-updated" &&
@@ -780,7 +780,7 @@ export const layer: Layer.Layer<
startRootRun: (input) =>
Effect.gen(function* () {
const assistantStreamingEnabled = yield* serverSettings.getSettings.pipe(
Effect.map((settings) => settings.enableAssistantStreaming),
Effect.map((settings) => settings.enableLegacyTokenStreaming),
Effect.mapError(
(cause) =>
new RunExecutionStartError({
@@ -65,6 +65,7 @@ const TestLayer = layerFromProjectRepository.pipe(
title: "Project",
workspaceRoot: "/project-root",
defaultModelSelection: null,
defaultThreadEnvMode: null,
scripts: [],
createdAt: "2026-06-21T00:00:00.000Z",
updatedAt: "2026-06-21T00:00:00.000Z",
@@ -51,6 +51,7 @@ const project = {
repositoryIdentity: null,
faviconPath: null,
defaultModelSelection: modelSelection,
defaultThreadEnvMode: null,
scripts: [],
createdAt: "2026-06-20T00:00:00.000Z",
updatedAt: "2026-06-20T00:00:00.000Z",
@@ -145,6 +146,7 @@ function makeHarness(options: HarnessOptions = {}) {
title: project.title,
workspaceRoot: project.workspaceRoot,
defaultModelSelection: project.defaultModelSelection,
defaultThreadEnvMode: null,
scripts: project.scripts,
createdAt: project.createdAt,
updatedAt: project.updatedAt,
@@ -65,6 +65,7 @@ function makeHarness(
title: "Project",
workspaceRoot: "/repo",
defaultModelSelection: modelSelection,
defaultThreadEnvMode: null,
scripts: [],
createdAt: "2026-06-20T00:00:00.000Z",
updatedAt: "2026-06-20T00:00:00.000Z",
@@ -79,7 +79,7 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* <
readonly buildInput: () => OrchestratorFixtureInput;
readonly driver: ProviderOrchestratorReplayVariant;
readonly harness: OrchestratorV2ProviderReplayHarness<Transcript, Error>;
readonly enableAssistantStreaming?: boolean;
readonly enableLegacyTokenStreaming?: boolean;
}) {
const rawTranscript = yield* readTranscript(input.driver.transcriptFile);
const replayTranscript = transcriptEntriesThroughLabel(
@@ -111,10 +111,10 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* <
};
const result = yield* runOrchestratorV2ProviderReplayScenario(scenario, input.harness, {
enableAssistantStreaming: input.enableAssistantStreaming ?? false,
enableLegacyTokenStreaming: input.enableLegacyTokenStreaming ?? false,
}).pipe(provideDeterministicTestRuntime);
input.driver.assertOutput(result, transcript);
if (input.enableAssistantStreaming !== true) {
if (input.enableLegacyTokenStreaming !== true) {
assert.isFalse(
result.domainEvents.some(isStreamingAssistantEvent),
"buffered delivery must not persist streaming assistant artifacts",
@@ -143,7 +143,7 @@ function runFixtureProviderWithRegisteredHarness(input: {
readonly fixtureName: string;
readonly buildInput: () => OrchestratorFixtureInput;
readonly driver: ProviderOrchestratorReplayVariant;
readonly enableAssistantStreaming?: boolean;
readonly enableLegacyTokenStreaming?: boolean;
}) {
switch (input.driver.driver) {
case "codex":
@@ -225,7 +225,7 @@ describe("orchestrator replay fixtures", () => {
fixtureName: "simple-cursor-streaming",
buildInput: simpleFixture.buildInput,
driver: simpleCursorProvider,
enableAssistantStreaming: true,
enableLegacyTokenStreaming: true,
});
assert.deepEqual(
@@ -123,6 +123,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
case "thread.unsnooze":
case "thread.pin":
case "thread.unpin":
case "thread.pin.reorder":
case "thread.visit":
case "thread.mark-unread":
case "thread.metadata.update":
@@ -172,7 +172,7 @@ export function runOrchestratorV2ProviderReplayScenario<
SqlClient.SqlClient,
MigrationError | PlatformError.PlatformError | SqlError
>;
readonly enableAssistantStreaming?: boolean;
readonly enableLegacyTokenStreaming?: boolean;
readonly runEffectWorker?: boolean;
} = {},
): Effect.Effect<
@@ -211,7 +211,7 @@ export function makeOrchestratorV2ProviderReplayLayer<
SqlClient.SqlClient,
MigrationError | PlatformError.PlatformError | SqlError
>;
readonly enableAssistantStreaming?: boolean;
readonly enableLegacyTokenStreaming?: boolean;
readonly runEffectWorker?: boolean;
readonly replayGate?: ProviderReplayGate;
} = {},
@@ -231,7 +231,7 @@ export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
SqlClient.SqlClient,
MigrationError | PlatformError.PlatformError | SqlError
>;
readonly enableAssistantStreaming?: boolean;
readonly enableLegacyTokenStreaming?: boolean;
readonly runEffectWorker?: boolean;
} = {},
): Layer.Layer<OrchestratorV2, Error | MigrationError | PlatformError.PlatformError | SqlError> {
@@ -247,7 +247,7 @@ export function makeOrchestratorV2ReplayLayerWithRegistry<Error>(
);
const databaseLayer = options.databaseLayer ?? SqlitePersistenceMemory;
const serverSettingsLayer = ServerSettingsService.layerTest({
enableAssistantStreaming: options.enableAssistantStreaming ?? false,
enableLegacyTokenStreaming: options.enableLegacyTokenStreaming ?? false,
}).pipe(Layer.orDie);
const storesLayer = Layer.mergeAll(
eventStoreLayer,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-4
View File
@@ -250,12 +250,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
title: command.title,
workspaceRoot: command.workspaceRoot,
defaultModelSelection: command.defaultModelSelection ?? null,
<<<<<<< HEAD
faviconPath: null,
scripts: [],
=======
scripts: command.scripts ?? [],
>>>>>>> f38dbfd84c (Integrate orchestration v2 with the application runtime)
createdAt: command.createdAt,
updatedAt: command.createdAt,
},
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,638 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ProjectId,
ThreadId,
TurnId,
ProviderDriverKind,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Option from "effect/Option";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts";
import { ProviderValidationError } from "../Errors.ts";
import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts";
import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts";
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts";
const defaultModelSelection = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
} as const;
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2_000,
): Promise<void> {
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
const poll = async (): Promise<void> => {
if (await predicate()) {
return;
}
if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
throw new Error("Timed out waiting for expectation.");
}
await Effect.runPromise(Effect.yieldNow);
return poll();
};
return poll();
}
const drainFibers = Effect.forEach(Array.from({ length: 10 }), () => Effect.yieldNow, {
discard: true,
});
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
function makeReadModel(
threads: ReadonlyArray<{
readonly id: ThreadId;
readonly session: {
readonly threadId: ThreadId;
readonly status: "starting" | "running" | "ready" | "interrupted" | "stopped" | "error";
readonly providerName: "codex" | "claudeAgent";
readonly runtimeMode: "approval-required" | "full-access" | "auto-accept-edits";
readonly activeTurnId: TurnId | null;
readonly lastError: string | null;
readonly updatedAt: string;
} | null;
readonly backgroundLiveness?: "working" | "monitoring" | null;
}>,
) {
const now = "2026-01-01T00:00:00.000Z";
const projectId = ProjectId.make("project-provider-session-reaper");
return {
snapshotSequence: 0,
updatedAt: now,
projects: [
{
id: projectId,
title: "Provider Reaper Project",
workspaceRoot: "/tmp/provider-reaper-project",
defaultModelSelection,
scripts: [],
createdAt: now,
updatedAt: now,
deletedAt: null,
},
],
threads: threads.map((thread) => ({
id: thread.id,
projectId,
title: `Thread ${thread.id}`,
modelSelection: defaultModelSelection,
interactionMode: "default" as const,
runtimeMode: "full-access" as const,
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
latestTurn: null,
messages: [],
session: thread.session,
backgroundLiveness: thread.backgroundLiveness ?? null,
activities: [],
proposedPlans: [],
checkpoints: [],
deletedAt: null,
})),
};
}
describe("ProviderSessionReaper", () => {
let runtime: ManagedRuntime.ManagedRuntime<
ProviderSessionReaper | ProviderSessionRuntime.ProviderSessionRuntimeRepository,
unknown
> | null = null;
let scope: Scope.Closeable | null = null;
afterEach(async () => {
if (scope) {
await Effect.runPromise(Scope.close(scope, Exit.void));
}
scope = null;
if (runtime) {
await runtime.dispose();
}
runtime = null;
});
// Shared start sequence so each test adds no manual Effect runners
// (no-manual-effect-runtime-in-tests tracks this file's legacy count).
async function startReaper() {
const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper));
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(reaper.start().pipe(Scope.provide(scope)));
}
async function createHarness(input: {
readonly readModel: ReturnType<typeof makeReadModel>;
readonly stopSessionImplementation?: (input: {
readonly threadId: ThreadId;
}) => ReturnType<ProviderServiceShape["stopSession"]>;
}) {
const stoppedThreadIds = new Set<ThreadId>();
const stopSession = vi.fn<ProviderServiceShape["stopSession"]>(
(request) =>
(input.stopSessionImplementation
? input.stopSessionImplementation(request)
: Effect.sync(() => {
stoppedThreadIds.add(request.threadId);
})) as ReturnType<ProviderServiceShape["stopSession"]>,
);
const providerService: ProviderServiceShape = {
startSession: () => unsupported(),
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession,
listSessions: () => Effect.succeed([]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
getInstanceInfo: (instanceId) => {
const driverKind = ProviderDriverKind.make(String(instanceId));
return Effect.succeed({
instanceId,
driverKind,
displayName: undefined,
enabled: true,
continuationIdentity: {
driverKind,
continuationKey: `${driverKind}:instance:${instanceId}`,
},
});
},
rollbackConversation: () => unsupported(),
streamEvents: Stream.empty,
};
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const layer = makeProviderSessionReaperLive({
inactivityThresholdMs: 1_000,
sweepIntervalMs: 60_000,
}).pipe(
Layer.provideMerge(providerSessionDirectoryLayer),
Layer.provideMerge(runtimeRepositoryLayer),
Layer.provideMerge(Layer.succeed(ProviderService, providerService)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
getProjectShellById: () => Effect.die("unused"),
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: (threadId) =>
Effect.succeed(
input.readModel.threads.find((thread) => thread.id === threadId)
? Option.some(input.readModel.threads.find((thread) => thread.id === threadId)!)
: Option.none(),
),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
searchThreads: () => Effect.succeed({ matches: [] }),
}),
),
Layer.provideMerge(NodeServices.layer),
);
runtime = ManagedRuntime.make(layer);
return { stopSession, stoppedThreadIds };
}
it("reaps stale persisted sessions without active turns", async () => {
const threadId = ThreadId.make("thread-reaper-stale");
const now = "2026-01-01T00:00:00.000Z";
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
);
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-stale",
},
runtimePayload: null,
}),
);
await startReaper();
await waitFor(() => harness.stopSession.mock.calls.length === 1);
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ threadId });
expect(harness.stoppedThreadIds.has(threadId)).toBe(true);
});
it("skips stale sessions when the thread still has an active turn", async () => {
const threadId = ThreadId.make("thread-reaper-active-turn");
const turnId = TurnId.make("turn-reaper-active");
const now = "2026-01-01T00:00:00.000Z";
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "running",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: turnId,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
);
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-active-turn",
},
runtimePayload: null,
}),
);
await startReaper();
await Effect.runPromise(drainFibers);
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("skips stale sessions while background work is still live", async () => {
const threadId = ThreadId.make("thread-reaper-background-work");
const now = "2026-01-01T00:00:00.000Z";
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
backgroundLiveness: "working",
},
]),
});
const repository = await runtime!.runPromise(
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
);
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-background-work",
},
runtimePayload: null,
}),
);
await startReaper();
await Effect.runPromise(drainFibers);
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("does not reap sessions that are still within the inactivity threshold", async () => {
const threadId = ThreadId.make("thread-reaper-fresh");
const now = DateTime.formatIso(await Effect.runPromise(DateTime.now));
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
);
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: now,
resumeCursor: {
opaque: "resume-fresh",
},
runtimePayload: null,
}),
);
await startReaper();
await Effect.runPromise(drainFibers);
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("skips persisted sessions that are already marked stopped", async () => {
const threadId = ThreadId.make("thread-reaper-stopped");
const now = "2026-01-01T00:00:00.000Z";
const harness = await createHarness({
readModel: makeReadModel([
{
id: threadId,
session: {
threadId,
status: "stopped",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
});
const repository = await runtime!.runPromise(
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
);
await runtime!.runPromise(
repository.upsert({
threadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "stopped",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-stopped",
},
runtimePayload: null,
}),
);
await startReaper();
await Effect.runPromise(drainFibers);
expect(harness.stopSession).not.toHaveBeenCalled();
const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId }));
expect(Option.isSome(remaining)).toBe(true);
});
it("continues reaping other sessions when one stop attempt fails", async () => {
const failedThreadId = ThreadId.make("thread-reaper-stop-failure");
const reapedThreadId = ThreadId.make("thread-reaper-stop-success");
const now = "2026-01-01T00:00:00.000Z";
const harness = await createHarness({
readModel: makeReadModel([
{
id: failedThreadId,
session: {
threadId: failedThreadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
{
id: reapedThreadId,
session: {
threadId: reapedThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
stopSessionImplementation: (request) =>
request.threadId === failedThreadId
? Effect.fail(
new ProviderValidationError({
operation: "ProviderSessionReaper.test",
issue: "simulated stop failure",
}),
)
: Effect.void,
});
const repository = await runtime!.runPromise(
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
);
await runtime!.runPromise(
repository.upsert({
threadId: failedThreadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-failure",
},
runtimePayload: null,
}),
);
await runtime!.runPromise(
repository.upsert({
threadId: reapedThreadId,
providerName: "codex",
providerInstanceId: null,
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:01:00.000Z",
resumeCursor: {
opaque: "resume-success",
},
runtimePayload: null,
}),
);
await startReaper();
await waitFor(() => harness.stopSession.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
failedThreadId,
reapedThreadId,
]);
});
it("continues reaping other sessions when one stop attempt defects", async () => {
const defectThreadId = ThreadId.make("thread-reaper-stop-defect");
const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect");
const now = "2026-01-01T00:00:00.000Z";
const harness = await createHarness({
readModel: makeReadModel([
{
id: defectThreadId,
session: {
threadId: defectThreadId,
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
{
id: reapedThreadId,
session: {
threadId: reapedThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
},
]),
stopSessionImplementation: (request) =>
request.threadId === defectThreadId
? Effect.die(new Error("simulated stop defect"))
: Effect.void,
});
const repository = await runtime!.runPromise(
Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository),
);
await runtime!.runPromise(
repository.upsert({
threadId: defectThreadId,
providerName: "claudeAgent",
providerInstanceId: null,
adapterKey: "claudeAgent",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:00:00.000Z",
resumeCursor: {
opaque: "resume-defect",
},
runtimePayload: null,
}),
);
await runtime!.runPromise(
repository.upsert({
threadId: reapedThreadId,
providerName: "codex",
providerInstanceId: null,
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt: "2026-04-14T00:01:00.000Z",
resumeCursor: {
opaque: "resume-after-defect",
},
runtimePayload: null,
}),
);
await startReaper();
await waitFor(() => harness.stopSession.mock.calls.length === 2);
expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([
defectThreadId,
reapedThreadId,
]);
});
});
@@ -1,152 +0,0 @@
import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schedule from "effect/Schedule";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import {
ProviderSessionReaper,
type ProviderSessionReaperShape,
} from "../Services/ProviderSessionReaper.ts";
import { forkParked } from "../../serverActivation.ts";
import { ProviderService } from "../Services/ProviderService.ts";
const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;
const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
export interface ProviderSessionReaperLiveOptions {
readonly inactivityThresholdMs?: number;
readonly sweepIntervalMs?: number;
}
const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>
Effect.gen(function* () {
const providerService = yield* ProviderService;
const directory = yield* ProviderSessionDirectory;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const inactivityThresholdMs = Math.max(
1,
options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS,
);
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
const sweep = Effect.gen(function* () {
const bindings = yield* directory.listBindings();
const now = yield* Clock.currentTimeMillis;
let reapedCount = 0;
for (const binding of bindings) {
if (binding.status === "stopped") {
continue;
}
const lastSeenMs = Date.parse(binding.lastSeenAt);
if (Number.isNaN(lastSeenMs)) {
yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", {
threadId: binding.threadId,
provider: binding.provider,
lastSeenAt: binding.lastSeenAt,
});
continue;
}
const idleDurationMs = now - lastSeenMs;
if (idleDurationMs < inactivityThresholdMs) {
continue;
}
const thread = yield* projectionSnapshotQuery
.getThreadShellById(binding.threadId)
.pipe(Effect.map(Option.getOrUndefined));
if (thread?.session?.activeTurnId != null) {
yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", {
threadId: binding.threadId,
activeTurnId: thread.session.activeTurnId,
idleDurationMs,
});
continue;
}
// The turn can settle while background work runs on (subagent
// fleets, workflow runs, Monitor watch loops). Those live inside the
// provider process, so stopping the session would kill them silently,
// and nothing bumps lastSeenAt between turns.
if (thread?.backgroundLiveness != null) {
yield* Effect.logDebug("provider.session.reaper.skipped-background-work", {
threadId: binding.threadId,
backgroundLiveness: thread.backgroundLiveness,
idleDurationMs,
});
continue;
}
const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(
Effect.tap(() =>
Effect.logInfo("provider.session.reaped", {
threadId: binding.threadId,
provider: binding.provider,
idleDurationMs,
reason: "inactivity_threshold",
}),
),
Effect.as(true),
Effect.catchCause((cause) =>
Effect.logWarning("provider.session.reaper.stop-failed", {
threadId: binding.threadId,
provider: binding.provider,
idleDurationMs,
cause,
}).pipe(Effect.as(false)),
),
);
if (reaped) {
reapedCount += 1;
}
}
if (reapedCount > 0) {
yield* Effect.logInfo("provider.session.reaper.sweep-complete", {
reapedCount,
totalBindings: bindings.length,
});
}
});
const start: ProviderSessionReaperShape["start"] = () =>
Effect.gen(function* () {
yield* forkParked(
sweep.pipe(
Effect.catch((error: unknown) =>
Effect.logWarning("provider.session.reaper.sweep-failed", {
error,
}),
),
Effect.catchDefect((defect: unknown) =>
Effect.logWarning("provider.session.reaper.sweep-defect", {
defect,
}),
),
Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),
),
);
yield* Effect.logInfo("provider.session.reaper.started", {
inactivityThresholdMs,
sweepIntervalMs,
});
});
return {
start,
} satisfies ProviderSessionReaperShape;
});
export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>
Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));
export const ProviderSessionReaperLive = makeProviderSessionReaperLive();
File diff suppressed because it is too large. Load diff
-13
View File
@@ -101,11 +101,6 @@ import {
} from "./orchestration-v2/runtimeLayer.ts";
import * as ResourceCleanupService from "./orchestration-v2/ResourceCleanupService.ts";
import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts";
import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts";
import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import {
clearPersistedServerRuntimeState,
makePersistedServerRuntimeState,
@@ -429,10 +424,7 @@ export const makeRoutesLayer = Layer.mergeAll(
Layer.provide(authHttpApiLayer),
Layer.provide(connectHttpApiLayer),
Layer.provide(orchestrationHttpApiLayer),
<<<<<<< HEAD
Layer.provide(pullRequestHttpApiLayer),
=======
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
Layer.provide(projectHttpApiLayer),
Layer.provide(serverEnvironmentHttpApiLayer),
Layer.provide(environmentAuthenticatedAuthLayer),
@@ -442,7 +434,6 @@ export const makeRoutesLayer = Layer.mergeAll(
staticAndDevRouteLayer,
websocketRpcRouteLayer,
),
<<<<<<< HEAD
// The MCP session registry is provided globally (shared with V2 provider
// sessions) rather than inline here.
McpHttpServer.layer,
@@ -450,10 +441,6 @@ export const makeRoutesLayer = Layer.mergeAll(
// Both transports consume the same service instance, so caches single-flight across clients
// and mutations observed on WebSocket invalidate patches subsequently read over HTTP.
Layer.provide(PullRequestServiceLive),
=======
McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
).pipe(
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
Layer.provide(PreviewAutomationBroker.layer),
Layer.provide(ServerSelfUpdate.layer),
Layer.provide(commandReadinessLayer),
+2
View File
@@ -418,6 +418,8 @@ const makeWsRpcLayer = (
);
const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService;
const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService;
const pullRequests = yield* PullRequestService.PullRequestService;
const usage = yield* UsageService.UsageService;
const projectService = yield* ProjectService.ProjectService;
const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const keybindings = yield* Keybindings.Keybindings;
@@ -14,13 +14,9 @@ import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalSt
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import { cn, isMacPlatform } from "../lib/utils";
import { primaryServerKeybindingsAtom } from "../state/server";
<<<<<<< HEAD
import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";
import LegacyThreadSidebar from "./LegacySidebar";
=======
import { useEnvironmentIdentificationMode, useSidebarV2Enabled } from "../hooks/useSettings";
import { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration";
>>>>>>> 844dad005a (feat(orchestration): track provider retries and thread visits)
import ThreadSidebar from "./Sidebar";
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
import { SidebarChromeHeader } from "./sidebar/SidebarChrome";
@@ -143,18 +139,11 @@ function ProjectProjectionRetention() {
export function AppSidebarLayout({ children }: { children: ReactNode }) {
const navigate = useNavigate();
<<<<<<< HEAD
const legacySidebarEnabled = useLegacySidebarEnabled();
// Settings routes show the settings nav in place of whichever thread
// sidebar is active.
=======
const sidebarV2Enabled = useSidebarV2Enabled();
// Seeds server-side visited tracking from this browser's localStorage the
// first time each thread shell loads (no-op on already-seeded servers).
useThreadVisitedMigration();
// Settings routes render the settings nav, which lives in the v1 component
// and is identical for both sidebars — so v1 stays mounted there.
>>>>>>> 844dad005a (feat(orchestration): track provider retries and thread visits)
const pathname = useLocation({ select: (location) => location.pathname });
const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
@@ -68,26 +68,11 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
);
if (envLocked) {
<<<<<<< HEAD
return (
<span className="inline-flex h-7 shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs">
{activeWorktreePath ? (
<>
<FolderGitIcon className="size-3" />
{resolveLockedWorkspaceLabel(activeWorktreePath)}
</>
) : (
<>
<FolderIcon className="size-3" />
{resolveLockedWorkspaceLabel(activeWorktreePath)}
</>
=======
const lockedRow = (
<span
className={cn(
"inline-flex shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs",
displayMode === "panel" && THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
)}
>
{activeWorktreePath ? (
@@ -55,16 +55,12 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
// only thing in the strip.
if (envLocked || onEnvironmentChange === undefined) {
return (
<<<<<<< HEAD
<span className="inline-flex h-7 min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs">
=======
<span
className={cn(
"inline-flex min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs",
displayMode === "panel" && THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
)}
>
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
{activeEnvironment?.isPrimary ? (
<MonitorIcon
className={
+112 -1
View File
@@ -131,6 +131,7 @@ import {
resolveThreadPanelPresentation,
} from "../rightPanelLayout";
import {
pullRequestSurfaceId,
selectActiveRightPanel,
selectActiveRightPanelSurface,
selectThreadPanelOpen,
@@ -152,7 +153,10 @@ import {
selectThreadPreviewMiniPlayer,
usePreviewMiniPlayerStore,
} from "../previewMiniPlayerStore";
import { RightPanelTabs } from "./RightPanelTabs";
import { PullRequestDetailPanel } from "./pullRequest/PullRequestDetailPanel";
import { PullRequestDetailGhost } from "./pullRequest/PullRequestGhosts";
import { PullRequestsUnavailableState } from "./pullRequest/PullRequestsUnavailableState";
import { RightPanelTabs, type PullRequestTabStatus } from "./RightPanelTabs";
import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
import { BranchToolbar } from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
@@ -1666,6 +1670,17 @@ function ChatViewContent(props: ChatViewProps) {
const activeRightPanelSurface = useRightPanelStore((state) =>
selectActiveRightPanelSurface(state.byThreadKey, activeThreadRef),
);
const [pullRequestTabStatuses, setPullRequestTabStatuses] = useState<
Record<string, PullRequestTabStatus>
>({});
const handlePullRequestTabStatusChange = useCallback((status: PullRequestTabStatus) => {
const id = pullRequestSurfaceId(status);
setPullRequestTabStatuses((current) =>
current[id]?.state === status.state && current[id]?.isDraft === status.isDraft
? current
: { ...current, [id]: status },
);
}, []);
const activeFileSurface =
activeRightPanelSurface?.kind === "file" ? activeRightPanelSurface : null;
const activePreviewState = useThreadPreviewState(activeThreadRef);
@@ -2054,6 +2069,8 @@ function ChatViewContent(props: ChatViewProps) {
const serverConfig = activeThread
? (activeEnvironment?.serverConfig ?? null)
: (primaryEnvironment?.serverConfig ?? null);
const pullRequestsCapabilityKnown = serverConfig !== null;
const supportsPullRequests = serverConfig?.environment.capabilities.pullRequests === true;
const versionMismatch = resolveServerConfigVersionMismatch(serverConfig);
const versionMismatchDismissKey =
versionMismatch && activeThread
@@ -3288,6 +3305,27 @@ function ChatViewContent(props: ChatViewProps) {
},
[activeProject, activeThreadRef],
);
// The thread's own change request, placed against the project it belongs to. Without a
// project there is nothing to resolve it against, so the caller falls back to the browser.
const threadRepository = activeProject?.repositoryIdentity?.displayName ?? null;
const openThreadPullRequest = useCallback(
(number: number) => {
if (
!supportsPullRequests ||
!activeThreadRef ||
!activeProject ||
threadRepository === null
) {
return;
}
useRightPanelStore.getState().openPullRequest(activeThreadRef, {
projectId: activeProject.id,
repository: threadRepository,
number,
});
},
[activeProject, activeThreadRef, supportsPullRequests, threadRepository],
);
const togglePreviewPanel = useCallback(() => {
if (!activeThreadRef || !isPreviewSupportedInRuntime()) return;
if (previewPanelOpen) {
@@ -4233,6 +4271,14 @@ function ChatViewContent(props: ChatViewProps) {
threadBranch: activeThread?.branch ?? null,
gitStatus: gitStatusQuery.data ?? null,
});
// The right panel offers the thread's own change request, so it can only offer it once the
// branch has one; until then the picker says so rather than opening an empty panel.
const addPullRequestSurface = useCallback(() => {
if (activeThreadPr === null) return;
openThreadPullRequest(activeThreadPr.number);
}, [activeThreadPr, openThreadPullRequest]);
const pullRequestSurfaceAvailable =
supportsPullRequests && activeThreadPr !== null && threadRepository !== null;
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
const nowMinute = useNowMinute();
@@ -6083,6 +6129,35 @@ function ChatViewContent(props: ChatViewProps) {
initialGitScope={initialDiffPanelGitScope}
/>
</Suspense>
) : activeRightPanelSurface?.kind === "pull-request" && !pullRequestsCapabilityKnown ? (
<PullRequestDetailGhost />
) : activeRightPanelSurface?.kind === "pull-request" && !supportsPullRequests ? (
<PullRequestsUnavailableState
title="Pull requests unavailable"
error="Update this environment's T3 Code server to browse pull requests."
/>
) : activeRightPanelSurface?.kind === "pull-request" ? (
// No onClose: the surface tab's own X owns closing here, and a second X in the header
// would be the same action twice. The thread context also drops the checkout button, so it
// is only right for the thread's own pull request, whose branch is already under the
// reader's feet. A link the agent wrote can open any other one here, and that one has to be
// checkable out like it is anywhere else.
<PullRequestDetailPanel
key={`${activeRightPanelSurface.repository}#${activeRightPanelSurface.number}`}
environmentId={activeThread.environmentId}
reference={{
projectId: activeRightPanelSurface.projectId as ProjectId,
repository: activeRightPanelSurface.repository,
number: activeRightPanelSurface.number,
}}
context={
activeThreadPr?.number === activeRightPanelSurface.number &&
threadRepository === activeRightPanelSurface.repository
? "thread"
: "page"
}
onStateChange={handlePullRequestTabStatusChange}
/>
) : activeRightPanelSurface?.kind === "agents" ? (
<AgentsPanel
model={agentPanelModel}
@@ -6186,6 +6261,10 @@ function ChatViewContent(props: ChatViewProps) {
rightPanelAvailable: activeProject !== null,
rightPanelOpen,
rightPanelShortcutLabel: shortcutLabelForCommand(keybindings, "rightPanel.toggle"),
// Suppressed while the Agents surface is visible: the roster itself is
// on screen, so the toggle badge would be pointing at nothing.
liveAgentCount:
rightPanelOpen && activeRightPanelSurface?.kind === "agents" ? 0 : agentPanelModel.liveCount,
onToggleTerminal: toggleTerminalVisibility,
onToggleThreadPanel: toggleThreadPanel,
onToggleRightPanel: toggleRightPanel,
@@ -6259,12 +6338,32 @@ function ChatViewContent(props: ChatViewProps) {
? panelLayoutControls
: null}
<ChatHeader
{...(!supportsPullRequests || threadRepository === null
? {}
: { onOpenPullRequest: openThreadPullRequest })}
activeThreadEnvironmentId={activeThread.environmentId}
activeThreadId={activeThread.id}
{...(routeKind === "draft" && draftId ? { draftId } : {})}
activeThreadTitle={activeThread.title}
isServerThread={isServerThread}
changeRequestState={activeThreadPr?.state ?? null}
activeProjectName={activeProject?.title}
activeProjectCwd={activeProject?.workspaceRoot ?? null}
activeProjectFaviconPath={activeProject?.faviconPath ?? null}
openInCwd={gitCwd}
activeProjectScripts={activeProject?.scripts}
preferredScriptId={
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
}
keybindings={keybindings}
availableEditors={availableEditors}
rightPanelOpen={inlineRightPanelOwnsTitleBar}
gitCwd={gitCwd}
onNewThreadInProject={handleNewThreadInActiveProject}
onRunProjectScript={runProjectScript}
onAddProjectScript={saveProjectScript}
onUpdateProjectScript={updateProjectScript}
onDeleteProjectScript={deleteProjectScript}
/>
</header>
@@ -6657,10 +6756,16 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddPullRequest={addPullRequestSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
terminalAvailable={activeProject !== null}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
pullRequestAvailable={pullRequestSurfaceAvailable}
agentsAvailable
pullRequestStatuses={pullRequestTabStatuses}
liveAgentCount={agentPanelModel.liveCount}
>
{rightPanelContent}
</RightPanelTabs>
@@ -6686,10 +6791,16 @@ function ChatViewContent(props: ChatViewProps) {
onAddTerminal={addTerminalSurface}
onAddDiff={addDiffSurface}
onAddFiles={addFilesSurface}
onAddPullRequest={addPullRequestSurface}
onAddAgents={addAgentsSurface}
browserAvailable={isPreviewSupportedInRuntime()}
terminalAvailable={activeProject !== null}
diffAvailable={isServerThread && isGitRepo}
filesAvailable={activeProject !== null}
pullRequestAvailable={pullRequestSurfaceAvailable}
agentsAvailable
pullRequestStatuses={pullRequestTabStatuses}
liveAgentCount={agentPanelModel.liveCount}
>
{rightPanelContent}
</RightPanelTabs>
+1 -7
View File
@@ -323,13 +323,7 @@ export default function DiffPanel({
headRef: selectedGitSource.headRef,
cacheKey: selectedGitSource.diffHash,
});
}, [
activeThread,
branchDiffPreview.data,
getDiffFileContents,
selectedGitSource,
selectedTurnId,
]);
}, [activeThread, branchDiffPreview.data, getDiffFileContents, selectedGitSource, selectedRunId]);
const localBranchRefs = useEnvironmentQuery(
selectedRunId === null &&
selectedGitScope === "branch" &&
@@ -36,6 +36,7 @@ import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "~/compon
import { RadioGroup } from "~/components/ui/radio-group";
import { Spinner } from "~/components/ui/spinner";
import { cn } from "~/lib/utils";
import { openPullRequestLink } from "~/lib/openPullRequestLink";
import {
buildMenuItems,
formatGitActionElapsed,
+4 -4
View File
@@ -448,7 +448,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
[discoveredPorts, navigateToThread, openPreview, threadRef],
);
const isThreadRunning =
thread.session?.status === "running" && thread.session.activeTurnId != null;
thread.runtime?.status === "running" && thread.runtime.activeRunId != null;
const threadStatus = resolveThreadStatusPill({
thread: {
...thread,
@@ -1793,7 +1793,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
return threadRef && thread ? [{ threadKey, threadRef, thread }] : [];
});
const hasRunningThread = selectedThreadEntries.some(
({ thread }) => thread.session?.status === "running" && thread.session.activeTurnId != null,
({ thread }) => thread.runtime?.status === "running" && thread.runtime.activeRunId != null,
);
const clicked = await api.contextMenu.show(
@@ -1803,7 +1803,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
if (clicked === "mark-unread") {
for (const { threadKey, thread } of selectedThreadEntries) {
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
markThreadUnread(threadKey, thread.latestRun?.completedAt);
}
clearSelection();
return;
@@ -2181,7 +2181,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
}
if (clicked === "mark-unread") {
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
markThreadUnread(threadKey, thread.latestRun?.completedAt);
return;
}
if (clicked === "copy-path") {
@@ -7,8 +7,8 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { ChevronDownIcon, DownloadIcon, PlusIcon, SettingsIcon } from "lucide-react";
import { useCallback, useMemo, useState } from "react";
import { ChevronDownIcon, DownloadIcon, PlusIcon, SettingsIcon, WrenchIcon } from "lucide-react";
import React, { useCallback, useMemo, useState } from "react";
import { commandForProjectScript, primaryProjectScript } from "~/projectScripts";
import { shortcutLabelForCommand } from "~/keybindings";
@@ -77,14 +77,11 @@ export default function ProjectScriptsControl({
onUpdateScript,
onDeleteScript,
}: ProjectScriptsControlProps) {
<<<<<<< HEAD
=======
const isPanel = displayMode === "panel";
const ActionGroup = isPanel ? "div" : Group;
const panelAnchorRef = React.useRef<HTMLDivElement | null>(null);
const addScriptFormId = React.useId();
const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
const [actionsMenuOpen, setActionsMenuOpen] = useState({
scripts: false,
imports: false,
@@ -42,14 +42,11 @@ import { PierreEntryIcon } from "./chat/PierreEntryIcon";
interface RightPanelTabsProps {
mode: PreviewPanelMode;
maximized?: boolean;
<<<<<<< HEAD
/** Forwarded to PreviewPanelShell so this surface persists its own width. */
widthStorageKey?: string;
/** Forwarded to PreviewPanelShell as the initial width before a user resize. */
defaultWidth?: number;
=======
inlineSize?: PreviewPanelInlineSize;
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
layoutControls?: ReactNode;
surfaces: readonly RightPanelSurface[];
activeSurfaceId: string | null;
@@ -603,12 +600,9 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<PreviewPanelShell
mode={props.mode}
{...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
<<<<<<< HEAD
{...(props.widthStorageKey !== undefined ? { widthStorageKey: props.widthStorageKey } : {})}
{...(props.defaultWidth !== undefined ? { defaultWidth: props.defaultWidth } : {})}
=======
{...(props.inlineSize ? { inlineSize: props.inlineSize } : {})}
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
>
<div
className={cn(
+151 -165
View File
@@ -1,48 +1,45 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import {
THREAD_JUMP_HINT_SHOW_DELAY_MS,
archiveSelectedThreadEntries,
buildBulkTitleRegenerationContextMenuItem,
buildMultiSelectThreadContextMenuItems,
createThreadJumpHintVisibilityController,
filterSidebarV2VisibleThreads,
getSidebarThreadIdsToPrewarm,
getVisibleSidebarThreadIds,
resolveAdjacentThreadId,
formatWorkingDurationLabel,
getFallbackThreadIdAfterDelete,
getVisibleThreadsForProject,
getProjectSortTimestamp,
getSidebarForkParentThreadId,
getSidebarThreadIdsToPrewarm,
getVisibleSidebarThreadIds,
getVisibleThreadsForProject,
hasUnseenCompletion,
isContextMenuPointerDown,
isSidebarSubagentThread,
isTrailingDoubleClick,
orderItemsByPreferredIds,
pinOrderKeyBetween,
planPinnedReorder,
resolveAdjacentThreadId,
resolveProjectStatusIndicator,
resolveSidebarStageBadgeLabel,
resolveThreadRowClassName,
resolveSidebarThreadStatus,
resolveSidebarV2Status,
resolveSidebarV2TopStatus,
resolveThreadLastVisitedAt,
resolveThreadRowClassName,
resolveThreadStatusPill,
resolveWorkingStartedAt,
searchSidebarThreadsByTitle,
formatWorkingDurationLabel,
shouldShowSidebarV2Duration,
shouldNavigateAfterProjectRemoval,
shouldClearThreadSelectionOnMouseDown,
shouldNavigateAfterProjectRemoval,
shouldShowSidebarV2Duration,
sortLogicalProjectsForSidebar,
sortSettledThreadsForSidebar,
pinOrderKeyBetween,
planPinnedReorder,
sortPinnedThreadsForSidebar,
sortThreadsForSidebar,
sortSidebarV2ProjectGroups,
resolveThreadLastVisitedAt,
sortSettledThreadsForSidebarV2,
sortThreadsForSidebarV2,
sortScopedProjectsForSidebar,
sortProjectsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
sortScopedProjectsForSidebar,
sortSettledThreadsForSidebar,
sortSidebarV2ProjectGroups,
sortThreadsForSidebar,
} from "./Sidebar.logic";
import { EnvironmentId, ProjectId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts";
import {
@@ -721,9 +718,6 @@ describe("isContextMenuPointerDown", () => {
});
describe("resolveSidebarThreadStatus", () => {
const session = {
threadId: ThreadId.make("thread-1"),
describe("resolveSidebarV2Status", () => {
const runtime = {
status: "running" as const,
activeRunId: null,
@@ -735,20 +729,16 @@ describe("resolveSidebarV2Status", () => {
const idle = { hasPendingApprovals: false, hasPendingUserInput: false, runtime: null };
it("prioritizes approval over a running session", () => {
expect(resolveSidebarThreadStatus({ ...idle, hasPendingApprovals: true, session })).toBe(
it("prioritizes approval over a running runtime", () => {
expect(resolveSidebarV2Status({ ...idle, hasPendingApprovals: true, runtime })).toBe(
expect(resolveSidebarThreadStatus({ ...idle, hasPendingApprovals: true, runtime })).toBe(
"approval",
);
});
it("prioritizes awaiting input over a running session, below approval", () => {
expect(resolveSidebarThreadStatus({ ...idle, hasPendingUserInput: true, session })).toBe(
it("prioritizes awaiting input over a running runtime, below approval", () => {
expect(resolveSidebarThreadStatus({ ...idle, hasPendingUserInput: true, runtime })).toBe(
"input",
);
it("prioritizes awaiting input over a running runtime, below approval", () => {
expect(resolveSidebarV2Status({ ...idle, hasPendingUserInput: true, runtime })).toBe("input");
expect(
resolveSidebarThreadStatus({
...idle,
@@ -759,10 +749,8 @@ describe("resolveSidebarV2Status", () => {
).toBe("approval");
});
it("reports working for running and starting sessions", () => {
expect(resolveSidebarThreadStatus({ ...idle, session })).toBe("working");
it("reports working for running and starting runtimes", () => {
expect(resolveSidebarV2Status({ ...idle, runtime })).toBe("working");
expect(resolveSidebarThreadStatus({ ...idle, runtime })).toBe("working");
expect(
resolveSidebarThreadStatus({
...idle,
@@ -792,10 +780,8 @@ describe("resolveSidebarV2Status", () => {
).toBe("waiting");
});
it("defaults to ready with no session", () => {
expect(resolveSidebarThreadStatus({ ...idle, session: null })).toBe("ready");
it("defaults to ready with no runtime", () => {
expect(resolveSidebarV2Status(idle)).toBe("ready");
expect(resolveSidebarThreadStatus(idle)).toBe("ready");
});
it("keeps a waiting runtime visible ahead of unread and woke presentation", () => {
@@ -856,136 +842,6 @@ describe("sortThreadsForSidebar", () => {
});
});
describe("pinOrderKeyBetween", () => {
it("produces keys that sort between their bounds", () => {
const middle = pinOrderKeyBetween(null, null)!;
const top = pinOrderKeyBetween(null, middle)!;
const bottom = pinOrderKeyBetween(middle, null)!;
expect(top < middle).toBe(true);
expect(middle < bottom).toBe(true);
const between = pinOrderKeyBetween(top, middle)!;
expect(top < between && between < middle).toBe(true);
});
it("extends into new digits when bounds are adjacent", () => {
const key = pinOrderKeyBetween("g", "h")!;
expect("g" < key && key < "h").toBe(true);
});
it("stays strictly ordered under repeated top insertion", () => {
// Every new pin lands at the head of the arranged run; keys must keep
// sorting before the previous head without ever bottoming out.
let head: string | null = null;
const keys: string[] = [];
for (let i = 0; i < 100; i += 1) {
const key: string = pinOrderKeyBetween(null, head)!;
expect(key).not.toBeNull();
if (head !== null) expect(key < head).toBe(true);
keys.push(key);
head = key;
}
expect(new Set(keys).size).toBe(100);
});
it("stays strictly ordered under repeated middle insertion", () => {
let low = pinOrderKeyBetween(null, null)!;
let high = pinOrderKeyBetween(low, null)!;
for (let i = 0; i < 100; i += 1) {
const key: string = pinOrderKeyBetween(low, high)!;
expect(low < key && key < high).toBe(true);
if (i % 2 === 0) low = key;
else high = key;
}
});
it("returns null for corrupt or out-of-order bounds instead of throwing", () => {
expect(pinOrderKeyBetween("z", "a")).toBeNull();
expect(pinOrderKeyBetween("A!", null)).toBeNull();
expect(pinOrderKeyBetween(null, "ma")).toBeNull();
expect(pinOrderKeyBetween("m", "m")).toBeNull();
});
});
describe("planPinnedReorder", () => {
it("writes only the moved thread when neighbors are keyed", () => {
const assignments = planPinnedReorder({
orderedIds: ["a", "c", "b"],
keysById: new Map([
["a", "f"],
["b", "m"],
["c", "t"],
]),
movedId: "c",
});
expect(assignments).toHaveLength(1);
expect(assignments[0]!.id).toBe("c");
expect(assignments[0]!.orderKey > "f" && assignments[0]!.orderKey < "m").toBe(true);
});
it("treats list edges as open bounds", () => {
const assignments = planPinnedReorder({
orderedIds: ["b", "a"],
keysById: new Map([
["a", "m"],
["b", null],
]),
movedId: "b",
});
expect(assignments).toHaveLength(1);
expect(assignments[0]!.orderKey < "m").toBe(true);
});
it("materializes keys for the whole section when a neighbor is keyless", () => {
const assignments = planPinnedReorder({
orderedIds: ["b", "a", "c"],
keysById: new Map([
["a", null],
["b", "m"],
["c", null],
]),
movedId: "b",
});
expect(assignments.map((entry) => entry.id)).toEqual(["b", "a", "c"]);
const keys = assignments.map((entry) => entry.orderKey);
expect([...keys].sort()).toEqual(keys);
expect(new Set(keys).size).toBe(keys.length);
});
});
describe("sortPinnedThreadsForSidebar", () => {
const pinnable = (input: { id: string; createdAt: string; pinOrderKey?: string | null }) => ({
id: input.id,
createdAt: input.createdAt,
pinOrderKey: input.pinOrderKey ?? null,
});
it("sorts keyed threads by key ahead of keyless threads in creation order", () => {
const sorted = sortPinnedThreadsForSidebar([
pinnable({ id: "keyless-old", createdAt: "2026-03-09T08:00:00.000Z" }),
pinnable({ id: "second", createdAt: "2026-03-09T09:00:00.000Z", pinOrderKey: "t" }),
pinnable({ id: "keyless-new", createdAt: "2026-03-09T12:00:00.000Z" }),
pinnable({ id: "first", createdAt: "2026-03-09T07:00:00.000Z", pinOrderKey: "g" }),
]);
expect(sorted.map((thread) => thread.id)).toEqual([
"first",
"second",
"keyless-new",
"keyless-old",
]);
});
it("breaks equal keys by id so raced writes render identically everywhere", () => {
const sorted = sortPinnedThreadsForSidebar([
pinnable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z", pinOrderKey: "m" }),
pinnable({ id: "a", createdAt: "2026-03-09T11:00:00.000Z", pinOrderKey: "m" }),
]);
expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
});
});
describe("sortSettledThreadsForSidebar", () => {
const settled = (input: {
id: string;
@@ -1876,3 +1732,133 @@ describe("resolveThreadLastVisitedAt", () => {
expect(resolveThreadLastVisitedAt(null, "2026-07-30T10:00:00.000Z")).toBeUndefined();
});
});
describe("pinOrderKeyBetween", () => {
it("produces keys that sort between their bounds", () => {
const middle = pinOrderKeyBetween(null, null)!;
const top = pinOrderKeyBetween(null, middle)!;
const bottom = pinOrderKeyBetween(middle, null)!;
expect(top < middle).toBe(true);
expect(middle < bottom).toBe(true);
const between = pinOrderKeyBetween(top, middle)!;
expect(top < between && between < middle).toBe(true);
});
it("extends into new digits when bounds are adjacent", () => {
const key = pinOrderKeyBetween("g", "h")!;
expect("g" < key && key < "h").toBe(true);
});
it("stays strictly ordered under repeated top insertion", () => {
// Every new pin lands at the head of the arranged run; keys must keep
// sorting before the previous head without ever bottoming out.
let head: string | null = null;
const keys: string[] = [];
for (let i = 0; i < 100; i += 1) {
const key: string = pinOrderKeyBetween(null, head)!;
expect(key).not.toBeNull();
if (head !== null) expect(key < head).toBe(true);
keys.push(key);
head = key;
}
expect(new Set(keys).size).toBe(100);
});
it("stays strictly ordered under repeated middle insertion", () => {
let low = pinOrderKeyBetween(null, null)!;
let high = pinOrderKeyBetween(low, null)!;
for (let i = 0; i < 100; i += 1) {
const key: string = pinOrderKeyBetween(low, high)!;
expect(low < key && key < high).toBe(true);
if (i % 2 === 0) low = key;
else high = key;
}
});
it("returns null for corrupt or out-of-order bounds instead of throwing", () => {
expect(pinOrderKeyBetween("z", "a")).toBeNull();
expect(pinOrderKeyBetween("A!", null)).toBeNull();
expect(pinOrderKeyBetween(null, "ma")).toBeNull();
expect(pinOrderKeyBetween("m", "m")).toBeNull();
});
});
describe("planPinnedReorder", () => {
it("writes only the moved thread when neighbors are keyed", () => {
const assignments = planPinnedReorder({
orderedIds: ["a", "c", "b"],
keysById: new Map([
["a", "f"],
["b", "m"],
["c", "t"],
]),
movedId: "c",
});
expect(assignments).toHaveLength(1);
expect(assignments[0]!.id).toBe("c");
expect(assignments[0]!.orderKey > "f" && assignments[0]!.orderKey < "m").toBe(true);
});
it("treats list edges as open bounds", () => {
const assignments = planPinnedReorder({
orderedIds: ["b", "a"],
keysById: new Map([
["a", "m"],
["b", null],
]),
movedId: "b",
});
expect(assignments).toHaveLength(1);
expect(assignments[0]!.orderKey < "m").toBe(true);
});
it("materializes keys for the whole section when a neighbor is keyless", () => {
const assignments = planPinnedReorder({
orderedIds: ["b", "a", "c"],
keysById: new Map([
["a", null],
["b", "m"],
["c", null],
]),
movedId: "b",
});
expect(assignments.map((entry) => entry.id)).toEqual(["b", "a", "c"]);
const keys = assignments.map((entry) => entry.orderKey);
expect([...keys].sort()).toEqual(keys);
expect(new Set(keys).size).toBe(keys.length);
});
});
describe("sortPinnedThreadsForSidebar", () => {
const pinnable = (input: { id: string; createdAt: string; pinOrderKey?: string | null }) => ({
id: input.id,
createdAt: input.createdAt,
pinOrderKey: input.pinOrderKey ?? null,
});
it("sorts keyed threads by key ahead of keyless threads in creation order", () => {
const sorted = sortPinnedThreadsForSidebar([
pinnable({ id: "keyless-old", createdAt: "2026-03-09T08:00:00.000Z" }),
pinnable({ id: "second", createdAt: "2026-03-09T09:00:00.000Z", pinOrderKey: "t" }),
pinnable({ id: "keyless-new", createdAt: "2026-03-09T12:00:00.000Z" }),
pinnable({ id: "first", createdAt: "2026-03-09T07:00:00.000Z", pinOrderKey: "g" }),
]);
expect(sorted.map((thread) => thread.id)).toEqual([
"first",
"second",
"keyless-new",
"keyless-old",
]);
});
it("breaks equal keys by id so raced writes render identically everywhere", () => {
const sorted = sortPinnedThreadsForSidebar([
pinnable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z", pinOrderKey: "m" }),
pinnable({ id: "a", createdAt: "2026-03-09T11:00:00.000Z", pinOrderKey: "m" }),
]);
expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]);
});
});
+4 -13
View File
@@ -495,8 +495,6 @@ export function resolveThreadRowClassName(input: {
);
}
// ── Sidebar thread status model ─────────────────────────────────────
// Five visual states, three colors: color is reserved for "act now"
// ── Sidebar v2 status model ─────────────────────────────────────────
// Six visual states, three colors: color is reserved for "act now"
// (approval), "in motion" (working), and "broken" (failed). Ready is the
@@ -507,14 +505,7 @@ export function resolveThreadRowClassName(input: {
// false Done.
// Unread completion is tracked separately: it describes whether a ready
// thread needs attention, not what the thread is currently doing.
export type SidebarThreadStatus =
| "approval"
| "input"
| "working"
| "monitoring"
| "failed"
| "ready";
export type SidebarV2Status = "approval" | "input" | "working" | "waiting" | "failed" | "ready";
export type SidebarThreadStatus = "approval" | "input" | "working" | "waiting" | "failed" | "ready";
type SidebarThreadStatusInput = Pick<
SidebarThreadSummary,
@@ -553,7 +544,7 @@ export type SidebarV2TopStatusKind =
| "working";
export function resolveSidebarV2TopStatus(input: {
readonly status: SidebarV2Status;
readonly status: SidebarThreadStatus;
readonly isUnread: boolean;
readonly isWoke: boolean;
}): SidebarV2TopStatusKind | null {
@@ -578,7 +569,7 @@ export function resolveSidebarV2TopStatus(input: {
return input.isUnread ? "done" : null;
}
export function shouldShowSidebarV2Duration(status: SidebarV2Status): boolean {
export function shouldShowSidebarV2Duration(status: SidebarThreadStatus): boolean {
return status === "working";
}
@@ -615,7 +606,7 @@ export function firstValidTimestamp(
return null;
}
// Sidebar sort: static creation order, newest thread on top. Activity NEVER
// v2 sort: static creation order, newest thread on top. Activity NEVER
// reorders the list — a row holds its position from open until settled, so
// the screen only moves at lifecycle transitions. Status (including pending
// approval) is carried by each card's edge strip, not by position.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+298 -42
View File
@@ -1,84 +1,340 @@
import { type EnvironmentId } from "@t3tools/contracts";
import { memo } from "react";
import { cn } from "~/lib/utils";
import { ProjectFavicon } from "../ProjectFavicon";
import {
type EnvironmentId,
type EditorId,
type ProjectScript,
type ResolvedKeybindingsConfig,
type ThreadId,
} from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { ChangeRequestStateLike } from "@t3tools/client-runtime/state/thread-settled";
import { ChevronDownIcon } from "lucide-react";
import {
memo,
useCallback,
useMemo,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
} from "react";
import GitActionsControl from "../GitActionsControl";
import { type DraftId } from "~/composerDraftStore";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { toastManager } from "../ui/toast";
import ProjectScriptsControl, {
type NewProjectScriptInput,
type ProjectScriptActionResult,
} from "../ProjectScriptsControl";
import { OpenInPicker } from "./OpenInPicker";
import { usePrimaryEnvironmentId } from "../../state/environments";
import { useT3ProjectFileScripts } from "~/hooks/useT3ProjectFileScripts";
import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { ProjectFavicon } from "../ProjectFavicon";
import {
WorkspaceBreadcrumb,
WorkspaceBreadcrumbItem,
WorkspaceBreadcrumbSeparator,
} from "../WorkspaceBreadcrumb";
import { cn } from "~/lib/utils";
interface ChatHeaderProps {
activeThreadEnvironmentId: EnvironmentId;
activeThreadId: ThreadId;
draftId?: DraftId;
activeThreadTitle: string;
/** Drafts have no server thread yet, so the title carries no action menu. */
isServerThread: boolean;
/** PR state feeding the settled classification, resolved by ChatView. */
changeRequestState: ChangeRequestStateLike | null;
activeProjectName: string | undefined;
activeProjectCwd: string | null;
activeProjectFaviconPath: string | null;
openInCwd: string | null;
activeProjectScripts: ReadonlyArray<ProjectScript> | undefined;
preferredScriptId: string | null;
keybindings: ResolvedKeybindingsConfig;
availableEditors: ReadonlyArray<EditorId>;
rightPanelOpen: boolean;
gitCwd: string | null;
readonly onOpenPullRequest?: ((number: number) => void) | undefined;
onNewThreadInProject: () => void;
onRunProjectScript: (script: ProjectScript) => void;
onAddProjectScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
onUpdateProjectScript: (
scriptId: string,
input: NewProjectScriptInput,
) => Promise<ProjectScriptActionResult>;
onDeleteProjectScript: (scriptId: string) => Promise<ProjectScriptActionResult>;
}
/**
* Rename commit rule shared with the sidebar's inline rename: trim, reject
* empty (the caller toasts), and skip the mutation when nothing changed.
*/
export function resolveRenameCommit(input: {
readonly title: string;
readonly originalTitle: string;
}): { action: "commit"; title: string } | { action: "reject-empty" } | { action: "noop" } {
const trimmed = input.title.trim();
if (trimmed.length === 0) return { action: "reject-empty" };
if (trimmed === input.originalTitle) return { action: "noop" };
return { action: "commit", title: trimmed };
}
export function shouldShowOpenInPicker(input: {
readonly activeProjectName: string | undefined;
readonly activeThreadEnvironmentId: EnvironmentId;
readonly primaryEnvironmentId: EnvironmentId | null;
}): boolean {
return (
Boolean(input.activeProjectName) &&
input.primaryEnvironmentId !== null &&
input.activeThreadEnvironmentId === input.primaryEnvironmentId
);
}
export const ChatHeader = memo(function ChatHeader({
activeThreadEnvironmentId,
activeThreadId,
draftId,
activeThreadTitle,
isServerThread,
changeRequestState,
activeProjectName,
activeProjectCwd,
activeProjectFaviconPath,
openInCwd,
activeProjectScripts,
preferredScriptId,
keybindings,
availableEditors,
rightPanelOpen,
gitCwd,
onOpenPullRequest,
onNewThreadInProject,
onRunProjectScript,
onAddProjectScript,
onUpdateProjectScript,
onDeleteProjectScript,
}: ChatHeaderProps) {
const primaryEnvironmentId = usePrimaryEnvironmentId();
const fileScripts = useT3ProjectFileScripts(
activeThreadEnvironmentId,
activeProjectScripts ? activeProjectCwd : null,
);
const showOpenInPicker = shouldShowOpenInPicker({
activeProjectName,
activeThreadEnvironmentId,
primaryEnvironmentId,
});
const activeThreadRef = useMemo(
() => scopeThreadRef(activeThreadEnvironmentId, activeThreadId),
[activeThreadEnvironmentId, activeThreadId],
);
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
// Inline rename, keyed by thread: navigating away drops an in-progress
// rename instead of committing stale text. Cleared on thread change (not
// just hidden) so returning to the thread doesn't revive the old draft.
const [renaming, setRenaming] = useState<{ threadId: ThreadId; title: string } | null>(null);
if (renaming !== null && renaming.threadId !== activeThreadId) {
setRenaming(null);
}
const renamingTitle = renaming?.threadId === activeThreadId ? renaming.title : null;
const renameCommittedRef = useRef(false);
const startRename = useCallback(() => {
renameCommittedRef.current = false;
setRenaming({ threadId: activeThreadId, title: activeThreadTitle });
}, [activeThreadId, activeThreadTitle]);
const commitRename = useCallback(
(title: string) => {
setRenaming(null);
const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle });
if (resolution.action === "reject-empty") {
toastManager.add({ type: "warning", title: "Thread title cannot be empty" });
return;
}
if (resolution.action === "noop") return;
void updateThreadMetadata({
environmentId: activeThreadEnvironmentId,
input: { threadId: activeThreadId, title: resolution.title },
}).then((result) => {
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add({
type: "error",
title: "Failed to rename thread",
description: error instanceof Error ? error.message : "An error occurred.",
});
}
});
},
[activeThreadEnvironmentId, activeThreadId, activeThreadTitle, updateThreadMetadata],
);
const { openMenu } = useThreadActionMenu({
threadRef: isServerThread ? activeThreadRef : null,
projectCwd: activeProjectCwd,
changeRequestState,
onStartRename: startRename,
});
const titleButtonRef = useRef<HTMLButtonElement | null>(null);
const openMenuFromTitle = useCallback(() => {
const rect = titleButtonRef.current?.getBoundingClientRect();
if (!rect) return;
openMenu({ x: rect.left, y: rect.bottom + 4 });
}, [openMenu]);
const handleHeaderContextMenu = useCallback(
(event: ReactMouseEvent) => {
if (!isServerThread || renamingTitle !== null) return;
// The right-side controls (git, scripts, open-in) keep their own
// behavior; only the breadcrumb area opens the thread menu.
if ((event.target as HTMLElement).closest("[data-chat-header-actions]")) return;
event.preventDefault();
openMenu({ x: event.clientX, y: event.clientY });
},
[isServerThread, openMenu, renamingTitle],
);
const handleRenameKeyDown = useCallback(
(event: ReactKeyboardEvent<HTMLInputElement>) => {
if (event.key === "Enter") {
renameCommittedRef.current = true;
commitRename(event.currentTarget.value);
} else if (event.key === "Escape") {
renameCommittedRef.current = true;
setRenaming(null);
}
},
[commitRename],
);
return (
<div
className={cn(
"flex min-w-0 flex-1 items-center gap-2 sm:gap-3",
rightPanelOpen ? "pr-10" : "pr-24",
)}
className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3"
onContextMenu={handleHeaderContextMenu}
>
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
<WorkspaceBreadcrumb ariaLabel="Thread breadcrumb" className="flex-1">
{/* The project always leads the header: knowing which project a
thread lives in is priority zero, and the thread title alone
doesn't answer it. */}
{activeProjectName ? (
<span className="inline-flex shrink-0 items-center gap-2">
<>
<WorkspaceBreadcrumbItem>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={`New thread in ${activeProjectName}`}
onClick={onNewThreadInProject}
className="inline-flex min-w-0 cursor-pointer items-center gap-1.5 rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
/>
}
>
<ProjectFavicon
environmentId={activeThreadEnvironmentId}
cwd={activeProjectCwd ?? ""}
faviconPath={activeProjectFaviconPath}
className="size-3.5"
/>
<span className="max-w-40 truncate">{activeProjectName}</span>
</TooltipTrigger>
<TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
</Tooltip>
</WorkspaceBreadcrumbItem>
<WorkspaceBreadcrumbSeparator />
</>
) : null}
<WorkspaceBreadcrumbItem current className="flex-1">
{renamingTitle !== null ? (
<input
autoFocus
aria-label="Thread title"
className="min-w-0 flex-1 rounded-sm bg-transparent text-sm font-medium text-foreground outline-none ring-1 ring-ring/50 focus:ring-ring"
defaultValue={renamingTitle}
onBlur={(event) => {
if (renameCommittedRef.current) return;
commitRename(event.currentTarget.value);
}}
onFocus={(event) => event.currentTarget.select()}
onKeyDown={handleRenameKeyDown}
/>
) : isServerThread ? (
<Tooltip>
<TooltipTrigger
render={
<button
ref={titleButtonRef}
type="button"
aria-label={`New thread in ${activeProjectName}`}
onClick={onNewThreadInProject}
className="inline-flex min-w-0 cursor-pointer items-center gap-1.5 rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
aria-label={`Thread actions for ${activeThreadTitle}`}
aria-haspopup="menu"
onClick={openMenuFromTitle}
className="group/thread-title inline-flex min-w-0 max-w-full cursor-pointer items-center gap-1 rounded-sm text-left focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
/>
}
>
<ProjectFavicon
environmentId={activeThreadEnvironmentId}
cwd={activeProjectCwd ?? ""}
className="size-3.5"
<h2 className="min-w-0 truncate">{activeThreadTitle}</h2>
<ChevronDownIcon
aria-hidden
className="size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/thread-title:opacity-100 group-focus-visible/thread-title:opacity-100"
/>
<span className="max-w-40 truncate text-sm font-medium">{activeProjectName}</span>
</TooltipTrigger>
<TooltipPopup side="top">New thread in {activeProjectName}</TooltipPopup>
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
</Tooltip>
<span aria-hidden className="text-muted-foreground/40">
/
</span>
</span>
) : null}
<Tooltip>
<TooltipTrigger
render={
<h2
aria-label={activeThreadTitle}
className="min-w-0 flex-1 truncate text-sm font-medium text-foreground"
>
{activeThreadTitle}
</h2>
<ChevronDownIcon
aria-hidden
className="size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/thread-title:opacity-100 group-focus-visible/thread-title:opacity-100"
) : (
<Tooltip>
<TooltipTrigger
render={
<h2 aria-label={activeThreadTitle} className="min-w-0 flex-1 truncate">
{activeThreadTitle}
</h2>
}
/>
=======
}
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
</Tooltip>
)}
</WorkspaceBreadcrumbItem>
</WorkspaceBreadcrumb>
<div
data-chat-header-actions
className={cn(
"flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3",
rightPanelOpen ? "pr-0" : "pr-16",
)}
>
{activeProjectScripts && (
<ProjectScriptsControl
scripts={activeProjectScripts}
fileScripts={fileScripts}
keybindings={keybindings}
preferredScriptId={preferredScriptId}
onRunScript={onRunProjectScript}
onAddScript={onAddProjectScript}
onUpdateScript={onUpdateProjectScript}
onDeleteScript={onDeleteProjectScript}
/>
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
</Tooltip>
>>>>>>> ad06049b75 (fix: port main fixes stranded by the v2 rewrite (round 2))
)}
{showOpenInPicker && (
<OpenInPicker
environmentId={activeThreadEnvironmentId}
keybindings={keybindings}
availableEditors={availableEditors}
openInCwd={openInCwd}
/>
)}
{activeProjectName && (
<GitActionsControl
gitCwd={gitCwd}
activeThreadRef={scopeThreadRef(activeThreadEnvironmentId, activeThreadId)}
onOpenPullRequest={onOpenPullRequest}
{...(draftId ? { draftId } : {})}
/>
)}
</div>
</div>
);
@@ -12,15 +12,10 @@ import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { Toggle } from "../ui/toggle";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
<<<<<<< HEAD
interface PanelLayoutControlsProps {
showTerminalControl?: boolean;
=======
export interface PanelLayoutControlsProps {
showThreadPanelControl?: boolean;
showTerminalControl?: boolean;
showRightPanelControl?: boolean;
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
terminalAvailable: boolean;
terminalOpen: boolean;
terminalShortcutLabel: string | null;
@@ -41,13 +36,9 @@ export interface PanelLayoutControlsProps {
}
export const PanelLayoutControls = memo(function PanelLayoutControls({
<<<<<<< HEAD
showTerminalControl = true,
=======
showThreadPanelControl = true,
showTerminalControl = true,
showRightPanelControl = true,
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
terminalAvailable,
terminalOpen,
terminalShortcutLabel,
@@ -100,8 +91,6 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
className="flex h-full shrink-0 items-center gap-1 [-webkit-app-region:no-drag]"
data-panel-layout-controls
>
<<<<<<< HEAD
=======
{showThreadPanelControl ? (
threadPanelPresentation === "popover" ? (
<Popover
@@ -129,7 +118,6 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
threadPanelTooltip(threadPanelToggle)
)
) : null}
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
{showTerminalControl ? (
<Tooltip>
<TooltipTrigger
@@ -143,7 +131,7 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
size="sm"
disabled={!terminalAvailable}
>
<PanelBottomIcon className="size-4" />
<PanelBottomIcon className="size-3.5" />
</Toggle>
}
/>
@@ -154,46 +142,6 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
</TooltipPopup>
</Tooltip>
) : null}
<<<<<<< HEAD
<Tooltip>
<TooltipTrigger
render={
<Toggle
className="shrink-0 [-webkit-app-region:no-drag]"
pressed={rightPanelOpen}
onPressedChange={onToggleRightPanel}
aria-label={
liveAgentCount > 0
? `Toggle right panel, ${liveAgentCount} ${liveAgentCount === 1 ? "agent" : "agents"} working`
: "Toggle right panel"
}
variant="ghost"
size="sm"
disabled={!rightPanelAvailable}
>
<PanelRightIcon className="size-4" />
{liveAgentCount > 0 ? (
<span
aria-hidden
className="absolute -top-1 -right-1 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-info px-1 text-[9px] font-semibold tabular-nums text-white"
>
{liveAgentCount}
</span>
) : null}
</Toggle>
}
/>
<TooltipPopup side="bottom">
{rightPanelAvailable
? `Toggle right panel${rightPanelShortcutLabel ? ` (${rightPanelShortcutLabel})` : ""}${
liveAgentCount > 0
? ` · ${liveAgentCount} ${liveAgentCount === 1 ? "agent" : "agents"} working`
: ""
}`
: "Right panel is unavailable"}
</TooltipPopup>
</Tooltip>
=======
{showRightPanelControl ? (
<Tooltip>
<TooltipTrigger
@@ -218,7 +166,6 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
</TooltipPopup>
</Tooltip>
) : null}
>>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
</div>
);
});
@@ -244,9 +191,9 @@ export const RightPanelMaximizeControl = memo(function RightPanelMaximizeControl
size="sm"
>
{maximized ? (
<Minimize2Icon className="size-4" />
<Minimize2Icon className="size-3.5" />
) : (
<Maximize2Icon className="size-4" />
<Maximize2Icon className="size-3.5" />
)}
</Toggle>
}
@@ -550,7 +550,6 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.glassOpacity,
settings.enableLegacyTokenStreaming,
settings.persistComposerContextStrip,
settings.enableAssistantStreaming,
settings.enableProviderUpdateChecks,
settings.sidebarAutoSettleAfterDays,
settings.sidebarAutoSettleOnMerge,
@@ -51,16 +51,9 @@ const SETTINGS_SECTION_ICONS: Readonly<
"/settings/appearance": PaletteIcon,
"/settings/keybindings": KeyboardIcon,
"/settings/providers": BotIcon,
<<<<<<< HEAD
"/settings/source-control": GitBranchIcon,
"/settings/connections": Link2Icon,
"/settings/scheduled-tasks": CalendarClockIcon,
=======
"/settings/scheduled-tasks": CalendarClockIcon,
"/settings/source-control": GitBranchIcon,
"/settings/connections": Link2Icon,
"/settings/beta": FlaskConicalIcon,
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
"/settings/archived": ArchiveIcon,
};
-8
View File
@@ -22,16 +22,8 @@ import {
getProjectOrderKey,
selectProjectGroupingSettings,
} from "../logicalProject";
<<<<<<< HEAD
<<<<<<< HEAD
import { resolveDefaultThreadEnvMode } from "@t3tools/shared/threadEnvMode";
import { readThreadShell, useProjects, useThread } from "../state/entities";
=======
import { readThreadShell, useProjects, useServerConfigs, useThreadShell } from "../state/entities";
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
=======
import { readThreadShell, useProjects, useThreadShell } from "../state/entities";
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
import { readT3ProjectFileDefaultThreadEnvMode } from "../lib/t3ProjectFileDefaults";
import { primaryServerSettingsAtom } from "../state/server";
-102
View File
@@ -14,111 +14,9 @@ const showContextMenuFallbackMock =
) => Promise<T | null>
>();
<<<<<<< HEAD
const requestConfirmDialogMock =
vi.fn<(message: string, options?: ConfirmDialogOptions) => Promise<boolean> | undefined>();
function registerListener<T>(listeners: Set<(event: T) => void>, listener: (event: T) => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
const terminalEventListeners = new Set<(event: TerminalEvent) => void>();
const shellStreamListeners = new Set<(event: OrchestrationShellStreamItem) => void>();
const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
const rpcClientMock = {
dispose: vi.fn(),
terminal: {
open: vi.fn(),
write: vi.fn(),
resize: vi.fn(),
clear: vi.fn(),
restart: vi.fn(),
close: vi.fn(),
onEvent: vi.fn((listener: (event: TerminalEvent) => void) =>
registerListener(terminalEventListeners, listener),
),
},
projects: {
searchEntries: vi.fn(),
writeFile: vi.fn(),
},
filesystem: {
browse: vi.fn(),
},
shell: {
openInEditor: vi.fn(),
},
git: {
pull: vi.fn(),
refreshStatus: vi.fn(),
onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
registerListener(gitStatusListeners, listener),
),
runStackedAction: vi.fn(),
listBranches: vi.fn(),
createWorktree: vi.fn(),
removeWorktree: vi.fn(),
createBranch: vi.fn(),
checkout: vi.fn(),
init: vi.fn(),
resolvePullRequest: vi.fn(),
preparePullRequestThread: vi.fn(),
},
server: {
getConfig: vi.fn(),
refreshProviders: vi.fn(),
upsertKeybinding: vi.fn(),
getSettings: vi.fn(),
updateSettings: vi.fn(),
subscribeConfig: vi.fn(),
subscribeLifecycle: vi.fn(),
subscribeAuthAccess: vi.fn(),
},
orchestration: {
dispatchCommand: vi.fn(),
getTurnDiff: vi.fn(),
getFullThreadDiff: vi.fn(),
subscribeShell: vi.fn((listener: (event: OrchestrationShellStreamItem) => void) =>
registerListener(shellStreamListeners, listener),
),
subscribeThread: vi.fn(() => () => undefined),
},
orchestrationV2: {
dispatchCommand: vi.fn(),
getThreadProjection: vi.fn(),
subscribeThread: vi.fn(() => () => undefined),
},
};
vi.mock("./environments/runtime", () => ({
getPrimaryEnvironmentConnection: () => ({
kind: "primary" as const,
knownEnvironment: {
id: "environment-local",
label: "Primary",
source: "manual" as const,
target: {
httpBaseUrl: "http://localhost:3000",
wsBaseUrl: "ws://localhost:3000",
},
environmentId: EnvironmentId.make("environment-local"),
},
client: rpcClientMock,
environmentId: EnvironmentId.make("environment-local"),
ensureBootstrapped: async () => undefined,
reconnect: async () => undefined,
dispose: async () => undefined,
}),
resetEnvironmentServiceForTests: vi.fn(),
resetSavedEnvironmentRegistryStoreForTests: vi.fn(),
resetSavedEnvironmentRuntimeStoreForTests: vi.fn(),
}));
=======
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
vi.mock("./contextMenuFallback", () => ({
showContextMenuFallback: showContextMenuFallbackMock,
}));
+402 -506
View File
@@ -11,7 +11,6 @@ import {
selectThreadPanelOpen,
selectThreadPanelVisibility,
selectThreadRightPanelState,
updatePullRequestTabStatus,
useRightPanelStore,
} from "./rightPanelStore";
@@ -183,557 +182,454 @@ describe("rightPanelStore", () => {
});
it("drops persisted plan surfaces and does not reopen an empty panel", () => {
it("persists inline preference without restoring an open popover", () => {
expect(
migratePersistedRightPanelState({
it("persists inline preference without restoring an open popover", () => {
expect(
migratePersistedRightPanelState({
threadPanelVisibilityByThreadKey: {
"env-1:thread-A": { inlineOpen: false, popoverOpen: true },
"env-1:thread-B": { inlineOpen: true, popoverOpen: true },
},
}),
).toEqual({
byThreadKey: {},
threadPanelVisibilityByThreadKey: {
"env-1:thread-A": { inlineOpen: false, popoverOpen: true },
"env-1:thread-B": { inlineOpen: true, popoverOpen: true },
"env-1:thread-A": { inlineOpen: false, popoverOpen: false },
},
}),
).toEqual({
byThreadKey: {},
threadPanelVisibilityByThreadKey: {
"env-1:thread-A": { inlineOpen: false, popoverOpen: false },
},
});
});
it("tracks inline and popover visibility independently", () => {
const store = useRightPanelStore.getState();
expect(selectThreadPanelOpen(store.threadPanelVisibilityByThreadKey, refA, "inline")).toBe(
true,
);
expect(selectThreadPanelOpen(store.threadPanelVisibilityByThreadKey, refA, "popover")).toBe(
false,
);
store.setThreadPanelOpen(refA, "inline", false);
store.toggleThreadPanel(refA, "popover");
expect(
selectThreadPanelVisibility(
useRightPanelStore.getState().threadPanelVisibilityByThreadKey,
refA,
),
).toEqual({ inlineOpen: false, popoverOpen: true });
expect(
selectThreadPanelVisibility(
useRightPanelStore.getState().threadPanelVisibilityByThreadKey,
refB,
),
).toEqual({ inlineOpen: true, popoverOpen: false });
});
it("closes the popover atomically when the real right panel opens", () => {
useRightPanelStore.getState().setThreadPanelOpen(refA, "popover", true);
useRightPanelStore.getState().open(refA, "diff");
expect(
selectThreadPanelVisibility(
useRightPanelStore.getState().threadPanelVisibilityByThreadKey,
refA,
),
).toEqual({ inlineOpen: true, popoverOpen: false });
});
it("keeps an open popover visible by promoting it to inline when the real panel closes", () => {
const store = useRightPanelStore.getState();
store.open(refA, "diff");
store.setThreadPanelOpen(refA, "inline", false);
store.setThreadPanelOpen(refA, "popover", true);
store.close(refA);
expect(
selectThreadPanelVisibility(
useRightPanelStore.getState().threadPanelVisibilityByThreadKey,
refA,
),
).toEqual({ inlineOpen: true, popoverOpen: true });
});
it("open sets the active panel for a thread", () => {
useRightPanelStore.getState().open(refA, "preview");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refB)).toBeNull();
});
it("opening a different kind keeps both surfaces and activates the new one", () => {
useRightPanelStore.getState().open(refA, "agents");
useRightPanelStore.getState().open(refA, "preview");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview");
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces,
).toHaveLength(2);
});
it("reopening an inactive singleton activates its existing surface", () => {
useRightPanelStore.getState().open(refA, "diff");
useRightPanelStore.getState().open(refA, "agents");
useRightPanelStore.getState().open(refA, "diff");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "diff",
surfaces: [
{ id: "diff", kind: "diff" },
{ id: "agents", kind: "agents" },
],
});
});
it("keeps files as a singleton surface", () => {
useRightPanelStore.getState().open(refA, "files");
useRightPanelStore.getState().open(refA, "files");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "files",
surfaces: [{ id: "files", kind: "files" }],
});
});
it("replaces the standalone explorer with peer file surfaces", () => {
useRightPanelStore.getState().open(refA, "files");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().openFile(refA, "README.md");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "file:README.md",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: null,
revealRequestId: 2,
},
{
id: "file:README.md",
kind: "file",
relativePath: "README.md",
revealLine: null,
revealRequestId: 1,
},
],
});
});
it("updates line reveal requests when reopening a file surface", () => {
useRightPanelStore.getState().openFile(refA, "src/index.ts", 42);
useRightPanelStore.getState().openFile(refA, "src/index.ts", 87);
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "file:src/index.ts",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: 87,
revealRequestId: 2,
},
],
});
});
useRightPanelStore.getState().openFile(refA, "src/index.ts");
it("tracks inline and popover visibility independently", () => {
const store = useRightPanelStore.getState();
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "file:src/index.ts",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: null,
revealRequestId: 3,
},
],
});
});
it("removes persisted file surfaces when their workspace no longer exists", () => {
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().open(refA, "agents");
useRightPanelStore.getState().openFile(refA, "README.md");
useRightPanelStore.getState().reconcileFileSurfaces(refA, false);
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "agents",
surfaces: [{ id: "agents", kind: "agents" }],
});
useRightPanelStore.getState().openFile(refB, "conductor.json");
useRightPanelStore.getState().reconcileFileSurfaces(refB, false);
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refB)).toEqual({
isOpen: false,
activeSurfaceId: null,
surfaces: [],
});
});
it("close hides the panel without clearing its selected surface", () => {
useRightPanelStore.getState().open(refA, "agents");
useRightPanelStore.getState().close(refA);
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull();
expect(
selectSelectedRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA),
).toEqual({ id: "agents", kind: "agents" });
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: false,
activeSurfaceId: "agents",
surfaces: [{ id: "agents", kind: "agents" }],
});
});
it("toggles empty panel visibility without creating a surface", () => {
useRightPanelStore.getState().toggleVisibility(refA);
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: null,
surfaces: [],
});
useRightPanelStore.getState().toggleVisibility(refA);
expect(useRightPanelStore.getState().byThreadKey).toEqual({});
});
it("toggle hides the panel without discarding the active surface", () => {
useRightPanelStore.getState().toggle(refA, "diff");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("diff");
useRightPanelStore.getState().toggle(refA, "diff");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull();
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: false,
activeSurfaceId: "diff",
surfaces: [{ id: "diff", kind: "diff" }],
});
});
it("toggle to a different kind switches active", () => {
useRightPanelStore.getState().toggle(refA, "preview");
useRightPanelStore.getState().toggle(refA, "agents");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("agents");
});
it("removeThread clears persisted state", () => {
useRightPanelStore.getState().open(refA, "agents");
useRightPanelStore.getState().removeThread(refA);
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull();
});
it("close on never-opened thread is a no-op", () => {
useRightPanelStore.getState().close(refA);
expect(useRightPanelStore.getState().byThreadKey).toEqual({});
});
it("tracks one surface per browser session", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openBrowser(refA, "tab-b");
const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);
expect(state.surfaces.map((surface) => surface.id)).toEqual(["browser:tab-a", "browser:tab-b"]);
expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
id: "browser:tab-b",
kind: "preview",
resourceId: "tab-b",
});
});
it("tracks one surface per pull request", () => {
const first = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4909 };
const second = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4910 };
useRightPanelStore.getState().openPullRequest(refA, first);
useRightPanelStore.getState().openPullRequest(refA, second);
useRightPanelStore.getState().openPullRequest(refA, first);
const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);
expect(state.surfaces.map((surface) => surface.id)).toEqual([
pullRequestSurfaceId(first),
pullRequestSurfaceId(second),
]);
expect(state.activeSurfaceId).toBe(pullRequestSurfaceId(first));
});
it("keeps one pull request read from two servers as two tabs", () => {
const local = {
environmentId: "local",
projectId: "project-a",
repository: "pingdotgg/t3code",
number: 4909,
};
const remote = { ...local, environmentId: "remote" };
useRightPanelStore.getState().openPullRequest(refA, local);
useRightPanelStore.getState().openPullRequest(refA, remote);
const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);
expect(state.surfaces.map((surface) => surface.id)).toEqual([
pullRequestSurfaceId(local),
pullRequestSurfaceId(remote),
]);
});
it("keeps the page's panel tabs reachable when the set of connected servers changes", () => {
// The pull-requests page keys its one shared panel by a fixed sentinel environment, not by
// whichever capable server happens to sort first (see PULL_REQUESTS_PANEL_ENVIRONMENT_ID in
// _chat.pull-requests.tsx) — a server disconnecting must not move every open tab to a store
// key nobody wrote them under.
const panelId = ThreadId.make("pull-requests-panel");
const stableRef = scopeThreadRef("pull-requests-panel" as EnvironmentId, panelId);
const fromServerA = {
environmentId: "server-a",
projectId: "project-a",
repository: "pingdotgg/t3code",
number: 1,
};
const fromServerB = {
environmentId: "server-b",
projectId: "project-b",
repository: "pingdotgg/t3code",
number: 2,
};
// Both servers connected: tabs from each open under the one stable ref.
useRightPanelStore.getState().openPullRequest(stableRef, fromServerA);
useRightPanelStore.getState().openPullRequest(stableRef, fromServerB);
// Server A disconnects. The stable ref does not depend on which servers remain connected, so
// the same lookup still finds both tabs.
const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, stableRef);
expect(state.surfaces.map((surface) => surface.id)).toEqual([
pullRequestSurfaceId(fromServerA),
pullRequestSurfaceId(fromServerB),
]);
// The bug this guards against: a ref keyed by the first capable environment instead of a
// fixed sentinel changes identity when that environment drops out, and a lookup under the new
// key finds nothing even though the tabs are still sitting under the old one.
const refWhileBothConnected = scopeThreadRef("server-a" as EnvironmentId, panelId);
const refAfterServerADisconnects = scopeThreadRef("server-b" as EnvironmentId, panelId);
expect(refWhileBothConnected).not.toEqual(refAfterServerADisconnects);
expect(
selectThreadRightPanelState(
useRightPanelStore.getState().byThreadKey,
refAfterServerADisconnects,
).surfaces,
).toEqual([]);
});
describe("updatePullRequestTabStatus", () => {
const status = (isDraft: boolean) => ({
projectId: "project-a",
repository: "pingdotgg/t3code",
number: 4909,
state: "open" as const,
isDraft,
});
// Regression for the tab wearing no state: this failed when the status was written under a
// key rebuilt from the pull request while the tab strip reads it under the surface's own id.
it("keys a status under the same id a surface opened from an environment carries", () => {
const target = {
environmentId: "remote",
projectId: "project-a",
repository: "pingdotgg/t3code",
number: 4909,
};
useRightPanelStore.getState().openPullRequest(refA, target);
const surface = selectSelectedRightPanelSurface(
useRightPanelStore.getState().byThreadKey,
refA,
expect(selectThreadPanelOpen(store.threadPanelVisibilityByThreadKey, refA, "inline")).toBe(
true,
);
expect(surface).not.toBeNull();
const statuses = updatePullRequestTabStatus({}, surface!.id, status(false));
expect(statuses[surface!.id]).toEqual(status(false));
});
it("keys a status under the same id a thread surface with no environment carries", () => {
const target = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4909 };
useRightPanelStore.getState().openPullRequest(refA, target);
const surface = selectSelectedRightPanelSurface(
useRightPanelStore.getState().byThreadKey,
refA,
expect(selectThreadPanelOpen(store.threadPanelVisibilityByThreadKey, refA, "popover")).toBe(
false,
);
expect(surface).not.toBeNull();
const statuses = updatePullRequestTabStatus({}, surface!.id, status(false));
expect(statuses[surface!.id]).toEqual(status(false));
store.setThreadPanelOpen(refA, "inline", false);
store.toggleThreadPanel(refA, "popover");
expect(
selectThreadPanelVisibility(
useRightPanelStore.getState().threadPanelVisibilityByThreadKey,
refA,
),
).toEqual({ inlineOpen: false, popoverOpen: true });
expect(
selectThreadPanelVisibility(
useRightPanelStore.getState().threadPanelVisibilityByThreadKey,
refB,
),
).toEqual({ inlineOpen: true, popoverOpen: false });
});
it("returns the identical map when the tab's state and draft flag are unchanged", () => {
const first = updatePullRequestTabStatus({}, "pull-request:1", status(false));
const second = updatePullRequestTabStatus(first, "pull-request:1", status(false));
expect(second).toBe(first);
it("closes the popover atomically when the real right panel opens", () => {
useRightPanelStore.getState().setThreadPanelOpen(refA, "popover", true);
useRightPanelStore.getState().open(refA, "diff");
expect(
selectThreadPanelVisibility(
useRightPanelStore.getState().threadPanelVisibilityByThreadKey,
refA,
),
).toEqual({ inlineOpen: true, popoverOpen: false });
});
it("replaces the entry when the draft flag changes", () => {
const first = updatePullRequestTabStatus({}, "pull-request:1", status(false));
const second = updatePullRequestTabStatus(first, "pull-request:1", status(true));
expect(second).not.toBe(first);
expect(second["pull-request:1"]).toEqual(status(true));
it("keeps an open popover visible by promoting it to inline when the real panel closes", () => {
const store = useRightPanelStore.getState();
store.open(refA, "diff");
store.setThreadPanelOpen(refA, "inline", false);
store.setThreadPanelOpen(refA, "popover", true);
store.close(refA);
expect(
selectThreadPanelVisibility(
useRightPanelStore.getState().threadPanelVisibilityByThreadKey,
refA,
),
).toEqual({ inlineOpen: true, popoverOpen: true });
});
});
it("tracks one surface per terminal session", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().openTerminal(refA, "term-2");
it("open sets the active panel for a thread", () => {
useRightPanelStore.getState().open(refA, "preview");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe(
"preview",
);
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refB)).toBeNull();
});
const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);
expect(state.surfaces).toEqual([
{
it("opening a different kind keeps both surfaces and activates the new one", () => {
useRightPanelStore.getState().open(refA, "agents");
useRightPanelStore.getState().open(refA, "preview");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe(
"preview",
);
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces,
).toHaveLength(2);
});
it("reopening an inactive singleton activates its existing surface", () => {
useRightPanelStore.getState().open(refA, "diff");
useRightPanelStore.getState().open(refA, "agents");
useRightPanelStore.getState().open(refA, "diff");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "diff",
surfaces: [
{ id: "diff", kind: "diff" },
{ id: "agents", kind: "agents" },
],
});
});
it("keeps files as a singleton surface", () => {
useRightPanelStore.getState().open(refA, "files");
useRightPanelStore.getState().open(refA, "files");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "files",
surfaces: [{ id: "files", kind: "files" }],
});
});
it("replaces the standalone explorer with peer file surfaces", () => {
useRightPanelStore.getState().open(refA, "files");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().openFile(refA, "README.md");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "file:README.md",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: null,
revealRequestId: 2,
},
{
id: "file:README.md",
kind: "file",
relativePath: "README.md",
revealLine: null,
revealRequestId: 1,
},
],
});
});
it("updates line reveal requests when reopening a file surface", () => {
useRightPanelStore.getState().openFile(refA, "src/index.ts", 42);
useRightPanelStore.getState().openFile(refA, "src/index.ts", 87);
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "file:src/index.ts",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: 87,
revealRequestId: 2,
},
],
});
useRightPanelStore.getState().openFile(refA, "src/index.ts");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "file:src/index.ts",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: null,
revealRequestId: 3,
},
],
});
});
it("removes persisted file surfaces when their workspace no longer exists", () => {
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().open(refA, "agents");
useRightPanelStore.getState().openFile(refA, "README.md");
useRightPanelStore.getState().reconcileFileSurfaces(refA, false);
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "agents",
surfaces: [{ id: "agents", kind: "agents" }],
});
useRightPanelStore.getState().openFile(refB, "conductor.json");
useRightPanelStore.getState().reconcileFileSurfaces(refB, false);
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refB)).toEqual({
isOpen: false,
activeSurfaceId: null,
surfaces: [],
});
});
it("close hides the panel without clearing its selected surface", () => {
useRightPanelStore.getState().open(refA, "agents");
useRightPanelStore.getState().close(refA);
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull();
expect(
selectSelectedRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA),
).toEqual({ id: "agents", kind: "agents" });
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: false,
activeSurfaceId: "agents",
surfaces: [{ id: "agents", kind: "agents" }],
});
});
it("toggles empty panel visibility without creating a surface", () => {
useRightPanelStore.getState().toggleVisibility(refA);
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: null,
surfaces: [],
});
useRightPanelStore.getState().toggleVisibility(refA);
expect(useRightPanelStore.getState().byThreadKey).toEqual({});
});
it("toggle hides the panel without discarding the active surface", () => {
useRightPanelStore.getState().toggle(refA, "diff");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("diff");
useRightPanelStore.getState().toggle(refA, "diff");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull();
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: false,
activeSurfaceId: "diff",
surfaces: [{ id: "diff", kind: "diff" }],
});
});
it("toggle to a different kind switches active", () => {
useRightPanelStore.getState().toggle(refA, "preview");
useRightPanelStore.getState().toggle(refA, "agents");
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe(
"agents",
);
});
it("removeThread clears persisted state", () => {
useRightPanelStore.getState().open(refA, "agents");
useRightPanelStore.getState().removeThread(refA);
expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull();
});
it("close on never-opened thread is a no-op", () => {
useRightPanelStore.getState().close(refA);
expect(useRightPanelStore.getState().byThreadKey).toEqual({});
});
it("tracks one surface per browser session", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openBrowser(refA, "tab-b");
const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);
expect(state.surfaces.map((surface) => surface.id)).toEqual([
"browser:tab-a",
"browser:tab-b",
]);
expect(
selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA),
).toEqual({
id: "browser:tab-b",
kind: "preview",
resourceId: "tab-b",
});
});
it("tracks one surface per pull request", () => {
const first = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4909 };
const second = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4910 };
useRightPanelStore.getState().openPullRequest(refA, first);
useRightPanelStore.getState().openPullRequest(refA, second);
useRightPanelStore.getState().openPullRequest(refA, first);
const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);
expect(state.surfaces.map((surface) => surface.id)).toEqual([
pullRequestSurfaceId(first),
pullRequestSurfaceId(second),
]);
expect(state.activeSurfaceId).toBe(pullRequestSurfaceId(first));
});
it("tracks one surface per terminal session", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().openTerminal(refA, "term-2");
const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);
expect(state.surfaces).toEqual([
{
id: "terminal:term-1",
kind: "terminal",
resourceId: "term-1",
terminalIds: ["term-1"],
activeTerminalId: "term-1",
},
{
id: "terminal:term-2",
kind: "terminal",
resourceId: "term-2",
terminalIds: ["term-2"],
activeTerminalId: "term-2",
},
]);
expect(state.activeSurfaceId).toBe("terminal:term-2");
});
it("tracks split panes and the active pane within a terminal surface", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().splitTerminal(refA, "terminal:term-1", "term-2");
expect(
selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA),
).toEqual({
id: "terminal:term-1",
kind: "terminal",
resourceId: "term-1",
terminalIds: ["term-1"],
activeTerminalId: "term-1",
},
{
id: "terminal:term-2",
terminalIds: ["term-1", "term-2"],
activeTerminalId: "term-2",
});
useRightPanelStore.getState().activateTerminal(refA, "terminal:term-1", "term-1");
useRightPanelStore.getState().closeTerminal(refA, "terminal:term-1", "term-1");
expect(
selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA),
).toEqual({
id: "terminal:term-1",
kind: "terminal",
resourceId: "term-2",
resourceId: "term-1",
terminalIds: ["term-2"],
activeTerminalId: "term-2",
},
]);
expect(state.activeSurfaceId).toBe("terminal:term-2");
});
it("tracks split panes and the active pane within a terminal surface", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().splitTerminal(refA, "terminal:term-1", "term-2");
expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
id: "terminal:term-1",
kind: "terminal",
resourceId: "term-1",
terminalIds: ["term-1", "term-2"],
activeTerminalId: "term-2",
});
});
useRightPanelStore.getState().activateTerminal(refA, "terminal:term-1", "term-1");
useRightPanelStore.getState().closeTerminal(refA, "terminal:term-1", "term-1");
expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
id: "terminal:term-1",
kind: "terminal",
resourceId: "term-1",
terminalIds: ["term-2"],
activeTerminalId: "term-2",
it("tracks vertical layout for a terminal surface", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().splitTerminal(refA, "terminal:term-1", "term-2", "vertical");
expect(
selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA),
).toEqual({
id: "terminal:term-1",
kind: "terminal",
resourceId: "term-1",
terminalIds: ["term-1", "term-2"],
activeTerminalId: "term-2",
splitDirection: "vertical",
});
});
});
it("tracks vertical layout for a terminal surface", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().splitTerminal(refA, "terminal:term-1", "term-2", "vertical");
it("closing the final terminal pane removes its surface and closes the panel", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeTerminal(refA, "terminal:term-1", "term-1");
expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
id: "terminal:term-1",
kind: "terminal",
resourceId: "term-1",
terminalIds: ["term-1", "term-2"],
activeTerminalId: "term-2",
splitDirection: "vertical",
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: false,
activeSurfaceId: null,
surfaces: [],
});
});
});
it("closing the final terminal pane removes its surface and closes the panel", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeTerminal(refA, "terminal:term-1", "term-1");
it("closing the active surface activates a neighboring surface", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeSurface(refA, "terminal:term-1");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: false,
activeSurfaceId: null,
surfaces: [],
expect(
selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)?.id,
).toBe("browser:tab-a");
});
});
it("closing the active surface activates a neighboring surface", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeSurface(refA, "terminal:term-1");
it("closing the final surface closes the panel", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeSurface(refA, "terminal:term-1");
expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)?.id).toBe(
"browser:tab-a",
);
});
it("closing the final surface closes the panel", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeSurface(refA, "terminal:term-1");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: false,
activeSurfaceId: null,
surfaces: [],
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: false,
activeSurfaceId: null,
surfaces: [],
});
});
});
it("closing other surfaces keeps the selected surface active", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().openTerminal(refA, "term-1");
it("closing other surfaces keeps the selected surface active", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeOtherSurfaces(refA, "file:src/index.ts");
useRightPanelStore.getState().closeOtherSurfaces(refA, "file:src/index.ts");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "file:src/index.ts",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: null,
revealRequestId: 1,
},
],
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "file:src/index.ts",
surfaces: [
{
id: "file:src/index.ts",
kind: "file",
relativePath: "src/index.ts",
revealLine: null,
revealRequestId: 1,
},
],
});
});
});
it("closing surfaces to the right activates the selected surface when active was removed", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().openTerminal(refA, "term-1");
it("closing surfaces to the right activates the selected surface when active was removed", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().closeSurfacesToRight(refA, "browser:tab-a");
useRightPanelStore.getState().closeSurfacesToRight(refA, "browser:tab-a");
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "browser:tab-a",
surfaces: [{ id: "browser:tab-a", kind: "preview", resourceId: "tab-a" }],
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: true,
activeSurfaceId: "browser:tab-a",
surfaces: [{ id: "browser:tab-a", kind: "preview", resourceId: "tab-a" }],
});
});
});
it("closing all surfaces closes the panel", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
it("closing all surfaces closes the panel", () => {
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openFile(refA, "src/index.ts");
useRightPanelStore.getState().closeAllSurfaces(refA);
useRightPanelStore.getState().closeAllSurfaces(refA);
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: false,
activeSurfaceId: null,
surfaces: [],
expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({
isOpen: false,
activeSurfaceId: null,
surfaces: [],
});
});
});
it("reconciles browser surfaces without deleting other surface kinds", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openBrowser(refA, "tab-b");
useRightPanelStore.getState().reconcileBrowserSurfaces(refA, ["tab-b", "tab-c"]);
it("reconciles browser surfaces without deleting other surface kinds", () => {
useRightPanelStore.getState().openTerminal(refA, "term-1");
useRightPanelStore.getState().openBrowser(refA, "tab-a");
useRightPanelStore.getState().openBrowser(refA, "tab-b");
useRightPanelStore.getState().reconcileBrowserSurfaces(refA, ["tab-b", "tab-c"]);
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces.map(
(surface) => surface.id,
),
).toEqual(["terminal:term-1", "browser:tab-b", "browser:tab-c"]);
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces.map(
(surface) => surface.id,
),
).toEqual(["terminal:term-1", "browser:tab-b", "browser:tab-c"]);
});
});
});
+13 -128
View File
@@ -15,27 +15,18 @@ import { Route as PairRouteImport } from './routes/pair'
import { Route as ConnectRouteImport } from './routes/connect'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
import { Route as SettingsScheduledTasksRouteImport } from './routes/settings.scheduled-tasks'
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
import { Route as SettingsProvidersRouteImport } from './routes/settings.providers'
import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
<<<<<<< HEAD
<<<<<<< HEAD
import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'
import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey'
import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'
import { Route as ChatPullRequestsRouteImport } from './routes/_chat.pull-requests'
import { Route as DebugOrchestrationV2RouteImport } from './routes/debug.orchestration-v2'
=======
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
=======
import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'
import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
@@ -68,16 +59,16 @@ const ChatIndexRoute = ChatIndexRouteImport.update({
path: '/',
getParentRoute: () => ChatRoute,
} as any)
const SettingsSourceControlRoute = SettingsSourceControlRouteImport.update({
id: '/source-control',
path: '/source-control',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsScheduledTasksRoute = SettingsScheduledTasksRouteImport.update({
id: '/scheduled-tasks',
path: '/scheduled-tasks',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsSourceControlRoute = SettingsSourceControlRouteImport.update({
id: '/source-control',
path: '/source-control',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsProvidersRoute = SettingsProvidersRouteImport.update({
id: '/providers',
path: '/providers',
@@ -108,16 +99,11 @@ const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
path: '/archived',
getParentRoute: () => SettingsRoute,
} as any)
<<<<<<< HEAD
<<<<<<< HEAD
=======
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
const SettingsAppearanceRoute = SettingsAppearanceRouteImport.update({
id: '/appearance',
path: '/appearance',
getParentRoute: () => SettingsRoute,
} as any)
<<<<<<< HEAD
const ProjectsProjectKeyRoute = ProjectsProjectKeyRouteImport.update({
id: '/projects/$projectKey',
path: '/projects/$projectKey',
@@ -126,9 +112,6 @@ const ProjectsProjectKeyRoute = ProjectsProjectKeyRouteImport.update({
const ConnectCallbackRoute = ConnectCallbackRouteImport.update({
id: '/connect_/callback',
path: '/connect/callback',
const DebugOrchestrationV2Route = DebugOrchestrationV2RouteImport.update({
id: '/debug/orchestration-v2',
path: '/debug/orchestration-v2',
getParentRoute: () => rootRouteImport,
} as any)
const ChatPullRequestsRoute = ChatPullRequestsRouteImport.update({
@@ -136,15 +119,6 @@ const ChatPullRequestsRoute = ChatPullRequestsRouteImport.update({
path: '/pull-requests',
getParentRoute: () => ChatRoute,
} as any)
=======
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
=======
const ConnectCallbackRoute = ConnectCallbackRouteImport.update({
id: '/connect_/callback',
path: '/connect/callback',
getParentRoute: () => rootRouteImport,
} as any)
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
const ChatDraftDraftIdRoute = ChatDraftDraftIdRouteImport.update({
id: '/draft/$draftId',
path: '/draft/$draftId',
@@ -162,20 +136,11 @@ export interface FileRoutesByFullPath {
'/connect': typeof ConnectRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
<<<<<<< HEAD
<<<<<<< HEAD
'/usage': typeof UsageRoute
'/pull-requests': typeof ChatPullRequestsRoute
'/connect/callback': typeof ConnectCallbackRoute
'/projects/$projectKey': typeof ProjectsProjectKeyRoute
'/settings/appearance': typeof SettingsAppearanceRoute
'/debug/orchestration-v2': typeof DebugOrchestrationV2Route
=======
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
=======
'/connect/callback': typeof ConnectCallbackRoute
'/settings/appearance': typeof SettingsAppearanceRoute
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -191,20 +156,11 @@ export interface FileRoutesByTo {
'/connect': typeof ConnectRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
<<<<<<< HEAD
<<<<<<< HEAD
'/usage': typeof UsageRoute
'/pull-requests': typeof ChatPullRequestsRoute
'/connect/callback': typeof ConnectCallbackRoute
'/projects/$projectKey': typeof ProjectsProjectKeyRoute
'/settings/appearance': typeof SettingsAppearanceRoute
'/debug/orchestration-v2': typeof DebugOrchestrationV2Route
=======
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
=======
'/connect/callback': typeof ConnectCallbackRoute
'/settings/appearance': typeof SettingsAppearanceRoute
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -223,20 +179,11 @@ export interface FileRoutesById {
'/connect': typeof ConnectRoute
'/pair': typeof PairRoute
'/settings': typeof SettingsRouteWithChildren
<<<<<<< HEAD
<<<<<<< HEAD
'/usage': typeof UsageRoute
'/_chat/pull-requests': typeof ChatPullRequestsRoute
'/connect_/callback': typeof ConnectCallbackRoute
'/projects/$projectKey': typeof ProjectsProjectKeyRoute
'/settings/appearance': typeof SettingsAppearanceRoute
'/debug/orchestration-v2': typeof DebugOrchestrationV2Route
=======
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
=======
'/connect_/callback': typeof ConnectCallbackRoute
'/settings/appearance': typeof SettingsAppearanceRoute
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
'/settings/archived': typeof SettingsArchivedRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
@@ -256,20 +203,11 @@ export interface FileRouteTypes {
| '/connect'
| '/pair'
| '/settings'
<<<<<<< HEAD
<<<<<<< HEAD
| '/usage'
| '/pull-requests'
| '/connect/callback'
| '/projects/$projectKey'
| '/settings/appearance'
| '/debug/orchestration-v2'
=======
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
=======
| '/connect/callback'
| '/settings/appearance'
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -285,20 +223,11 @@ export interface FileRouteTypes {
| '/connect'
| '/pair'
| '/settings'
<<<<<<< HEAD
<<<<<<< HEAD
| '/usage'
| '/pull-requests'
| '/connect/callback'
| '/projects/$projectKey'
| '/settings/appearance'
| '/debug/orchestration-v2'
=======
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
=======
| '/connect/callback'
| '/settings/appearance'
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -316,20 +245,11 @@ export interface FileRouteTypes {
| '/connect'
| '/pair'
| '/settings'
<<<<<<< HEAD
<<<<<<< HEAD
| '/usage'
| '/_chat/pull-requests'
| '/connect_/callback'
| '/projects/$projectKey'
| '/settings/appearance'
| '/debug/orchestration-v2'
=======
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
=======
| '/connect_/callback'
| '/settings/appearance'
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
| '/settings/archived'
| '/settings/connections'
| '/settings/diagnostics'
@@ -348,17 +268,9 @@ export interface RootRouteChildren {
ConnectRoute: typeof ConnectRoute
PairRoute: typeof PairRoute
SettingsRoute: typeof SettingsRouteWithChildren
<<<<<<< HEAD
<<<<<<< HEAD
UsageRoute: typeof UsageRoute
ConnectCallbackRoute: typeof ConnectCallbackRoute
ProjectsProjectKeyRoute: typeof ProjectsProjectKeyRoute
DebugOrchestrationV2Route: typeof DebugOrchestrationV2Route
=======
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
=======
ConnectCallbackRoute: typeof ConnectCallbackRoute
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
}
declare module '@tanstack/react-router' {
@@ -405,13 +317,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ChatIndexRouteImport
parentRoute: typeof ChatRoute
}
'/settings/source-control': {
id: '/settings/source-control'
path: '/source-control'
fullPath: '/settings/source-control'
preLoaderRoute: typeof SettingsSourceControlRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/scheduled-tasks': {
id: '/settings/scheduled-tasks'
path: '/scheduled-tasks'
@@ -419,6 +324,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsScheduledTasksRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/source-control': {
id: '/settings/source-control'
path: '/source-control'
fullPath: '/settings/source-control'
preLoaderRoute: typeof SettingsSourceControlRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/providers': {
id: '/settings/providers'
path: '/providers'
@@ -461,10 +373,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsArchivedRouteImport
parentRoute: typeof SettingsRoute
}
<<<<<<< HEAD
<<<<<<< HEAD
=======
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
'/settings/appearance': {
id: '/settings/appearance'
path: '/appearance'
@@ -472,7 +380,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsAppearanceRouteImport
parentRoute: typeof SettingsRoute
}
<<<<<<< HEAD
'/projects/$projectKey': {
id: '/projects/$projectKey'
path: '/projects/$projectKey'
@@ -480,19 +387,11 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ProjectsProjectKeyRouteImport
parentRoute: typeof rootRouteImport
}
=======
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
'/connect_/callback': {
id: '/connect_/callback'
path: '/connect/callback'
fullPath: '/connect/callback'
preLoaderRoute: typeof ConnectCallbackRouteImport
<<<<<<< HEAD
'/debug/orchestration-v2': {
id: '/debug/orchestration-v2'
path: '/debug/orchestration-v2'
fullPath: '/debug/orchestration-v2'
preLoaderRoute: typeof DebugOrchestrationV2RouteImport
parentRoute: typeof rootRouteImport
}
'/_chat/pull-requests': {
@@ -502,12 +401,6 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ChatPullRequestsRouteImport
parentRoute: typeof ChatRoute
}
=======
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
=======
parentRoute: typeof rootRouteImport
}
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
'/_chat/draft/$draftId': {
id: '/_chat/draft/$draftId'
path: '/draft/$draftId'
@@ -574,17 +467,9 @@ const rootRouteChildren: RootRouteChildren = {
ConnectRoute: ConnectRoute,
PairRoute: PairRoute,
SettingsRoute: SettingsRouteWithChildren,
<<<<<<< HEAD
<<<<<<< HEAD
UsageRoute: UsageRoute,
ConnectCallbackRoute: ConnectCallbackRoute,
ProjectsProjectKeyRoute: ProjectsProjectKeyRoute,
DebugOrchestrationV2Route: DebugOrchestrationV2Route,
=======
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
=======
ConnectCallbackRoute: ConnectCallbackRoute,
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
@@ -1291,9 +1291,15 @@ function PullRequestsRouteView() {
const panelToggleControls = (
<PanelLayoutControls
showTerminalControl={false}
showThreadPanelControl={false}
terminalAvailable={false}
terminalOpen={false}
terminalShortcutLabel={null}
threadPanelOpen={false}
threadPanelPresentation="inline"
threadPanelShortcutLabel={null}
threadPanelHasAttention={false}
onToggleThreadPanel={() => undefined}
rightPanelAvailable={rightPanelState.surfaces.length > 0}
rightPanelOpen={rightPanelState.isOpen}
rightPanelShortcutLabel={null}
-5
View File
@@ -185,7 +185,6 @@ export function readEnvironmentSupportsTitleRegeneration(environmentId: Environm
);
}
<<<<<<< HEAD
/** Whether the environment's server understands thread.pin.reorder (and
orderKey on thread.pin). Same version-skew contract as settlement. */
export function readEnvironmentSupportsPinReorder(environmentId: EnvironmentId): boolean {
@@ -195,12 +194,8 @@ export function readEnvironmentSupportsPinReorder(environmentId: EnvironmentId):
);
}
export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null {
return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref));
=======
export function readThreadProjection(ref: ScopedThreadRef): EnvironmentThread | null {
return appAtomRegistry.get(environmentThreadDetails.threadAtom(ref));
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
}
/** Whether the environment's server understands thread.settle/unsettle.
+1 -1
View File
@@ -52,7 +52,7 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
labelPrefix: "web:thread-search",
});
function useDebouncedValue<A>(value: A, delayMs: number): A {
export function useDebouncedValue<A>(value: A, delayMs: number): A {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
-6
View File
@@ -5,12 +5,9 @@
- [Install and first run](./user/install.md)
- [Permission modes](./user/permission-modes.md)
- [Keyboard shortcuts](./user/keybindings.md)
<<<<<<< HEAD
- [Organizing threads](./user/thread-sidebar.md)
- [Review usage](./user/usage.md)
- [Customize a project icon](./user/project-settings.md)
=======
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
- [Remote access](./user/remote-access.md)
- [Appearance](./user/appearance.md)
- [Keeping app and server in sync](./user/updating.md)
@@ -46,7 +43,6 @@ policy in [CONTRIBUTING.md](../CONTRIBUTING.md); agent rules in [AGENTS.md](../A
- [Observability](./operations/observability.md)
- [Relay observability](./operations/relay-observability.md)
- [Mobile app store screenshots](./operations/mobile-app-store-screenshots.md)
<<<<<<< HEAD
- [Getting started](./getting-started/quick-start.md)
- [Architecture](./architecture/overview.md)
- [T3 Connect](./cloud/t3-connect-clerk.md)
@@ -57,5 +53,3 @@ policy in [CONTRIBUTING.md](../CONTRIBUTING.md); agent rules in [AGENTS.md](../A
[Cursor](./providers/cursor.md)
- [Reference](./reference/encyclopedia.md)
- [User guides](./user/keybindings.md)
=======
>>>>>>> 290392fac9 (fix: reconcile rebase with latest main)
@@ -77,9 +77,17 @@ export interface UnsettleThreadInput extends ThreadCommandInput {
readonly reason: "user";
}
export type PinThreadInput = ThreadCommandInput;
export interface PinThreadInput extends ThreadCommandInput {
/** Initial slot in the user-arranged pinned order; omit to pin keyless. */
readonly orderKey?: string;
}
export type UnpinThreadInput = ThreadCommandInput;
export interface ReorderPinnedThreadInput extends ThreadCommandInput {
/** Fractional-index key that sorts between the drop position's neighbors. */
readonly orderKey: string;
}
export interface SnoozeThreadInput extends ThreadCommandInput {
readonly snoozedUntil: string;
}
@@ -384,7 +392,25 @@ export const settleThread = Effect.fn("EnvironmentCommands.settleThread")(functi
export const pinThread = Effect.fn("EnvironmentCommands.pinThread")(function* (
input: PinThreadInput,
) {
return yield* simpleThreadCommand("thread.pin", input);
const commandId = yield* allocateCommandId(input);
return yield* dispatch({
type: "thread.pin",
commandId,
threadId: input.threadId,
...(input.orderKey === undefined ? {} : { orderKey: input.orderKey }),
});
});
export const reorderPinnedThread = Effect.fn("EnvironmentCommands.reorderPinnedThread")(function* (
input: ReorderPinnedThreadInput,
) {
const commandId = yield* allocateCommandId(input);
return yield* dispatch({
type: "thread.pin.reorder",
commandId,
threadId: input.threadId,
orderKey: input.orderKey,
});
});
export const unpinThread = Effect.fn("EnvironmentCommands.unpinThread")(function* (
@@ -99,6 +99,8 @@ export interface EnvironmentThreadShell {
readonly snoozedUntil: string | null;
readonly snoozedAt: string | null;
readonly pinnedAt: string | null;
/** Slot in the user-arranged pinned order; null for keyless (legacy) pins. */
readonly pinOrderKey: string | null;
/**
* Server-tracked visited watermark. `undefined` means the environment's
* server predates visited tracking and clients should fall back to any
@@ -210,6 +212,7 @@ export function presentThreadShell(
snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
snoozedAt: nullableIso(thread.snoozedAt ?? null),
pinnedAt: nullableIso(thread.pinnedAt ?? null),
pinOrderKey: thread.pinOrderKey ?? null,
...(thread.lastVisitedAt === undefined
? {}
: { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
@@ -114,6 +114,7 @@ export function applyOrchestrationV2ProjectionEvent(
case "thread.unsnoozed":
case "thread.pinned":
case "thread.unpinned":
case "thread.pin-reordered":
case "thread.metadata-updated":
case "thread.runtime-mode-updated":
case "thread.interaction-mode-updated":
@@ -708,6 +708,7 @@ export function createServerEnvironmentAtoms<R, E>(
label: "environment-data:server:usage-summary",
tag: WS_METHODS.serverGetUsageSummary,
staleTimeMs: 60_000,
}),
resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
label: "environment-data:server:resource-telemetry",
tag: WS_METHODS.subscribeResourceTelemetry,
+9 -1
View File
@@ -10,7 +10,7 @@ import {
ProviderItemId,
TrimmedNonEmptyString,
} from "./baseSchemas.ts";
import { RepositoryIdentity } from "./environment.ts";
import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts";
import { ModelSelection } from "./modelSelection.ts";
import type { OrchestrationV2StoredEvent } from "./orchestrationV2.ts";
import { ProjectScript } from "./project.ts";
@@ -31,6 +31,11 @@ export const ApplicationProjectCreatedPayload = Schema.Struct({
workspaceRoot: TrimmedNonEmptyString,
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
defaultModelSelection: Schema.NullOr(ModelSelection),
// Per-project override for where new threads start; optional so persisted
// events from older servers still decode.
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
// Optional so persisted events from older servers still decode.
faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -43,6 +48,9 @@ export const ApplicationProjectMetaUpdatedPayload = Schema.Struct({
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
// Absent = leave unchanged; null = clear the override.
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
scripts: Schema.optional(Schema.Array(ProjectScript)),
updatedAt: IsoDateTime,
});
+2 -31
View File
@@ -27,7 +27,8 @@ import {
RuntimeMode,
} from "./providerPolicy.ts";
import { ProviderInstanceId } from "./providerInstance.ts";
import { Project, ProjectScript } from "./project.ts";
import { Project, ProjectScript, ProjectScriptIcon } from "./project.ts";
import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts";
import { OrchestrationProjectShell } from "./orchestrationProject.ts";
import {
ApplicationEventMetadata,
@@ -59,36 +60,6 @@ export {
export const CorrelationId = CommandId;
export type CorrelationId = typeof CorrelationId.Type;
export const ProjectScriptIcon = Schema.Literals([
"play",
"test",
"lint",
"configure",
"build",
"debug",
]);
export type ProjectScriptIcon = typeof ProjectScriptIcon.Type;
export const ProjectScript = Schema.Struct({
id: TrimmedNonEmptyString,
name: TrimmedNonEmptyString,
command: TrimmedNonEmptyString,
icon: ProjectScriptIcon,
runOnWorktreeCreate: Schema.Boolean,
/**
* URL to open in the in-app browser preview when this script runs (or
* when the user explicitly requests a preview). Optional; only honored on
* the desktop build.
*/
previewUrl: Schema.optional(TrimmedNonEmptyString),
/**
* When true, automatically open the preview panel pointed at `previewUrl`
* the moment this script starts. Ignored without `previewUrl` or on web.
*/
autoOpenPreview: Schema.optional(Schema.Boolean),
});
export type ProjectScript = typeof ProjectScript.Type;
export const ProjectFaviconPath = TrimmedNonEmptyString.check(
Schema.isMaxLength(1024),
Schema.isPattern(/\.(?:avif|gif|ico|jpe?g|png|svg|webp)$/i),
@@ -1,7 +1,7 @@
import * as Schema from "effect/Schema";
import { IsoDateTime, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts";
import { RepositoryIdentity } from "./environment.ts";
import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts";
import { ModelSelection } from "./modelSelection.ts";
import { ProjectScript } from "./project.ts";
@@ -12,6 +12,11 @@ export const OrchestrationProjectShell = Schema.Struct({
workspaceRoot: TrimmedNonEmptyString,
repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),
defaultModelSelection: Schema.NullOr(ModelSelection),
// Per-project override for where new threads start. Null/absent means
// "no override": clients fall back to t3.json, then the global setting.
defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)),
// Optional on the wire so cached snapshots from older servers still decode.
faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
+21
View File
@@ -325,6 +325,9 @@ export const OrchestrationV2AppThread = Schema.Struct({
snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
// Fractional-index slot in the user-arranged pinned order. Optional so
// payloads from pre-reorder servers still decode.
pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
lastVisitedAt: Schema.NullOr(Schema.DateTimeUtc).pipe(
Schema.withDecodingDefault(Effect.succeed(null)),
),
@@ -1098,6 +1101,7 @@ export const OrchestrationV2DomainEvent = Schema.Union([
"thread.unsnoozed",
"thread.pinned",
"thread.unpinned",
"thread.pin-reordered",
"thread.visited",
"thread.marked-unread",
"thread.metadata-updated",
@@ -1301,6 +1305,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
/** Omitted by servers that predate thread pinning. */
pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
/** Slot in the user-arranged pinned order; omitted by pre-reorder servers. */
pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
/**
* Omitted by servers that predate server-side visited tracking; clients fall
* back to their local visited state when the field is absent.
@@ -1818,6 +1824,7 @@ export const OrchestrationV2DomainEventJson = Schema.Union([
"thread.unsnoozed",
"thread.pinned",
"thread.unpinned",
"thread.pin-reordered",
"thread.visited",
"thread.marked-unread",
"thread.metadata-updated",
@@ -1994,12 +2001,26 @@ export const OrchestrationV2Command = Schema.Union([
type: Schema.Literal("thread.pin"),
commandId: CommandId,
threadId: ThreadId,
// Initial slot in the user-arranged pinned order (see thread.pin.reorder).
// Optional: clients on pre-reorder servers omit it, and the pinned block
// falls back to creation order for keyless threads.
orderKey: Schema.optional(TrimmedNonEmptyString),
}),
Schema.Struct({
type: Schema.Literal("thread.unpin"),
commandId: CommandId,
threadId: ThreadId,
}),
Schema.Struct({
type: Schema.Literal("thread.pin.reorder"),
commandId: CommandId,
threadId: ThreadId,
// Fractional-index key: pinned threads sort lexicographically by these
// keys, so a drag writes one key to one thread — neighbors are never
// touched. Clients compute a key that sorts between the dropped
// position's neighbors.
orderKey: TrimmedNonEmptyString,
}),
Schema.Struct({
type: Schema.Literal("thread.visit"),
commandId: CommandId,
+1 -5
View File
@@ -96,6 +96,7 @@ import {
RelayClientInstallProgressEventSchema,
RelayClientStatusSchema,
} from "./relayClient.ts";
import {
ORCHESTRATION_V2_WS_METHODS,
OrchestrationGetWorkflowScriptError,
OrchestrationV2DispatchCommandError,
@@ -104,11 +105,6 @@ import {
OrchestrationV2RpcSchemas,
OrchestrationV2ThreadLaunchError,
} from "./orchestrationV2.ts";
import {
RelayClientInstallFailedError,
RelayClientInstallProgressEventSchema,
RelayClientStatusSchema,
} from "./relayClient.ts";
import {
ProjectListEntriesError,
ProjectListEntriesInput,