feat(web): first-run welcome wizard with agent setup and project import (#5362)
Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
c843c19294
commit
09aac71563
122 files changed
+15526
-500
No files matched your search
@@ -54,7 +54,7 @@ const readWithLogs = (fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) => {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
return {
|
||||
result: yield* settings.get,
|
||||
result: yield* Effect.result(settings.get),
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
records,
|
||||
};
|
||||
@@ -73,12 +73,13 @@ describe("DesktopClientSettings diagnostics", () => {
|
||||
Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(FileSystem.layerNoop({}));
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
if (result.result._tag !== "Success") return assert.fail("expected a successful read");
|
||||
assert.isTrue(Option.isNone(result.result.success));
|
||||
assert.deepEqual(result.records, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("logs non-missing filesystem failures with the settings path", () => {
|
||||
it.effect("reports non-missing filesystem failures and logs the settings path", () => {
|
||||
const permissionError = PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
@@ -93,7 +94,12 @@ describe("DesktopClientSettings diagnostics", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
if (result.result._tag !== "Failure") return assert.fail("expected a read failure");
|
||||
assert.instanceOf(
|
||||
result.result.failure,
|
||||
DesktopClientSettings.DesktopClientSettingsReadError,
|
||||
);
|
||||
assert.strictEqual(result.result.failure.cause, permissionError);
|
||||
assert.equal(result.records.length, 1);
|
||||
assert.deepEqual(result.records[0]?.message, [
|
||||
"Could not read desktop client settings.",
|
||||
@@ -103,7 +109,7 @@ describe("DesktopClientSettings diagnostics", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("logs malformed settings documents with the settings path", () =>
|
||||
it.effect("reports malformed settings documents and logs the settings path", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* readWithLogs(
|
||||
FileSystem.layerNoop({
|
||||
@@ -111,7 +117,12 @@ describe("DesktopClientSettings diagnostics", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
assert.isTrue(Option.isNone(result.result));
|
||||
if (result.result._tag !== "Failure") return assert.fail("expected a decode failure");
|
||||
assert.instanceOf(
|
||||
result.result.failure,
|
||||
DesktopClientSettings.DesktopClientSettingsReadError,
|
||||
);
|
||||
assert.equal(result.result.failure.operation, "decode-document");
|
||||
assert.equal(result.records.length, 1);
|
||||
const message = result.records[0]?.message;
|
||||
if (!Array.isArray(message)) {
|
||||
|
||||
@@ -44,6 +44,7 @@ const clientSettings: ClientSettings = {
|
||||
fontSizeTerminal: 12,
|
||||
fontSmoothing: true,
|
||||
glassOpacity: 80,
|
||||
onboardingCompletedAt: null,
|
||||
panelAnimationDurationMs: 0,
|
||||
planModeEnabled: false,
|
||||
proactivePanelsEnabled: true,
|
||||
@@ -136,6 +137,59 @@ describe("DesktopClientSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
for (const failure of [
|
||||
{ label: "permission", reason: "PermissionDenied" },
|
||||
{ label: "I/O", reason: "Unknown" },
|
||||
] as const) {
|
||||
it.effect(`preserves saved preferences across ${failure.label} read failures and retries`, () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
const savedSettings = {
|
||||
...clientSettings,
|
||||
onboardingCompletedAt: "2026-09-05T12:00:00.000Z",
|
||||
};
|
||||
yield* settings.set(savedSettings);
|
||||
const savedContents = yield* fileSystem.readFileString(environment.clientSettingsPath);
|
||||
const cause = PlatformError.systemError({
|
||||
_tag: failure.reason,
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: environment.clientSettingsPath,
|
||||
});
|
||||
let failRead = true;
|
||||
const retryableSettings = yield* DesktopClientSettings.make.pipe(
|
||||
Effect.provideService(
|
||||
FileSystem.FileSystem,
|
||||
FileSystem.FileSystem.of({
|
||||
...fileSystem,
|
||||
readFileString: (path) =>
|
||||
Effect.suspend(() =>
|
||||
failRead ? Effect.fail(cause) : fileSystem.readFileString(path),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const error = yield* retryableSettings.get.pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsReadError);
|
||||
assert.equal(error.operation, "read-file");
|
||||
assert.equal(error.path, environment.clientSettingsPath);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(
|
||||
yield* fileSystem.readFileString(environment.clientSettingsPath),
|
||||
savedContents,
|
||||
);
|
||||
|
||||
failRead = false;
|
||||
assert.deepEqual(yield* retryableSettings.get, Option.some(savedSettings));
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("reports the failed client settings write operation and path", () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
@@ -222,17 +276,31 @@ describe("DesktopClientSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("treats malformed client settings documents as absent", () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(environment.clientSettingsPath, "{not-json");
|
||||
for (const document of [
|
||||
{ label: "malformed JSON", contents: "{not-json" },
|
||||
{ label: "invalid direct settings", contents: '{"fontSizeCode":"large"}' },
|
||||
{ label: "invalid legacy settings", contents: '{"settings":{"fontSizeCode":"large"}}' },
|
||||
]) {
|
||||
it.effect(`reports ${document.label} without treating the settings file as absent`, () =>
|
||||
withClientSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(environment.clientSettingsPath, document.contents);
|
||||
|
||||
assert.isTrue(Option.isNone(yield* settings.get));
|
||||
}),
|
||||
),
|
||||
);
|
||||
const error = yield* settings.get.pipe(Effect.flip);
|
||||
assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsReadError);
|
||||
assert.equal(error.operation, "decode-document");
|
||||
assert.equal(error.path, environment.clientSettingsPath);
|
||||
assert.instanceOf(error.cause, Schema.SchemaError);
|
||||
assert.equal(
|
||||
yield* fileSystem.readFileString(environment.clientSettingsPath),
|
||||
document.contents,
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -12,25 +12,33 @@ import * as Ref from "effect/Ref";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
|
||||
const ClientSettingsDocumentSchema = Schema.Struct({
|
||||
settings: ClientSettingsSchema,
|
||||
});
|
||||
|
||||
const ClientSettingsJson = fromLenientJson(ClientSettingsSchema);
|
||||
const LegacyClientSettingsDocumentJson = fromLenientJson(ClientSettingsDocumentSchema);
|
||||
const decodeLegacyClientSettingsDocumentJson = Schema.decodeEffect(
|
||||
LegacyClientSettingsDocumentJson,
|
||||
const decodeClientSettingsDocument = Schema.decodeEffect(
|
||||
fromLenientJson(Schema.Record(Schema.String, Schema.Unknown)),
|
||||
);
|
||||
const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
|
||||
const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
|
||||
decodeLegacyClientSettingsDocumentJson(raw).pipe(
|
||||
Effect.map((document) => document.settings),
|
||||
Effect.catchTags({
|
||||
SchemaError: () => decodeClientSettingsJsonValue(raw),
|
||||
}),
|
||||
const decodeClientSettingsValue = Schema.decodeUnknownEffect(ClientSettingsSchema);
|
||||
const decodeClientSettingsJson = Effect.fnUntraced(function* (raw: string) {
|
||||
const document = yield* decodeClientSettingsDocument(raw);
|
||||
// Select the shape before validation so invalid legacy settings cannot become defaults.
|
||||
return yield* decodeClientSettingsValue(
|
||||
Object.hasOwn(document, "settings") ? document.settings : document,
|
||||
);
|
||||
});
|
||||
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
|
||||
|
||||
export class DesktopClientSettingsReadError extends Schema.TaggedErrorClass<DesktopClientSettingsReadError>()(
|
||||
"DesktopClientSettingsReadError",
|
||||
{
|
||||
operation: Schema.Literals(["read-file", "decode-document"]),
|
||||
path: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Desktop client settings read failed during ${this.operation} at ${this.path}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const DesktopClientSettingsWriteOperation = Schema.Literals([
|
||||
"create-temporary-file-name",
|
||||
"encode-document",
|
||||
@@ -55,7 +63,7 @@ export class DesktopClientSettingsWriteError extends Schema.TaggedErrorClass<Des
|
||||
export class DesktopClientSettings extends Context.Service<
|
||||
DesktopClientSettings,
|
||||
{
|
||||
readonly get: Effect.Effect<Option.Option<ClientSettings>>;
|
||||
readonly get: Effect.Effect<Option.Option<ClientSettings>, DesktopClientSettingsReadError>;
|
||||
readonly set: (
|
||||
settings: ClientSettings,
|
||||
) => Effect.Effect<void, DesktopClientSettingsWriteError>;
|
||||
@@ -65,7 +73,7 @@ export class DesktopClientSettings extends Context.Service<
|
||||
const readClientSettings = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
settingsPath: string,
|
||||
): Effect.Effect<Option.Option<ClientSettings>> =>
|
||||
): Effect.Effect<Option.Option<ClientSettings>, DesktopClientSettingsReadError> =>
|
||||
fileSystem.readFileString(settingsPath).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchTags({
|
||||
@@ -74,7 +82,15 @@ const readClientSettings = (
|
||||
? Effect.succeed(Option.none<string>())
|
||||
: Effect.logWarning("Could not read desktop client settings.", cause).pipe(
|
||||
Effect.annotateLogs({ settingsPath }),
|
||||
Effect.as(Option.none<string>()),
|
||||
Effect.andThen(
|
||||
Effect.fail(
|
||||
new DesktopClientSettingsReadError({
|
||||
operation: "read-file",
|
||||
path: settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
Effect.flatMap(
|
||||
@@ -87,7 +103,15 @@ const readClientSettings = (
|
||||
SchemaError: (cause) =>
|
||||
Effect.logWarning("Could not decode desktop client settings.", cause).pipe(
|
||||
Effect.annotateLogs({ settingsPath }),
|
||||
Effect.as(Option.none<ClientSettings>()),
|
||||
Effect.andThen(
|
||||
Effect.fail(
|
||||
new DesktopClientSettingsReadError({
|
||||
operation: "decode-document",
|
||||
path: settingsPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -43,6 +43,15 @@ describe("RPC authorization scopes", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("requires write access to import agent session history", () => {
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.agentSessionsScan)).toBe(
|
||||
AuthOrchestrationReadScope,
|
||||
);
|
||||
expect(requiredScopeForRpcMethod(WS_METHODS.agentSessionsImport)).toBe(
|
||||
AuthOrchestrationOperateScope,
|
||||
);
|
||||
});
|
||||
|
||||
it("reads the reviewer menu under the same scope as the pull request it belongs to", () => {
|
||||
// The candidate list is a read like the detail beside it, and asking somebody for a review is
|
||||
// a write like every other pull request operation.
|
||||
|
||||
@@ -99,6 +99,8 @@ export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.projectsWriteFile]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.agentSessionsScan]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.agentSessionsImport]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.attachmentsCreateUploadUrl]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.attachmentsDelete]: AuthOrchestrationOperateScope,
|
||||
|
||||
@@ -90,6 +90,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getImportedAgentSessionSources: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () =>
|
||||
Effect.sync(() => {
|
||||
getThreadCheckpointContextCalls += 1;
|
||||
@@ -202,6 +203,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getImportedAgentSessionSources: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadRuntimeContext: () => Effect.die("unused"),
|
||||
@@ -289,6 +291,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getImportedAgentSessionSources: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadRuntimeContext: () => Effect.die("unused"),
|
||||
@@ -361,6 +364,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getImportedAgentSessionSources: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadRuntimeContext: () => Effect.die("unused"),
|
||||
@@ -418,6 +422,7 @@ describe("CheckpointDiffQuery.layer", () => {
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getImportedAgentSessionSources: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadRuntimeContext: () => Effect.die("unused"),
|
||||
|
||||
@@ -1342,6 +1342,36 @@ describe("CheckpointReactor", () => {
|
||||
).toBe("v1\n");
|
||||
});
|
||||
|
||||
it("does not create checkpoints while importing historical user messages", async () => {
|
||||
const harness = await createHarness({
|
||||
hasSession: false,
|
||||
seedFilesystemCheckpoints: false,
|
||||
threadWorktreePath: null,
|
||||
});
|
||||
if (runtime === null) throw new Error("Checkpoint test runtime was not initialized.");
|
||||
|
||||
await runtime.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.history.import",
|
||||
commandId: CommandId.make("cmd-import-history-without-checkpoint"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
messages: [
|
||||
{
|
||||
messageId: MessageId.make("imported-user-message"),
|
||||
role: "user",
|
||||
text: "A message from an existing agent session",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
await harness.drain();
|
||||
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("captures turn completion checkpoint from project workspace root when provider session cwd is unavailable", async () => {
|
||||
const harness = await createHarness({
|
||||
hasSession: false,
|
||||
|
||||
@@ -615,6 +615,7 @@ const make = Effect.gen(function* () {
|
||||
) {
|
||||
if (event.type === "thread.message-sent") {
|
||||
if (
|
||||
event.metadata.historyImport === true ||
|
||||
event.payload.role !== "user" ||
|
||||
event.payload.streaming ||
|
||||
event.payload.turnId !== null
|
||||
|
||||
@@ -418,6 +418,7 @@ describe("OrchestrationEngine", () => {
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getImportedAgentSessionSources: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadRuntimeContext: () => Effect.die("unused"),
|
||||
|
||||
@@ -108,6 +108,102 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-curs
|
||||
},
|
||||
);
|
||||
|
||||
it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-import-shell-")))(
|
||||
"imported thread shell projection",
|
||||
(it) => {
|
||||
it.effect("does not mark imported user messages as queued work in thread shells", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const createdAt = "2026-08-24T10:00:00.000Z";
|
||||
const threadId = ThreadId.make("import:codex:shell-session");
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-import-shell-thread"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.make("cmd-import-shell-thread"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-import-shell-thread"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-import-shell"),
|
||||
title: "Imported thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
yield* eventStore.append({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.make("evt-import-shell-message"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.make("cmd-import-shell-message"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-import-shell-message"),
|
||||
metadata: { historyImport: true },
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make("import:codex:shell-session:0"),
|
||||
role: "user",
|
||||
text: "Imported user prompt",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const readLatestUserMessageAt = sql<{ readonly latestUserMessageAt: string | null }>`
|
||||
SELECT latest_user_message_at AS "latestUserMessageAt"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = ${threadId}
|
||||
`;
|
||||
assert.deepEqual(yield* readLatestUserMessageAt, [{ latestUserMessageAt: null }]);
|
||||
|
||||
const sessionEvent = yield* eventStore.append({
|
||||
type: "thread.session-set",
|
||||
eventId: EventId.make("evt-import-shell-session"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.make("cmd-import-shell-session"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("cmd-import-shell-session"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* projectionPipeline.projectEvent(sessionEvent);
|
||||
assert.deepEqual(yield* readLatestUserMessageAt, [{ latestUserMessageAt: null }]);
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
it.effect("bootstraps all projection states and writes projection rows", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
isImportedAgentSessionMessageId,
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationSessionStatus,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { compareDateTimeStrings } from "@t3tools/shared/dateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -248,7 +250,7 @@ function retainProjectionMessagesAfterRevert(
|
||||
}
|
||||
|
||||
for (const message of messages) {
|
||||
if (message.role === "system") {
|
||||
if (message.role === "system" || isImportedAgentSessionMessageId(message.messageId)) {
|
||||
retainedMessageIds.add(message.messageId);
|
||||
continue;
|
||||
}
|
||||
@@ -258,7 +260,10 @@ function retainProjectionMessagesAfterRevert(
|
||||
}
|
||||
|
||||
const retainedUserCount = messages.filter(
|
||||
(message) => message.role === "user" && retainedMessageIds.has(message.messageId),
|
||||
(message) =>
|
||||
message.role === "user" &&
|
||||
!isImportedAgentSessionMessageId(message.messageId) &&
|
||||
retainedMessageIds.has(message.messageId),
|
||||
).length;
|
||||
const missingUserCount = Math.max(0, turnCount - retainedUserCount);
|
||||
if (missingUserCount > 0) {
|
||||
@@ -271,7 +276,7 @@ function retainProjectionMessagesAfterRevert(
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
compareDateTimeStrings(left.createdAt, right.createdAt) ||
|
||||
left.messageId.localeCompare(right.messageId),
|
||||
)
|
||||
.slice(0, missingUserCount);
|
||||
@@ -281,7 +286,10 @@ function retainProjectionMessagesAfterRevert(
|
||||
}
|
||||
|
||||
const retainedAssistantCount = messages.filter(
|
||||
(message) => message.role === "assistant" && retainedMessageIds.has(message.messageId),
|
||||
(message) =>
|
||||
message.role === "assistant" &&
|
||||
!isImportedAgentSessionMessageId(message.messageId) &&
|
||||
retainedMessageIds.has(message.messageId),
|
||||
).length;
|
||||
const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount);
|
||||
if (missingAssistantCount > 0) {
|
||||
@@ -294,7 +302,7 @@ function retainProjectionMessagesAfterRevert(
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
compareDateTimeStrings(left.createdAt, right.createdAt) ||
|
||||
left.messageId.localeCompare(right.messageId),
|
||||
)
|
||||
.slice(0, missingAssistantCount);
|
||||
@@ -903,6 +911,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
updatedAt: event.occurredAt,
|
||||
latestUserMessageAt:
|
||||
event.payload.role === "user" &&
|
||||
!isImportedAgentSessionMessageId(event.payload.messageId) &&
|
||||
(previousLatest === null || event.payload.createdAt > previousLatest)
|
||||
? event.payload.createdAt
|
||||
: previousLatest,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
type AgentSessionImportSource,
|
||||
CheckpointRef,
|
||||
EventId,
|
||||
MessageId,
|
||||
@@ -11,6 +12,7 @@ import { assert, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
@@ -2134,7 +2136,9 @@ projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) =
|
||||
//
|
||||
// Straggler user message at T03.5 (turn_id NULL, not any pending_message_id)
|
||||
// and a turnless activity at T03.6 — both belong to the page containing T03+.
|
||||
const seedFanOutThread = Effect.fnUntraced(function* () {
|
||||
const seedFanOutThread = Effect.fnUntraced(function* (options?: {
|
||||
readonly importedMessageCount?: number;
|
||||
}) {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
// Tests in this block share one in-memory database; reset before seeding.
|
||||
@@ -2163,6 +2167,20 @@ projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) =
|
||||
'turn-5', 0, 0, 0, '2026-03-01T00:00:00.000Z', '2026-03-01T00:00:10.000Z', NULL)
|
||||
`;
|
||||
|
||||
if (options?.importedMessageCount) {
|
||||
for (let index = 0; index < options.importedMessageCount; index += 1) {
|
||||
const messageId = `import:codex:session-w:${String(index).padStart(6, "0")}`;
|
||||
const role = index % 2 === 0 ? "user" : "assistant";
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
|
||||
)
|
||||
VALUES (${messageId}, 'thread-w', NULL, ${role}, ${"imported message " + index}, 0,
|
||||
'2026-02-28T00:00:00.000Z', '2026-02-28T00:00:00.000Z')
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
const turns: ReadonlyArray<{
|
||||
turn: string;
|
||||
pendingMessage: string | null;
|
||||
@@ -2396,6 +2414,51 @@ projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) =
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps imported history on the oldest page after resumed turns", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedFanOutThread({ importedMessageCount: 12 });
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
const completePage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 50 });
|
||||
assert.equal(completePage._tag, "Some");
|
||||
if (completePage._tag !== "Some") return;
|
||||
assert.equal(
|
||||
completePage.value.thread.messages.filter((message) => message.id.startsWith("import:"))
|
||||
.length,
|
||||
12,
|
||||
);
|
||||
assert.equal(completePage.value.page?.hasMore, false);
|
||||
assert.equal(completePage.value.page?.beforeCursor, null);
|
||||
|
||||
const recentPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
|
||||
assert.equal(recentPage._tag, "Some");
|
||||
if (recentPage._tag !== "Some") return;
|
||||
assert.equal(
|
||||
recentPage.value.thread.messages.some((message) => message.id.startsWith("import:")),
|
||||
false,
|
||||
);
|
||||
const cursor = recentPage.value.page?.beforeCursor;
|
||||
assert.notEqual(cursor, null);
|
||||
assert.notEqual(cursor, undefined);
|
||||
if (cursor === null || cursor === undefined) return;
|
||||
|
||||
const oldestPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
|
||||
turnLimit: 1,
|
||||
beforeCursor: cursor,
|
||||
});
|
||||
assert.equal(oldestPage._tag, "Some");
|
||||
if (oldestPage._tag !== "Some") return;
|
||||
|
||||
const importedIds = oldestPage.value.thread.messages
|
||||
.map((message) => message.id)
|
||||
.filter((messageId) => messageId.startsWith("import:"));
|
||||
assert.equal(importedIds.length, 12);
|
||||
assert.equal(new Set(importedIds).size, 12);
|
||||
assert.equal(oldestPage.value.page?.hasMore, false);
|
||||
assert.equal(oldestPage.value.page?.beforeCursor, null);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("a cursor for a different thread degrades to the first page", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedFanOutThread();
|
||||
@@ -2779,3 +2842,237 @@ projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) =
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
projectionSnapshotLayer("ProjectionSnapshotQuery imported sources", (it) => {
|
||||
const encodeJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
|
||||
const source: AgentSessionImportSource = {
|
||||
provider: "codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex-home"),
|
||||
providerSessionId: "native-session",
|
||||
filePath: "/tmp/transcript.jsonl",
|
||||
size: 128,
|
||||
mtimeMs: 1_700_000_000_000,
|
||||
device: 1,
|
||||
inode: 2,
|
||||
birthtimeMs: 1_699_000_000_000,
|
||||
};
|
||||
|
||||
const seedImportedSession = Effect.fn("seedImportedSession")(function* (
|
||||
projectId: ProjectId,
|
||||
source: AgentSessionImportSource,
|
||||
) {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const threadId = ThreadId.make(
|
||||
`import:${source.providerInstanceId}:${source.providerSessionId}`,
|
||||
);
|
||||
const timestamp = "2026-03-02T00:00:00.000Z";
|
||||
yield* sql`
|
||||
INSERT OR IGNORE INTO projection_projects (
|
||||
project_id, title, workspace_root, scripts_json, created_at, updated_at
|
||||
) VALUES (${projectId}, 'Imported project', '/tmp/imported-project', '[]',
|
||||
${timestamp}, ${timestamp})
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_threads (
|
||||
thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode,
|
||||
created_at, updated_at
|
||||
) VALUES (${threadId}, ${projectId}, 'Imported thread',
|
||||
${encodeJson({ instanceId: source.providerInstanceId, model: "gpt-5-codex" })},
|
||||
'full-access', 'default',
|
||||
${timestamp}, ${timestamp})
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO provider_session_runtime (
|
||||
thread_id, provider_name, provider_instance_id, adapter_key, runtime_mode, status,
|
||||
last_seen_at, resume_cursor_json, runtime_payload_json
|
||||
) VALUES (${threadId}, ${source.provider}, ${source.providerInstanceId},
|
||||
${source.provider}, 'full-access', 'stopped', ${timestamp},
|
||||
${encodeJson({ threadId: source.providerSessionId })},
|
||||
${encodeJson({ importedTranscripts: [source] })})
|
||||
`;
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id, thread_id, role, text, is_streaming, created_at, updated_at
|
||||
) VALUES (${`${threadId}:000000`}, ${threadId}, 'user', 'Imported history', 0,
|
||||
${timestamp}, ${timestamp})
|
||||
`;
|
||||
return { threadId, source };
|
||||
});
|
||||
|
||||
it.effect("reads completed source copies without decoding message bodies", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const query = yield* ProjectionSnapshotQuery;
|
||||
const projectId = ProjectId.make("project-import-metadata");
|
||||
const imported = yield* seedImportedSession(projectId, source);
|
||||
const copiedSource = {
|
||||
...source,
|
||||
filePath: "/tmp/transcript-copy.jsonl",
|
||||
mtimeMs: null,
|
||||
inode: null,
|
||||
birthtimeMs: null,
|
||||
};
|
||||
yield* sql`
|
||||
UPDATE provider_session_runtime
|
||||
SET runtime_payload_json = ${encodeJson({
|
||||
cwd: "/tmp/imported-project",
|
||||
importedTranscripts: [source, copiedSource],
|
||||
})}
|
||||
WHERE thread_id = ${imported.threadId}
|
||||
`;
|
||||
yield* sql`
|
||||
UPDATE projection_thread_messages SET attachments_json = 'not-json'
|
||||
WHERE thread_id = ${imported.threadId}
|
||||
`;
|
||||
|
||||
const counter = makeSqlStatementCounter();
|
||||
const sources = yield* query
|
||||
.getImportedAgentSessionSources(projectId)
|
||||
.pipe(Effect.withTracer(counter.tracer));
|
||||
assert.deepEqual(sources, [imported, { threadId: imported.threadId, source: copiedSource }]);
|
||||
assert.equal(counter.count(), 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("requires active project threads, a binding, and an imported message", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const query = yield* ProjectionSnapshotQuery;
|
||||
const projectId = ProjectId.make("project-import-completion");
|
||||
const completed = yield* seedImportedSession(projectId, {
|
||||
...source,
|
||||
providerSessionId: "completed",
|
||||
});
|
||||
yield* sql`
|
||||
UPDATE projection_thread_messages SET message_id = ${`${completed.threadId}:legacy`}
|
||||
WHERE thread_id = ${completed.threadId}
|
||||
`;
|
||||
const partials = yield* Effect.forEach(
|
||||
[
|
||||
"no-binding",
|
||||
"no-history",
|
||||
"no-imported-message",
|
||||
"wrong-message-thread",
|
||||
"archived",
|
||||
"deleted",
|
||||
],
|
||||
(providerSessionId) => seedImportedSession(projectId, { ...source, providerSessionId }),
|
||||
);
|
||||
const [noBinding, noHistory, noImportedMessage, wrongMessageThread, archived, deleted] =
|
||||
partials;
|
||||
assert.isDefined(noBinding);
|
||||
assert.isDefined(noHistory);
|
||||
assert.isDefined(noImportedMessage);
|
||||
assert.isDefined(wrongMessageThread);
|
||||
assert.isDefined(archived);
|
||||
assert.isDefined(deleted);
|
||||
yield* sql`DELETE FROM provider_session_runtime WHERE thread_id = ${noBinding.threadId}`;
|
||||
yield* sql`DELETE FROM projection_thread_messages WHERE thread_id = ${noHistory.threadId}`;
|
||||
yield* sql`
|
||||
UPDATE projection_thread_messages SET message_id = ${`normal:${noImportedMessage.threadId}`}
|
||||
WHERE thread_id = ${noImportedMessage.threadId}
|
||||
`;
|
||||
yield* sql`
|
||||
UPDATE projection_thread_messages SET thread_id = 'unrelated-thread'
|
||||
WHERE thread_id = ${wrongMessageThread.threadId}
|
||||
`;
|
||||
yield* sql`
|
||||
UPDATE projection_threads SET archived_at = '2026-03-03T00:00:00.000Z'
|
||||
WHERE thread_id = ${archived.threadId}
|
||||
`;
|
||||
yield* sql`
|
||||
UPDATE projection_threads SET deleted_at = '2026-03-03T00:00:00.000Z'
|
||||
WHERE thread_id = ${deleted.threadId}
|
||||
`;
|
||||
const otherProjectId = ProjectId.make("project-import-other");
|
||||
const otherProject = yield* seedImportedSession(otherProjectId, {
|
||||
...source,
|
||||
providerSessionId: "other-project",
|
||||
});
|
||||
const deletedProjectId = ProjectId.make("project-import-deleted");
|
||||
yield* seedImportedSession(deletedProjectId, {
|
||||
...source,
|
||||
providerSessionId: "deleted-project",
|
||||
});
|
||||
yield* sql`
|
||||
UPDATE projection_projects SET deleted_at = '2026-03-03T00:00:00.000Z'
|
||||
WHERE project_id = ${deletedProjectId}
|
||||
`;
|
||||
|
||||
assert.deepEqual(yield* query.getImportedAgentSessionSources(projectId), [completed]);
|
||||
assert.deepEqual(yield* query.getImportedAgentSessionSources(otherProjectId), [otherProject]);
|
||||
assert.deepEqual(yield* query.getImportedAgentSessionSources(deletedProjectId), []);
|
||||
assert.deepEqual(
|
||||
yield* query.getImportedAgentSessionSources(ProjectId.make("project-import-missing")),
|
||||
[],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps original sources when the current runtime provider and cursor change", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const query = yield* ProjectionSnapshotQuery;
|
||||
const projectId = ProjectId.make("project-import-switched");
|
||||
const imported = yield* seedImportedSession(projectId, {
|
||||
...source,
|
||||
provider: "claudeAgent",
|
||||
providerInstanceId: ProviderInstanceId.make("claude-original"),
|
||||
providerSessionId: "original-session",
|
||||
});
|
||||
yield* sql`
|
||||
UPDATE provider_session_runtime
|
||||
SET provider_name = 'codex', provider_instance_id = 'codex-new', adapter_key = 'codex',
|
||||
resume_cursor_json = '{"threadId":"new-session"}'
|
||||
WHERE thread_id = ${imported.threadId}
|
||||
`;
|
||||
|
||||
assert.deepEqual(yield* query.getImportedAgentSessionSources(projectId), [imported]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips invalid source payloads and entries without dropping valid sources", () =>
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const query = yield* ProjectionSnapshotQuery;
|
||||
const projectId = ProjectId.make("project-import-invalid");
|
||||
const imported = yield* seedImportedSession(projectId, {
|
||||
...source,
|
||||
providerSessionId: "a-invalid",
|
||||
});
|
||||
const valid = yield* seedImportedSession(projectId, {
|
||||
...source,
|
||||
providerSessionId: "z-valid",
|
||||
});
|
||||
for (const payload of [null, "not-json", "null", "[]", "{}", '{"importedTranscripts":{}}']) {
|
||||
yield* sql`
|
||||
UPDATE provider_session_runtime SET runtime_payload_json = ${payload}
|
||||
WHERE thread_id = ${imported.threadId}
|
||||
`;
|
||||
assert.deepEqual(yield* query.getImportedAgentSessionSources(projectId), [valid]);
|
||||
}
|
||||
yield* sql`
|
||||
UPDATE provider_session_runtime SET runtime_payload_json = X'FF'
|
||||
WHERE thread_id = ${imported.threadId}
|
||||
`;
|
||||
assert.deepEqual(yield* query.getImportedAgentSessionSources(projectId), [valid]);
|
||||
|
||||
yield* sql`
|
||||
UPDATE provider_session_runtime
|
||||
SET runtime_payload_json = ${encodeJson({
|
||||
importedTranscripts: [
|
||||
null,
|
||||
{},
|
||||
{ ...imported.source, size: -1 },
|
||||
{ ...imported.source, provider: "cursor" },
|
||||
{ ...imported.source, providerInstanceId: "wrong-instance" },
|
||||
{ ...imported.source, providerSessionId: "wrong-session" },
|
||||
imported.source,
|
||||
],
|
||||
})}
|
||||
WHERE thread_id = ${imported.threadId}
|
||||
`;
|
||||
assert.deepEqual(yield* query.getImportedAgentSessionSources(projectId), [imported, valid]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
AgentSessionImportSource,
|
||||
ApprovalRequestId,
|
||||
ChatAttachment,
|
||||
CheckpointRef,
|
||||
@@ -75,6 +76,14 @@ import {
|
||||
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
||||
const decodeShellSnapshot = Schema.decodeUnknownEffect(OrchestrationShellSnapshot);
|
||||
const decodeThread = Schema.decodeUnknownEffect(OrchestrationThread);
|
||||
const decodeImportedTranscriptsPayload = Schema.decodeUnknownOption(
|
||||
Schema.fromJsonString(
|
||||
Schema.Struct({
|
||||
importedTranscripts: Schema.Array(Schema.Unknown),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const decodeAgentSessionImportSource = Schema.decodeUnknownOption(AgentSessionImportSource);
|
||||
// Keep detail reads consistent with the in-memory projector's retained
|
||||
// activity window. Applying the limit in SQL avoids decoding an unbounded
|
||||
// payload_json set before the projector can enforce that invariant.
|
||||
@@ -164,6 +173,10 @@ const WorkspaceRootLookupInput = Schema.Struct({
|
||||
const ProjectIdLookupInput = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
});
|
||||
const ProjectionImportedAgentSessionSourcesRowSchema = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
runtimePayload: Schema.Unknown,
|
||||
});
|
||||
const ThreadIdLookupInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
@@ -983,6 +996,33 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const listImportedAgentSessionSourceRows = SqlSchema.findAll({
|
||||
Request: ProjectIdLookupInput,
|
||||
Result: ProjectionImportedAgentSessionSourcesRowSchema,
|
||||
execute: ({ projectId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
threads.thread_id AS "threadId",
|
||||
runtime.runtime_payload_json AS "runtimePayload"
|
||||
FROM projection_threads AS threads
|
||||
INNER JOIN projection_projects AS projects
|
||||
ON projects.project_id = threads.project_id
|
||||
INNER JOIN provider_session_runtime AS runtime
|
||||
ON runtime.thread_id = threads.thread_id
|
||||
WHERE threads.project_id = ${projectId}
|
||||
AND threads.deleted_at IS NULL
|
||||
AND threads.archived_at IS NULL
|
||||
AND projects.deleted_at IS NULL
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM projection_thread_messages AS messages
|
||||
WHERE messages.thread_id = threads.thread_id
|
||||
AND messages.message_id GLOB 'import:*'
|
||||
)
|
||||
ORDER BY threads.thread_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const getThreadCheckpointContextThreadRow = SqlSchema.findOneOption({
|
||||
Request: ThreadIdLookupInput,
|
||||
Result: ProjectionThreadCheckpointContextThreadRowSchema,
|
||||
@@ -2663,6 +2703,33 @@ pending_approval_requests AS (
|
||||
Effect.map(Option.map((row) => row.threadId)),
|
||||
);
|
||||
|
||||
const getImportedAgentSessionSources: ProjectionSnapshotQueryShape["getImportedAgentSessionSources"] =
|
||||
Effect.fn("ProjectionSnapshotQuery.getImportedAgentSessionSources")(function* (projectId) {
|
||||
const rows = yield* listImportedAgentSessionSourceRows({ projectId }).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getImportedAgentSessionSources:query",
|
||||
"ProjectionSnapshotQuery.getImportedAgentSessionSources:decodeRows",
|
||||
),
|
||||
),
|
||||
);
|
||||
return rows.flatMap((row) => {
|
||||
const payload = decodeImportedTranscriptsPayload(row.runtimePayload);
|
||||
if (Option.isNone(payload)) return [];
|
||||
return payload.value.importedTranscripts.flatMap((entry) => {
|
||||
const source = decodeAgentSessionImportSource(entry);
|
||||
if (
|
||||
Option.isNone(source) ||
|
||||
row.threadId !==
|
||||
`import:${source.value.providerInstanceId}:${source.value.providerSessionId}`
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
return [{ threadId: row.threadId, source: source.value }];
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const getThreadCheckpointContext: ProjectionSnapshotQueryShape["getThreadCheckpointContext"] = (
|
||||
threadId,
|
||||
) =>
|
||||
@@ -3151,33 +3218,6 @@ pending_approval_requests AS (
|
||||
);
|
||||
|
||||
const oldest = windowRows[0];
|
||||
// An empty window (no turns before the cursor, or a thread with no
|
||||
// turns at all) still returns thread metadata with empty collections
|
||||
// for turn-linked rows; turnless rows are bounded to the same empty
|
||||
// range. The first page of a turnless thread stays unwindowed so
|
||||
// pre-turn content (e.g. a just-created thread) is not hidden.
|
||||
const bounds: ThreadDetailBounds | undefined =
|
||||
oldest === undefined && cursor === null
|
||||
? undefined
|
||||
: {
|
||||
minAnchorAt: oldest?.anchorAt ?? "",
|
||||
minTurnKey: oldest?.turnKey ?? "",
|
||||
beforeAnchorAt: cursor?.beforeAnchorAt ?? ANCHOR_UNBOUNDED,
|
||||
beforeTurnKey: cursor?.beforeTurnId ?? "",
|
||||
};
|
||||
// Empty window behind a cursor: nothing older remains.
|
||||
const emptyBounds =
|
||||
oldest === undefined && cursor !== null
|
||||
? { minAnchorAt: "", minTurnKey: "", beforeAnchorAt: "", beforeTurnKey: "" }
|
||||
: undefined;
|
||||
|
||||
const thread = yield* getThreadDetailByIdBounded(threadId, emptyBounds ?? bounds, {
|
||||
mode: "client",
|
||||
});
|
||||
if (Option.isNone(thread)) {
|
||||
return Option.none<OrchestrationThreadDetailSnapshot>();
|
||||
}
|
||||
|
||||
const hasMore =
|
||||
oldest !== undefined &&
|
||||
(yield* listTurnWindowRows({
|
||||
@@ -3194,6 +3234,34 @@ pending_approval_requests AS (
|
||||
),
|
||||
),
|
||||
)).length > 0;
|
||||
// An empty window (no turns before the cursor, or a thread with no
|
||||
// turns at all) still returns thread metadata with empty collections
|
||||
// for turn-linked rows; turnless rows are bounded to the same empty
|
||||
// range. The first page of a turnless thread stays unwindowed so
|
||||
// pre-turn content (e.g. a just-created thread) is not hidden. Once
|
||||
// paging reaches the oldest turn, include turnless messages before
|
||||
// the first turn, such as history imported from a provider session.
|
||||
const bounds: ThreadDetailBounds | undefined =
|
||||
oldest === undefined && cursor === null
|
||||
? undefined
|
||||
: {
|
||||
minAnchorAt: hasMore ? (oldest?.anchorAt ?? "") : "",
|
||||
minTurnKey: hasMore ? (oldest?.turnKey ?? "") : "",
|
||||
beforeAnchorAt: cursor?.beforeAnchorAt ?? ANCHOR_UNBOUNDED,
|
||||
beforeTurnKey: cursor?.beforeTurnId ?? "",
|
||||
};
|
||||
// Empty window behind a cursor: nothing older remains.
|
||||
const emptyBounds =
|
||||
oldest === undefined && cursor !== null
|
||||
? { minAnchorAt: "", minTurnKey: "", beforeAnchorAt: "", beforeTurnKey: "" }
|
||||
: undefined;
|
||||
|
||||
const thread = yield* getThreadDetailByIdBounded(threadId, emptyBounds ?? bounds, {
|
||||
mode: "client",
|
||||
});
|
||||
if (Option.isNone(thread)) {
|
||||
return Option.none<OrchestrationThreadDetailSnapshot>();
|
||||
}
|
||||
|
||||
const { snapshotSequence } = yield* getSnapshotSequence();
|
||||
const watermarkRow = yield* getThreadEventWatermarkRow({
|
||||
@@ -3253,6 +3321,7 @@ pending_approval_requests AS (
|
||||
getActiveProjectByWorkspaceRoot,
|
||||
getProjectShellById,
|
||||
getFirstActiveThreadIdByProjectId,
|
||||
getImportedAgentSessionSources,
|
||||
getThreadCheckpointContext,
|
||||
getFullThreadDiffContext,
|
||||
getThreadShellById,
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* @module ProjectionSnapshotQuery
|
||||
*/
|
||||
import type {
|
||||
AgentSessionImportSource,
|
||||
ApprovalRequestId,
|
||||
CheckpointRef,
|
||||
OrchestrationCheckpointSummary,
|
||||
@@ -170,6 +171,15 @@ export interface ProjectionSnapshotQueryShape {
|
||||
projectId: ProjectId,
|
||||
) => Effect.Effect<Option.Option<ThreadId>, ProjectionRepositoryError>;
|
||||
|
||||
/** Read completed import sources without loading thread history. */
|
||||
readonly getImportedAgentSessionSources: (projectId: ProjectId) => Effect.Effect<
|
||||
ReadonlyArray<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly source: AgentSessionImportSource;
|
||||
}>,
|
||||
ProjectionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Read the checkpoint context needed to resolve a single thread diff.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,509 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
it.layer(NodeServices.layer)("thread history import", (it) => {
|
||||
it.effect("marks imported thread creation without changing live creation", () =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = "2026-08-24T10:00:00.000Z";
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const readModel = yield* projectEvent(createEmptyReadModel(createdAt), {
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-project-created"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: projectId,
|
||||
type: "project.created",
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.make("command-project-created"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("command-project-created"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId,
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
const makeCreateCommand = (threadId: ThreadId) => ({
|
||||
type: "thread.create" as const,
|
||||
commandId: CommandId.make(`command-create-${threadId}`),
|
||||
threadId,
|
||||
projectId,
|
||||
title: "Imported thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access" as const,
|
||||
interactionMode: "default" as const,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const imported = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
...makeCreateCommand(ThreadId.make("import:codex:session-1")),
|
||||
historyImport: true,
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
const live = yield* decideOrchestrationCommand({
|
||||
command: makeCreateCommand(ThreadId.make("live-thread")),
|
||||
readModel,
|
||||
});
|
||||
|
||||
expect(imported).toMatchObject({
|
||||
type: "thread.created",
|
||||
metadata: { historyImport: true },
|
||||
});
|
||||
expect(live).toMatchObject({ type: "thread.created" });
|
||||
expect(live).not.toMatchObject({ metadata: { historyImport: true } });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles imported messages at the latest absolute timestamp", () =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = "2026-08-24T10:30:00.000+02:00";
|
||||
const threadId = ThreadId.make("import:codex:session-1");
|
||||
const readModel = yield* projectEvent(createEmptyReadModel(createdAt), {
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-thread-created"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
type: "thread.created",
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.make("command-thread-created"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("command-thread-created"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Imported thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
|
||||
const events = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.history.import",
|
||||
commandId: CommandId.make("command-import-history"),
|
||||
threadId,
|
||||
messages: [
|
||||
{
|
||||
messageId: MessageId.make(`${threadId}:000000`),
|
||||
role: "user",
|
||||
text: "Fix the bug",
|
||||
createdAt,
|
||||
},
|
||||
{
|
||||
messageId: MessageId.make(`${threadId}:000001`),
|
||||
role: "assistant",
|
||||
text: "Fixed",
|
||||
createdAt: "2026-08-24T09:00:00.000Z",
|
||||
},
|
||||
],
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
|
||||
expect(events).toMatchObject([
|
||||
{
|
||||
type: "thread.message-sent",
|
||||
metadata: { historyImport: true },
|
||||
payload: { role: "user", text: "Fix the bug", turnId: null, streaming: false },
|
||||
},
|
||||
{
|
||||
type: "thread.message-sent",
|
||||
metadata: { historyImport: true },
|
||||
payload: { role: "assistant", text: "Fixed", turnId: null, streaming: false },
|
||||
},
|
||||
{
|
||||
type: "thread.settled",
|
||||
metadata: { historyImport: true },
|
||||
occurredAt: "2026-08-24T09:00:00.000Z",
|
||||
payload: {
|
||||
settledAt: "2026-08-24T09:00:00.000Z",
|
||||
updatedAt: "2026-08-24T09:00:00.000Z",
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
let projected = readModel;
|
||||
const plannedEvents = Array.isArray(events) ? events : [events];
|
||||
for (const [index, event] of plannedEvents.entries()) {
|
||||
projected = yield* projectEvent(projected, { ...event, sequence: index + 2 });
|
||||
}
|
||||
projected = yield* projectEvent(projected, {
|
||||
sequence: 5,
|
||||
eventId: EventId.make("event-import-reverted"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
type: "thread.reverted",
|
||||
occurredAt: "2026-08-24T10:02:00.000Z",
|
||||
commandId: CommandId.make("command-import-reverted"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("command-import-reverted"),
|
||||
metadata: {},
|
||||
payload: { threadId, turnCount: 0 },
|
||||
});
|
||||
expect(projected.threads[0]?.messages.map((message) => message.text)).toEqual([
|
||||
"Fix the bug",
|
||||
"Fixed",
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows a thread with a newly imported user message to be settled", () =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = "2026-08-24T10:00:00.000Z";
|
||||
yield* TestClock.setTime(Date.parse("2026-08-24T10:00:30.000Z"));
|
||||
const threadId = ThreadId.make("import:codex:session-1");
|
||||
const withThread = yield* projectEvent(createEmptyReadModel(createdAt), {
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-import-thread-created"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
type: "thread.created",
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.make("command-import-thread-created"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("command-import-thread-created"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Imported thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
const readModel = yield* projectEvent(withThread, {
|
||||
sequence: 2,
|
||||
eventId: EventId.make("event-import-user-message"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
type: "thread.message-sent",
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.make("command-import-user-message"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("command-import-user-message"),
|
||||
metadata: { historyImport: true },
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make("import:codex:session-1:0"),
|
||||
role: "user",
|
||||
text: "Existing prompt",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.settle",
|
||||
commandId: CommandId.make("command-settle-imported-thread"),
|
||||
threadId,
|
||||
},
|
||||
readModel,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ type: "thread.settled" });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects history import after a client message reaches the thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = "2026-08-24T10:00:00.000Z";
|
||||
const liveMessageAt = "2026-08-24T10:02:00.000Z";
|
||||
const threadId = ThreadId.make("import:codex:client-race");
|
||||
const withThread = yield* projectEvent(createEmptyReadModel(createdAt), {
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-client-race-thread-created"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
type: "thread.created",
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.make("command-client-race-thread-created"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("command-client-race-thread-created"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Imported thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
const readModel = yield* projectEvent(withThread, {
|
||||
sequence: 2,
|
||||
eventId: EventId.make("event-client-race-message"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
type: "thread.message-sent",
|
||||
occurredAt: liveMessageAt,
|
||||
commandId: CommandId.make("command-client-race-message"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("command-client-race-message"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make("client-race-message"),
|
||||
role: "user",
|
||||
text: "Start live work",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: liveMessageAt,
|
||||
updatedAt: liveMessageAt,
|
||||
},
|
||||
});
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.history.import",
|
||||
commandId: CommandId.make("command-client-race-import"),
|
||||
threadId,
|
||||
messages: [
|
||||
{
|
||||
messageId: MessageId.make(`${threadId}:000000`),
|
||||
role: "user",
|
||||
text: "Old work",
|
||||
createdAt,
|
||||
},
|
||||
],
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
expect(error.message).toContain("must be active and empty");
|
||||
expect(readModel.threads[0]?.updatedAt).toBe(liveMessageAt);
|
||||
}),
|
||||
);
|
||||
|
||||
for (const requestKind of ["approval.requested", "user-input.requested"] as const) {
|
||||
it.effect(`rejects history import with an open ${requestKind} activity`, () =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = "2026-08-24T10:00:00.000Z";
|
||||
const threadId = ThreadId.make(`import:codex:${requestKind}`);
|
||||
const withThread = yield* projectEvent(createEmptyReadModel(createdAt), {
|
||||
sequence: 1,
|
||||
eventId: EventId.make(`event-${requestKind}-thread-created`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
type: "thread.created",
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.make(`command-${requestKind}-thread-created`),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make(`command-${requestKind}-thread-created`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Imported thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
const readModel = yield* projectEvent(withThread, {
|
||||
sequence: 2,
|
||||
eventId: EventId.make(`event-${requestKind}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
type: "thread.activity-appended",
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.make(`command-${requestKind}`),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make(`command-${requestKind}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
activity: {
|
||||
id: EventId.make(`activity-${requestKind}`),
|
||||
tone: "approval",
|
||||
kind: requestKind,
|
||||
summary: "Pending request",
|
||||
payload: { requestId: "request-1" },
|
||||
turnId: null,
|
||||
createdAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.history.import",
|
||||
commandId: CommandId.make(`command-import-${requestKind}`),
|
||||
threadId,
|
||||
messages: [
|
||||
{
|
||||
messageId: MessageId.make(`${threadId}:000000`),
|
||||
role: "user",
|
||||
text: "Old work",
|
||||
createdAt,
|
||||
},
|
||||
],
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
expect(error.message).toContain("must be active and empty");
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("rejects a live user message in the imported-session namespace", () =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = "2026-08-24T10:00:00.000Z";
|
||||
const threadId = ThreadId.make("thread-live-message");
|
||||
const readModel = yield* projectEvent(createEmptyReadModel(createdAt), {
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-live-thread-created"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
type: "thread.created",
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.make("command-live-thread-created"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("command-live-thread-created"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Live thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("command-live-import-id"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: MessageId.make("import:forged-live-message"),
|
||||
role: "user",
|
||||
text: "Live work",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
expect(error.message).toContain("reserved imported-session namespace");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects live assistant messages in the imported-session namespace", () =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = "2026-08-24T10:00:00.000Z";
|
||||
const threadId = ThreadId.make("thread-live-assistant-message");
|
||||
const readModel = yield* projectEvent(createEmptyReadModel(createdAt), {
|
||||
sequence: 1,
|
||||
eventId: EventId.make("event-live-assistant-thread-created"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
type: "thread.created",
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.make("command-live-assistant-thread-created"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.make("command-live-assistant-thread-created"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Live thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
});
|
||||
|
||||
for (const commandType of [
|
||||
"thread.message.assistant.delta",
|
||||
"thread.message.assistant.complete",
|
||||
] as const) {
|
||||
const command =
|
||||
commandType === "thread.message.assistant.delta"
|
||||
? {
|
||||
type: commandType,
|
||||
commandId: CommandId.make("command-live-assistant-delta-import-id"),
|
||||
threadId,
|
||||
messageId: MessageId.make("import:forged-live-assistant-message"),
|
||||
delta: "Live work",
|
||||
createdAt,
|
||||
}
|
||||
: {
|
||||
type: commandType,
|
||||
commandId: CommandId.make("command-live-assistant-complete-import-id"),
|
||||
threadId,
|
||||
messageId: MessageId.make("import:forged-live-assistant-message"),
|
||||
createdAt,
|
||||
};
|
||||
const error = yield* Effect.flip(decideOrchestrationCommand({ command, readModel }));
|
||||
|
||||
expect(error._tag).toBe("OrchestrationCommandInvariantError");
|
||||
expect(error.message).toContain("reserved imported-session namespace");
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2,12 +2,14 @@ import {
|
||||
EventId,
|
||||
MessageId,
|
||||
UserInputRequestedPayload,
|
||||
isImportedAgentSessionMessageId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
import { compareDateTimeStrings } from "@t3tools/shared/dateTime";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -98,7 +100,7 @@ function hasQueuedTurnStartForThread(
|
||||
let latestUserMessageAt: string | null = null;
|
||||
let latestUserMessageAtMs = Number.NEGATIVE_INFINITY;
|
||||
for (const message of thread.messages) {
|
||||
if (message.role !== "user") continue;
|
||||
if (message.role !== "user" || isImportedAgentSessionMessageId(message.id)) continue;
|
||||
const messageAtMs = Date.parse(message.createdAt);
|
||||
latestUserMessageAtMs = Math.max(latestUserMessageAtMs, messageAtMs);
|
||||
if (messageAtMs === latestUserMessageAtMs) {
|
||||
@@ -347,6 +349,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
...(command.historyImport === true ? { metadata: { historyImport: true } } : {}),
|
||||
})),
|
||||
type: "thread.created",
|
||||
payload: {
|
||||
@@ -905,6 +908,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.turn.start": {
|
||||
if (isImportedAgentSessionMessageId(command.message.messageId)) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Message id '${command.message.messageId}' uses the reserved imported-session namespace.`,
|
||||
});
|
||||
}
|
||||
const targetThread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
@@ -1272,6 +1281,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.message.assistant.delta": {
|
||||
if (isImportedAgentSessionMessageId(command.messageId)) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Message id '${command.messageId}' uses the reserved imported-session namespace.`,
|
||||
});
|
||||
}
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
@@ -1299,6 +1314,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.message.assistant.complete": {
|
||||
if (isImportedAgentSessionMessageId(command.messageId)) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Message id '${command.messageId}' uses the reserved imported-session namespace.`,
|
||||
});
|
||||
}
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
@@ -1325,6 +1346,79 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.history.import": {
|
||||
const thread = yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
if (
|
||||
thread.deletedAt !== null ||
|
||||
thread.archivedAt !== null ||
|
||||
thread.messages.length > 0 ||
|
||||
thread.latestTurn !== null ||
|
||||
thread.session !== null ||
|
||||
hasOpenBlockingRequest(thread)
|
||||
) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Thread '${command.threadId}' must be active and empty before history can be imported.`,
|
||||
});
|
||||
}
|
||||
const firstMessage = command.messages[0];
|
||||
if (firstMessage === undefined) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: "Thread history imports require at least one message.",
|
||||
});
|
||||
}
|
||||
|
||||
const events: Array<PlannedOrchestrationEvent> = [];
|
||||
for (const message of command.messages) {
|
||||
events.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: message.createdAt,
|
||||
commandId: command.commandId,
|
||||
metadata: { historyImport: true },
|
||||
})),
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: message.messageId,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: message.createdAt,
|
||||
updatedAt: message.createdAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
const settledAt = command.messages.reduce(
|
||||
(latest, message) =>
|
||||
compareDateTimeStrings(message.createdAt, latest) > 0 ? message.createdAt : latest,
|
||||
firstMessage.createdAt,
|
||||
);
|
||||
events.push({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: settledAt,
|
||||
commandId: command.commandId,
|
||||
metadata: { historyImport: true },
|
||||
})),
|
||||
type: "thread.settled",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
settledAt,
|
||||
updatedAt: settledAt,
|
||||
},
|
||||
});
|
||||
return events;
|
||||
}
|
||||
|
||||
case "thread.proposed-plan.upsert": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import type { OrchestrationEvent, OrchestrationReadModel, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
isImportedAgentSessionMessageId,
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationMessage,
|
||||
OrchestrationSession,
|
||||
OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import { compareDateTimeStrings } from "@t3tools/shared/dateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Predicate from "effect/Predicate";
|
||||
@@ -117,7 +119,7 @@ function retainThreadMessagesAfterRevert(
|
||||
): ReadonlyArray<OrchestrationMessage> {
|
||||
const retainedMessageIds = new Set<string>();
|
||||
for (const message of messages) {
|
||||
if (message.role === "system") {
|
||||
if (message.role === "system" || isImportedAgentSessionMessageId(message.id)) {
|
||||
retainedMessageIds.add(message.id);
|
||||
continue;
|
||||
}
|
||||
@@ -127,7 +129,10 @@ function retainThreadMessagesAfterRevert(
|
||||
}
|
||||
|
||||
const retainedUserCount = messages.filter(
|
||||
(message) => message.role === "user" && retainedMessageIds.has(message.id),
|
||||
(message) =>
|
||||
message.role === "user" &&
|
||||
!isImportedAgentSessionMessageId(message.id) &&
|
||||
retainedMessageIds.has(message.id),
|
||||
).length;
|
||||
const missingUserCount = Math.max(0, turnCount - retainedUserCount);
|
||||
if (missingUserCount > 0) {
|
||||
@@ -140,7 +145,8 @@ function retainThreadMessagesAfterRevert(
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
|
||||
compareDateTimeStrings(left.createdAt, right.createdAt) ||
|
||||
left.id.localeCompare(right.id),
|
||||
)
|
||||
.slice(0, missingUserCount);
|
||||
for (const message of fallbackUserMessages) {
|
||||
@@ -149,7 +155,10 @@ function retainThreadMessagesAfterRevert(
|
||||
}
|
||||
|
||||
const retainedAssistantCount = messages.filter(
|
||||
(message) => message.role === "assistant" && retainedMessageIds.has(message.id),
|
||||
(message) =>
|
||||
message.role === "assistant" &&
|
||||
!isImportedAgentSessionMessageId(message.id) &&
|
||||
retainedMessageIds.has(message.id),
|
||||
).length;
|
||||
const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount);
|
||||
if (missingAssistantCount > 0) {
|
||||
@@ -162,7 +171,8 @@ function retainThreadMessagesAfterRevert(
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
|
||||
compareDateTimeStrings(left.createdAt, right.createdAt) ||
|
||||
left.id.localeCompare(right.id),
|
||||
)
|
||||
.slice(0, missingAssistantCount);
|
||||
for (const message of fallbackAssistantMessages) {
|
||||
|
||||
@@ -12,12 +12,24 @@ const layer = it.layer(
|
||||
);
|
||||
|
||||
layer("ProjectionThreadMessageRepository", (it) => {
|
||||
it.effect("finds the latest user-message time within one thread", () =>
|
||||
it.effect("finds the latest live user-message time within one thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadMessageRepository;
|
||||
const threadId = ThreadId.make("thread-latest-user-message");
|
||||
assert.isNull(yield* repository.getLatestUserMessageAt({ threadId }));
|
||||
|
||||
yield* repository.upsert({
|
||||
messageId: MessageId.make("import:codex:latest-user-message:000000"),
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "user",
|
||||
text: "Imported prompt",
|
||||
isStreaming: false,
|
||||
createdAt: "2026-02-28T19:05:06.000Z",
|
||||
updatedAt: "2026-02-28T19:05:06.000Z",
|
||||
});
|
||||
assert.isNull(yield* repository.getLatestUserMessageAt({ threadId }));
|
||||
|
||||
const messages = [
|
||||
{ role: "user", createdAt: "2026-02-28T19:05:02.000Z" },
|
||||
{ role: "user", createdAt: "2026-02-28T19:05:01.000Z" },
|
||||
|
||||
@@ -191,6 +191,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
SELECT MAX(created_at) AS "latestUserMessageAt"
|
||||
FROM projection_thread_messages
|
||||
WHERE thread_id = ${threadId} AND role = 'user'
|
||||
AND message_id NOT GLOB 'import:*'
|
||||
`,
|
||||
});
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
|
||||
import {
|
||||
AgentSessionImportSource,
|
||||
IsoDateTime,
|
||||
ProviderInstanceId,
|
||||
ProviderSessionRuntimeStatus,
|
||||
@@ -58,6 +59,16 @@ export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInp
|
||||
export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
|
||||
export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;
|
||||
|
||||
export const RecordImportedTranscriptInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
source: AgentSessionImportSource,
|
||||
});
|
||||
export type RecordImportedTranscriptInput = typeof RecordImportedTranscriptInput.Type;
|
||||
|
||||
export interface ProviderSessionRuntimeUpsertOptions {
|
||||
readonly onConflict?: "update" | "ignore";
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.
|
||||
*/
|
||||
@@ -67,10 +78,17 @@ export class ProviderSessionRuntimeRepository extends Context.Service<
|
||||
/**
|
||||
* Insert or replace a provider runtime row.
|
||||
*
|
||||
* Upserts by canonical `threadId`, including JSON payload/cursor fields.
|
||||
* Upserts by canonical `threadId`, retaining imported transcript records
|
||||
* from the current database row.
|
||||
*/
|
||||
readonly upsert: (
|
||||
runtime: ProviderSessionRuntime,
|
||||
options?: ProviderSessionRuntimeUpsertOptions,
|
||||
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
|
||||
|
||||
/** Record one source file without replacing the current session state. */
|
||||
readonly recordImportedTranscript: (
|
||||
input: RecordImportedTranscriptInput,
|
||||
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
|
||||
|
||||
/**
|
||||
@@ -129,6 +147,10 @@ const GetRuntimeRequestSchema = Schema.Struct({
|
||||
|
||||
const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
|
||||
|
||||
const RecordImportedTranscriptRequestSchema = RecordImportedTranscriptInput.mapFields(
|
||||
Struct.assign({ source: Schema.fromJsonString(AgentSessionImportSource) }),
|
||||
);
|
||||
|
||||
function toPersistenceSqlOrDecodeError(
|
||||
sqlOperation: string,
|
||||
decodeOperation: string,
|
||||
@@ -147,6 +169,8 @@ function toPersistenceSqlOrDecodeError(
|
||||
export const make = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
// Runtime writes can carry stale payloads. Only recordImportedTranscript may
|
||||
// change source records, so restore that field from the row being updated.
|
||||
const upsertRuntimeRow = SqlSchema.void({
|
||||
Request: ProviderSessionRuntimeDbRowSchema,
|
||||
execute: (runtime) =>
|
||||
@@ -171,7 +195,11 @@ export const make = Effect.gen(function* () {
|
||||
${runtime.status},
|
||||
${runtime.lastSeenAt},
|
||||
${runtime.resumeCursor},
|
||||
${runtime.runtimePayload}
|
||||
CASE
|
||||
WHEN json_type(${runtime.runtimePayload}) = 'object'
|
||||
THEN json_remove(${runtime.runtimePayload}, '$.importedTranscripts')
|
||||
ELSE ${runtime.runtimePayload}
|
||||
END
|
||||
)
|
||||
ON CONFLICT (thread_id)
|
||||
DO UPDATE SET
|
||||
@@ -182,7 +210,107 @@ export const make = Effect.gen(function* () {
|
||||
status = excluded.status,
|
||||
last_seen_at = excluded.last_seen_at,
|
||||
resume_cursor_json = excluded.resume_cursor_json,
|
||||
runtime_payload_json = excluded.runtime_payload_json
|
||||
runtime_payload_json = CASE
|
||||
WHEN json_type(
|
||||
CASE
|
||||
WHEN json_valid(provider_session_runtime.runtime_payload_json)
|
||||
THEN provider_session_runtime.runtime_payload_json
|
||||
ELSE '{}'
|
||||
END,
|
||||
'$.importedTranscripts'
|
||||
) IS NOT NULL
|
||||
THEN json_set(
|
||||
CASE
|
||||
WHEN json_type(excluded.runtime_payload_json) = 'object'
|
||||
THEN excluded.runtime_payload_json
|
||||
ELSE '{}'
|
||||
END,
|
||||
'$.importedTranscripts',
|
||||
json_extract(provider_session_runtime.runtime_payload_json, '$.importedTranscripts')
|
||||
)
|
||||
ELSE excluded.runtime_payload_json
|
||||
END
|
||||
`,
|
||||
});
|
||||
|
||||
const insertRuntimeRow = SqlSchema.void({
|
||||
Request: ProviderSessionRuntimeDbRowSchema,
|
||||
execute: (runtime) =>
|
||||
sql`
|
||||
INSERT INTO provider_session_runtime (
|
||||
thread_id,
|
||||
provider_name,
|
||||
provider_instance_id,
|
||||
adapter_key,
|
||||
runtime_mode,
|
||||
status,
|
||||
last_seen_at,
|
||||
resume_cursor_json,
|
||||
runtime_payload_json
|
||||
)
|
||||
VALUES (
|
||||
${runtime.threadId},
|
||||
${runtime.providerName},
|
||||
${runtime.providerInstanceId},
|
||||
${runtime.adapterKey},
|
||||
${runtime.runtimeMode},
|
||||
${runtime.status},
|
||||
${runtime.lastSeenAt},
|
||||
${runtime.resumeCursor},
|
||||
CASE
|
||||
WHEN json_type(${runtime.runtimePayload}) = 'object'
|
||||
THEN json_remove(${runtime.runtimePayload}, '$.importedTranscripts')
|
||||
ELSE ${runtime.runtimePayload}
|
||||
END
|
||||
)
|
||||
ON CONFLICT (thread_id) DO NOTHING
|
||||
`,
|
||||
});
|
||||
|
||||
const recordImportedTranscriptRow = SqlSchema.void({
|
||||
Request: RecordImportedTranscriptRequestSchema,
|
||||
execute: ({ threadId, source }) =>
|
||||
sql`
|
||||
WITH current_runtime AS (
|
||||
SELECT CASE
|
||||
WHEN json_valid(runtime_payload_json) THEN CASE
|
||||
WHEN json_type(runtime_payload_json) = 'object' THEN runtime_payload_json
|
||||
ELSE '{}'
|
||||
END
|
||||
ELSE '{}'
|
||||
END AS payload
|
||||
FROM provider_session_runtime
|
||||
WHERE thread_id = ${threadId}
|
||||
)
|
||||
UPDATE provider_session_runtime
|
||||
SET runtime_payload_json = (
|
||||
SELECT json_set(
|
||||
payload,
|
||||
'$.importedTranscripts',
|
||||
json((
|
||||
SELECT json_group_array(json(value))
|
||||
FROM (
|
||||
SELECT value
|
||||
FROM json_each(CASE
|
||||
WHEN json_type(payload, '$.importedTranscripts') = 'array'
|
||||
THEN json_extract(payload, '$.importedTranscripts')
|
||||
ELSE '[]'
|
||||
END)
|
||||
WHERE CASE
|
||||
WHEN type = 'object' THEN
|
||||
json_extract(value, '$.providerInstanceId')
|
||||
IS NOT json_extract(${source}, '$.providerInstanceId')
|
||||
OR json_extract(value, '$.filePath') IS NOT json_extract(${source}, '$.filePath')
|
||||
ELSE 0
|
||||
END
|
||||
UNION ALL
|
||||
SELECT ${source} AS value
|
||||
)
|
||||
))
|
||||
)
|
||||
FROM current_runtime
|
||||
)
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -235,8 +363,8 @@ export const make = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime) =>
|
||||
upsertRuntimeRow(runtime).pipe(
|
||||
const upsert: ProviderSessionRuntimeRepository["Service"]["upsert"] = (runtime, options) =>
|
||||
(options?.onConflict === "ignore" ? insertRuntimeRow(runtime) : upsertRuntimeRow(runtime)).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProviderSessionRuntimeRepository.upsert:query",
|
||||
@@ -246,6 +374,18 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const recordImportedTranscript: ProviderSessionRuntimeRepository["Service"]["recordImportedTranscript"] =
|
||||
(input) =>
|
||||
recordImportedTranscriptRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProviderSessionRuntimeRepository.recordImportedTranscript:query",
|
||||
"ProviderSessionRuntimeRepository.recordImportedTranscript:encodeRequest",
|
||||
{ threadId: input.threadId },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getByThreadId: ProviderSessionRuntimeRepository["Service"]["getByThreadId"] = (input) =>
|
||||
getRuntimeRowByThreadId(input).pipe(
|
||||
Effect.mapError(
|
||||
@@ -324,6 +464,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return {
|
||||
upsert,
|
||||
recordImportedTranscript,
|
||||
getByThreadId,
|
||||
list,
|
||||
deleteByThreadId,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,297 @@
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
AgentSessionImportProjectChangedError,
|
||||
AgentSessionImportProjectNotFoundError,
|
||||
AgentSessionSource,
|
||||
AgentSessionScanError,
|
||||
isImportedAgentSessionMessageId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ThreadId,
|
||||
type AgentSessionImportInput,
|
||||
type AgentSessionImportResult,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import * as ProviderSessionDirectory from "../provider/Services/ProviderSessionDirectory.ts";
|
||||
import * as AgentSessionScanner from "./AgentSessionScanner.ts";
|
||||
|
||||
const CLAUDE_SESSION_ID_PATTERN =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
|
||||
class AgentSessionUnresumableSessionError extends Schema.TaggedErrorClass<AgentSessionUnresumableSessionError>()(
|
||||
"AgentSessionUnresumableSessionError",
|
||||
{
|
||||
source: AgentSessionSource,
|
||||
providerSessionId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Session '${this.providerSessionId}' from '${this.source}' cannot be resumed.`;
|
||||
}
|
||||
}
|
||||
|
||||
class AgentSessionThreadProjectConflictError extends Schema.TaggedErrorClass<AgentSessionThreadProjectConflictError>()(
|
||||
"AgentSessionThreadProjectConflictError",
|
||||
{
|
||||
threadId: ThreadId,
|
||||
expectedProjectId: ProjectId,
|
||||
actualProjectId: ProjectId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Imported thread '${this.threadId}' belongs to project '${this.actualProjectId}', not '${this.expectedProjectId}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
class AgentSessionThreadModifiedError extends Schema.TaggedErrorClass<AgentSessionThreadModifiedError>()(
|
||||
"AgentSessionThreadModifiedError",
|
||||
{ threadId: ThreadId },
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Imported thread '${this.threadId}' changed before its history import completed.`;
|
||||
}
|
||||
}
|
||||
|
||||
function hasImportedHistory(thread: OrchestrationThread): boolean {
|
||||
return thread.messages.some((message) => isImportedAgentSessionMessageId(message.id));
|
||||
}
|
||||
|
||||
function hasImportBlockingActivity(
|
||||
thread: OrchestrationThread,
|
||||
importedHistoryPresent: boolean,
|
||||
): boolean {
|
||||
return (
|
||||
thread.archivedAt !== null ||
|
||||
thread.deletedAt !== null ||
|
||||
thread.latestTurn !== null ||
|
||||
thread.session !== null ||
|
||||
thread.messages.some((message) => !isImportedAgentSessionMessageId(message.id)) ||
|
||||
thread.proposedPlans.length > 0 ||
|
||||
thread.activities.length > 0 ||
|
||||
thread.checkpoints.length > 0 ||
|
||||
thread.snoozedUntil != null ||
|
||||
thread.snoozedAt != null ||
|
||||
thread.pinnedAt != null ||
|
||||
thread.pinOrderKey != null ||
|
||||
thread.titleRegeneration != null ||
|
||||
thread.linkedPullRequest != null ||
|
||||
thread.unsettledAt != null ||
|
||||
(importedHistoryPresent
|
||||
? thread.settledOverride !== "settled"
|
||||
: thread.settledOverride !== null || thread.settledAt !== null)
|
||||
);
|
||||
}
|
||||
|
||||
/** Import recent transcript text and persist the cursor needed to resume its provider session. */
|
||||
export const importRecentAgentThreads = Effect.fn("importRecentAgentThreads")(function* (
|
||||
input: AgentSessionImportInput,
|
||||
) {
|
||||
const scanner = yield* AgentSessionScanner.AgentSessionScanner;
|
||||
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
|
||||
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
|
||||
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const project = yield* snapshots.getProjectShellById(input.projectId).pipe(
|
||||
Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-projects", cause })),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(new AgentSessionImportProjectNotFoundError({ projectId: input.projectId })),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const workspaceRoot = project.workspaceRoot;
|
||||
if (
|
||||
input.expectedWorkspaceRoot !== undefined &&
|
||||
normalizeProjectPathForComparison(workspaceRoot) !==
|
||||
normalizeProjectPathForComparison(input.expectedWorkspaceRoot)
|
||||
) {
|
||||
return yield* new AgentSessionImportProjectChangedError({ projectId: input.projectId });
|
||||
}
|
||||
const completedSources = yield* snapshots
|
||||
.getImportedAgentSessionSources(input.projectId)
|
||||
.pipe(
|
||||
Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-projects", cause })),
|
||||
);
|
||||
const threads = scanner.recentThreads(
|
||||
workspaceRoot,
|
||||
completedSources.map((entry) => entry.source),
|
||||
);
|
||||
const importedThreadIds = new Set<ThreadId>();
|
||||
let importedCount = 0;
|
||||
let skippedCount = 0;
|
||||
|
||||
yield* Stream.runForEach(threads, (outcome) =>
|
||||
Effect.gen(function* () {
|
||||
if (outcome._tag === "Skipped") {
|
||||
skippedCount += 1;
|
||||
return;
|
||||
}
|
||||
if (outcome._tag === "AlreadyImported" || outcome._tag === "Duplicate") {
|
||||
const threadId = ThreadId.make(
|
||||
`import:${outcome.source.providerInstanceId}:${outcome.source.providerSessionId}`,
|
||||
);
|
||||
if (outcome._tag === "AlreadyImported") {
|
||||
importedThreadIds.add(threadId);
|
||||
importedCount += 1;
|
||||
} else if (importedThreadIds.has(threadId)) {
|
||||
const recorded = yield* directory
|
||||
.recordImportedTranscript({ threadId, source: outcome.source })
|
||||
.pipe(Effect.result);
|
||||
if (recorded._tag === "Failure") {
|
||||
skippedCount += 1;
|
||||
yield* Effect.logWarning("Could not record an imported transcript copy", {
|
||||
threadId,
|
||||
cause: recorded.failure,
|
||||
});
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
const thread = outcome.thread;
|
||||
const threadId = ThreadId.make(
|
||||
`import:${thread.providerInstanceId}:${thread.providerSessionId}`,
|
||||
);
|
||||
const imported = yield* Effect.gen(function* () {
|
||||
const provider = ProviderDriverKind.make(thread.source);
|
||||
const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;
|
||||
const existingThread = yield* snapshots.getThreadDetailById(threadId);
|
||||
const existingBinding = yield* directory.getBinding(threadId);
|
||||
|
||||
if (
|
||||
thread.source === "claudeAgent" &&
|
||||
!CLAUDE_SESSION_ID_PATTERN.test(thread.providerSessionId)
|
||||
) {
|
||||
return yield* new AgentSessionUnresumableSessionError({
|
||||
source: thread.source,
|
||||
providerSessionId: thread.providerSessionId,
|
||||
});
|
||||
}
|
||||
|
||||
if (Option.isSome(existingThread) && existingThread.value.projectId !== input.projectId) {
|
||||
return yield* new AgentSessionThreadProjectConflictError({
|
||||
threadId,
|
||||
expectedProjectId: input.projectId,
|
||||
actualProjectId: existingThread.value.projectId,
|
||||
});
|
||||
}
|
||||
|
||||
const importedHistoryPresent = Option.isSome(existingThread)
|
||||
? hasImportedHistory(existingThread.value)
|
||||
: false;
|
||||
if (
|
||||
Option.isSome(existingThread) &&
|
||||
importedHistoryPresent &&
|
||||
Option.isSome(existingBinding)
|
||||
) {
|
||||
yield* directory.recordImportedTranscript({ threadId, source: outcome.source });
|
||||
return true;
|
||||
}
|
||||
|
||||
if (
|
||||
Option.isSome(existingThread) &&
|
||||
hasImportBlockingActivity(existingThread.value, importedHistoryPresent)
|
||||
) {
|
||||
return yield* new AgentSessionThreadModifiedError({ threadId });
|
||||
}
|
||||
|
||||
if (
|
||||
Option.isSome(existingBinding) &&
|
||||
(existingBinding.value.provider !== provider ||
|
||||
existingBinding.value.providerInstanceId !== thread.providerInstanceId ||
|
||||
existingBinding.value.status !== "stopped")
|
||||
) {
|
||||
return yield* new AgentSessionThreadModifiedError({ threadId });
|
||||
}
|
||||
|
||||
// Install the cursor before the thread becomes visible. A concurrent
|
||||
// real session can replace it, while insert-ignore keeps this import
|
||||
// from replacing that newer binding.
|
||||
if (Option.isNone(existingBinding)) {
|
||||
yield* directory.upsert(
|
||||
{
|
||||
threadId,
|
||||
provider,
|
||||
providerInstanceId: thread.providerInstanceId,
|
||||
status: "stopped",
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
resumeCursor:
|
||||
thread.source === "codex"
|
||||
? { threadId: thread.providerSessionId }
|
||||
: { threadId, resume: thread.providerSessionId },
|
||||
runtimePayload: { cwd: workspaceRoot },
|
||||
},
|
||||
{ onConflict: "ignore" },
|
||||
);
|
||||
}
|
||||
|
||||
if (Option.isNone(existingThread)) {
|
||||
yield* engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make(yield* crypto.randomUUIDv4),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: { instanceId: thread.providerInstanceId, model },
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: thread.createdAt,
|
||||
historyImport: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (!importedHistoryPresent) {
|
||||
yield* engine.dispatch({
|
||||
type: "thread.history.import",
|
||||
commandId: CommandId.make(yield* crypto.randomUUIDv4),
|
||||
threadId,
|
||||
messages: thread.messages.map((message, index) => ({
|
||||
messageId: MessageId.make(`${threadId}:${String(index).padStart(6, "0")}`),
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
createdAt: message.createdAt,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
yield* directory.recordImportedTranscript({ threadId, source: outcome.source });
|
||||
|
||||
return true;
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("Could not import an agent session", {
|
||||
provider: thread.source,
|
||||
sessionId: thread.providerSessionId,
|
||||
cause,
|
||||
}).pipe(Effect.as(false)),
|
||||
),
|
||||
);
|
||||
|
||||
if (imported) {
|
||||
importedThreadIds.add(threadId);
|
||||
importedCount += 1;
|
||||
} else {
|
||||
skippedCount += 1;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
return { importedCount, skippedCount } satisfies AgentSessionImportResult;
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -41,6 +41,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
|
||||
getProjectShellById: (projectId) =>
|
||||
Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getImportedAgentSessionSources: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadRuntimeContext: () => Effect.die("unused"),
|
||||
|
||||
@@ -26,6 +26,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
|
||||
@@ -119,7 +120,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
driverKind: DRIVER_KIND,
|
||||
instanceId,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings;
|
||||
const effectiveConfig = {
|
||||
...config,
|
||||
enabled,
|
||||
binaryPath: expandHomePath(config.binaryPath),
|
||||
} satisfies ClaudeSettings;
|
||||
const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
|
||||
resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
|
||||
@@ -33,6 +33,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderDriverError } from "../Errors.ts";
|
||||
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
|
||||
@@ -157,6 +158,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
const effectiveConfig = {
|
||||
...config,
|
||||
enabled,
|
||||
binaryPath: expandHomePath(config.binaryPath),
|
||||
homePath: homeLayout.effectiveHomePath ?? "",
|
||||
} satisfies CodexSettings;
|
||||
const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
|
||||
|
||||
@@ -222,6 +222,7 @@ function makeScopedRuntimeFactory(options?: { readonly failConstruction?: boolea
|
||||
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||
upsert: () => Effect.void,
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
|
||||
@@ -516,6 +516,7 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||
upsert: () => Effect.void,
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
|
||||
@@ -24,7 +24,6 @@
|
||||
*/
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Path from "effect/Path";
|
||||
import {
|
||||
type ClaudeSettings,
|
||||
type CodexSettings,
|
||||
@@ -35,9 +34,12 @@ import {
|
||||
type ProviderInstanceConfigMap,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { isHostWindows } from "@t3tools/shared/hostProcess";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
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 Stream from "effect/Stream";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
@@ -45,6 +47,7 @@ import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import type { BuiltInDriversEnv } from "../builtInDrivers.ts";
|
||||
import { AntigravityInstallation } from "../AntigravityInstallation.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { expandHomePath } from "../../pathExpansion.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ClaudeDriver } from "../Drivers/ClaudeDriver.ts";
|
||||
import { CodexDriver } from "../Drivers/CodexDriver.ts";
|
||||
@@ -139,6 +142,80 @@ const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSetti
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const makeTildeProviderFixtures = Effect.fn(
|
||||
"ProviderInstanceRegistryLive.test.makeTildeProviderFixtures",
|
||||
)(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const homePath = expandHomePath("~");
|
||||
const fixtureDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
directory: homePath,
|
||||
prefix: ".t3-provider-path-test-",
|
||||
});
|
||||
const codexPath = path.join(fixtureDir, "codex");
|
||||
const claudePath = path.join(fixtureDir, "claude");
|
||||
const claudeHomePath = path.join(fixtureDir, "claude-home");
|
||||
const codexScriptPath = path.join(fixtureDir, "codex-script.json");
|
||||
const codexFixtureDir = path.join(import.meta.dirname, "../testFixtures");
|
||||
|
||||
yield* fileSystem.copyFile(path.join(codexFixtureDir, "codexCollabMockPeer.sh"), codexPath);
|
||||
yield* fileSystem.copyFile(
|
||||
path.join(codexFixtureDir, "codexCollabMockPeer.mjs"),
|
||||
path.join(fixtureDir, "codexCollabMockPeer.mjs"),
|
||||
);
|
||||
yield* fileSystem.copyFile(
|
||||
path.join(codexFixtureDir, "codexMultiAgentWire.json"),
|
||||
path.join(fixtureDir, "codexMultiAgentWire.json"),
|
||||
);
|
||||
yield* fileSystem.writeFileString(
|
||||
codexScriptPath,
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off - fixed script document read by the external Codex mock peer.
|
||||
JSON.stringify({ rootThreadId: "probe-thread", notifications: [] }),
|
||||
);
|
||||
yield* fileSystem.chmod(codexPath, 0o755);
|
||||
|
||||
yield* fileSystem.writeFileString(
|
||||
claudePath,
|
||||
[
|
||||
"#!/usr/bin/env node",
|
||||
'import * as NodeReadline from "node:readline";',
|
||||
'if (process.argv.includes("--version")) {',
|
||||
' process.stdout.write("claude 2.1.219\\n");',
|
||||
" process.exit(0);",
|
||||
"}",
|
||||
"const lines = NodeReadline.createInterface({ input: process.stdin });",
|
||||
'lines.on("line", (line) => {',
|
||||
" const message = JSON.parse(line);",
|
||||
' if (message.type !== "control_request" || message.request?.subtype !== "initialize") return;',
|
||||
" process.stdout.write(JSON.stringify({",
|
||||
' type: "control_response",',
|
||||
" response: {",
|
||||
' subtype: "success",',
|
||||
" request_id: message.request_id,",
|
||||
" response: {",
|
||||
" commands: [], agents: [], models: [],",
|
||||
' output_style: "default", available_output_styles: ["default"],',
|
||||
' account: { email: "[email protected]", subscriptionType: "pro", tokenSource: "oauth" },',
|
||||
" },",
|
||||
" },",
|
||||
' }) + "\\n");',
|
||||
"});",
|
||||
"setInterval(() => {}, 1_000);",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fileSystem.chmod(claudePath, 0o755);
|
||||
yield* fileSystem.makeDirectory(claudeHomePath);
|
||||
|
||||
const asTildePath = (filePath: string) => `~/${path.relative(homePath, filePath)}`;
|
||||
return {
|
||||
codexBinaryPath: asTildePath(codexPath),
|
||||
claudeBinaryPath: asTildePath(claudePath),
|
||||
claudeHomePath,
|
||||
codexScriptPath,
|
||||
};
|
||||
});
|
||||
|
||||
describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
// `ServerConfig.layerTest` needs `FileSystem` to materialize its scratch
|
||||
// directory. `Layer.merge` just unions requirements, so we have to push
|
||||
@@ -261,6 +338,60 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.live("runs Codex and Claude readiness probes from configured tilde paths", () =>
|
||||
Effect.gen(function* () {
|
||||
if (yield* isHostWindows) return;
|
||||
|
||||
const fixtures = yield* makeTildeProviderFixtures();
|
||||
|
||||
const codexId = ProviderInstanceId.make("codex_tilde");
|
||||
const claudeId = ProviderInstanceId.make("claude_tilde");
|
||||
const configMap: ProviderInstanceConfigMap = {
|
||||
[codexId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: true,
|
||||
environment: [
|
||||
{
|
||||
name: "T3_CODEX_COLLAB_SCRIPT",
|
||||
value: fixtures.codexScriptPath,
|
||||
sensitive: false,
|
||||
},
|
||||
],
|
||||
config: makeCodexConfig({ enabled: true, binaryPath: fixtures.codexBinaryPath }),
|
||||
},
|
||||
[claudeId]: {
|
||||
driver: ProviderDriverKind.make("claudeAgent"),
|
||||
enabled: true,
|
||||
config: makeClaudeConfig({
|
||||
enabled: true,
|
||||
binaryPath: fixtures.claudeBinaryPath,
|
||||
homePath: fixtures.claudeHomePath,
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
const { registry } = yield* makeProviderInstanceRegistry({
|
||||
drivers: [CodexDriver, ClaudeDriver],
|
||||
configMap,
|
||||
});
|
||||
const codex = yield* registry.getInstance(codexId);
|
||||
const claude = yield* registry.getInstance(claudeId);
|
||||
expect(codex).toBeDefined();
|
||||
expect(claude).toBeDefined();
|
||||
|
||||
const [codexSnapshot, claudeSnapshot] = yield* Effect.all(
|
||||
[codex!.snapshot.refresh, claude!.snapshot.refresh],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
expect(codexSnapshot).toMatchObject({ status: "ready", installed: true, version: "0.0.0" });
|
||||
expect(claudeSnapshot).toMatchObject({
|
||||
status: "ready",
|
||||
installed: true,
|
||||
version: "2.1.219",
|
||||
});
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.live(
|
||||
"shadows instances whose driver is not registered in this build without failing boot",
|
||||
() =>
|
||||
|
||||
@@ -4271,6 +4271,7 @@ const getBinding = vi.fn((threadId: ThreadId) =>
|
||||
const boundedListing = makeProviderServiceLayer({
|
||||
directory: {
|
||||
upsert: () => Effect.void,
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("ProviderService.listSessions does not use getProvider"),
|
||||
getBinding,
|
||||
listThreadIds,
|
||||
|
||||
@@ -4,9 +4,13 @@ import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ProviderDriverKind, ThreadId } from "@t3tools/contracts";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { assertSome } from "@effect/vitest/utils";
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type AgentSessionImportSource,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -20,9 +24,22 @@ import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntim
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
|
||||
const importedSource = {
|
||||
provider: "codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
providerSessionId: "provider-session",
|
||||
filePath: "/tmp/provider-session.jsonl",
|
||||
size: 100,
|
||||
mtimeMs: 1_000,
|
||||
device: 1,
|
||||
inode: 123,
|
||||
birthtimeMs: 500,
|
||||
} satisfies AgentSessionImportSource;
|
||||
|
||||
function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlClient, E, R>) {
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe(Layer.provide(persistenceLayer));
|
||||
return Layer.mergeAll(
|
||||
persistenceLayer,
|
||||
runtimeRepositoryLayer,
|
||||
ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)),
|
||||
NodeServices.layer,
|
||||
@@ -30,7 +47,7 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
|
||||
}
|
||||
|
||||
it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryLive", (it) => {
|
||||
it("upserts and reads thread bindings", () =>
|
||||
it.effect("upserts and reads thread bindings", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
@@ -39,13 +56,14 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
threadId: initialThreadId,
|
||||
});
|
||||
|
||||
const provider = yield* directory.getProvider(initialThreadId);
|
||||
assert.equal(provider, "codex");
|
||||
const resolvedBinding = yield* directory.getBinding(initialThreadId);
|
||||
assertSome(resolvedBinding, {
|
||||
expect(Option.getOrThrow(resolvedBinding)).toMatchObject({
|
||||
threadId: initialThreadId,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
});
|
||||
@@ -57,6 +75,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
threadId: nextThreadId,
|
||||
});
|
||||
const updatedBinding = yield* directory.getBinding(nextThreadId);
|
||||
@@ -74,10 +93,11 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
}
|
||||
|
||||
const threadIds = yield* directory.listThreadIds();
|
||||
assert.deepEqual(threadIds, [nextThreadId]);
|
||||
}));
|
||||
expect(threadIds).toEqual(expect.arrayContaining([initialThreadId, nextThreadId]));
|
||||
}),
|
||||
);
|
||||
|
||||
it("persists runtime fields and merges payload updates", () =>
|
||||
it.effect("persists runtime fields and merges payload updates", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
@@ -86,6 +106,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
threadId,
|
||||
status: "starting",
|
||||
resumeCursor: {
|
||||
@@ -99,6 +120,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
threadId,
|
||||
status: "running",
|
||||
runtimePayload: {
|
||||
@@ -120,9 +142,158 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
activeTurnId: "turn-1",
|
||||
});
|
||||
}
|
||||
}));
|
||||
}),
|
||||
);
|
||||
|
||||
it("lists persisted bindings with metadata in oldest-first order", () =>
|
||||
it.effect("keeps the existing binding when an insert conflicts", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const threadId = ThreadId.make("thread-insert-conflict");
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
threadId,
|
||||
status: "running",
|
||||
resumeCursor: { threadId: "active-provider-thread" },
|
||||
});
|
||||
|
||||
yield* directory.upsert(
|
||||
{
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
threadId,
|
||||
status: "stopped",
|
||||
resumeCursor: { threadId: "stale-provider-thread" },
|
||||
},
|
||||
{ onConflict: "ignore" },
|
||||
);
|
||||
|
||||
const binding = yield* directory.getBinding(threadId);
|
||||
expect(Option.getOrThrow(binding)).toMatchObject({
|
||||
threadId,
|
||||
status: "running",
|
||||
resumeCursor: { threadId: "active-provider-thread" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records source files without replacing the current provider session", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
const source = { ...importedSource, providerSessionId: "record-source" };
|
||||
const threadId = ThreadId.make(
|
||||
`import:${source.providerInstanceId}:${source.providerSessionId}`,
|
||||
);
|
||||
const runtimePayload = { cwd: "/tmp/project", activeTurnId: "active-turn" };
|
||||
yield* directory.upsert({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
providerInstanceId: ProviderInstanceId.make("claude-current"),
|
||||
status: "running",
|
||||
resumeCursor: { resume: "current-native-session" },
|
||||
runtimePayload,
|
||||
});
|
||||
const before = Option.getOrThrow(yield* repository.getByThreadId({ threadId }));
|
||||
|
||||
yield* directory.recordImportedTranscript({ threadId, source });
|
||||
const replacement = { ...source, size: 200, mtimeMs: 2_000 };
|
||||
yield* directory.recordImportedTranscript({ threadId, source: replacement });
|
||||
const secondFile = { ...source, filePath: "/tmp/provider-session-copy.jsonl" };
|
||||
yield* directory.recordImportedTranscript({ threadId, source: secondFile });
|
||||
|
||||
expect(Option.getOrThrow(yield* repository.getByThreadId({ threadId }))).toEqual({
|
||||
...before,
|
||||
runtimePayload: { ...runtimePayload, importedTranscripts: [replacement, secondFile] },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not create a binding when recording an imported transcript", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const threadId = ThreadId.make("import:codex:missing-source-binding");
|
||||
|
||||
yield* directory.recordImportedTranscript({ threadId, source: importedSource });
|
||||
|
||||
expect(Option.isNone(yield* directory.getBinding(threadId))).toBe(true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps newly recorded sources when a runtime write uses a stale payload", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
const firstSource = { ...importedSource, providerSessionId: "stale-source" };
|
||||
const threadId = ThreadId.make(
|
||||
`import:${firstSource.providerInstanceId}:${firstSource.providerSessionId}`,
|
||||
);
|
||||
yield* directory.upsert({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
status: "stopped",
|
||||
resumeCursor: { threadId: "original-native-session" },
|
||||
runtimePayload: { cwd: "/tmp/stale-source-project" },
|
||||
});
|
||||
yield* directory.recordImportedTranscript({ threadId, source: firstSource });
|
||||
const stale = Option.getOrThrow(yield* repository.getByThreadId({ threadId }));
|
||||
const secondSource = { ...firstSource, filePath: "/tmp/stale-source-copy.jsonl" };
|
||||
yield* directory.recordImportedTranscript({ threadId, source: secondSource });
|
||||
|
||||
yield* repository.upsert({
|
||||
...stale,
|
||||
status: "running",
|
||||
resumeCursor: { threadId: "new-native-session" },
|
||||
lastSeenAt: "2026-08-24T10:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(Option.getOrThrow(yield* repository.getByThreadId({ threadId }))).toEqual({
|
||||
...stale,
|
||||
status: "running",
|
||||
resumeCursor: { threadId: "new-native-session" },
|
||||
lastSeenAt: "2026-08-24T10:00:00.000Z",
|
||||
runtimePayload: {
|
||||
cwd: "/tmp/stale-source-project",
|
||||
importedTranscripts: [firstSource, secondSource],
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reserves imported source records for the atomic recording method", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
for (const onConflict of ["update", "ignore"] as const) {
|
||||
const source = { ...importedSource, providerSessionId: `reserved-source-${onConflict}` };
|
||||
const threadId = ThreadId.make(
|
||||
`import:${source.providerInstanceId}:${source.providerSessionId}`,
|
||||
);
|
||||
const binding = {
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
};
|
||||
yield* directory.upsert(
|
||||
{ ...binding, runtimePayload: { cwd: "/tmp/project", importedTranscripts: [source] } },
|
||||
{ onConflict },
|
||||
);
|
||||
expect(Option.getOrThrow(yield* directory.getBinding(threadId)).runtimePayload).toEqual({
|
||||
cwd: "/tmp/project",
|
||||
});
|
||||
|
||||
yield* directory.recordImportedTranscript({ threadId, source });
|
||||
yield* directory.upsert({ ...binding, runtimePayload: null });
|
||||
|
||||
expect(Option.getOrThrow(yield* directory.getBinding(threadId)).runtimePayload).toEqual({
|
||||
importedTranscripts: [source],
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lists persisted bindings with metadata in oldest-first order", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
@@ -162,12 +333,15 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
},
|
||||
});
|
||||
|
||||
const bindings = yield* directory.listBindings();
|
||||
const bindings = (yield* directory.listBindings()).filter(
|
||||
(binding) => binding.threadId === olderThreadId || binding.threadId === newerThreadId,
|
||||
);
|
||||
|
||||
assert.deepEqual(bindings, [
|
||||
{
|
||||
threadId: olderThreadId,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
status: "starting",
|
||||
@@ -182,6 +356,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
{
|
||||
threadId: newerThreadId,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
adapterKey: "codex",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
@@ -194,40 +369,45 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
},
|
||||
},
|
||||
]);
|
||||
}));
|
||||
}),
|
||||
);
|
||||
|
||||
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
const threadId = ThreadId.make("thread-provider-change");
|
||||
it.effect(
|
||||
"resets adapterKey to the new provider when provider changes without an explicit adapter key",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
const threadId = ThreadId.make("thread-provider-change");
|
||||
|
||||
yield* runtimeRepository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-01-01T00:00:00.000Z",
|
||||
resumeCursor: null,
|
||||
runtimePayload: null,
|
||||
});
|
||||
yield* runtimeRepository.upsert({
|
||||
threadId,
|
||||
providerName: "claudeAgent",
|
||||
providerInstanceId: null,
|
||||
adapterKey: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: "2026-01-01T00:00:00.000Z",
|
||||
resumeCursor: null,
|
||||
runtimePayload: null,
|
||||
});
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId,
|
||||
});
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
threadId,
|
||||
});
|
||||
|
||||
const runtime = yield* runtimeRepository.getByThreadId({ threadId });
|
||||
assert.equal(Option.isSome(runtime), true);
|
||||
if (Option.isSome(runtime)) {
|
||||
assert.equal(runtime.value.providerName, "codex");
|
||||
assert.equal(runtime.value.adapterKey, "codex");
|
||||
}
|
||||
}));
|
||||
const runtime = yield* runtimeRepository.getByThreadId({ threadId });
|
||||
assert.equal(Option.isSome(runtime), true);
|
||||
if (Option.isSome(runtime)) {
|
||||
assert.equal(runtime.value.providerName, "codex");
|
||||
assert.equal(runtime.value.adapterKey, "codex");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it("rehydrates persisted mappings across layer restart", () =>
|
||||
it.effect("rehydrates persisted mappings across layer restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-directory-"));
|
||||
const dbPath = NodePath.join(tempDir, "orchestration.sqlite");
|
||||
@@ -239,6 +419,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
yield* directory.upsert({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
threadId,
|
||||
});
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
@@ -250,7 +431,7 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
assert.equal(provider, "codex");
|
||||
|
||||
const resolvedBinding = yield* directory.getBinding(threadId);
|
||||
assertSome(resolvedBinding, {
|
||||
expect(Option.getOrThrow(resolvedBinding)).toMatchObject({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
});
|
||||
@@ -267,5 +448,6 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
}).pipe(Effect.provide(directoryLayer));
|
||||
|
||||
NodeFS.rmSync(tempDir, { recursive: true, force: true });
|
||||
}));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -100,7 +100,7 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const upsert: ProviderSessionDirectoryShape["upsert"] = Effect.fn(function* (binding) {
|
||||
const upsert: ProviderSessionDirectoryShape["upsert"] = Effect.fn(function* (binding, options) {
|
||||
const existing = yield* repository
|
||||
.getByThreadId({ threadId: binding.threadId })
|
||||
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:getByThreadId")));
|
||||
@@ -126,25 +126,30 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
yield* repository
|
||||
.upsert({
|
||||
threadId: resolvedThreadId,
|
||||
providerName: binding.provider,
|
||||
providerInstanceId,
|
||||
adapterKey:
|
||||
binding.adapterKey ??
|
||||
(providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),
|
||||
runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
|
||||
status: binding.status ?? existingRuntime?.status ?? "running",
|
||||
lastSeenAt: now,
|
||||
resumeCursor:
|
||||
binding.resumeCursor !== undefined
|
||||
? binding.resumeCursor
|
||||
: (existingRuntime?.resumeCursor ?? null),
|
||||
runtimePayload: mergeRuntimePayload(
|
||||
existingRuntime?.runtimePayload ?? null,
|
||||
binding.runtimePayload,
|
||||
),
|
||||
})
|
||||
.upsert(
|
||||
{
|
||||
threadId: resolvedThreadId,
|
||||
providerName: binding.provider,
|
||||
providerInstanceId,
|
||||
adapterKey:
|
||||
binding.adapterKey ??
|
||||
(providerChanged
|
||||
? binding.provider
|
||||
: (existingRuntime?.adapterKey ?? binding.provider)),
|
||||
runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
|
||||
status: binding.status ?? existingRuntime?.status ?? "running",
|
||||
lastSeenAt: now,
|
||||
resumeCursor:
|
||||
binding.resumeCursor !== undefined
|
||||
? binding.resumeCursor
|
||||
: (existingRuntime?.resumeCursor ?? null),
|
||||
runtimePayload: mergeRuntimePayload(
|
||||
existingRuntime?.runtimePayload ?? null,
|
||||
binding.runtimePayload,
|
||||
),
|
||||
},
|
||||
options,
|
||||
)
|
||||
.pipe(Effect.mapError(toPersistenceError("ProviderSessionDirectory.upsert:upsert")));
|
||||
});
|
||||
|
||||
@@ -164,6 +169,15 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const recordImportedTranscript: ProviderSessionDirectoryShape["recordImportedTranscript"] = (
|
||||
input,
|
||||
) =>
|
||||
repository
|
||||
.recordImportedTranscript(input)
|
||||
.pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.recordImportedTranscript")),
|
||||
);
|
||||
|
||||
const listThreadIds: ProviderSessionDirectoryShape["listThreadIds"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")),
|
||||
@@ -184,6 +198,7 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
|
||||
return {
|
||||
upsert,
|
||||
recordImportedTranscript,
|
||||
getProvider,
|
||||
getBinding,
|
||||
listThreadIds,
|
||||
|
||||
@@ -217,6 +217,7 @@ describe("ProviderSessionReaper", () => {
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
|
||||
getImportedAgentSessionSources: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.die("unused"),
|
||||
getFullThreadDiffContext: () => Effect.die("unused"),
|
||||
getThreadRuntimeContext: () => Effect.die("unused"),
|
||||
|
||||
@@ -1,8 +1,55 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import { mergeProviderInstanceEnvironment } from "./ProviderInstanceEnvironment.ts";
|
||||
|
||||
describe("mergeProviderInstanceEnvironment", () => {
|
||||
it.effect.each([
|
||||
{ value: "~/.account", tail: ".account" },
|
||||
{ value: "~\\.account\\work", tail: ".account\\work" },
|
||||
])("expands configured provider homes set to $value", ({ value, tail }) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const baseEnv = {
|
||||
CODEX_HOME: "~/.inherited-codex",
|
||||
CLAUDE_CONFIG_DIR: "~/.inherited-claude",
|
||||
};
|
||||
const environment = mergeProviderInstanceEnvironment(
|
||||
[
|
||||
{ name: "CODEX_HOME", value, sensitive: false },
|
||||
{ name: "CLAUDE_CONFIG_DIR", value, sensitive: false },
|
||||
{ name: "CUSTOM_VALUE", value, sensitive: false },
|
||||
],
|
||||
baseEnv,
|
||||
);
|
||||
|
||||
expect(environment).toEqual({
|
||||
CODEX_HOME: path.join(NodeOS.homedir(), tail),
|
||||
CLAUDE_CONFIG_DIR: path.join(NodeOS.homedir(), tail),
|
||||
CUSTOM_VALUE: value,
|
||||
});
|
||||
expect(baseEnv).toEqual({
|
||||
CODEX_HOME: "~/.inherited-codex",
|
||||
CLAUDE_CONFIG_DIR: "~/.inherited-claude",
|
||||
});
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it("leaves inherited provider homes unchanged", () => {
|
||||
const baseEnv = { CODEX_HOME: "~/.codex", CLAUDE_CONFIG_DIR: "~\\.claude" };
|
||||
|
||||
expect(
|
||||
mergeProviderInstanceEnvironment(
|
||||
[{ name: "CUSTOM_VALUE", value: "~/.custom", sensitive: false }],
|
||||
baseEnv,
|
||||
),
|
||||
).toEqual({ ...baseEnv, CUSTOM_VALUE: "~/.custom" });
|
||||
});
|
||||
|
||||
it("overrides inherited environment values and preserves empty strings", () => {
|
||||
expect(
|
||||
mergeProviderInstanceEnvironment(
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { ProviderInstanceEnvironment } from "@t3tools/contracts";
|
||||
|
||||
import { expandHomePath } from "../pathExpansion.ts";
|
||||
|
||||
export function mergeProviderInstanceEnvironment(
|
||||
environment: ProviderInstanceEnvironment | undefined,
|
||||
baseEnv: NodeJS.ProcessEnv = process.env,
|
||||
@@ -10,7 +12,11 @@ export function mergeProviderInstanceEnvironment(
|
||||
|
||||
const next: NodeJS.ProcessEnv = { ...baseEnv };
|
||||
for (const variable of environment) {
|
||||
next[variable.name] = variable.value;
|
||||
// Child processes do not apply shell expansion to environment values.
|
||||
next[variable.name] =
|
||||
variable.name === "CODEX_HOME" || variable.name === "CLAUDE_CONFIG_DIR"
|
||||
? expandHomePath(variable.value)
|
||||
: variable.value;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
AgentSessionImportSource,
|
||||
ProviderInstanceId,
|
||||
ProviderDriverKind,
|
||||
ProviderSessionRuntimeStatus,
|
||||
@@ -40,11 +41,22 @@ export type ProviderSessionDirectoryWriteError =
|
||||
| ProviderValidationError
|
||||
| ProviderSessionDirectoryPersistenceError;
|
||||
|
||||
export interface ProviderSessionDirectoryUpsertOptions {
|
||||
readonly onConflict?: "update" | "ignore";
|
||||
}
|
||||
|
||||
export interface ProviderSessionDirectoryShape {
|
||||
readonly upsert: (
|
||||
binding: ProviderRuntimeBinding,
|
||||
options?: ProviderSessionDirectoryUpsertOptions,
|
||||
) => Effect.Effect<void, ProviderSessionDirectoryWriteError>;
|
||||
|
||||
/** Record an imported file without changing the current provider session. */
|
||||
readonly recordImportedTranscript: (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly source: AgentSessionImportSource;
|
||||
}) => Effect.Effect<void, ProviderSessionDirectoryPersistenceError>;
|
||||
|
||||
readonly getProvider: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryReadError>;
|
||||
|
||||
@@ -57,6 +57,14 @@ rl.on("line", (line) => {
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (method === "account/read") {
|
||||
write({ id, result: { account: { type: "apiKey" }, requiresOpenaiAuth: false } });
|
||||
return;
|
||||
}
|
||||
if (method === "skills/list" || method === "model/list") {
|
||||
write({ id, result: { data: [] } });
|
||||
return;
|
||||
}
|
||||
if (method === "thread/start") {
|
||||
write({ id, result: fixture.responses.threadStart });
|
||||
return;
|
||||
|
||||
@@ -138,7 +138,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
expect(AgentAwarenessRelay.eventThreadId(event)).toBe(threadId);
|
||||
});
|
||||
|
||||
it("does not publish start intents, streaming content, or non-awareness activity events", () => {
|
||||
it("does not publish imported, start-intent, streaming, or non-awareness events", () => {
|
||||
const now = "2026-05-25T00:00:00.000Z";
|
||||
const base = {
|
||||
sequence: 1,
|
||||
@@ -147,6 +147,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1" as ThreadId,
|
||||
occurredAt: now,
|
||||
metadata: {},
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -202,6 +203,36 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
},
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(false);
|
||||
expect(
|
||||
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
|
||||
...base,
|
||||
type: "thread.created",
|
||||
metadata: { historyImport: true },
|
||||
payload: { threadId: "thread-1" as ThreadId },
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(false);
|
||||
expect(
|
||||
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
|
||||
...base,
|
||||
type: "thread.settled",
|
||||
metadata: { historyImport: true },
|
||||
payload: { threadId: "thread-1" as ThreadId },
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(false);
|
||||
expect(
|
||||
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
|
||||
...base,
|
||||
type: "thread.created",
|
||||
payload: { threadId: "thread-1" as ThreadId },
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(true);
|
||||
expect(
|
||||
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
|
||||
...base,
|
||||
type: "thread.settled",
|
||||
payload: { threadId: "thread-1" as ThreadId },
|
||||
} as unknown as OrchestrationEvent),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("deduplicates awareness state updates whose only change is their event timestamp", () => {
|
||||
@@ -400,17 +431,32 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps the orchestration listener armed until relay config is installed", () =>
|
||||
it.effect("keeps the listener armed and skips imported thread work", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const events = yield* Queue.unbounded<OrchestrationEvent>();
|
||||
const threadShellRequested = yield* Deferred.make<void>();
|
||||
const releaseThreadShell = yield* Deferred.make<void>();
|
||||
const threadShellRequests: Array<ThreadId> = [];
|
||||
let fetchCallCount = 0;
|
||||
const secrets = makeMemorySecretStore();
|
||||
const now = "2026-05-25T00:00:00.000Z";
|
||||
const projectId = "project-1" as ProjectId;
|
||||
const threadId = "thread-1" as ThreadId;
|
||||
const importedThreadId = "import:codex:session-1" as ThreadId;
|
||||
const environmentId = "env-1" as EnvironmentId;
|
||||
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (() => {
|
||||
fetchCallCount += 1;
|
||||
return Promise.resolve(Response.json({ ok: true, deliveries: [] }));
|
||||
}) as unknown as typeof fetch;
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
}),
|
||||
);
|
||||
|
||||
const project = {
|
||||
id: projectId,
|
||||
title: "T3 Code",
|
||||
@@ -473,15 +519,18 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: 1,
|
||||
projects: [project],
|
||||
threads: [thread],
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationShellSnapshot),
|
||||
getThreadShellById: () =>
|
||||
Deferred.succeed(threadShellRequested, undefined).pipe(
|
||||
Effect.ignore,
|
||||
Effect.as(Option.some(thread)),
|
||||
),
|
||||
getThreadShellById: (requestedThreadId: ThreadId) =>
|
||||
Effect.gen(function* () {
|
||||
threadShellRequests.push(requestedThreadId);
|
||||
if (requestedThreadId !== threadId) return Option.none();
|
||||
yield* Deferred.succeed(threadShellRequested, undefined);
|
||||
yield* Deferred.await(releaseThreadShell);
|
||||
return Option.some(thread);
|
||||
}),
|
||||
getProjectShellById: () => Effect.succeed(Option.some(project)),
|
||||
} as unknown as ProjectionSnapshotQueryShape;
|
||||
|
||||
@@ -511,17 +560,40 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
yield* Effect.gen(function* () {
|
||||
const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
|
||||
yield* relay.start();
|
||||
yield* secrets.setString(RELAY_URL_SECRET, "http://127.0.0.1:1");
|
||||
yield* secrets.setString(RELAY_URL_SECRET, "https://relay.example.test");
|
||||
yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");
|
||||
yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");
|
||||
yield* Queue.offer(events, {
|
||||
type: "thread.activity-appended",
|
||||
type: "thread.created",
|
||||
sequence: 1,
|
||||
eventId: "evt-import-created",
|
||||
commandId: CommandId.make("cmd-import-created"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: importedThreadId,
|
||||
metadata: { historyImport: true },
|
||||
payload: { threadId: importedThreadId },
|
||||
occurredAt: now,
|
||||
} as unknown as OrchestrationEvent);
|
||||
yield* Queue.offer(events, {
|
||||
type: "thread.settled",
|
||||
sequence: 2,
|
||||
eventId: "evt-import-settled",
|
||||
commandId: CommandId.make("cmd-import-settled"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: importedThreadId,
|
||||
metadata: { historyImport: true },
|
||||
payload: { threadId: importedThreadId },
|
||||
occurredAt: now,
|
||||
} as unknown as OrchestrationEvent);
|
||||
yield* Queue.offer(events, {
|
||||
type: "thread.activity-appended",
|
||||
sequence: 3,
|
||||
eventId: "evt-1",
|
||||
commandId: CommandId.make("cmd-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
actor: { kind: "server" },
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
activity: {
|
||||
@@ -532,6 +604,9 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
} as unknown as OrchestrationEvent);
|
||||
|
||||
yield* Deferred.await(threadShellRequested).pipe(Effect.timeout("2 seconds"));
|
||||
expect(threadShellRequests).toEqual([threadId]);
|
||||
expect(fetchCallCount).toBe(0);
|
||||
yield* Deferred.succeed(releaseThreadShell, undefined);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AgentAwarenessRelay.layer.pipe(
|
||||
@@ -692,6 +767,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
actor: { kind: "server" },
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
activity: {
|
||||
|
||||
@@ -67,6 +67,9 @@ export function eventThreadId(event: OrchestrationEvent): ThreadId | null {
|
||||
}
|
||||
|
||||
export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean {
|
||||
if (event.metadata.historyImport === true) {
|
||||
return false;
|
||||
}
|
||||
switch (event.type) {
|
||||
case "thread.message-sent":
|
||||
case "thread.turn-start-requested":
|
||||
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
type ProviderInstallState,
|
||||
ProviderSetupError,
|
||||
ResolvedKeybindingRule,
|
||||
type ServerLifecycleStreamEvent,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
WS_METHODS,
|
||||
@@ -91,6 +92,7 @@ const decodeTransferThreadSnapshot = Schema.decodeUnknownEffect(
|
||||
const decodeTransferShellSnapshot = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(OrchestrationShellSnapshot),
|
||||
);
|
||||
const encodeTestJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
@@ -127,6 +129,7 @@ import {
|
||||
AntigravityInstallationError,
|
||||
} from "./provider/AntigravityInstallation.ts";
|
||||
import type { ProviderInstance } from "./provider/ProviderDriver.ts";
|
||||
import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
|
||||
import { ProviderAdapterRequestError } from "./provider/Errors.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts";
|
||||
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
|
||||
@@ -513,6 +516,9 @@ const buildAppUnderTest = (options?: {
|
||||
projectSetupScriptRunner?: Partial<
|
||||
ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]
|
||||
>;
|
||||
providerSessionDirectory?: Partial<
|
||||
ProviderSessionDirectory.ProviderSessionDirectory["Service"]
|
||||
>;
|
||||
terminalManager?: Partial<TerminalManager.TerminalManager["Service"]>;
|
||||
orchestrationEngine?: Partial<OrchestrationEngine.OrchestrationEngineService["Service"]>;
|
||||
threadDeletionReactor?: Partial<ThreadDeletionReactor["Service"]>;
|
||||
@@ -785,6 +791,13 @@ const buildAppUnderTest = (options?: {
|
||||
managedDirectory: "unused-test-antigravity-runtime",
|
||||
...options?.layers?.antigravityInstallation,
|
||||
}),
|
||||
Layer.mock(ProviderSessionDirectory.ProviderSessionDirectory)({
|
||||
upsert: () => Effect.void,
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
...options?.layers?.providerSessionDirectory,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Layer.provide(
|
||||
@@ -973,6 +986,7 @@ const buildAppUnderTest = (options?: {
|
||||
}),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getImportedAgentSessionSources: () => Effect.succeed([]),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
...options?.layers?.projectionSnapshotQuery,
|
||||
}),
|
||||
@@ -5332,6 +5346,103 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("keeps agent session import project failures structured over websocket rpc", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const projectId = ProjectId.make("missing-import-project");
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const error = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.agentSessionsImport]({ projectId }).pipe(Effect.flip),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(error._tag, "AgentSessionImportProjectNotFoundError");
|
||||
if (error._tag === "AgentSessionImportProjectNotFoundError") {
|
||||
assert.equal(error.projectId, projectId);
|
||||
}
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("returns scanner skip counts over websocket rpc", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const codexHome = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-agent-import-rpc-codex-",
|
||||
});
|
||||
const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-agent-import-rpc-workspace-",
|
||||
});
|
||||
const transcriptDirectory = path.join(codexHome, "sessions", "2026", "08", "31");
|
||||
const transcriptPath = path.join(transcriptDirectory, "rollout-skipped.jsonl");
|
||||
yield* fileSystem.makeDirectory(transcriptDirectory, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
transcriptPath,
|
||||
encodeTestJson({
|
||||
timestamp: "2026-08-31T12:00:00.000Z",
|
||||
type: "session_meta",
|
||||
payload: { id: "rpc-skipped-session", cwd: workspaceRoot },
|
||||
}),
|
||||
);
|
||||
yield* fileSystem.utimes(transcriptPath, 0, 0);
|
||||
|
||||
const projectId = ProjectId.make("agent-import-rpc-project");
|
||||
const project = {
|
||||
id: projectId,
|
||||
title: "Agent import RPC",
|
||||
workspaceRoot,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-08-31T12:00:00.000Z",
|
||||
updatedAt: "2026-08-31T12:00:00.000Z",
|
||||
} as const;
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
serverSettings: {
|
||||
getSettings: Effect.succeed({
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providerInstances: {
|
||||
[ProviderInstanceId.make("codex")]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
config: { homePath: codexHome },
|
||||
},
|
||||
[ProviderInstanceId.make("claudeAgent")]: {
|
||||
driver: ProviderDriverKind.make("claudeAgent"),
|
||||
enabled: false,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getProjectShellById: (requestedProjectId) =>
|
||||
Effect.succeed(
|
||||
requestedProjectId === projectId ? Option.some(project) : Option.none(),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const result = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
Effect.gen(function* () {
|
||||
const scan = yield* client[WS_METHODS.agentSessionsScan]({});
|
||||
assert.deepEqual(
|
||||
scan.candidates.map((candidate) => candidate.path),
|
||||
[workspaceRoot],
|
||||
);
|
||||
return yield* client[WS_METHODS.agentSessionsImport]({ projectId });
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepEqual(result, { importedCount: 0, skippedCount: 1 });
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("uploads Codex thread feedback through websocket rpc", () =>
|
||||
Effect.gen(function* () {
|
||||
const input = {
|
||||
@@ -6239,6 +6350,98 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("subscribeServerLifecycle buffers updates published during snapshot capture", () =>
|
||||
Effect.gen(function* () {
|
||||
const pubsub = yield* PubSub.unbounded<ServerLifecycleStreamEvent>();
|
||||
const streamSubscribed = yield* Deferred.make<void>();
|
||||
const snapshotPublished = yield* Deferred.make<void>();
|
||||
const bootstrapProjectId = ProjectId.make("project-bootstrap");
|
||||
const bootstrapThreadId = ThreadId.make("thread-bootstrap");
|
||||
const snapshotEvent = {
|
||||
version: 1 as const,
|
||||
sequence: 1,
|
||||
type: "welcome" as const,
|
||||
payload: {
|
||||
environment: testEnvironmentDescriptor,
|
||||
cwd: "/tmp/project",
|
||||
projectName: "project",
|
||||
bootstrapStatus: "pending" as const,
|
||||
},
|
||||
};
|
||||
const gapEvent = {
|
||||
version: 1 as const,
|
||||
sequence: 2,
|
||||
type: "welcome" as const,
|
||||
payload: {
|
||||
environment: testEnvironmentDescriptor,
|
||||
cwd: "/tmp/project",
|
||||
projectName: "project",
|
||||
bootstrapStatus: "complete" as const,
|
||||
bootstrapProjectId,
|
||||
bootstrapThreadId,
|
||||
bootstrapProjectCreated: true,
|
||||
bootstrapThreadCreated: true,
|
||||
},
|
||||
};
|
||||
const sentinelEvent = {
|
||||
version: 1 as const,
|
||||
sequence: 3,
|
||||
type: "ready" as const,
|
||||
payload: { at: "2026-01-01T00:00:01.000Z", environment: testEnvironmentDescriptor },
|
||||
};
|
||||
const liveStream = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(pubsub);
|
||||
yield* Deferred.succeed(streamSubscribed, undefined);
|
||||
return Stream.fromSubscription(subscription);
|
||||
}),
|
||||
);
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
serverLifecycleEvents: {
|
||||
snapshot: PubSub.publish(pubsub, gapEvent).pipe(
|
||||
Effect.andThen(Deferred.succeed(snapshotPublished, undefined)),
|
||||
Effect.as({ sequence: 1, events: [snapshotEvent] }),
|
||||
),
|
||||
stream: liveStream,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Deferred.await(snapshotPublished);
|
||||
yield* Deferred.await(streamSubscribed);
|
||||
yield* PubSub.publish(pubsub, sentinelEvent);
|
||||
}).pipe(Effect.forkScoped);
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
const events = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[WS_METHODS.subscribeServerLifecycle]({}).pipe(Stream.take(2), Stream.runCollect),
|
||||
),
|
||||
);
|
||||
|
||||
const [first, second] = Array.from(events);
|
||||
assert.equal(first?.type, "welcome");
|
||||
assert.equal(first?.sequence, 1);
|
||||
if (first?.type !== "welcome") {
|
||||
assert.fail("expected the pending bootstrap event");
|
||||
}
|
||||
assert.equal(first.payload.bootstrapStatus, "pending");
|
||||
assert.equal(second?.type, "welcome");
|
||||
assert.equal(second?.sequence, 2);
|
||||
if (second?.type !== "welcome") {
|
||||
assert.fail("expected the bootstrap completion event");
|
||||
}
|
||||
assert.equal(second.payload.bootstrapStatus, "complete");
|
||||
assert.equal(second.payload.bootstrapProjectId, bootstrapProjectId);
|
||||
assert.equal(second.payload.bootstrapThreadId, bootstrapThreadId);
|
||||
assert.equal(second.payload.bootstrapProjectCreated, true);
|
||||
assert.equal(second.payload.bootstrapThreadCreated, true);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket rpc projects.searchEntries", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -151,6 +151,7 @@ it.effect("marks active running sessions that have persisted resume state", () =
|
||||
),
|
||||
),
|
||||
upsert: (binding) => Effect.sync(() => upserts.push(binding)),
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
@@ -265,6 +266,7 @@ it.effect.each(["marked update", "opt-in restart"] as const)(
|
||||
firstMarkerCleared ? Deferred.succeed(continuationCleared, undefined) : Effect.void,
|
||||
),
|
||||
),
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
@@ -391,6 +393,7 @@ it.effect("does not continue archived or deleted marked sessions", () => {
|
||||
);
|
||||
},
|
||||
upsert: () => Effect.void,
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
@@ -446,6 +449,7 @@ it.effect("retries continuation preparation before settling a persistent failure
|
||||
}),
|
||||
),
|
||||
upsert: () => Effect.void,
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
@@ -517,6 +521,7 @@ it.effect("reconciles multiple active and archived orphans but skips live sessio
|
||||
),
|
||||
),
|
||||
upsert: (binding) => Effect.sync(() => upserts.push(binding)),
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
@@ -596,6 +601,7 @@ it.effect(
|
||||
}),
|
||||
),
|
||||
upsert: () => Effect.fail(writeFailure),
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
@@ -633,6 +639,7 @@ it.effect("retries failed projections and continues after a persistent failure",
|
||||
directory: {
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
upsert: () => Effect.void,
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
@@ -682,6 +689,7 @@ it.effect("does not fail startup when the live provider session inventory cannot
|
||||
Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
|
||||
getBinding: () => Effect.die("unused"),
|
||||
upsert: () => Effect.die("unused"),
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
@@ -754,6 +762,7 @@ for (const scenario of [
|
||||
Effect.sync(() => {
|
||||
upserts.push(binding);
|
||||
}),
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
@@ -827,6 +836,7 @@ for (const preparedStatus of [
|
||||
if (binding.status !== "starting" || sends.length === 0) return;
|
||||
yield* Deferred.succeed(cleared, undefined);
|
||||
}),
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () =>
|
||||
@@ -932,6 +942,7 @@ it.effect("settles failed opt-in recovery without retrying the provider turn", (
|
||||
Effect.sync(() => {
|
||||
binding = next;
|
||||
}),
|
||||
recordImportedTranscript: () => Effect.die("unused"),
|
||||
getProvider: () => Effect.die("unused"),
|
||||
listThreadIds: () => Effect.die("unused"),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
|
||||
@@ -155,6 +155,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
||||
),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.some(bootstrapThreadId)),
|
||||
getImportedAgentSessionSources: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadRuntimeContext: () => Effect.die("unused"),
|
||||
@@ -181,6 +182,8 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
|
||||
assert.deepStrictEqual(targets, {
|
||||
bootstrapProjectId,
|
||||
bootstrapThreadId,
|
||||
bootstrapProjectCreated: false,
|
||||
bootstrapThreadCreated: false,
|
||||
});
|
||||
assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []);
|
||||
});
|
||||
@@ -212,6 +215,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getImportedAgentSessionSources: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadRuntimeContext: () => Effect.die("unused"),
|
||||
@@ -237,6 +241,8 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
|
||||
assert.equal(typeof targets.bootstrapProjectId, "string");
|
||||
assert.equal(typeof targets.bootstrapThreadId, "string");
|
||||
assert.equal(targets.bootstrapProjectCreated, true);
|
||||
assert.equal(targets.bootstrapThreadCreated, true);
|
||||
const commands = yield* Ref.get(dispatchCalls);
|
||||
assert.deepStrictEqual(
|
||||
commands.map((command) => command.type),
|
||||
@@ -250,6 +256,60 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"resolveAutoBootstrapWelcomeTargets preserves a project created before thread failure",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const targets = yield* ServerRuntimeStartup.resolveAutoBootstrapWelcomeTargets.pipe(
|
||||
Effect.provideService(ServerConfig.ServerConfig, {
|
||||
cwd: "/tmp/startup-project",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
|
||||
getUserInputActivity: () => Effect.die("unused"),
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getArchivedShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getEventReplayStats: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.die("thread lookup failed"),
|
||||
getImportedAgentSessionSources: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadRuntimeContext: () => Effect.die("unused"),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
getThreadDetailSnapshot: () => Effect.die("unused"),
|
||||
searchThreads: () => Effect.succeed({ matches: [] }),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
readThreadEvents: () => Stream.empty,
|
||||
getThreadReplayStats: () => Effect.die("unused thread replay stats"),
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
),
|
||||
streamDomainEvents: Stream.empty,
|
||||
subscribeDomainEvents: Effect.succeed(Stream.empty),
|
||||
latestSequence: Effect.succeed(0),
|
||||
} satisfies OrchestrationEngine.OrchestrationEngineService["Service"]),
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
assert.equal(typeof targets.bootstrapProjectId, "string");
|
||||
assert.equal(targets.bootstrapProjectCreated, true);
|
||||
assert.equal(targets.bootstrapThreadId, undefined);
|
||||
assert.equal(targets.bootstrapThreadCreated, undefined);
|
||||
assert.deepStrictEqual(yield* Ref.get(dispatchCalls), ["project.create"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
@@ -278,6 +338,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getImportedAgentSessionSources: () => Effect.die("unused"),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadRuntimeContext: () => Effect.die("unused"),
|
||||
@@ -309,3 +370,31 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
|
||||
assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("completeAutoBootstrapWelcome settles failures without bootstrap targets", () =>
|
||||
Effect.gen(function* () {
|
||||
const completion = yield* ServerRuntimeStartup.completeAutoBootstrapWelcome(
|
||||
Effect.fail("bootstrap failed"),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(completion, { bootstrapStatus: "complete" });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("completeAutoBootstrapWelcome settles unexpected defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const completion = yield* ServerRuntimeStartup.completeAutoBootstrapWelcome(
|
||||
Effect.die("bootstrap defect"),
|
||||
);
|
||||
|
||||
assert.deepStrictEqual(completion, { bootstrapStatus: "complete" });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("completeAutoBootstrapWelcome settles an empty bootstrap result", () =>
|
||||
Effect.gen(function* () {
|
||||
const completion = yield* ServerRuntimeStartup.completeAutoBootstrapWelcome(Effect.succeed({}));
|
||||
|
||||
assert.deepStrictEqual(completion, { bootstrapStatus: "complete" });
|
||||
}),
|
||||
);
|
||||
@@ -194,6 +194,8 @@ export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
|
||||
|
||||
let bootstrapProjectId: ProjectId | undefined;
|
||||
let bootstrapThreadId: ThreadId | undefined;
|
||||
let bootstrapProjectCreated = false;
|
||||
let bootstrapThreadCreated = false;
|
||||
|
||||
if (serverConfig.autoBootstrapProjectFromCwd) {
|
||||
yield* Effect.gen(function* () {
|
||||
@@ -216,45 +218,79 @@ export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
|
||||
workspaceRoot: serverConfig.cwd,
|
||||
createdAt,
|
||||
});
|
||||
bootstrapProjectId = nextProjectId;
|
||||
bootstrapProjectCreated = true;
|
||||
} else {
|
||||
nextProjectId = existingProject.value.id;
|
||||
bootstrapProjectId = nextProjectId;
|
||||
nextThreadModelSelection =
|
||||
existingProject.value.defaultModelSelection ?? getAutoBootstrapThreadModelSelection();
|
||||
}
|
||||
|
||||
const existingThreadId =
|
||||
yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
|
||||
if (Option.isNone(existingThreadId)) {
|
||||
const createdAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const createdThreadId = ThreadId.make(yield* randomUUID);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make(yield* randomUUID),
|
||||
threadId: createdThreadId,
|
||||
projectId: nextProjectId,
|
||||
title: "New thread",
|
||||
modelSelection: nextThreadModelSelection,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
});
|
||||
bootstrapProjectId = nextProjectId;
|
||||
bootstrapThreadId = createdThreadId;
|
||||
} else {
|
||||
bootstrapProjectId = nextProjectId;
|
||||
bootstrapThreadId = existingThreadId.value;
|
||||
}
|
||||
yield* Effect.gen(function* () {
|
||||
const existingThreadId =
|
||||
yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
|
||||
if (Option.isNone(existingThreadId)) {
|
||||
const createdAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const createdThreadId = ThreadId.make(yield* randomUUID);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make(yield* randomUUID),
|
||||
threadId: createdThreadId,
|
||||
projectId: nextProjectId,
|
||||
title: "New thread",
|
||||
modelSelection: nextThreadModelSelection,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
});
|
||||
bootstrapThreadId = createdThreadId;
|
||||
bootstrapThreadCreated = true;
|
||||
} else {
|
||||
bootstrapThreadId = existingThreadId.value;
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Cause.hasInterrupts(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("startup thread auto-bootstrap failed", {
|
||||
bootstrapProjectId: nextProjectId,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
...(bootstrapProjectId ? { bootstrapProjectId } : {}),
|
||||
...(bootstrapThreadId ? { bootstrapThreadId } : {}),
|
||||
...(bootstrapProjectId ? { bootstrapProjectCreated } : {}),
|
||||
...(bootstrapThreadId ? { bootstrapThreadCreated } : {}),
|
||||
} as const;
|
||||
});
|
||||
|
||||
export const completeAutoBootstrapWelcome = <A extends object, E, R>(
|
||||
bootstrap: Effect.Effect<A, E, R>,
|
||||
) =>
|
||||
bootstrap.pipe(
|
||||
Effect.matchCauseEffect({
|
||||
onFailure: (cause) =>
|
||||
Cause.hasInterrupts(cause)
|
||||
? Effect.failCause(cause)
|
||||
: Effect.logWarning("startup auto-bootstrap failed", { cause }).pipe(
|
||||
Effect.as({ bootstrapStatus: "complete" as const }),
|
||||
),
|
||||
onSuccess: (targets) =>
|
||||
Effect.succeed({
|
||||
...targets,
|
||||
bootstrapStatus: "complete" as const,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const resolveStartupBrowserTarget = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
|
||||
@@ -839,36 +875,31 @@ export const make = (options?: StartupOptions) =>
|
||||
runStartupPhase(
|
||||
"welcome.autobootstrap",
|
||||
Effect.gen(function* () {
|
||||
const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets.pipe(
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
const bootstrapCompletion = yield* completeAutoBootstrapWelcome(
|
||||
resolveAutoBootstrapWelcomeTargets.pipe(
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
),
|
||||
);
|
||||
if (!bootstrapTargets.bootstrapProjectId && !bootstrapTargets.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Effect.logDebug("startup phase: publishing bootstrapped welcome event", {
|
||||
environmentId: environment.environmentId,
|
||||
cwd: welcomeBase.cwd,
|
||||
projectName: welcomeBase.projectName,
|
||||
bootstrapProjectId: bootstrapTargets.bootstrapProjectId,
|
||||
bootstrapThreadId: bootstrapTargets.bootstrapThreadId,
|
||||
});
|
||||
yield* Effect.logDebug(
|
||||
"startup phase: publishing completed bootstrap welcome event",
|
||||
{
|
||||
environmentId: environment.environmentId,
|
||||
cwd: welcomeBase.cwd,
|
||||
projectName: welcomeBase.projectName,
|
||||
...bootstrapCompletion,
|
||||
},
|
||||
);
|
||||
yield* lifecycleEvents.publish({
|
||||
version: 1,
|
||||
type: "welcome",
|
||||
payload: {
|
||||
environment,
|
||||
...welcomeBase,
|
||||
...bootstrapTargets,
|
||||
...bootstrapCompletion,
|
||||
},
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("startup auto-bootstrap welcome failed", {
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
}).pipe(Effect.ignoreCause({ log: true })),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -914,7 +945,11 @@ export const make = (options?: StartupOptions) =>
|
||||
lifecycleEvents.publish({
|
||||
version: 1,
|
||||
type: "welcome",
|
||||
payload: { environment, ...welcomeBase },
|
||||
payload: {
|
||||
environment,
|
||||
...welcomeBase,
|
||||
bootstrapStatus: serverConfig.autoBootstrapProjectFromCwd ? "pending" : "complete",
|
||||
},
|
||||
}),
|
||||
);
|
||||
yield* options?.activate ?? Effect.void;
|
||||
|
||||
@@ -14,6 +14,7 @@ import * as Duration from "effect/Duration";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
@@ -22,6 +23,7 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
|
||||
import * as ServerSettingsModule from "./serverSettings.ts";
|
||||
import { resolveProviderInstanceTerminalEnvironment } from "./terminal/Manager.ts";
|
||||
|
||||
const decodeSettingsPatch = Schema.decodeUnknownEffect(ServerSettingsPatch);
|
||||
const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
|
||||
@@ -1102,4 +1104,39 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
);
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("materializes provider secrets for terminal environment resolution", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const instanceId = ProviderInstanceId.make("codex_terminal");
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
environment: [
|
||||
{ name: "OPENROUTER_API_KEY", value: "sk-terminal-secret", sensitive: true },
|
||||
],
|
||||
config: { homePath: "~/.codex-terminal" },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const environment = yield* resolveProviderInstanceTerminalEnvironment({
|
||||
serverSettings,
|
||||
path,
|
||||
rawProviderInstanceId: instanceId,
|
||||
env: undefined,
|
||||
});
|
||||
const persisted = yield* fileSystem.readFileString(serverConfig.settingsPath);
|
||||
|
||||
assert.equal(environment.OPENROUTER_API_KEY, "sk-terminal-secret");
|
||||
assert.match(environment.CODEX_HOME ?? "", /[\\/][.]codex-terminal$/);
|
||||
assert.notInclude(persisted, "sk-terminal-secret");
|
||||
assert.include(persisted, '"valueRedacted": true');
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
});
|
||||
@@ -7,9 +7,14 @@ import {
|
||||
type TerminalMetadataStreamEvent,
|
||||
type TerminalOpenInput,
|
||||
type TerminalRestartInput,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
ServerSettingsError,
|
||||
TerminalProviderInstanceNotFoundError,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
@@ -23,11 +28,16 @@ import * as Path from "effect/Path";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { expect } from "vite-plus/test";
|
||||
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as TerminalManager from "./Manager.ts";
|
||||
import * as PtyAdapter from "./PtyAdapter.ts";
|
||||
|
||||
@@ -215,6 +225,9 @@ interface CreateManagerOptions {
|
||||
maxRetainedInactiveSessions?: number;
|
||||
historyByteLimit?: number;
|
||||
ptyAdapter?: FakePtyAdapter;
|
||||
resolveProviderInstanceEnvironment?: Parameters<
|
||||
typeof TerminalManager.makeWithOptions
|
||||
>[0]["resolveProviderInstanceEnvironment"];
|
||||
}
|
||||
|
||||
interface ManagerFixture {
|
||||
@@ -259,6 +272,9 @@ const createManager = (
|
||||
...(options.maxRetainedInactiveSessions !== undefined
|
||||
? { maxRetainedInactiveSessions: options.maxRetainedInactiveSessions }
|
||||
: {}),
|
||||
...(options.resolveProviderInstanceEnvironment !== undefined
|
||||
? { resolveProviderInstanceEnvironment: options.resolveProviderInstanceEnvironment }
|
||||
: {}),
|
||||
});
|
||||
const eventsRef = yield* Ref.make<ReadonlyArray<TerminalEvent>>([]);
|
||||
const unsubscribe = yield* manager.subscribe((event) =>
|
||||
@@ -1736,6 +1752,26 @@ it.layer(
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("expands provider home paths passed to setup terminals", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter } = yield* createManager(5);
|
||||
|
||||
yield* manager.open({
|
||||
...openInput(),
|
||||
env: {
|
||||
CODEX_HOME: "~/.codex-work",
|
||||
CLAUDE_CONFIG_DIR: "~/.claude-work",
|
||||
CUSTOM_ACCOUNT: "~/leave-this-value-alone",
|
||||
},
|
||||
});
|
||||
|
||||
const environment = ptyAdapter.spawnInputs[0]?.env;
|
||||
expect(environment?.CODEX_HOME).toMatch(/[\\/][.]codex-work$/);
|
||||
expect(environment?.CLAUDE_CONFIG_DIR).toMatch(/[\\/][.]claude-work$/);
|
||||
expect(environment?.CUSTOM_ACCOUNT).toBe("~/leave-this-value-alone");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("strips AppImage runtime env from terminal sessions", () =>
|
||||
Effect.gen(function* () {
|
||||
const appDir = "/tmp/.mount_T3Codeabc123";
|
||||
@@ -1822,6 +1858,382 @@ it.layer(
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolves a provider instance environment before spawning", () =>
|
||||
Effect.gen(function* () {
|
||||
const providerInstanceId = ProviderInstanceId.make("codex_work");
|
||||
const { manager, ptyAdapter } = yield* createManager(5, {
|
||||
env: { T3CODE_SECRET: "server-only" },
|
||||
resolveProviderInstanceEnvironment: (requestedId, env) =>
|
||||
Effect.succeed({
|
||||
...env,
|
||||
PROVIDER_SECRET: requestedId === providerInstanceId ? "secret-value" : "wrong",
|
||||
CODEX_HOME: "/accounts/codex-work",
|
||||
}),
|
||||
});
|
||||
|
||||
const snapshot = yield* manager.open(
|
||||
openInput({ providerInstanceId, env: { CLIENT_FLAG: "1" } }),
|
||||
);
|
||||
|
||||
expect(ptyAdapter.spawnInputs[0]?.env.PROVIDER_SECRET).toBe("secret-value");
|
||||
expect(ptyAdapter.spawnInputs[0]?.env.CODEX_HOME).toBe("/accounts/codex-work");
|
||||
expect(ptyAdapter.spawnInputs[0]?.env.CLIENT_FLAG).toBe("1");
|
||||
expect(ptyAdapter.spawnInputs[0]?.env.T3CODE_SECRET).toBeUndefined();
|
||||
expect(snapshot).not.toHaveProperty("env");
|
||||
expect(snapshot).not.toHaveProperty("providerInstanceId");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails closed when a provider instance is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const providerInstanceId = ProviderInstanceId.make("deleted_instance");
|
||||
const { manager, ptyAdapter } = yield* createManager(5, {
|
||||
resolveProviderInstanceEnvironment: (requestedId) =>
|
||||
Effect.fail(
|
||||
new TerminalProviderInstanceNotFoundError({
|
||||
providerInstanceId: ProviderInstanceId.make(requestedId),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const error = yield* manager.open(openInput({ providerInstanceId })).pipe(Effect.flip);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
error,
|
||||
new TerminalProviderInstanceNotFoundError({ providerInstanceId }),
|
||||
);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves the settings failure when provider environment resolution fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const providerInstanceId = ProviderInstanceId.make("codex_work");
|
||||
const settingsCause = new Error("secret store read failed");
|
||||
const settingsError = new ServerSettingsError({
|
||||
settingsPath: "/test/settings.json",
|
||||
operation: "read-secret",
|
||||
providerInstanceId,
|
||||
environmentVariable: "OPENROUTER_API_KEY",
|
||||
cause: settingsCause,
|
||||
});
|
||||
const serverSettings = ServerSettings.ServerSettingsService.of({
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Effect.fail(settingsError),
|
||||
updateSettings: () => Effect.fail(settingsError),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.succeed(Stream.empty),
|
||||
});
|
||||
|
||||
const error = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({
|
||||
serverSettings,
|
||||
path,
|
||||
rawProviderInstanceId: providerInstanceId,
|
||||
env: undefined,
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "TerminalProviderEnvironmentError",
|
||||
providerInstanceId,
|
||||
});
|
||||
expect(error.cause).toBe(settingsError);
|
||||
expect(error.message).not.toContain(settingsError.message);
|
||||
expect(error.message).not.toContain("OPENROUTER_API_KEY");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect.each([
|
||||
{
|
||||
name: "Codex home",
|
||||
driver: "codex",
|
||||
variable: "CODEX_HOME",
|
||||
config: { homePath: "/configured/codex" },
|
||||
expectedHome: "/configured/codex",
|
||||
},
|
||||
{
|
||||
name: "Codex shadow home",
|
||||
driver: "codex",
|
||||
variable: "CODEX_HOME",
|
||||
config: { homePath: "/configured/codex", shadowHomePath: "/configured/codex-shadow" },
|
||||
expectedHome: "/configured/codex-shadow",
|
||||
},
|
||||
{
|
||||
name: "Claude home",
|
||||
driver: "claudeAgent",
|
||||
variable: "CLAUDE_CONFIG_DIR",
|
||||
config: { homePath: "/configured/claude" },
|
||||
expectedHome: "/configured/claude",
|
||||
},
|
||||
])("prefers $name over the instance environment", ({ driver, variable, config, expectedHome }) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const environment = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({
|
||||
serverSettings,
|
||||
path,
|
||||
rawProviderInstanceId: "configured_home",
|
||||
env: undefined,
|
||||
});
|
||||
|
||||
expect(environment[variable]).toBe(path.resolve(expectedHome));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
ServerSettings.layerTest({
|
||||
providerInstances: {
|
||||
[ProviderInstanceId.make("configured_home")]: {
|
||||
driver: ProviderDriverKind.make(driver),
|
||||
environment: [{ name: variable, value: "~/.environment-account", sensitive: false }],
|
||||
config,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolves the legacy Codex default instance", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const environment = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({
|
||||
serverSettings,
|
||||
path,
|
||||
rawProviderInstanceId: "codex",
|
||||
env: undefined,
|
||||
});
|
||||
|
||||
expect(environment.CODEX_HOME).toMatch(/[\\/][.]codex-legacy$/);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
ServerSettings.ServerSettingsService.layerTest({
|
||||
providerInstances: {},
|
||||
providers: { codex: { homePath: "~/.codex-legacy" } },
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolves the legacy Claude default instance", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const environment = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({
|
||||
serverSettings,
|
||||
path,
|
||||
rawProviderInstanceId: "claudeAgent",
|
||||
env: undefined,
|
||||
});
|
||||
|
||||
expect(environment.CLAUDE_CONFIG_DIR).toMatch(/[\\/][.]claude-legacy$/);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
ServerSettings.ServerSettingsService.layerTest({
|
||||
providerInstances: {},
|
||||
providers: { claudeAgent: { homePath: "~/.claude-legacy" } },
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("prefers an explicit default instance over legacy provider settings", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const environment = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({
|
||||
serverSettings,
|
||||
path,
|
||||
rawProviderInstanceId: "codex",
|
||||
env: undefined,
|
||||
});
|
||||
|
||||
expect(environment.CODEX_HOME).toMatch(/[\\/][.]codex-explicit$/);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
ServerSettings.ServerSettingsService.layerTest({
|
||||
providers: { codex: { homePath: "~/.codex-legacy" } },
|
||||
providerInstances: {
|
||||
[ProviderInstanceId.make("codex")]: {
|
||||
driver: "codex",
|
||||
config: { homePath: "~/.codex-explicit" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("keeps unknown provider instance ids unavailable after legacy hydration", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const error = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({
|
||||
serverSettings,
|
||||
path,
|
||||
rawProviderInstanceId: "codex_unknown",
|
||||
env: undefined,
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "TerminalProviderInstanceNotFoundError",
|
||||
providerInstanceId: "codex_unknown",
|
||||
});
|
||||
}).pipe(Effect.provide(ServerSettings.ServerSettingsService.layerTest())),
|
||||
);
|
||||
|
||||
it.effect("restarts a running terminal when the resolved provider environment changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const providerInstanceId = ProviderInstanceId.make("codex_work");
|
||||
let providerSecret = "first-secret";
|
||||
const { manager, ptyAdapter } = yield* createManager(5, {
|
||||
resolveProviderInstanceEnvironment: () =>
|
||||
Effect.succeed({ PROVIDER_SECRET: providerSecret }),
|
||||
});
|
||||
|
||||
yield* manager.open(openInput({ providerInstanceId }));
|
||||
providerSecret = "second-secret";
|
||||
yield* manager.open(openInput({ providerInstanceId }));
|
||||
|
||||
expect(ptyAdapter.processes[0]?.killed).toBe(true);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(2);
|
||||
expect(ptyAdapter.spawnInputs[1]?.env.PROVIDER_SECRET).toBe("second-secret");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("restarts with current provider secrets and clears bounded history", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const path = yield* Path.Path;
|
||||
const providerInstanceId = ProviderInstanceId.make("codex_restart");
|
||||
const { manager, ptyAdapter, logsDir } = yield* createManager(2, {
|
||||
historyByteLimit: 8,
|
||||
resolveProviderInstanceEnvironment: (rawProviderInstanceId, env) =>
|
||||
TerminalManager.resolveProviderInstanceTerminalEnvironment({
|
||||
serverSettings,
|
||||
path,
|
||||
rawProviderInstanceId,
|
||||
env,
|
||||
}),
|
||||
});
|
||||
const homePath = path.join(logsDir, "codex");
|
||||
const updateSecret = (value: string) =>
|
||||
serverSettings.updateSettings({
|
||||
providerInstances: {
|
||||
[providerInstanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
config: { homePath },
|
||||
environment: [{ name: "PROVIDER_SECRET", value, sensitive: true }],
|
||||
},
|
||||
},
|
||||
});
|
||||
const input = {
|
||||
providerInstanceId,
|
||||
env: { CLIENT_FLAG: "1", PROVIDER_SECRET: "client-value" },
|
||||
};
|
||||
const outputProcessed = yield* Deferred.make<void>();
|
||||
const unsubscribe = yield* manager.subscribe((event) =>
|
||||
event.type === "output"
|
||||
? Deferred.succeed(outputProcessed, undefined).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
);
|
||||
yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
|
||||
|
||||
yield* updateSecret("first-secret");
|
||||
yield* manager.restart(restartInput(input));
|
||||
const firstProcess = ptyAdapter.processes[0]!;
|
||||
expect(ptyAdapter.spawnInputs[0]?.env.PROVIDER_SECRET).toBe("first-secret");
|
||||
firstProcess.emitData("discarded\nold-one\nold-two\n");
|
||||
yield* Deferred.await(outputProcessed);
|
||||
expect((yield* manager.open(openInput(input))).history).toBe("old-two\n");
|
||||
|
||||
yield* updateSecret("second-secret");
|
||||
const restarted = yield* manager.restart(restartInput(input));
|
||||
|
||||
expect(firstProcess.killed).toBe(true);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(2);
|
||||
expect(ptyAdapter.spawnInputs[1]?.env).toMatchObject({
|
||||
PROVIDER_SECRET: "second-secret",
|
||||
CODEX_HOME: homePath,
|
||||
CLIENT_FLAG: "1",
|
||||
});
|
||||
expect(restarted.history).toBe("");
|
||||
expect(restarted.status).toBe("running");
|
||||
expect(restarted).not.toHaveProperty("env");
|
||||
expect(restarted).not.toHaveProperty("providerInstanceId");
|
||||
const logPath = yield* historyLogPath(logsDir);
|
||||
expect(yield* readFileString(logPath)).toBe("");
|
||||
|
||||
ptyAdapter.processes[1]!.emitData("discarded again\nnew-one\nnew-two\n");
|
||||
yield* manager.close({ threadId: "thread-1" });
|
||||
expect(yield* readFileString(logPath)).toBe("new-two\n");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
ServerSettings.layer.pipe(
|
||||
Layer.provide(ServerSecretStore.layer),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provide(
|
||||
ServerConfig.layerTest(process.cwd(), { prefix: "t3code-terminal-provider-restart-" }),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("attaches to a running provider terminal without resolving the provider again", () =>
|
||||
Effect.gen(function* () {
|
||||
const providerInstanceId = ProviderInstanceId.make("codex_work");
|
||||
let providerAvailable = true;
|
||||
const { manager, ptyAdapter } = yield* createManager(5, {
|
||||
resolveProviderInstanceEnvironment: (requestedId) =>
|
||||
providerAvailable
|
||||
? Effect.succeed({ PROVIDER_SECRET: "secret-value" })
|
||||
: Effect.fail(
|
||||
new TerminalProviderInstanceNotFoundError({
|
||||
providerInstanceId: ProviderInstanceId.make(requestedId),
|
||||
}),
|
||||
),
|
||||
});
|
||||
yield* manager.open(openInput({ providerInstanceId }));
|
||||
providerAvailable = false;
|
||||
const events: TerminalAttachStreamEvent[] = [];
|
||||
|
||||
const unsubscribe = yield* manager.attachStream(
|
||||
{ ...openInput({ providerInstanceId }), restartIfNotRunning: true },
|
||||
(event) => Effect.sync(() => events.push(event)),
|
||||
);
|
||||
unsubscribe();
|
||||
|
||||
expect(events[0]?.type).toBe("snapshot");
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(1);
|
||||
expect(ptyAdapter.processes[0]?.killed).toBe(false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails closed when attaching would create a missing provider terminal", () =>
|
||||
Effect.gen(function* () {
|
||||
const providerInstanceId = ProviderInstanceId.make("deleted_instance");
|
||||
const { manager, ptyAdapter } = yield* createManager(5, {
|
||||
resolveProviderInstanceEnvironment: (requestedId) =>
|
||||
Effect.fail(
|
||||
new TerminalProviderInstanceNotFoundError({
|
||||
providerInstanceId: ProviderInstanceId.make(requestedId),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const error = yield* manager
|
||||
.attachStream(openInput({ providerInstanceId }), () => Effect.void)
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.deepStrictEqual(
|
||||
error,
|
||||
new TerminalProviderInstanceNotFoundError({ providerInstanceId }),
|
||||
);
|
||||
expect(ptyAdapter.spawnInputs).toHaveLength(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("starts zsh with prompt spacer disabled to avoid `%` end markers", () =>
|
||||
Effect.gen(function* () {
|
||||
if ((yield* HostProcessPlatform) === "win32") return;
|
||||
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
TerminalError,
|
||||
TerminalHistoryError,
|
||||
TerminalNotRunningError,
|
||||
TerminalProviderInstanceNotFoundError,
|
||||
TerminalProviderEnvironmentError,
|
||||
TerminalResizeError,
|
||||
TerminalSessionLookupError,
|
||||
TerminalWriteError,
|
||||
@@ -31,6 +33,9 @@ import {
|
||||
type TerminalSessionStatus,
|
||||
type TerminalSummary,
|
||||
type TerminalWriteInput,
|
||||
ClaudeSettings,
|
||||
CodexSettings,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
@@ -52,11 +57,17 @@ import * as Semaphore from "effect/Semaphore";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../provider/ProviderInstanceEnvironment.ts";
|
||||
import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
|
||||
import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts";
|
||||
import { deriveProviderInstanceConfigMap } from "../provider/Layers/ProviderInstanceRegistryHydration.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import {
|
||||
increment,
|
||||
terminalRestartsTotal,
|
||||
terminalSessionsTotal,
|
||||
} from "../observability/Metrics.ts";
|
||||
import { expandHomePath } from "../pathExpansion.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import * as PortScanner from "../preview/PortScanner.ts";
|
||||
import * as PtyAdapter from "./PtyAdapter.ts";
|
||||
@@ -69,6 +80,8 @@ export {
|
||||
TerminalError,
|
||||
TerminalHistoryError,
|
||||
TerminalNotRunningError,
|
||||
TerminalProviderInstanceNotFoundError,
|
||||
TerminalProviderEnvironmentError,
|
||||
TerminalResizeError,
|
||||
TerminalSessionLookupError,
|
||||
TerminalWriteError,
|
||||
@@ -86,6 +99,8 @@ const DEFAULT_OPEN_ROWS = 30;
|
||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const MAX_TERMINAL_LABEL_LENGTH = 128;
|
||||
const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
|
||||
const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings);
|
||||
|
||||
class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubprocessCheckError>()(
|
||||
"TerminalSubprocessCheckError",
|
||||
@@ -1267,7 +1282,8 @@ function createTerminalSpawnEnv(
|
||||
}
|
||||
if (runtimeEnv) {
|
||||
for (const [key, value] of Object.entries(runtimeEnv)) {
|
||||
spawnEnv[key] = value;
|
||||
spawnEnv[key] =
|
||||
key === "CODEX_HOME" || key === "CLAUDE_CONFIG_DIR" ? expandHomePath(value) : value;
|
||||
}
|
||||
}
|
||||
// Both PTY backends feed truecolor-capable terminal clients.
|
||||
@@ -1306,17 +1322,78 @@ interface TerminalManagerOptions {
|
||||
readonly threadId: string;
|
||||
readonly terminalId: string;
|
||||
}) => Effect.Effect<void>;
|
||||
resolveProviderInstanceEnvironment?: (
|
||||
providerInstanceId: string,
|
||||
env: Record<string, string> | undefined,
|
||||
) => Effect.Effect<
|
||||
Record<string, string>,
|
||||
TerminalProviderInstanceNotFoundError | TerminalProviderEnvironmentError
|
||||
>;
|
||||
}
|
||||
|
||||
export const resolveProviderInstanceTerminalEnvironment = Effect.fn(
|
||||
"terminal.resolveProviderInstanceTerminalEnvironment",
|
||||
)(function* (input: {
|
||||
readonly serverSettings: ServerSettings.ServerSettingsService["Service"];
|
||||
readonly path: Path.Path;
|
||||
readonly rawProviderInstanceId: string;
|
||||
readonly env: Record<string, string> | undefined;
|
||||
}) {
|
||||
const providerInstanceId = ProviderInstanceId.make(input.rawProviderInstanceId);
|
||||
const settings = yield* input.serverSettings.getSettings.pipe(
|
||||
Effect.mapError((cause) => new TerminalProviderEnvironmentError({ providerInstanceId, cause })),
|
||||
);
|
||||
const instance = deriveProviderInstanceConfigMap(settings)[providerInstanceId];
|
||||
if (instance === undefined) {
|
||||
return yield* new TerminalProviderInstanceNotFoundError({ providerInstanceId });
|
||||
}
|
||||
|
||||
let resolved = mergeProviderInstanceEnvironment(instance.environment, input.env ?? {});
|
||||
if (instance.driver === "codex") {
|
||||
const config = decodeCodexSettings(instance.config ?? {});
|
||||
if (Option.isSome(config)) {
|
||||
const layout = yield* resolveCodexHomeLayout(config.value).pipe(
|
||||
Effect.provideService(Path.Path, input.path),
|
||||
);
|
||||
if (layout.effectiveHomePath)
|
||||
resolved = { ...resolved, CODEX_HOME: layout.effectiveHomePath };
|
||||
}
|
||||
} else if (instance.driver === "claudeAgent") {
|
||||
const config = decodeClaudeSettings(instance.config ?? {});
|
||||
if (Option.isSome(config)) {
|
||||
resolved = yield* makeClaudeEnvironment(config.value, resolved).pipe(
|
||||
Effect.provideService(Path.Path, input.path),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(resolved).filter((entry): entry is [string, string] => entry[1] !== undefined),
|
||||
);
|
||||
});
|
||||
|
||||
export const make = Effect.fn("TerminalManager.make")(function* () {
|
||||
const { terminalLogsDir } = yield* ServerConfig.ServerConfig;
|
||||
const ptyAdapter = yield* PtyAdapter.PtyAdapter;
|
||||
const portDiscovery = yield* PortScanner.PortDiscovery;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const path = yield* Path.Path;
|
||||
const resolveProviderInstanceEnvironment = Effect.fn(
|
||||
"terminal.resolveProviderInstanceEnvironment",
|
||||
)((rawProviderInstanceId: string, env: Record<string, string> | undefined) =>
|
||||
resolveProviderInstanceTerminalEnvironment({
|
||||
serverSettings,
|
||||
path,
|
||||
rawProviderInstanceId,
|
||||
env,
|
||||
}),
|
||||
);
|
||||
return yield* makeWithOptions({
|
||||
logsDir: terminalLogsDir,
|
||||
ptyAdapter,
|
||||
registerTerminalProcesses: portDiscovery.registerTerminalProcesses,
|
||||
unregisterTerminal: portDiscovery.unregisterTerminal,
|
||||
resolveProviderInstanceEnvironment,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1339,6 +1416,24 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
|
||||
const baseEnv = options.env ?? process.env;
|
||||
const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv));
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
const resolveLaunchInputEnvironment = Effect.fn("terminal.resolveLaunchInputEnvironment")(
|
||||
function* <Input extends TerminalOpenInput | TerminalAttachInput | TerminalRestartInput>(
|
||||
input: Input,
|
||||
): Effect.fn.Return<
|
||||
Input,
|
||||
TerminalProviderInstanceNotFoundError | TerminalProviderEnvironmentError
|
||||
> {
|
||||
if (input.providerInstanceId === undefined) return input;
|
||||
const resolver = options.resolveProviderInstanceEnvironment;
|
||||
if (resolver === undefined) {
|
||||
return yield* new TerminalProviderInstanceNotFoundError({
|
||||
providerInstanceId: ProviderInstanceId.make(input.providerInstanceId),
|
||||
});
|
||||
}
|
||||
const env = yield* resolver(input.providerInstanceId, input.env);
|
||||
return { ...input, env };
|
||||
},
|
||||
);
|
||||
// One process-table snapshot per poll tick, shared across every terminal.
|
||||
// Per-terminal `pgrep`/`ps` calls multiply spawn load by terminal count and
|
||||
// can exhaust the PID space on hosts with many sessions (#6332).
|
||||
@@ -2468,7 +2563,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
|
||||
});
|
||||
|
||||
const open: TerminalManager["Service"]["open"] = (input) =>
|
||||
withThreadLock(input.threadId, openLocked(input));
|
||||
withThreadLock(
|
||||
input.threadId,
|
||||
resolveLaunchInputEnvironment(input).pipe(Effect.flatMap(openLocked)),
|
||||
);
|
||||
|
||||
const openOrAttachForStream = (input: TerminalAttachInput) =>
|
||||
withThreadLock(
|
||||
@@ -2485,11 +2583,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
|
||||
});
|
||||
}
|
||||
|
||||
return yield* openLocked({
|
||||
const resolvedInput = yield* resolveLaunchInputEnvironment({
|
||||
...input,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
});
|
||||
return yield* openLocked(resolvedInput);
|
||||
}
|
||||
|
||||
const session = existing.value;
|
||||
@@ -2497,11 +2596,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
|
||||
const targetRows = input.rows ?? session.rows;
|
||||
|
||||
if (!session.process && input.cwd && input.restartIfNotRunning === true) {
|
||||
return yield* openLocked({
|
||||
const resolvedInput = yield* resolveLaunchInputEnvironment({
|
||||
...input,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
});
|
||||
return yield* openLocked(resolvedInput);
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -2753,84 +2853,87 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
|
||||
}),
|
||||
);
|
||||
|
||||
const restartResolved = (input: TerminalRestartInput) =>
|
||||
Effect.gen(function* () {
|
||||
yield* increment(terminalRestartsTotal, { scope: "thread" });
|
||||
const terminalId = input.terminalId;
|
||||
yield* assertValidCwd(input.cwd);
|
||||
|
||||
const sessionKey = toSessionKey(input.threadId, terminalId);
|
||||
const existingSession = yield* getSession(input.threadId, terminalId);
|
||||
let session: TerminalSessionState;
|
||||
if (Option.isNone(existingSession)) {
|
||||
const cols = input.cols ?? DEFAULT_OPEN_COLS;
|
||||
const rows = input.rows ?? DEFAULT_OPEN_ROWS;
|
||||
session = {
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
worktreePath: input.worktreePath ?? null,
|
||||
status: "starting",
|
||||
pid: null,
|
||||
history: new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit),
|
||||
pendingHistoryControlSequence: "",
|
||||
pendingProcessEvents: [],
|
||||
pendingProcessEventIndex: 0,
|
||||
processEventDrainRunning: false,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: yield* nowIso,
|
||||
eventSequence: 0,
|
||||
cols,
|
||||
rows,
|
||||
process: null,
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
childCommandLabel: null,
|
||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
||||
};
|
||||
const createdSession = session;
|
||||
yield* modifyManagerState((state) => {
|
||||
const sessions = new Map(state.sessions);
|
||||
sessions.set(sessionKey, createdSession);
|
||||
return [undefined, { ...state, sessions }] as const;
|
||||
});
|
||||
yield* evictInactiveSessionsIfNeeded();
|
||||
} else {
|
||||
session = existingSession.value;
|
||||
yield* stopProcess(session);
|
||||
session.cwd = input.cwd;
|
||||
session.worktreePath = input.worktreePath ?? null;
|
||||
session.runtimeEnv = normalizedRuntimeEnv(input.env);
|
||||
}
|
||||
|
||||
const cols = input.cols ?? session.cols;
|
||||
const rows = input.rows ?? session.rows;
|
||||
|
||||
session.history.clear();
|
||||
session.pendingHistoryControlSequence = "";
|
||||
session.pendingProcessEvents = [];
|
||||
session.pendingProcessEventIndex = 0;
|
||||
session.processEventDrainRunning = false;
|
||||
yield* persistHistory(input.threadId, terminalId, session.history);
|
||||
yield* startSession(
|
||||
session,
|
||||
{
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
|
||||
cols,
|
||||
rows,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
},
|
||||
"restarted",
|
||||
);
|
||||
return snapshot(session);
|
||||
});
|
||||
|
||||
const restart: TerminalManager["Service"]["restart"] = (input) =>
|
||||
withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
yield* increment(terminalRestartsTotal, { scope: "thread" });
|
||||
const terminalId = input.terminalId;
|
||||
yield* assertValidCwd(input.cwd);
|
||||
|
||||
const sessionKey = toSessionKey(input.threadId, terminalId);
|
||||
const existingSession = yield* getSession(input.threadId, terminalId);
|
||||
let session: TerminalSessionState;
|
||||
if (Option.isNone(existingSession)) {
|
||||
const cols = input.cols ?? DEFAULT_OPEN_COLS;
|
||||
const rows = input.rows ?? DEFAULT_OPEN_ROWS;
|
||||
session = {
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
worktreePath: input.worktreePath ?? null,
|
||||
status: "starting",
|
||||
pid: null,
|
||||
history: new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit),
|
||||
pendingHistoryControlSequence: "",
|
||||
pendingProcessEvents: [],
|
||||
pendingProcessEventIndex: 0,
|
||||
processEventDrainRunning: false,
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: yield* nowIso,
|
||||
eventSequence: 0,
|
||||
cols,
|
||||
rows,
|
||||
process: null,
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
childCommandLabel: null,
|
||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
||||
};
|
||||
const createdSession = session;
|
||||
yield* modifyManagerState((state) => {
|
||||
const sessions = new Map(state.sessions);
|
||||
sessions.set(sessionKey, createdSession);
|
||||
return [undefined, { ...state, sessions }] as const;
|
||||
});
|
||||
yield* evictInactiveSessionsIfNeeded();
|
||||
} else {
|
||||
session = existingSession.value;
|
||||
yield* stopProcess(session);
|
||||
session.cwd = input.cwd;
|
||||
session.worktreePath = input.worktreePath ?? null;
|
||||
session.runtimeEnv = normalizedRuntimeEnv(input.env);
|
||||
}
|
||||
|
||||
const cols = input.cols ?? session.cols;
|
||||
const rows = input.rows ?? session.rows;
|
||||
|
||||
session.history.clear();
|
||||
session.pendingHistoryControlSequence = "";
|
||||
session.pendingProcessEvents = [];
|
||||
session.pendingProcessEventIndex = 0;
|
||||
session.processEventDrainRunning = false;
|
||||
yield* persistHistory(input.threadId, terminalId, session.history);
|
||||
yield* startSession(
|
||||
session,
|
||||
{
|
||||
threadId: input.threadId,
|
||||
terminalId,
|
||||
cwd: input.cwd,
|
||||
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
|
||||
cols,
|
||||
rows,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
},
|
||||
"restarted",
|
||||
);
|
||||
return snapshot(session);
|
||||
}),
|
||||
resolveLaunchInputEnvironment(input).pipe(Effect.flatMap(restartResolved)),
|
||||
);
|
||||
|
||||
const close: TerminalManager["Service"]["close"] = (input) =>
|
||||
|
||||
+40
-1
@@ -53,6 +53,7 @@ import {
|
||||
type RelayClientInstallProgressEvent,
|
||||
ServerSelfUpdateError,
|
||||
type ServerSelfUpdateProgressEvent,
|
||||
type ServerLifecycleStreamEvent,
|
||||
type FilesystemBrowseFailure,
|
||||
FilesystemBrowseError,
|
||||
AssetWorkspaceContextNotFoundError,
|
||||
@@ -96,6 +97,7 @@ import {
|
||||
} from "./observability/RpcInstrumentation.ts";
|
||||
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
|
||||
import * as ProviderService from "./provider/Services/ProviderService.ts";
|
||||
import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
|
||||
import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts";
|
||||
import { ProviderAuthService } from "./provider/Services/ProviderAuthService.ts";
|
||||
import { ProviderInstanceRegistry } from "./provider/Services/ProviderInstanceRegistry.ts";
|
||||
@@ -119,6 +121,8 @@ import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
|
||||
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
|
||||
import * as ReviewService from "./review/ReviewService.ts";
|
||||
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
|
||||
import * as AgentSessionScanner from "./project/AgentSessionScanner.ts";
|
||||
import { importRecentAgentThreads } from "./project/AgentSessionImporter.ts";
|
||||
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
|
||||
import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
|
||||
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
|
||||
@@ -512,6 +516,7 @@ const makeWsRpcLayer = (
|
||||
const portDiscovery = yield* PortScanner.PortDiscovery;
|
||||
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const providerService = yield* ProviderService.ProviderService;
|
||||
const providerSessionDirectory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
|
||||
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
|
||||
const providerAuth = yield* ProviderAuthService;
|
||||
const providerInstances = yield* ProviderInstanceRegistry;
|
||||
@@ -560,6 +565,7 @@ const makeWsRpcLayer = (
|
||||
return true;
|
||||
});
|
||||
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const agentSessionScanner = yield* AgentSessionScanner.AgentSessionScanner;
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
|
||||
const rpcClientIds = yield* Ref.make(new Set<RpcClientId>());
|
||||
@@ -2332,6 +2338,31 @@ const makeWsRpcLayer = (
|
||||
deletePendingAttachment(input.attachmentId),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.agentSessionsScan]: () =>
|
||||
observeRpcEffect(WS_METHODS.agentSessionsScan, agentSessionScanner.scan, {
|
||||
"rpc.aggregate": "workspace",
|
||||
}),
|
||||
[WS_METHODS.agentSessionsImport]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.agentSessionsImport,
|
||||
importRecentAgentThreads(input).pipe(
|
||||
Effect.provideService(AgentSessionScanner.AgentSessionScanner, agentSessionScanner),
|
||||
Effect.provideService(
|
||||
OrchestrationEngine.OrchestrationEngineService,
|
||||
orchestrationEngine,
|
||||
),
|
||||
Effect.provideService(
|
||||
ProjectionSnapshotQuery.ProjectionSnapshotQuery,
|
||||
projectionSnapshotQuery,
|
||||
),
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.provideService(
|
||||
ProviderSessionDirectory.ProviderSessionDirectory,
|
||||
providerSessionDirectory,
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.assetsCreateUrl]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.assetsCreateUrl,
|
||||
@@ -2746,11 +2777,18 @@ const makeWsRpcLayer = (
|
||||
observeRpcStreamEffect(
|
||||
WS_METHODS.subscribeServerLifecycle,
|
||||
Effect.gen(function* () {
|
||||
const liveBuffer = yield* Queue.unbounded<ServerLifecycleStreamEvent>();
|
||||
yield* Effect.forkScoped(
|
||||
lifecycleEvents.stream.pipe(
|
||||
Stream.runForEach((event) => Queue.offer(liveBuffer, event)),
|
||||
),
|
||||
{ startImmediately: true },
|
||||
);
|
||||
const snapshot = yield* lifecycleEvents.snapshot;
|
||||
const snapshotEvents = Array.from(snapshot.events).toSorted(
|
||||
(left, right) => left.sequence - right.sequence,
|
||||
);
|
||||
const liveEvents = lifecycleEvents.stream.pipe(
|
||||
const liveEvents = Stream.fromQueue(liveBuffer).pipe(
|
||||
Stream.filter((event) => event.sequence > snapshot.sequence),
|
||||
);
|
||||
return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);
|
||||
@@ -2877,6 +2915,7 @@ export const websocketRpcRouteLayer = Layer.unwrap(
|
||||
previewAutomationBroker,
|
||||
).pipe(
|
||||
Layer.provideMerge(RpcSerialization.layerJson),
|
||||
Layer.provide(AgentSessionScanner.layer),
|
||||
Layer.provide(ProviderMaintenanceRunner.layer),
|
||||
Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),
|
||||
// One server-lifetime service means clients share the same PR caches, and a WS
|
||||
|
||||
@@ -310,6 +310,63 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
expect(testApi.calls.session).toBe(2);
|
||||
});
|
||||
|
||||
it("keeps manual token submission pending until the session is authenticated", async () => {
|
||||
vi.useFakeTimers();
|
||||
let authenticated = false;
|
||||
let settled = false;
|
||||
try {
|
||||
const testApi = await installAuthApi({
|
||||
session: () =>
|
||||
authenticated
|
||||
? authenticatedSession(LOOPBACK_AUTH)
|
||||
: unauthenticatedSession(LOOPBACK_AUTH),
|
||||
browserSession: () => Effect.succeed(browserSession(["orchestration:read"])),
|
||||
});
|
||||
const { submitServerAuthCredential } = await import("./environments/primary");
|
||||
|
||||
const submission = submitServerAuthCredential("retry-token").finally(() => {
|
||||
settled = true;
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(testApi.calls.browserSession).toEqual([{ credential: "retry-token" }]);
|
||||
expect(testApi.calls.session).toBe(1);
|
||||
expect(settled).toBe(false);
|
||||
|
||||
authenticated = true;
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
await expect(submission).resolves.toBeUndefined();
|
||||
expect(testApi.calls.session).toBe(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("fails manual token submission when the session is not established", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const testApi = await installAuthApi({
|
||||
session: () => unauthenticatedSession(LOOPBACK_AUTH),
|
||||
browserSession: () => Effect.succeed(browserSession(["orchestration:read"])),
|
||||
});
|
||||
const { PrimaryEnvironmentAuthSessionTimeoutError, submitServerAuthCredential } =
|
||||
await import("./environments/primary/auth");
|
||||
|
||||
const submission = submitServerAuthCredential("retry-token");
|
||||
const failure = submission.then(
|
||||
() => null,
|
||||
(error: unknown) => error,
|
||||
);
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
|
||||
await expect(failure).resolves.toBeInstanceOf(PrimaryEnvironmentAuthSessionTimeoutError);
|
||||
expect(testApi.calls.browserSession).toEqual([{ credential: "retry-token" }]);
|
||||
expect(testApi.calls.session).toBeGreaterThan(1);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a blank pairing token with a structured validation error", async () => {
|
||||
const { PrimaryEnvironmentPairingCredentialRequiredError, submitServerAuthCredential } =
|
||||
await import("./environments/primary/auth");
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import {
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
EnvironmentId,
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
ThreadId,
|
||||
type ClientSettings,
|
||||
type DesktopPreviewBridge,
|
||||
} from "@t3tools/contracts";
|
||||
import { act } from "react";
|
||||
import { create, type ReactTestRenderer } from "react-test-renderer";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getClientSettings: vi.fn<() => Promise<ClientSettings | null>>(),
|
||||
setClientSettings: vi.fn<(settings: ClientSettings) => Promise<void>>(),
|
||||
createTab: vi.fn<DesktopPreviewBridge["createTab"]>(),
|
||||
closeTab: vi.fn<DesktopPreviewBridge["closeTab"]>(),
|
||||
registerWebview: vi.fn<DesktopPreviewBridge["registerWebview"]>(),
|
||||
getPreviewConfig: vi.fn<DesktopPreviewBridge["getPreviewConfig"]>(),
|
||||
activeRecordings: new Set<string>(),
|
||||
}));
|
||||
|
||||
vi.mock("~/localApi", () => ({
|
||||
ensureLocalApi: () => ({ persistence: mocks }),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/preview/previewBridge", () => ({
|
||||
previewBridge: {
|
||||
createTab: mocks.createTab,
|
||||
closeTab: mocks.closeTab,
|
||||
registerWebview: mocks.registerWebview,
|
||||
getPreviewConfig: mocks.getPreviewConfig,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/components/preview/usePreviewBridge", () => ({
|
||||
usePreviewBridge: () => undefined,
|
||||
}));
|
||||
|
||||
vi.mock("./browserRecording", () => ({
|
||||
useActiveBrowserRecordingTabIds: () => mocks.activeRecordings,
|
||||
stopBrowserRecording: async () => null,
|
||||
}));
|
||||
|
||||
import {
|
||||
__resetClientSettingsPersistenceForTests,
|
||||
ensureClientSettingsHydrated,
|
||||
} from "~/hooks/useSettings";
|
||||
import { useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
import * as desktopTabLifetime from "./desktopTabLifetime";
|
||||
import { HostedBrowserWebview } from "./HostedBrowserWebview";
|
||||
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
|
||||
function deferred<A>() {
|
||||
let resolve!: (value: A) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const promise = new Promise<A>((resolvePromise, rejectPromise) => {
|
||||
resolve = resolvePromise;
|
||||
reject = rejectPromise;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
__resetClientSettingsPersistenceForTests();
|
||||
useBrowserSurfaceStore.setState({ activityByTabId: {}, byTabId: {} });
|
||||
mocks.getClientSettings.mockReset();
|
||||
mocks.setClientSettings.mockReset().mockResolvedValue(undefined);
|
||||
mocks.createTab.mockReset().mockResolvedValue(undefined);
|
||||
mocks.closeTab.mockReset().mockResolvedValue(undefined);
|
||||
mocks.registerWebview.mockReset().mockResolvedValue(undefined);
|
||||
mocks.getPreviewConfig.mockReset().mockResolvedValue({
|
||||
partition: "persist:t3-preview-work",
|
||||
webPreferences: "contextIsolation=yes",
|
||||
preloadUrl: null,
|
||||
});
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
vi.stubGlobal("window", globalThis);
|
||||
vi.stubGlobal("navigator", { platform: "Linux" });
|
||||
vi.stubGlobal(
|
||||
"requestAnimationFrame",
|
||||
vi.fn(() => 0),
|
||||
);
|
||||
vi.stubGlobal("cancelAnimationFrame", vi.fn());
|
||||
vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useFakeTimers();
|
||||
await act(() => renderer?.unmount());
|
||||
renderer = undefined;
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
vi.useRealTimers();
|
||||
__resetClientSettingsPersistenceForTests();
|
||||
useBrowserSurfaceStore.setState({ activityByTabId: {}, byTabId: {} });
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("HostedBrowserWebview settings hydration", () => {
|
||||
it("starts a retained background tab only after a settings read succeeds on retry", async () => {
|
||||
const firstRead = deferred<ClientSettings | null>();
|
||||
const retryRead = deferred<ClientSettings | null>();
|
||||
const tabCreation = deferred<void>();
|
||||
mocks.getClientSettings
|
||||
.mockReturnValueOnce(firstRead.promise)
|
||||
.mockReturnValueOnce(retryRead.promise);
|
||||
mocks.createTab.mockReturnValueOnce(tabCreation.promise);
|
||||
const acquire = vi.spyOn(desktopTabLifetime, "acquireDesktopTab");
|
||||
const createGuest = vi.fn((_attributes: unknown) =>
|
||||
Object.assign(new EventTarget(), { getWebContentsId: () => 41 }),
|
||||
);
|
||||
const threadRef = {
|
||||
environmentId: EnvironmentId.make("host-settings-retry"),
|
||||
threadId: ThreadId.make("thread-settings-retry"),
|
||||
};
|
||||
const runtimeTabId = "retained-background-tab";
|
||||
useBrowserSurfaceStore.getState().acquireActivity(runtimeTabId);
|
||||
|
||||
await act(() => {
|
||||
renderer = create(
|
||||
<HostedBrowserWebview
|
||||
threadRef={threadRef}
|
||||
tabId="server-tab"
|
||||
runtimeTabId={runtimeTabId}
|
||||
initialUrl="https://example.com"
|
||||
viewport={FILL_PREVIEW_VIEWPORT}
|
||||
pictureInPicture={false}
|
||||
profileId="work"
|
||||
zoomFactor={1.25}
|
||||
/>,
|
||||
{
|
||||
createNodeMock: (element) =>
|
||||
element.type === "webview"
|
||||
? createGuest(element.props)
|
||||
: { scrollLeft: 0, scrollTop: 0, scrollTo: () => undefined },
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
expect(mocks.getClientSettings).toHaveBeenCalledOnce();
|
||||
expect(acquire).not.toHaveBeenCalled();
|
||||
expect(createGuest).not.toHaveBeenCalled();
|
||||
expect(mocks.createTab).not.toHaveBeenCalled();
|
||||
|
||||
const failure = new Error("Saved settings are unavailable");
|
||||
await act(async () => {
|
||||
const hydration = ensureClientSettingsHydrated();
|
||||
firstRead.reject(failure);
|
||||
await expect(hydration).rejects.toBe(failure);
|
||||
});
|
||||
expect(acquire).not.toHaveBeenCalled();
|
||||
expect(createGuest).not.toHaveBeenCalled();
|
||||
expect(mocks.createTab).not.toHaveBeenCalled();
|
||||
|
||||
let retry!: Promise<void>;
|
||||
await act(() => {
|
||||
retry = ensureClientSettingsHydrated();
|
||||
});
|
||||
expect(mocks.getClientSettings).toHaveBeenCalledTimes(2);
|
||||
expect(acquire).not.toHaveBeenCalled();
|
||||
expect(createGuest).not.toHaveBeenCalled();
|
||||
expect(mocks.createTab).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => {
|
||||
retryRead.resolve({
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
browserDefaultZoomFactor: 1.25,
|
||||
browserDefaultAppearance: "dark",
|
||||
browserProfiles: [{ id: "work", name: "Work", kind: "persistent" }],
|
||||
browserDefaultProfileId: "work",
|
||||
});
|
||||
await retry;
|
||||
});
|
||||
|
||||
expect(acquire).toHaveBeenCalledExactlyOnceWith(runtimeTabId);
|
||||
expect(mocks.getPreviewConfig).toHaveBeenCalledExactlyOnceWith(threadRef.environmentId, "work");
|
||||
expect(createGuest).toHaveBeenCalledOnce();
|
||||
expect(createGuest).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
partition: "persist:t3-preview-work",
|
||||
src: "https://example.com",
|
||||
}),
|
||||
);
|
||||
expect(mocks.createTab).toHaveBeenCalledExactlyOnceWith(runtimeTabId, {
|
||||
zoomFactor: 1.25,
|
||||
colorScheme: "dark",
|
||||
});
|
||||
expect(mocks.registerWebview).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => {
|
||||
tabCreation.resolve();
|
||||
await tabCreation.promise;
|
||||
});
|
||||
expect(mocks.registerWebview).toHaveBeenCalledExactlyOnceWith(runtimeTabId, 41);
|
||||
expect(mocks.closeTab).not.toHaveBeenCalled();
|
||||
expect(mocks.setClientSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { previewBridge } from "~/components/preview/previewBridge";
|
||||
import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
|
||||
import { useClientSettingsHydrated } from "~/hooks/useSettings";
|
||||
import { cn, isMacPlatform } from "~/lib/utils";
|
||||
|
||||
import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
@@ -66,6 +67,7 @@ export function HostedBrowserWebview(props: {
|
||||
zoomFactor,
|
||||
profileId,
|
||||
} = props;
|
||||
const clientSettingsHydrated = useClientSettingsHydrated();
|
||||
const config = usePreviewWebviewConfig(threadRef.environmentId, profileId);
|
||||
const [initialSrc] = useState(() => initialUrl ?? "about:blank");
|
||||
const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
|
||||
@@ -94,6 +96,7 @@ export function HostedBrowserWebview(props: {
|
||||
usePreviewBridge({ threadRef, tabId, runtimeTabId });
|
||||
|
||||
useEffect(() => {
|
||||
if (!clientSettingsHydrated) return;
|
||||
crashRecoveryRef.current = INITIAL_WEBVIEW_CRASH_RECOVERY_STATE;
|
||||
const lease = acquireDesktopTab(runtimeTabId);
|
||||
tabLeaseRef.current = lease;
|
||||
@@ -101,7 +104,7 @@ export function HostedBrowserWebview(props: {
|
||||
if (tabLeaseRef.current === lease) tabLeaseRef.current = null;
|
||||
lease.release();
|
||||
};
|
||||
}, [runtimeTabId]);
|
||||
}, [clientSettingsHydrated, runtimeTabId]);
|
||||
|
||||
const [webviewGeneration, setWebviewGeneration] = useState(0);
|
||||
const [recoverySrc, setRecoverySrc] = useState(initialSrc);
|
||||
@@ -118,7 +121,7 @@ export function HostedBrowserWebview(props: {
|
||||
useEffect(() => {
|
||||
const webview = webviewRef.current;
|
||||
const bridge = previewBridge;
|
||||
if (!webview || !config || !bridge) return;
|
||||
if (!clientSettingsHydrated || !webview || !config || !bridge) return;
|
||||
let disposed = false;
|
||||
let recoveryTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
const register = () => {
|
||||
@@ -164,7 +167,7 @@ export function HostedBrowserWebview(props: {
|
||||
webview.removeEventListener("dom-ready", register);
|
||||
webview.removeEventListener("render-process-gone", recoverGuest);
|
||||
};
|
||||
}, [config, initialSrc, runtimeTabId, webviewGeneration]);
|
||||
}, [clientSettingsHydrated, config, initialSrc, runtimeTabId, webviewGeneration]);
|
||||
|
||||
const active = presentation.visible && presentation.rect !== null;
|
||||
const lastRect = presentation.rect;
|
||||
@@ -249,7 +252,7 @@ export function HostedBrowserWebview(props: {
|
||||
wrapper.scrollTo({ left: 0, top: 0 });
|
||||
}, [runtimeTabId, viewport._tag, viewportHeight, viewportWidth]);
|
||||
|
||||
if (!config) return null;
|
||||
if (!clientSettingsHydrated || !config) return null;
|
||||
|
||||
const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive;
|
||||
const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import { DEFAULT_BROWSER_PROFILE_ID, INCOGNITO_BROWSER_PROFILE_ID } from "@t3tools/contracts";
|
||||
|
||||
import { ensureClientSettingsHydrated } from "~/hooks/useSettings";
|
||||
|
||||
const settings = vi.hoisted(() => ({ current: {} as Record<string, unknown> }));
|
||||
|
||||
vi.mock("~/hooks/useSettings", () => ({
|
||||
getClientSettings: () => settings.current,
|
||||
useClientSettings: () => undefined,
|
||||
ensureClientSettingsHydrated: () => Promise.resolve(),
|
||||
ensureClientSettingsHydrated: vi.fn(async () => undefined),
|
||||
}));
|
||||
|
||||
const { getBrowserDefaults } = await import("./browserDefaults");
|
||||
const { getBrowserDefaults, resolveBrowserDefaults } = await import("./browserDefaults");
|
||||
|
||||
const withDefaultProfile = (browserDefaultProfileId: string) => {
|
||||
settings.current = {
|
||||
@@ -41,3 +43,22 @@ describe("getBrowserDefaults profile resolution", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBrowserDefaults", () => {
|
||||
it("rejects failed reads and uses the saved profile after a successful retry", async () => {
|
||||
withDefaultProfile("work");
|
||||
settings.current.browserDefaultZoomFactor = 1.25;
|
||||
settings.current.browserDefaultAppearance = "dark";
|
||||
const failure = new Error("Settings read failed");
|
||||
vi.mocked(ensureClientSettingsHydrated).mockRejectedValueOnce(failure);
|
||||
|
||||
await expect(resolveBrowserDefaults()).rejects.toBe(failure);
|
||||
await expect(resolveBrowserDefaults()).resolves.toMatchObject({
|
||||
viewport: { _tag: "fill" },
|
||||
zoomFactor: 1.25,
|
||||
appearance: "dark",
|
||||
autoShowFloatingPreview: true,
|
||||
profileId: "work",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -79,6 +79,7 @@ export function getBrowserDefaults(): BrowserDefaults {
|
||||
* Opening a preview is asynchronous anyway, and before hydration the snapshot
|
||||
* is the schema defaults rather than the user's — a tab opened in that window
|
||||
* would be born at the wrong viewport, zoom and appearance and never corrected.
|
||||
* Read failures reject so a new tab cannot use the wrong profile or viewport.
|
||||
*/
|
||||
export async function resolveBrowserDefaults(): Promise<BrowserDefaults> {
|
||||
await ensureClientSettingsHydrated();
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type { BrowserLinkTarget } from "@t3tools/contracts";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { resolveLinkTarget } from "./browserLinkTarget";
|
||||
import { ensureClientSettingsHydrated } from "~/hooks/useSettings";
|
||||
|
||||
import { resolveBrowserLinkTargetPreference, resolveLinkTarget } from "./browserLinkTarget";
|
||||
|
||||
const settings = vi.hoisted(() => ({ browserLinkTarget: "system" as BrowserLinkTarget }));
|
||||
|
||||
vi.mock("~/hooks/useSettings", () => ({
|
||||
ensureClientSettingsHydrated: vi.fn(async () => undefined),
|
||||
getClientSettings: () => settings,
|
||||
}));
|
||||
|
||||
const click = { metaKey: false, ctrlKey: false };
|
||||
|
||||
@@ -67,3 +77,17 @@ describe("resolveLinkTarget", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBrowserLinkTargetPreference", () => {
|
||||
it.each(["system", "app"] as const)(
|
||||
"rejects failed reads instead of using the current %s preference",
|
||||
async (preference) => {
|
||||
settings.browserLinkTarget = preference;
|
||||
const failure = new Error("Settings read failed");
|
||||
vi.mocked(ensureClientSettingsHydrated).mockRejectedValueOnce(failure);
|
||||
|
||||
await expect(resolveBrowserLinkTargetPreference()).rejects.toBe(failure);
|
||||
await expect(resolveBrowserLinkTargetPreference()).resolves.toBe(preference);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -55,6 +55,7 @@ export function isWebUrl(url: string): boolean {
|
||||
* hydration the snapshot is the schema default ("system"), so a link clicked
|
||||
* in the first moments after launch would ignore a persisted "app" — opening
|
||||
* is asynchronous anyway, so waiting costs nothing the user can see.
|
||||
* Read failures reject rather than choosing a browser without the saved preference.
|
||||
*/
|
||||
export async function resolveBrowserLinkTargetPreference(): Promise<BrowserLinkTarget> {
|
||||
await ensureClientSettingsHydrated();
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { ensureClientSettingsHydrated } from "~/hooks/useSettings";
|
||||
|
||||
const {
|
||||
clientSettings,
|
||||
events,
|
||||
@@ -241,6 +243,35 @@ describe("browser recording", () => {
|
||||
await stopBrowserRecording("recording-tab");
|
||||
});
|
||||
|
||||
it("clears a failed settings read before retrying recording", async () => {
|
||||
const tabId = "settings-read-failure-tab";
|
||||
const error = new Error("Settings read failed");
|
||||
vi.mocked(ensureClientSettingsHydrated).mockRejectedValueOnce(error);
|
||||
|
||||
await expect(startBrowserRecording(tabId)).rejects.toBe(error);
|
||||
|
||||
expect(readActiveBrowserRecordingTabIds()).toEqual(new Set());
|
||||
expect(useBrowserSurfaceStore.getState().activityByTabId[tabId]).toBeUndefined();
|
||||
expect(animationFrameCount).toBe(0);
|
||||
expect(startScreencast).not.toHaveBeenCalled();
|
||||
expect(stopScreencast).not.toHaveBeenCalled();
|
||||
expect(getDisplayMedia).not.toHaveBeenCalled();
|
||||
expect(FakeMediaRecorder.instances).toHaveLength(0);
|
||||
|
||||
clientSettings.browserRecordingFrameRate = 60;
|
||||
await startBrowserRecording(tabId);
|
||||
|
||||
expect(getDisplayMedia).toHaveBeenCalledWith({
|
||||
audio: false,
|
||||
video: { frameRate: { max: 60 } },
|
||||
});
|
||||
await stopBrowserRecording(tabId);
|
||||
|
||||
expect(startScreencast).toHaveBeenCalledOnce();
|
||||
expect(readActiveBrowserRecordingTabIds()).toEqual(new Set());
|
||||
expect(useBrowserSurfaceStore.getState().activityByTabId[tabId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("stops the native stream when MediaRecorder cleanup fails", async () => {
|
||||
const stopTrack = vi.fn();
|
||||
getDisplayMedia.mockResolvedValueOnce({
|
||||
|
||||
@@ -516,10 +516,12 @@ export async function startBrowserRecording(
|
||||
activeRecordings.set(tabId, recording);
|
||||
publishActiveRecordingTabIds();
|
||||
try {
|
||||
const frameRatePromise = ensureClientSettingsHydrated().then(
|
||||
() => getClientSettings().browserRecordingFrameRate,
|
||||
);
|
||||
const [frameRate] = await Promise.all([frameRatePromise, waitForBrowserRecordingPaint()]);
|
||||
await ensureClientSettingsHydrated().catch((cause: unknown) => {
|
||||
clearActiveRecording(recording);
|
||||
throw cause;
|
||||
});
|
||||
const frameRate = getClientSettings().browserRecordingFrameRate;
|
||||
await waitForBrowserRecordingPaint();
|
||||
const throwIfStartupCancelled = async (): Promise<void> => {
|
||||
// Once a grant starts, a stop lets startup finish so the caller receives an artifact.
|
||||
// Only a contended start can be cancelled before it reaches native capture.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
DEFAULT_PREVIEW_APPEARANCE,
|
||||
DEFAULT_PREVIEW_ZOOM_FACTOR,
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
EnvironmentId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -21,8 +22,10 @@ vi.mock("./browserRecording", () => ({
|
||||
}));
|
||||
|
||||
import { acquireDesktopTab } from "./desktopTabLifetime";
|
||||
import * as browserDefaults from "./browserDefaults";
|
||||
import { __setClientSettingsForTests } from "~/hooks/useSettings";
|
||||
|
||||
/** Client settings are unset in tests, so creation carries the schema defaults. */
|
||||
/** Tests load default settings unless they select other preferences. */
|
||||
const DEFAULT_TAB_STATE = {
|
||||
zoomFactor: DEFAULT_PREVIEW_ZOOM_FACTOR,
|
||||
colorScheme: DEFAULT_PREVIEW_APPEARANCE,
|
||||
@@ -31,6 +34,7 @@ import { previewRuntimeTabId } from "./previewRuntimeTabId";
|
||||
|
||||
describe("desktopTabLifetime", () => {
|
||||
beforeEach(() => {
|
||||
__setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
|
||||
closeTab.mockClear();
|
||||
createTab.mockClear();
|
||||
stopBrowserRecording.mockClear();
|
||||
@@ -40,6 +44,35 @@ describe("desktopTabLifetime", () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("does not create a desktop tab after a failed settings read and permits a later retry", async () => {
|
||||
vi.useFakeTimers();
|
||||
const failure = new Error("Settings read failed");
|
||||
vi.spyOn(browserDefaults, "resolveBrowserDefaults").mockRejectedValueOnce(failure);
|
||||
const failed = acquireDesktopTab("tab_settings_retry");
|
||||
|
||||
await expect(failed.ready).rejects.toBe(failure);
|
||||
expect(createTab).not.toHaveBeenCalled();
|
||||
failed.release();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
__setClientSettingsForTests({
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
browserDefaultZoomFactor: 1.25,
|
||||
browserDefaultAppearance: "dark",
|
||||
});
|
||||
createTab.mockResolvedValueOnce(undefined);
|
||||
const retry = acquireDesktopTab("tab_settings_retry");
|
||||
await retry.ready;
|
||||
|
||||
expect(createTab).toHaveBeenCalledExactlyOnceWith("tab_settings_retry", {
|
||||
zoomFactor: 1.25,
|
||||
colorScheme: "dark",
|
||||
});
|
||||
retry.release();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
|
||||
it("shares tab creation readiness across concurrent leases", async () => {
|
||||
|
||||
@@ -38,6 +38,14 @@ export class BrowserPreviewUnavailableError extends Data.TaggedError(
|
||||
readonly message: string;
|
||||
}> {}
|
||||
|
||||
export class BrowserSettingsReadError extends Data.TaggedError("BrowserSettingsReadError")<{
|
||||
readonly cause: unknown;
|
||||
}> {
|
||||
override get message(): string {
|
||||
return "Saved browser settings could not be loaded.";
|
||||
}
|
||||
}
|
||||
|
||||
export type OpenPreviewMutation<E = unknown> = (input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly input: PreviewOpenInput;
|
||||
@@ -47,8 +55,13 @@ export async function openUrlInPreview<E>(input: {
|
||||
readonly threadRef: ScopedThreadRef;
|
||||
readonly url: string;
|
||||
readonly openPreview: OpenPreviewMutation<E>;
|
||||
}): Promise<AtomCommandResult<void, E>> {
|
||||
const defaults = await resolveBrowserDefaults();
|
||||
}): Promise<AtomCommandResult<void, E | BrowserSettingsReadError>> {
|
||||
const defaults = await resolveBrowserDefaults().catch(
|
||||
(cause: unknown) => new BrowserSettingsReadError({ cause }),
|
||||
);
|
||||
if (defaults instanceof BrowserSettingsReadError) {
|
||||
return AsyncResult.failure(Cause.fail(defaults));
|
||||
}
|
||||
const result = await input.openPreview({
|
||||
environmentId: input.threadRef.environmentId,
|
||||
input: {
|
||||
@@ -82,7 +95,12 @@ export async function openFileInPreview<AssetError, PreviewError>(input: {
|
||||
readonly input: { readonly resource: AssetResource };
|
||||
}) => Promise<AtomCommandResult<AssetCreateUrlResult, AssetError>>;
|
||||
readonly openPreview: OpenPreviewMutation<PreviewError>;
|
||||
}): Promise<AtomCommandResult<void, AssetError | PreviewError | BrowserPreviewUnavailableError>> {
|
||||
}): Promise<
|
||||
AtomCommandResult<
|
||||
void,
|
||||
AssetError | PreviewError | BrowserPreviewUnavailableError | BrowserSettingsReadError
|
||||
>
|
||||
> {
|
||||
if (!isPreviewSupportedInRuntime()) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { recordVisitForThread } from "~/browserHistoryStore";
|
||||
@@ -12,7 +15,7 @@ import {
|
||||
resolveBrowserLinkTargetPreference,
|
||||
resolveLinkTarget,
|
||||
} from "./browserLinkTarget";
|
||||
import { openUrlInPreview } from "./openFileInPreview";
|
||||
import { BrowserSettingsReadError, openUrlInPreview } from "./openFileInPreview";
|
||||
|
||||
const NO_MODIFIER = { metaKey: false, ctrlKey: false } as const;
|
||||
|
||||
@@ -24,8 +27,8 @@ const NO_MODIFIER = { metaKey: false, ctrlKey: false } as const;
|
||||
*
|
||||
* An in-app open that fails falls back to the system browser rather than
|
||||
* dropping the click: the user asked for the link, and the setting only says
|
||||
* where it should go first. The returned promise rejects only when that
|
||||
* fallback fails too, the same way `shell.openExternal` does.
|
||||
* where it should go first. Failed settings reads reject without opening a
|
||||
* browser. The promise also rejects if the system-browser fallback fails.
|
||||
*/
|
||||
export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): (
|
||||
url: string,
|
||||
@@ -52,6 +55,8 @@ export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): (
|
||||
recordVisitForThread(targetThreadRef, url);
|
||||
return;
|
||||
}
|
||||
const failure = squashAtomCommandFailure(result);
|
||||
if (failure instanceof BrowserSettingsReadError) throw failure;
|
||||
console.error(result.cause);
|
||||
}
|
||||
const api = readLocalApi();
|
||||
|
||||
@@ -52,22 +52,45 @@ describe("clientPersistenceStorage", () => {
|
||||
expect(readBrowserClientSettings()).toEqual(settings);
|
||||
});
|
||||
|
||||
it("reports structured decode failures while preserving the fallback", async () => {
|
||||
it.each(["not-json", '{"wordWrap":"invalid"}'])(
|
||||
"does not treat invalid saved settings as absent: %s",
|
||||
async (value) => {
|
||||
const testWindow = getTestWindow();
|
||||
testWindow.localStorage.setItem("t3code:client-settings:v1", value);
|
||||
const { readBrowserClientSettings } = await import("./clientPersistenceStorage");
|
||||
|
||||
expect(() => readBrowserClientSettings()).toThrow(
|
||||
expect.objectContaining({
|
||||
_tag: "LocalStorageOperationError",
|
||||
operation: "decode",
|
||||
storageKey: "t3code:client-settings:v1",
|
||||
}),
|
||||
);
|
||||
expect(testWindow.localStorage.getItem("t3code:client-settings:v1")).toBe(value);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves saved settings across a transient read failure", async () => {
|
||||
const testWindow = getTestWindow();
|
||||
testWindow.localStorage.setItem("t3code:client-settings:v1", "not-json");
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
const settings = { ...DEFAULT_CLIENT_SETTINGS, timestampFormat: "12-hour" as const };
|
||||
testWindow.localStorage.setItem("t3code:client-settings:v1", JSON.stringify(settings));
|
||||
const write = vi.spyOn(testWindow.localStorage, "setItem");
|
||||
const failure = new Error("storage unavailable");
|
||||
vi.spyOn(testWindow.localStorage, "getItem").mockImplementationOnce(() => {
|
||||
throw failure;
|
||||
});
|
||||
const { readBrowserClientSettings } = await import("./clientPersistenceStorage");
|
||||
|
||||
expect(readBrowserClientSettings()).toBeNull();
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
"Could not read persisted client settings.",
|
||||
expect(() => readBrowserClientSettings()).toThrow(
|
||||
expect.objectContaining({
|
||||
_tag: "LocalStorageOperationError",
|
||||
operation: "decode",
|
||||
operation: "read",
|
||||
storageKey: "t3code:client-settings:v1",
|
||||
cause: expect.anything(),
|
||||
cause: failure,
|
||||
}),
|
||||
);
|
||||
expect(readBrowserClientSettings()).toEqual(settings);
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("defaults word wrap on and discards obsolete wrapping preferences", async () => {
|
||||
|
||||
@@ -13,12 +13,7 @@ export function readBrowserClientSettings(): ClientSettings | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return getLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, ClientSettingsSchema);
|
||||
} catch (error) {
|
||||
console.error("Could not read persisted client settings.", error);
|
||||
return null;
|
||||
}
|
||||
return getLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, ClientSettingsSchema);
|
||||
}
|
||||
|
||||
export function writeBrowserClientSettings(settings: ClientSettings): void {
|
||||
|
||||
@@ -176,6 +176,7 @@ import {
|
||||
openFileInPreview,
|
||||
openUrlInPreview,
|
||||
BrowserPreviewUnavailableError,
|
||||
BrowserSettingsReadError,
|
||||
} from "../browser/openFileInPreview";
|
||||
import { resolveLinkTarget } from "../browser/browserLinkTarget";
|
||||
import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview";
|
||||
@@ -2357,6 +2358,18 @@ function useChatMarkdownState({
|
||||
}
|
||||
return openUrlInPreview({ threadRef, url, openPreview }).then((result) => {
|
||||
if (result._tag === "Success") recordVisitForThread(threadRef, url);
|
||||
else if (!isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
if (error instanceof BrowserSettingsReadError) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open link in browser",
|
||||
description: error.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
});
|
||||
},
|
||||
@@ -2789,14 +2802,14 @@ const CHAT_MARKDOWN_COMPONENTS = {
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// The click was taken from the shell, so an in-app open that fails
|
||||
// hands the link to the system browser instead of dropping it.
|
||||
// Keep the link here if saved settings could not be read.
|
||||
void openExternalLinkInPreview(href).then((result) => {
|
||||
if (result._tag === "Success" || isAtomCommandInterrupted(result)) return;
|
||||
reportMarkdownActionFailure(
|
||||
{ operation: "open-link-in-preview", target: href },
|
||||
result.cause,
|
||||
);
|
||||
if (squashAtomCommandFailure(result) instanceof BrowserSettingsReadError) return;
|
||||
void readLocalApi()?.shell.openExternal(href);
|
||||
});
|
||||
}}
|
||||
|
||||
@@ -162,6 +162,7 @@ import {
|
||||
useThreadPreviewState,
|
||||
} from "../previewStateStore";
|
||||
import { previewRuntimeTabId } from "../browser/previewRuntimeTabId";
|
||||
import { BrowserSettingsReadError } from "../browser/openFileInPreview";
|
||||
import { addBrowserSurface } from "./preview/addBrowserSurface";
|
||||
import { closePreviewSession } from "./preview/closePreviewSession";
|
||||
import { ThreadPreviewMiniPlayer } from "./preview/ThreadPreviewMiniPlayer";
|
||||
@@ -3718,6 +3719,18 @@ export default function ChatView(props: ChatViewProps) {
|
||||
threadRef: activeThreadRef,
|
||||
openPreview,
|
||||
...(profileId === undefined ? {} : { profileId }),
|
||||
}).then((result) => {
|
||||
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
|
||||
const error = squashAtomCommandFailure(result);
|
||||
if (error instanceof BrowserSettingsReadError) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open browser",
|
||||
description: error.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
[activeThreadRef, openPreview],
|
||||
|
||||
@@ -1,11 +1,98 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
shouldClearTerminalSelectionAction,
|
||||
shouldHandleTerminalExit,
|
||||
terminalContextMenuItems,
|
||||
terminalSelectionLineRange,
|
||||
terminalSelectionMenuItems,
|
||||
terminalThemeFromApp,
|
||||
} from "./ThreadTerminalDrawer";
|
||||
|
||||
describe("terminal selection menus", () => {
|
||||
it("omits Add to chat when the terminal has no chat target", () => {
|
||||
expect(terminalSelectionMenuItems().map(({ id }) => id)).toEqual(["add-to-chat", "copy"]);
|
||||
expect(terminalContextMenuItems({ hasSelection: true }).map(({ id }) => id)).toEqual([
|
||||
"add-to-chat",
|
||||
"copy",
|
||||
"paste",
|
||||
]);
|
||||
|
||||
expect(terminalSelectionMenuItems({ canAddToChat: false }).map(({ id }) => id)).toEqual([
|
||||
"copy",
|
||||
]);
|
||||
expect(
|
||||
terminalContextMenuItems({ hasSelection: true, canAddToChat: false }).map(({ id }) => id),
|
||||
).toEqual(["copy", "paste"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminalThemeFromApp", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("uses terminal colors inherited by the mount instead of a light document theme", () => {
|
||||
const root = { classList: { contains: () => false } };
|
||||
const body = {};
|
||||
const drawer = {};
|
||||
let canvasColor = "#000";
|
||||
const colors: Record<string, [number, number, number, number]> = {
|
||||
"#000": [0, 0, 0, 255],
|
||||
"#fff": [255, 255, 255, 255],
|
||||
"#ddd": [221, 221, 221, 255],
|
||||
"#111": [17, 17, 17, 255],
|
||||
};
|
||||
|
||||
vi.stubGlobal("document", {
|
||||
documentElement: root,
|
||||
body,
|
||||
querySelector: () => drawer,
|
||||
createElement: () => ({
|
||||
width: 0,
|
||||
height: 0,
|
||||
getContext: () => ({
|
||||
clearRect: () => undefined,
|
||||
fillRect: () => undefined,
|
||||
get fillStyle() {
|
||||
return canvasColor;
|
||||
},
|
||||
set fillStyle(value: string) {
|
||||
canvasColor = value;
|
||||
},
|
||||
getImageData: () => ({ data: colors[canvasColor] ?? [0, 0, 0, 0] }),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
vi.stubGlobal("getComputedStyle", (element: object) => {
|
||||
const local = element === drawer;
|
||||
const values = local
|
||||
? {
|
||||
"--terminal-background": "#000",
|
||||
"--terminal-foreground": "#fff",
|
||||
"--terminal-cursor": "#ddd",
|
||||
"--terminal-selection-background": "rgba(255, 255, 255, 0.2)",
|
||||
}
|
||||
: {
|
||||
"--terminal-background": "#fff",
|
||||
"--terminal-foreground": "#111",
|
||||
};
|
||||
return {
|
||||
backgroundColor: local ? "#000" : "#fff",
|
||||
color: local ? "#fff" : "#111",
|
||||
colorScheme: local ? "dark" : "light",
|
||||
getPropertyValue: (name: string) => values[name as keyof typeof values] ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
const theme = terminalThemeFromApp();
|
||||
|
||||
expect(theme.background).toEqual({ r: 0, g: 0, b: 0 });
|
||||
expect(theme.foreground).toEqual({ r: 255, g: 255, b: 255 });
|
||||
expect(theme.cursor).toEqual({ r: 221, g: 221, b: 221 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminal selection actions", () => {
|
||||
it("clears a pending or currently owned menu when the selection disappears", () => {
|
||||
expect(
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import {
|
||||
type ContextMenuItem,
|
||||
type ProviderInstanceId,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ScopedThreadRef,
|
||||
type ThreadId,
|
||||
@@ -41,6 +42,7 @@ import {
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button";
|
||||
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
|
||||
import { readTextFromClipboard, writeTextToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { type TerminalContextSelection } from "~/lib/terminalContext";
|
||||
@@ -172,16 +174,23 @@ function terminalFontOptions(family: string, size: number): { family?: string; s
|
||||
}
|
||||
|
||||
export function terminalThemeFromApp(mountElement?: HTMLElement | null): GhosttyTheme {
|
||||
const isDark = document.documentElement.classList.contains("dark");
|
||||
const fallbackBackground = isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)";
|
||||
const fallbackForeground = isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)";
|
||||
const drawerSurface =
|
||||
mountElement?.closest(".thread-terminal-drawer") ??
|
||||
document.querySelector(".thread-terminal-drawer") ??
|
||||
document.body;
|
||||
const drawerStyles = getComputedStyle(drawerSurface);
|
||||
const themeStyles = mountElement ? getComputedStyle(mountElement) : drawerStyles;
|
||||
const colorScheme = themeStyles.colorScheme;
|
||||
const isDark =
|
||||
colorScheme === "dark"
|
||||
? true
|
||||
: colorScheme === "light"
|
||||
? false
|
||||
: document.documentElement.classList.contains("dark");
|
||||
const fallbackBackground = isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)";
|
||||
const fallbackForeground = isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)";
|
||||
const bodyStyles = getComputedStyle(document.body);
|
||||
const themeStyles = getComputedStyle(document.documentElement);
|
||||
const rootThemeStyles = getComputedStyle(document.documentElement);
|
||||
const background = normalizeComputedColor(
|
||||
drawerStyles.backgroundColor,
|
||||
normalizeComputedColor(bodyStyles.backgroundColor, fallbackBackground),
|
||||
@@ -190,8 +199,16 @@ export function terminalThemeFromApp(mountElement?: HTMLElement | null): Ghostty
|
||||
drawerStyles.color,
|
||||
normalizeComputedColor(bodyStyles.color, fallbackForeground),
|
||||
);
|
||||
const terminalBackground = readThemeColor(themeStyles, "--terminal-background", background);
|
||||
const terminalForeground = readThemeColor(themeStyles, "--terminal-foreground", foreground);
|
||||
const terminalBackground = readThemeColor(
|
||||
themeStyles,
|
||||
"--terminal-background",
|
||||
readThemeColor(rootThemeStyles, "--terminal-background", background),
|
||||
);
|
||||
const terminalForeground = readThemeColor(
|
||||
themeStyles,
|
||||
"--terminal-foreground",
|
||||
readThemeColor(rootThemeStyles, "--terminal-foreground", foreground),
|
||||
);
|
||||
const terminalCursor = readThemeColor(
|
||||
themeStyles,
|
||||
"--terminal-cursor",
|
||||
@@ -232,10 +249,14 @@ export function terminalSelectionLineRange(position: {
|
||||
|
||||
export type TerminalContextMenuAction = "add-to-chat" | "copy" | "paste";
|
||||
|
||||
/** Post-selection popup: just the two selection actions, always enabled. */
|
||||
export function terminalSelectionMenuItems(): ContextMenuItem<"add-to-chat" | "copy">[] {
|
||||
/** Post-selection popup: available selection actions, always enabled. */
|
||||
export function terminalSelectionMenuItems(options?: {
|
||||
canAddToChat?: boolean;
|
||||
}): ContextMenuItem<"add-to-chat" | "copy">[] {
|
||||
return [
|
||||
{ id: "add-to-chat", label: "Add to chat" },
|
||||
...(options?.canAddToChat === false
|
||||
? []
|
||||
: ([{ id: "add-to-chat", label: "Add to chat" }] satisfies ContextMenuItem<"add-to-chat">[])),
|
||||
{ id: "copy", label: "Copy" },
|
||||
];
|
||||
}
|
||||
@@ -248,11 +269,13 @@ export function terminalSelectionMenuItems(): ContextMenuItem<"add-to-chat" | "c
|
||||
*/
|
||||
export function terminalContextMenuItems(options: {
|
||||
hasSelection: boolean;
|
||||
canAddToChat?: boolean;
|
||||
}): ContextMenuItem<TerminalContextMenuAction>[] {
|
||||
const { hasSelection, canAddToChat = true } = options;
|
||||
return [
|
||||
...terminalSelectionMenuItems().map((item) => ({
|
||||
...terminalSelectionMenuItems({ canAddToChat }).map((item) => ({
|
||||
...item,
|
||||
disabled: !options.hasSelection,
|
||||
disabled: !hasSelection,
|
||||
})),
|
||||
{ id: "paste", label: "Paste" },
|
||||
];
|
||||
@@ -292,8 +315,9 @@ interface TerminalViewportProps {
|
||||
cwd: string;
|
||||
worktreePath?: string | null;
|
||||
runtimeEnv?: Record<string, string>;
|
||||
providerInstanceId?: ProviderInstanceId;
|
||||
onSessionExited: () => void;
|
||||
onAddTerminalContext: (selection: TerminalContextSelection) => void;
|
||||
onAddTerminalContext?: (selection: TerminalContextSelection) => void;
|
||||
focusRequestId: number;
|
||||
autoFocus: boolean;
|
||||
visible: boolean;
|
||||
@@ -317,6 +341,7 @@ export function TerminalViewport({
|
||||
cwd,
|
||||
worktreePath,
|
||||
runtimeEnv,
|
||||
providerInstanceId,
|
||||
onSessionExited,
|
||||
onAddTerminalContext,
|
||||
focusRequestId,
|
||||
@@ -357,8 +382,9 @@ export function TerminalViewport({
|
||||
onSessionExited();
|
||||
});
|
||||
const handleAddTerminalContext = useEffectEvent((selection: TerminalContextSelection) => {
|
||||
onAddTerminalContext(selection);
|
||||
onAddTerminalContext?.(selection);
|
||||
});
|
||||
const canAddSelectionToChat = useEffectEvent(() => onAddTerminalContext !== undefined);
|
||||
const readTerminalLabel = useEffectEvent(() => terminalLabel);
|
||||
const terminalFontFamily = useClientSettings((settings) =>
|
||||
resolveTerminalFontPreference({
|
||||
@@ -383,6 +409,7 @@ export function TerminalViewport({
|
||||
cwd,
|
||||
...(worktreePath !== undefined ? { worktreePath } : {}),
|
||||
...(runtimeEnv ? { env: runtimeEnv } : {}),
|
||||
...(providerInstanceId ? { providerInstanceId } : {}),
|
||||
},
|
||||
});
|
||||
const writeTerminal = useEffectEvent((data: string) =>
|
||||
@@ -635,7 +662,10 @@ export function TerminalViewport({
|
||||
let clicked: TerminalContextMenuAction | null;
|
||||
try {
|
||||
clicked = await localApi.contextMenu.show(
|
||||
terminalContextMenuItems({ hasSelection: selectionAction !== null }),
|
||||
terminalContextMenuItems({
|
||||
hasSelection: selectionAction !== null,
|
||||
canAddToChat: canAddSelectionToChat(),
|
||||
}),
|
||||
{ x: event.clientX, y: event.clientY },
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -648,7 +678,9 @@ export function TerminalViewport({
|
||||
}
|
||||
switch (clicked) {
|
||||
case "add-to-chat":
|
||||
if (selectionAction) addSelectionToChat(selectionAction.selection);
|
||||
if (selectionAction && canAddSelectionToChat()) {
|
||||
addSelectionToChat(selectionAction.selection);
|
||||
}
|
||||
return;
|
||||
case "copy":
|
||||
if (selectionAction) await copySelection(selectionAction.clipboardText, requestId);
|
||||
@@ -675,7 +707,10 @@ export function TerminalViewport({
|
||||
const requestId = ++selectionActionRequestIdRef.current;
|
||||
openSelectionMenuRequestIdRef.current = requestId;
|
||||
const clicked = await localApi.contextMenu
|
||||
.show(terminalSelectionMenuItems(), nextAction.position)
|
||||
.show(
|
||||
terminalSelectionMenuItems({ canAddToChat: canAddSelectionToChat() }),
|
||||
nextAction.position,
|
||||
)
|
||||
.finally(() => {
|
||||
if (openSelectionMenuRequestIdRef.current === requestId) {
|
||||
openSelectionMenuRequestIdRef.current = null;
|
||||
@@ -686,7 +721,7 @@ export function TerminalViewport({
|
||||
}
|
||||
switch (clicked) {
|
||||
case "add-to-chat":
|
||||
addSelectionToChat(nextAction.selection);
|
||||
if (canAddSelectionToChat()) addSelectionToChat(nextAction.selection);
|
||||
return;
|
||||
case "copy":
|
||||
await copySelection(nextAction.clipboardText, requestId);
|
||||
@@ -768,6 +803,14 @@ export function TerminalViewport({
|
||||
threadRef,
|
||||
openPreview,
|
||||
fallbackToBrowser,
|
||||
}).catch((error: unknown) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open link",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import type { Discovery } from "@t3tools/client-runtime/relay";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { act, type ButtonHTMLAttributes } from "react";
|
||||
import { create, type ReactTestRenderer } from "react-test-renderer";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
type DiscoveredEnvironments = Discovery.RelayEnvironmentDiscoveryState["environments"];
|
||||
|
||||
const discovery = vi.hoisted(() => ({
|
||||
state: null as Discovery.RelayEnvironmentDiscoveryState | null,
|
||||
listeners: new Set<() => void>(),
|
||||
refreshCommand: Symbol("refresh"),
|
||||
registerCommand: Symbol("register"),
|
||||
refresh: vi.fn<() => Promise<AtomCommandResult<void, never>>>(),
|
||||
register: vi.fn(),
|
||||
listEnvironments: vi.fn<() => Promise<DiscoveredEnvironments>>(),
|
||||
}));
|
||||
|
||||
vi.mock("~/state/relay", () => ({
|
||||
relayEnvironmentDiscovery: { refresh: discovery.refreshCommand },
|
||||
}));
|
||||
vi.mock("~/connection/catalog", () => ({
|
||||
environmentCatalog: { register: discovery.registerCommand },
|
||||
}));
|
||||
vi.mock("~/state/use-atom-command", () => ({
|
||||
useAtomCommand: (command: unknown) =>
|
||||
command === discovery.refreshCommand ? discovery.refresh : discovery.register,
|
||||
}));
|
||||
vi.mock("~/state/environments", async () => {
|
||||
const { useSyncExternalStore } = await import("react");
|
||||
const subscribe = (listener: () => void) => {
|
||||
discovery.listeners.add(listener);
|
||||
return () => discovery.listeners.delete(listener);
|
||||
};
|
||||
const read = () => {
|
||||
if (discovery.state === null) throw new Error("Discovery fixture is not initialized");
|
||||
return discovery.state;
|
||||
};
|
||||
return { useRelayEnvironmentDiscovery: () => useSyncExternalStore(subscribe, read, read) };
|
||||
});
|
||||
vi.mock("../ConnectionStatusDot", () => ({ ConnectionStatusDot: () => null }));
|
||||
vi.mock("../ui/button", () => ({
|
||||
Button: ({ children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (
|
||||
<button {...props}>{children}</button>
|
||||
),
|
||||
}));
|
||||
vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
|
||||
|
||||
import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
|
||||
|
||||
const newMachineId = EnvironmentId.make("new-computer");
|
||||
const linkedMachines: DiscoveredEnvironments = new Map([
|
||||
[
|
||||
newMachineId,
|
||||
{
|
||||
environment: {
|
||||
environmentId: newMachineId,
|
||||
label: "Work laptop",
|
||||
endpoint: {
|
||||
httpBaseUrl: "https://relay.example.test",
|
||||
wsBaseUrl: "wss://relay.example.test/ws",
|
||||
providerKind: "manual",
|
||||
},
|
||||
linkedAt: "2026-09-05T12:00:00.000Z",
|
||||
},
|
||||
availability: "online",
|
||||
status: Option.none(),
|
||||
error: Option.none(),
|
||||
},
|
||||
],
|
||||
]);
|
||||
|
||||
let renderer: ReactTestRenderer | null;
|
||||
let page: EventTarget & { visibilityState: DocumentVisibilityState };
|
||||
let browserWindow: EventTarget;
|
||||
|
||||
function publish(state: Discovery.RelayEnvironmentDiscoveryState) {
|
||||
discovery.state = state;
|
||||
for (const listener of discovery.listeners) listener();
|
||||
}
|
||||
|
||||
async function mount(refreshWhileEmpty = true) {
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
<CloudEnvironmentConnectRows
|
||||
primaryEnvironmentId={null}
|
||||
savedEnvironments={[]}
|
||||
showSavedEnvironments
|
||||
refreshWhileEmpty={refreshWhileEmpty}
|
||||
empty={<p>Waiting for your computer to connect.</p>}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function advance(milliseconds: number) {
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(milliseconds);
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
page = Object.assign(new EventTarget(), { visibilityState: "visible" as const });
|
||||
browserWindow = new EventTarget();
|
||||
vi.stubGlobal("document", page);
|
||||
vi.stubGlobal("window", browserWindow);
|
||||
renderer = null;
|
||||
discovery.listeners.clear();
|
||||
discovery.state = {
|
||||
environments: new Map(),
|
||||
refreshing: false,
|
||||
offline: false,
|
||||
error: Option.none(),
|
||||
};
|
||||
discovery.listEnvironments.mockReset().mockResolvedValue(new Map());
|
||||
discovery.refresh.mockReset().mockImplementation(async () => {
|
||||
publish({ environments: new Map(), refreshing: true, offline: false, error: Option.none() });
|
||||
const environments = await discovery.listEnvironments();
|
||||
publish({ environments, refreshing: false, offline: false, error: Option.none() });
|
||||
return AsyncResult.success(undefined);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(async () => renderer?.unmount());
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("cloud onboarding discovery", () => {
|
||||
it("shows a newly linked computer without remounting and stops polling once found", async () => {
|
||||
discovery.listEnvironments
|
||||
.mockResolvedValueOnce(new Map())
|
||||
.mockResolvedValueOnce(linkedMachines);
|
||||
await mount();
|
||||
expect(renderer!.root.findByType("p").children).toEqual([
|
||||
"Waiting for your computer to connect.",
|
||||
]);
|
||||
|
||||
await advance(5_000);
|
||||
|
||||
expect(renderer!.root.findAllByType("p").map((node) => node.children)).toContainEqual([
|
||||
"Work laptop",
|
||||
]);
|
||||
expect(renderer!.root.findByType("button").children).toEqual(["Connect"]);
|
||||
await advance(30_000);
|
||||
expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("waits while hidden and refreshes immediately when visible again", async () => {
|
||||
page.visibilityState = "hidden";
|
||||
await mount();
|
||||
await advance(30_000);
|
||||
expect(discovery.listEnvironments).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => {
|
||||
page.visibilityState = "visible";
|
||||
page.dispatchEvent(new Event("visibilitychange"));
|
||||
});
|
||||
expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
|
||||
|
||||
page.visibilityState = "hidden";
|
||||
page.dispatchEvent(new Event("visibilitychange"));
|
||||
browserWindow.dispatchEvent(new Event("focus"));
|
||||
await advance(30_000);
|
||||
expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not overlap a slow refresh or restart polling after unmount", async () => {
|
||||
let resolveRefresh!: (environments: DiscoveredEnvironments) => void;
|
||||
const pending = new Promise<DiscoveredEnvironments>((resolve) => {
|
||||
resolveRefresh = resolve;
|
||||
});
|
||||
discovery.listEnvironments.mockResolvedValueOnce(new Map()).mockReturnValueOnce(pending);
|
||||
await mount();
|
||||
await advance(5_000);
|
||||
expect(renderer!.root.findByType("p").children).toEqual([
|
||||
"Waiting for your computer to connect.",
|
||||
]);
|
||||
|
||||
browserWindow.dispatchEvent(new Event("focus"));
|
||||
page.dispatchEvent(new Event("visibilitychange"));
|
||||
await advance(30_000);
|
||||
expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
|
||||
|
||||
await act(async () => renderer!.unmount());
|
||||
renderer = null;
|
||||
await act(async () => resolveRefresh(new Map()));
|
||||
await advance(30_000);
|
||||
expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("pauses while offline and resumes when discovery is online", async () => {
|
||||
await mount();
|
||||
await act(async () => publish({ ...discovery.state!, offline: true }));
|
||||
await advance(30_000);
|
||||
expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
|
||||
|
||||
await act(async () => publish({ ...discovery.state!, offline: false }));
|
||||
await advance(5_000);
|
||||
expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not add polling to other cloud lists", async () => {
|
||||
await mount(false);
|
||||
await advance(30_000);
|
||||
expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
|
||||
import * as Option from "effect/Option";
|
||||
import { type ReactNode, useCallback, useEffect, useState } from "react";
|
||||
import { type ReactNode, useCallback, useEffect, useEffectEvent, useState } from "react";
|
||||
|
||||
import { environmentCatalog } from "~/connection/catalog";
|
||||
import { cn } from "~/lib/utils";
|
||||
@@ -25,6 +25,8 @@ import { Skeleton } from "../ui/skeleton";
|
||||
import { toastManager } from "../ui/toast";
|
||||
import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnectionPresentation";
|
||||
|
||||
const EMPTY_DISCOVERY_REFRESH_INTERVAL_MS = 5_000;
|
||||
|
||||
export interface SavedCloudEnvironmentConnection {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly connection: EnvironmentConnectionPresentation;
|
||||
@@ -55,11 +57,13 @@ export function CloudEnvironmentConnectRows({
|
||||
primaryEnvironmentId,
|
||||
savedEnvironments,
|
||||
showSavedEnvironments = false,
|
||||
refreshWhileEmpty = false,
|
||||
empty = null,
|
||||
}: {
|
||||
readonly primaryEnvironmentId: EnvironmentId | null;
|
||||
readonly savedEnvironments: ReadonlyArray<SavedCloudEnvironmentConnection>;
|
||||
readonly showSavedEnvironments?: boolean;
|
||||
readonly refreshWhileEmpty?: boolean;
|
||||
readonly empty?: ReactNode;
|
||||
}) {
|
||||
const environmentsState = useRelayEnvironmentDiscovery();
|
||||
@@ -69,6 +73,10 @@ export function CloudEnvironmentConnectRows({
|
||||
const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const refreshDiscoveryWhenIdle = useEffectEvent(async () => {
|
||||
if (environmentsState.refreshing || environmentsState.offline) return;
|
||||
await refreshRelayEnvironments();
|
||||
});
|
||||
const connectRelayEnvironment = useCallback(
|
||||
(environment: RelayClientEnvironmentRecord) =>
|
||||
registerEnvironment(
|
||||
@@ -89,8 +97,10 @@ export function CloudEnvironmentConnectRows({
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshRelayEnvironments();
|
||||
}, [refreshRelayEnvironments]);
|
||||
if (!refreshWhileEmpty || document.visibilityState === "visible") {
|
||||
void refreshRelayEnvironments();
|
||||
}
|
||||
}, [refreshRelayEnvironments, refreshWhileEmpty]);
|
||||
|
||||
const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {
|
||||
setConnectingEnvironmentId(environment.environmentId);
|
||||
@@ -132,10 +142,54 @@ export function CloudEnvironmentConnectRows({
|
||||
environment.environmentId !== primaryEnvironmentId &&
|
||||
(showSavedEnvironments || !savedById.has(environment.environmentId)),
|
||||
);
|
||||
// Discovery clears its list on refresh, so poll only until a machine appears.
|
||||
const shouldRefreshWhileEmpty =
|
||||
refreshWhileEmpty && visibleEnvironments.length === 0 && !environmentsState.offline;
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldRefreshWhileEmpty) return;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let disposed = false;
|
||||
let pending = false;
|
||||
const visible = () => document.visibilityState === "visible";
|
||||
const schedule = () => {
|
||||
clearTimeout(timer);
|
||||
if (!disposed && visible()) {
|
||||
timer = setTimeout(() => void refresh(), EMPTY_DISCOVERY_REFRESH_INTERVAL_MS);
|
||||
}
|
||||
};
|
||||
const refresh = async () => {
|
||||
if (disposed || pending || !visible()) return;
|
||||
clearTimeout(timer);
|
||||
pending = true;
|
||||
try {
|
||||
await refreshDiscoveryWhenIdle();
|
||||
} finally {
|
||||
pending = false;
|
||||
schedule();
|
||||
}
|
||||
};
|
||||
const onFocus = () => void refresh();
|
||||
const onVisibilityChange = () => {
|
||||
clearTimeout(timer);
|
||||
if (visible()) void refresh();
|
||||
};
|
||||
|
||||
schedule();
|
||||
window.addEventListener("focus", onFocus);
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
return () => {
|
||||
disposed = true;
|
||||
clearTimeout(timer);
|
||||
window.removeEventListener("focus", onFocus);
|
||||
document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||
};
|
||||
}, [shouldRefreshWhileEmpty]);
|
||||
|
||||
const standalone = showSavedEnvironments || savedEnvironments.length === 0;
|
||||
|
||||
if (
|
||||
!refreshWhileEmpty &&
|
||||
standalone &&
|
||||
visibleEnvironments.length === 0 &&
|
||||
environmentsState.refreshing &&
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useLocation, useNavigate } from "@tanstack/react-router";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { RotateCcwIcon } from "lucide-react";
|
||||
import { useEffect, useLayoutEffect, useState } from "react";
|
||||
|
||||
import {
|
||||
ensureClientSettingsHydrated,
|
||||
useClientSettings,
|
||||
useClientSettingsHydrationStatus,
|
||||
} from "../../hooks/useSettings";
|
||||
import { mountOnboardingTheme } from "../../hooks/useTheme";
|
||||
import { useCompleteOnboarding } from "../../onboarding/firstRun";
|
||||
import {
|
||||
isFirstRunWorkspaceProvenanceAuthoritative,
|
||||
isFreshFirstRunWorkspace,
|
||||
resolveFirstRunDecision,
|
||||
resolveHostedFirstRunDecision,
|
||||
transitionFirstRunGateState,
|
||||
type FirstRunGateState,
|
||||
} from "../../onboarding/firstRun.logic";
|
||||
import {
|
||||
useAllEnvironmentShellsBootstrapped,
|
||||
useProjects,
|
||||
useThreadShells,
|
||||
} from "../../state/entities";
|
||||
import { useEnvironments } from "../../state/environments";
|
||||
import { environmentProjects } from "../../state/projects";
|
||||
import { primaryServerConfigAtom, primaryServerWelcomeAtom } from "../../state/server";
|
||||
import { environmentShell } from "../../state/shell";
|
||||
import { environmentThreadShells } from "../../state/threads";
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
/**
|
||||
* Holds back authenticated and hosted app trees until the first-run decision
|
||||
* is known, so a fresh install never flashes the main screen before the wizard.
|
||||
* Nothing renders while pending — no shell, no EventRouter (whose welcome
|
||||
* payload would otherwise navigate into a thread), no dialogs.
|
||||
*
|
||||
* Decision order: a set `onboardingCompletedAt` resolves to the app as soon as
|
||||
* settings hydrate (the common case, no server round-trip). A `null` flag also
|
||||
* covers installs that predate the field, so it alone is not enough — the gate
|
||||
* waits for environment shells to bootstrap and inspects the workspace.
|
||||
* Hosted mode instead checks its saved environment catalog. A timeout shows
|
||||
* recovery for an unreachable primary server without mounting the app tree.
|
||||
*/
|
||||
|
||||
const FIRST_RUN_DECISION_TIMEOUT_MS = 4_000;
|
||||
|
||||
const primaryShellLiveAtom = Atom.make((get) => {
|
||||
const serverConfig = get(primaryServerConfigAtom);
|
||||
return (
|
||||
serverConfig !== null &&
|
||||
get(environmentShell.stateValueAtom(serverConfig.environment.environmentId)).status === "live"
|
||||
);
|
||||
}).pipe(Atom.withLabel("web-onboarding-primary-shell-live"));
|
||||
|
||||
const workspaceEvidenceLiveAtom = Atom.make((get) => {
|
||||
const environmentIds = new Set([
|
||||
...get(environmentProjects.projectsAtom).map((project) => project.environmentId),
|
||||
...get(environmentThreadShells.threadShellsAtom).map((thread) => thread.environmentId),
|
||||
]);
|
||||
|
||||
for (const environmentId of environmentIds) {
|
||||
if (get(environmentShell.stateValueAtom(environmentId)).status !== "live") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}).pipe(Atom.withLabel("web-onboarding-workspace-evidence-live"));
|
||||
|
||||
export function FirstRunGate({
|
||||
enabled,
|
||||
hostedStatic,
|
||||
children,
|
||||
}: {
|
||||
readonly enabled: boolean;
|
||||
readonly hostedStatic: boolean;
|
||||
readonly children: React.ReactNode;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const pathname = useLocation({ select: (location) => location.pathname });
|
||||
const hydrationStatus = useClientSettingsHydrationStatus();
|
||||
const hydrated = hydrationStatus === "ready";
|
||||
const completeOnboarding = useCompleteOnboarding();
|
||||
const onboardingCompletedAt = useClientSettings((settings) => settings.onboardingCompletedAt);
|
||||
const bootstrapped = useAllEnvironmentShellsBootstrapped();
|
||||
const { environments, isReady: environmentCatalogReady } = useEnvironments();
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const serverConfig = useAtomValue(primaryServerConfigAtom);
|
||||
const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
|
||||
const primaryShellLive = useAtomValue(primaryShellLiveAtom);
|
||||
const workspaceEvidenceLive = useAtomValue(workspaceEvidenceLiveAtom);
|
||||
// Within a session settings stay hydrated, so remounts (e.g. returning from
|
||||
// the wizard) resolve synchronously instead of blanking a frame.
|
||||
const [gateState, setGateState] = useState<FirstRunGateState>(() => ({
|
||||
decision:
|
||||
(!enabled && !hostedStatic) || (hydrated && onboardingCompletedAt !== null)
|
||||
? "app"
|
||||
: "pending",
|
||||
stalled: false,
|
||||
}));
|
||||
const { decision, stalled } = gateState;
|
||||
const settingsReadFailed = hydrationStatus === "failed" || hydrationStatus === "retrying";
|
||||
const ownsOnboardingTheme = settingsReadFailed || stalled || decision === "wizard";
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!ownsOnboardingTheme) return;
|
||||
return mountOnboardingTheme();
|
||||
}, [ownsOnboardingTheme]);
|
||||
|
||||
// A workspace still counts as fresh when its only content is the server's
|
||||
// own cwd auto-bootstrap: web mode creates a project + thread from cwd at
|
||||
// startup (`autoBootstrapProjectFromCwd` defaults on there), so "no
|
||||
// projects at all" would mean `npx t3` users never see the wizard. Any
|
||||
// other project, more than one thread, or state in a non-primary
|
||||
// environment is real user state — the aggregate hooks span every
|
||||
// environment, and a saved remote's project must never read as "the
|
||||
// bootstrap project" just because its root string matches the primary cwd.
|
||||
const serverCwd = serverConfig?.cwd ?? null;
|
||||
const primaryEnvironmentId = serverConfig?.environment.environmentId ?? null;
|
||||
const workspaceFresh = isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd,
|
||||
bootstrapProjectId: serverWelcome?.bootstrapProjectId,
|
||||
bootstrapThreadId: serverWelcome?.bootstrapThreadId,
|
||||
bootstrapProjectCreated: serverWelcome?.bootstrapProjectCreated,
|
||||
bootstrapThreadCreated: serverWelcome?.bootstrapThreadCreated,
|
||||
projects,
|
||||
threads,
|
||||
});
|
||||
|
||||
const { decision: nextDecision, persistCompletion } = hostedStatic
|
||||
? resolveHostedFirstRunDecision({
|
||||
hydrated,
|
||||
completed: onboardingCompletedAt !== null,
|
||||
catalogReady: environmentCatalogReady,
|
||||
environmentCount: environments.length,
|
||||
})
|
||||
: resolveFirstRunDecision({
|
||||
enabled,
|
||||
hydrated,
|
||||
completed: onboardingCompletedAt !== null,
|
||||
bootstrapped,
|
||||
authoritative: primaryShellLive,
|
||||
workspaceAuthoritative: workspaceEvidenceLive,
|
||||
workspaceProvenanceAuthoritative: isFirstRunWorkspaceProvenanceAuthoritative({
|
||||
welcomeReceived: serverWelcome !== null,
|
||||
bootstrapStatus: serverWelcome?.bootstrapStatus ?? null,
|
||||
}),
|
||||
catalogReady: environmentCatalogReady,
|
||||
serverConfigAvailable: serverConfig !== null,
|
||||
workspaceFresh,
|
||||
projectCount: projects.length,
|
||||
threadCount: threads.length,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (decision === "wizard" || !hydrated) return;
|
||||
|
||||
if (persistCompletion && onboardingCompletedAt === null) {
|
||||
void completeOnboarding().catch(() => undefined);
|
||||
}
|
||||
|
||||
setGateState((state) =>
|
||||
transitionFirstRunGateState(state, { type: "evidence", decision: nextDecision }),
|
||||
);
|
||||
}, [
|
||||
completeOnboarding,
|
||||
decision,
|
||||
hydrated,
|
||||
nextDecision,
|
||||
onboardingCompletedAt,
|
||||
persistCompletion,
|
||||
]);
|
||||
|
||||
// A stalled server read gets a recovery screen, but never mounts the app.
|
||||
// The timer starts after settings hydrate so slow local hydration does not
|
||||
// show a false connection failure.
|
||||
useEffect(() => {
|
||||
if (!enabled || decision !== "pending" || !hydrated) return;
|
||||
const timer = window.setTimeout(
|
||||
() => setGateState((state) => transitionFirstRunGateState(state, { type: "timeout" })),
|
||||
FIRST_RUN_DECISION_TIMEOUT_MS,
|
||||
);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [decision, enabled, hydrated]);
|
||||
|
||||
useEffect(() => {
|
||||
if (decision === "wizard" && pathname !== "/welcome") {
|
||||
void navigate({ to: "/welcome", replace: true });
|
||||
}
|
||||
}, [decision, navigate, pathname]);
|
||||
|
||||
if (settingsReadFailed) {
|
||||
return <FirstRunRecovery reason="settings" retrying={hydrationStatus === "retrying"} />;
|
||||
}
|
||||
if (decision !== "app") {
|
||||
return stalled ? <FirstRunRecovery reason="connection" /> : null;
|
||||
}
|
||||
return children;
|
||||
}
|
||||
|
||||
function FirstRunRecovery({
|
||||
reason,
|
||||
retrying = false,
|
||||
}: {
|
||||
readonly reason: "settings" | "connection";
|
||||
readonly retrying?: boolean;
|
||||
}) {
|
||||
const settingsReadFailed = reason === "settings";
|
||||
return (
|
||||
<main className="flex h-dvh min-h-0 items-center justify-center bg-background px-6 text-foreground">
|
||||
<div className="flex max-w-sm flex-col items-center text-center">
|
||||
<h1 className="text-lg font-semibold">
|
||||
{settingsReadFailed ? "Could not read settings" : "Still connecting"}
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
{settingsReadFailed
|
||||
? "Your saved settings could not be loaded."
|
||||
: "T3 Code could not confirm this workspace."}
|
||||
</p>
|
||||
<Button
|
||||
className="mt-5"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={retrying}
|
||||
onClick={() => {
|
||||
if (settingsReadFailed) {
|
||||
void ensureClientSettingsHydrated().catch(() => undefined);
|
||||
} else {
|
||||
window.location.reload();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<RotateCcwIcon />
|
||||
{settingsReadFailed ? "Retry" : "Reload"}
|
||||
</Button>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,190 @@
|
||||
import {
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
EnvironmentId,
|
||||
ThreadId,
|
||||
type ClientSettings,
|
||||
type PreviewAutomationResponse,
|
||||
type PreviewAutomationStreamEvent,
|
||||
type PreviewOpenInput,
|
||||
type PreviewSessionSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { act } from "react";
|
||||
import { create, type ReactTestRenderer } from "react-test-renderer";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { __resetClientSettingsPersistenceForTests } from "~/hooks/useSettings";
|
||||
import { readThreadPreviewState, resetPreviewStateForTests } from "~/previewStateStore";
|
||||
import { appAtomRegistry, AppAtomRegistryProvider } from "~/rpc/atomRegistry";
|
||||
|
||||
import { PreviewAutomationHosts } from "./PreviewAutomationHosts";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getClientSettings: vi.fn<() => Promise<ClientSettings | null>>(),
|
||||
setClientSettings: vi.fn(),
|
||||
open: vi.fn(async (_target: { environmentId: EnvironmentId; input: PreviewOpenInput }) =>
|
||||
AsyncResult.success(snapshot),
|
||||
),
|
||||
list: vi.fn(async () => AsyncResult.success(emptyList)),
|
||||
resize: vi.fn(),
|
||||
respond:
|
||||
vi.fn<
|
||||
(target: { environmentId: EnvironmentId; input: PreviewAutomationResponse }) => Promise<void>
|
||||
>(),
|
||||
focus: vi.fn(async () => undefined),
|
||||
}));
|
||||
|
||||
vi.mock("~/localApi", () => ({
|
||||
ensureLocalApi: () => ({ persistence: mocks }),
|
||||
}));
|
||||
vi.mock("~/env", () => ({ isElectron: true }));
|
||||
vi.mock("~/state/environments", () => ({
|
||||
useEnvironments: () => ({ environments: [{ environmentId }] }),
|
||||
}));
|
||||
vi.mock("~/state/preview", () => ({
|
||||
previewEnvironment: {
|
||||
automationRequests: () => requestsAtom,
|
||||
list: () => listAtom,
|
||||
open: mocks.open,
|
||||
resize: mocks.resize,
|
||||
respondToAutomation: mocks.respond,
|
||||
focusAutomationHost: mocks.focus,
|
||||
},
|
||||
}));
|
||||
vi.mock("~/state/use-atom-command", () => ({
|
||||
useAtomCommand: (command: unknown) => command,
|
||||
}));
|
||||
vi.mock("~/state/use-atom-query-runner", () => ({
|
||||
useAtomQueryRunner: () => mocks.list,
|
||||
}));
|
||||
vi.mock("./previewBridge", () => ({ previewBridge: { automation: {} } }));
|
||||
|
||||
const environmentId = EnvironmentId.make("automation-environment");
|
||||
const threadId = ThreadId.make("automation-thread");
|
||||
const threadRef = { environmentId, threadId };
|
||||
const viewport = { _tag: "freeform", width: 1440, height: 900 } as const;
|
||||
const savedSettings: ClientSettings = {
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
browserDefaultViewport: viewport,
|
||||
browserDefaultProfileId: "work",
|
||||
browserProfiles: [{ id: "work", name: "Work", kind: "persistent" }],
|
||||
};
|
||||
const snapshot: PreviewSessionSnapshot = {
|
||||
threadId,
|
||||
tabId: "automation-tab",
|
||||
navStatus: { _tag: "Idle" },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
viewport,
|
||||
profileId: "work",
|
||||
updatedAt: "2026-09-05T00:00:00.000Z",
|
||||
};
|
||||
const emptyList = { sessions: [], serverEpoch: "test-server", revision: 0 };
|
||||
const listAtom = Atom.make(AsyncResult.success(emptyList));
|
||||
const requestsAtom = Atom.make<AsyncResult.AsyncResult<PreviewAutomationStreamEvent, Error>>(
|
||||
AsyncResult.initial(false),
|
||||
);
|
||||
const requestEvent: PreviewAutomationStreamEvent = {
|
||||
type: "request",
|
||||
connectionId: "automation-connection",
|
||||
request: {
|
||||
requestId: "open-request",
|
||||
threadId,
|
||||
operation: "open",
|
||||
input: { open: false, reuseExistingTab: false },
|
||||
timeoutMs: 15_000,
|
||||
},
|
||||
};
|
||||
|
||||
function deferred<A>() {
|
||||
let resolve!: (value: A) => void;
|
||||
const promise = new Promise<A>((complete) => {
|
||||
resolve = complete;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
let renderer: ReactTestRenderer | null = null;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getClientSettings.mockReset().mockResolvedValue(savedSettings);
|
||||
mocks.respond.mockReset();
|
||||
__resetClientSettingsPersistenceForTests();
|
||||
resetPreviewStateForTests();
|
||||
appAtomRegistry.set(requestsAtom, AsyncResult.initial(false));
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
vi.stubGlobal("window", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
|
||||
vi.stubGlobal("document", { hasFocus: () => false, querySelectorAll: () => [] });
|
||||
await act(() => {
|
||||
renderer = create(
|
||||
<AppAtomRegistryProvider>
|
||||
<PreviewAutomationHosts />
|
||||
</AppAtomRegistryProvider>,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await act(() => renderer?.unmount());
|
||||
renderer = null;
|
||||
resetPreviewStateForTests();
|
||||
__resetClientSettingsPersistenceForTests();
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("PreviewAutomationHosts open", () => {
|
||||
it("waits for saved settings before opening a tab with the configured profile and viewport", async () => {
|
||||
const readStarted = deferred<void>();
|
||||
const read = deferred<ClientSettings>();
|
||||
const response = deferred<PreviewAutomationResponse>();
|
||||
mocks.getClientSettings.mockImplementationOnce(() => {
|
||||
readStarted.resolve();
|
||||
return read.promise;
|
||||
});
|
||||
mocks.respond.mockImplementationOnce(async ({ input }) => response.resolve(input));
|
||||
|
||||
await act(async () => {
|
||||
appAtomRegistry.set(requestsAtom, AsyncResult.success(requestEvent));
|
||||
await readStarted.promise;
|
||||
});
|
||||
expect(mocks.open).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => {
|
||||
read.resolve(savedSettings);
|
||||
await response.promise;
|
||||
});
|
||||
|
||||
expect(mocks.open).toHaveBeenCalledExactlyOnceWith({
|
||||
environmentId,
|
||||
input: { threadId, viewport, profileId: "work" },
|
||||
});
|
||||
expect(mocks.getClientSettings).toHaveBeenCalledOnce();
|
||||
await expect(response.promise).resolves.toMatchObject({ requestId: "open-request", ok: true });
|
||||
expect(readThreadPreviewState(threadRef).snapshot).toEqual(snapshot);
|
||||
expect(mocks.setClientSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports a settings read failure without opening a tab", async () => {
|
||||
vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
mocks.getClientSettings.mockRejectedValueOnce(new Error("Settings read failed"));
|
||||
const response = deferred<PreviewAutomationResponse>();
|
||||
mocks.respond.mockImplementationOnce(async ({ input }) => response.resolve(input));
|
||||
|
||||
await act(async () => {
|
||||
appAtomRegistry.set(requestsAtom, AsyncResult.success(requestEvent));
|
||||
await response.promise;
|
||||
});
|
||||
|
||||
await expect(response.promise).resolves.toMatchObject({
|
||||
requestId: "open-request",
|
||||
ok: false,
|
||||
error: { _tag: "PreviewAutomationExecutionError" },
|
||||
});
|
||||
expect(mocks.getClientSettings).toHaveBeenCalledOnce();
|
||||
expect(mocks.open).not.toHaveBeenCalled();
|
||||
expect(readThreadPreviewState(threadRef).snapshot).toBeNull();
|
||||
expect(mocks.setClientSettings).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -41,7 +41,11 @@ import {
|
||||
acquireBrowserSurfaceActivity,
|
||||
useBrowserSurfaceStore,
|
||||
} from "~/browser/browserSurfaceStore";
|
||||
import { browserDefaultOpenViewport, resolveBrowserDefaults } from "~/browser/browserDefaults";
|
||||
import {
|
||||
browserDefaultOpenProfileId,
|
||||
browserDefaultOpenViewport,
|
||||
resolveBrowserDefaults,
|
||||
} from "~/browser/browserDefaults";
|
||||
import { runBrowserViewportMutation } from "~/browser/browserViewportActions";
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
import { isElectron } from "~/env";
|
||||
@@ -412,6 +416,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
const reusedExistingTab = activeTabId !== null;
|
||||
tabId = activeTabId;
|
||||
if (!activeTabId) {
|
||||
const defaults = await resolveBrowserDefaults();
|
||||
const result = await open({
|
||||
environmentId,
|
||||
input: {
|
||||
@@ -419,7 +424,8 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
...(resolvedInputUrl ? { url: resolvedInputUrl } : {}),
|
||||
// An agent that didn't state a size gets the user's
|
||||
// configured default, same as a hand-opened tab.
|
||||
viewport: browserDefaultOpenViewport(await resolveBrowserDefaults()),
|
||||
viewport: browserDefaultOpenViewport(defaults),
|
||||
profileId: browserDefaultOpenProfileId(defaults),
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
DEFAULT_BROWSER_PROFILE_ID,
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
@@ -46,6 +49,7 @@ import {
|
||||
} from "~/browser/browserViewportActions";
|
||||
import { browserResponsiveViewportForToggle, useBrowserDefaults } from "~/browser/browserDefaults";
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
import { BrowserSettingsReadError } from "~/browser/openFileInPreview";
|
||||
import { PreviewUnreachable } from "./PreviewUnreachable";
|
||||
import { revealInFileExplorerLabel } from "./fileExplorerLabel";
|
||||
import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
|
||||
@@ -186,6 +190,16 @@ export function PreviewView({
|
||||
return true;
|
||||
}
|
||||
const result = await openPreviewSession({ openPreview: open, threadRef, url: resolvedUrl });
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
if (error instanceof BrowserSettingsReadError) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open browser",
|
||||
description: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
return result._tag === "Success";
|
||||
},
|
||||
[open, runtimeTabId, threadRef],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
DEFAULT_BROWSER_PROFILE_ID,
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
type PreviewOpenInput,
|
||||
type PreviewSessionSnapshot,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
resetPreviewStateForTests,
|
||||
} from "~/previewStateStore";
|
||||
import { selectThreadRightPanelState, useRightPanelStore } from "~/rightPanelStore";
|
||||
import { __setClientSettingsForTests } from "~/hooks/useSettings";
|
||||
|
||||
import { addBrowserSurface } from "./addBrowserSurface";
|
||||
|
||||
@@ -32,6 +34,7 @@ const snapshot = (tabId: string): PreviewSessionSnapshot => ({
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
__setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
|
||||
resetPreviewStateForTests();
|
||||
useRightPanelStore.setState({ byThreadKey: {} });
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
|
||||
import type { OpenPreviewMutation } from "~/browser/openFileInPreview";
|
||||
import type { BrowserSettingsReadError, OpenPreviewMutation } from "~/browser/openFileInPreview";
|
||||
import { useRightPanelStore } from "~/rightPanelStore";
|
||||
|
||||
import { openPreviewSession } from "./openPreviewSession";
|
||||
@@ -15,7 +15,7 @@ export async function addBrowserSurface<E>(input: {
|
||||
readonly openPreview: OpenPreviewMutation<E>;
|
||||
/** Omit to use the configured default profile. */
|
||||
readonly profileId?: string | undefined;
|
||||
}): Promise<AtomCommandResult<void, E>> {
|
||||
}): Promise<AtomCommandResult<void, E | BrowserSettingsReadError>> {
|
||||
const result = await openPreviewSession({
|
||||
openPreview: input.openPreview,
|
||||
threadRef: input.threadRef,
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
|
||||
import type { OpenPreviewMutation } from "~/browser/openFileInPreview";
|
||||
import type { BrowserSettingsReadError, OpenPreviewMutation } from "~/browser/openFileInPreview";
|
||||
import { recordVisitForThread } from "~/browserHistoryStore";
|
||||
import { useRightPanelStore } from "~/rightPanelStore";
|
||||
import { openPreviewSession } from "./openPreviewSession";
|
||||
@@ -14,7 +14,7 @@ export async function openDiscoveredPort<E>(input: {
|
||||
readonly threadRef: ScopedThreadRef;
|
||||
readonly port: DiscoveredLocalServer;
|
||||
readonly openPreview: OpenPreviewMutation<E>;
|
||||
}): Promise<AtomCommandResult<void, E>> {
|
||||
}): Promise<AtomCommandResult<void, E | BrowserSettingsReadError>> {
|
||||
const resolvedUrl = resolveDiscoveredServerUrl(input.threadRef.environmentId, input.port.url);
|
||||
const result = await openPreviewSession({
|
||||
openPreview: input.openPreview,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
DEFAULT_BROWSER_PROFILE_ID,
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
type PreviewOpenInput,
|
||||
type PreviewSessionSnapshot,
|
||||
@@ -7,8 +8,11 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import * as browserDefaults from "~/browser/browserDefaults";
|
||||
import { BrowserSettingsReadError, openUrlInPreview } from "~/browser/openFileInPreview";
|
||||
import { __setClientSettingsForTests } from "~/hooks/useSettings";
|
||||
import { readThreadPreviewState, resetPreviewStateForTests } from "~/previewStateStore";
|
||||
|
||||
import { openPreviewSession } from "./openPreviewSession";
|
||||
@@ -31,7 +35,14 @@ const snapshot: PreviewSessionSnapshot = {
|
||||
updatedAt: "2026-06-11T23:00:00.000Z",
|
||||
};
|
||||
|
||||
beforeEach(resetPreviewStateForTests);
|
||||
beforeEach(() => {
|
||||
resetPreviewStateForTests();
|
||||
__setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("openPreviewSession", () => {
|
||||
it("creates an idle tab without recording a recently visited URL", async () => {
|
||||
@@ -88,4 +99,44 @@ describe("openPreviewSession", () => {
|
||||
expect(readThreadPreviewState(threadRef).snapshot).toBeNull();
|
||||
expect(readThreadPreviewState(threadRef).recentlySeenUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(["session", "link"] as const)(
|
||||
"does not open a %s with unread settings and uses the saved profile on retry",
|
||||
async (entryPoint) => {
|
||||
const failure = new Error("Settings read failed");
|
||||
vi.spyOn(browserDefaults, "resolveBrowserDefaults").mockRejectedValueOnce(failure);
|
||||
const viewport = { _tag: "freeform", width: 1280, height: 720 } as const;
|
||||
__setClientSettingsForTests({
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
browserDefaultViewport: viewport,
|
||||
browserDefaultProfileId: "work",
|
||||
browserProfiles: [{ id: "work", name: "Work", kind: "persistent" }],
|
||||
});
|
||||
const openPreview = vi.fn(async () => AsyncResult.success(snapshot));
|
||||
const input = { openPreview, threadRef, url: "https://t3.chat/" };
|
||||
const open = entryPoint === "session" ? openPreviewSession : openUrlInPreview;
|
||||
|
||||
const result = await open(input);
|
||||
|
||||
expect(result._tag).toBe("Failure");
|
||||
if (result._tag === "Failure") {
|
||||
expect(Cause.squash(result.cause)).toBeInstanceOf(BrowserSettingsReadError);
|
||||
expect(Cause.squash(result.cause)).toMatchObject({ cause: failure });
|
||||
}
|
||||
expect(openPreview).not.toHaveBeenCalled();
|
||||
expect(readThreadPreviewState(threadRef).snapshot).toBeNull();
|
||||
expect(readThreadPreviewState(threadRef).recentlySeenUrls).toEqual([]);
|
||||
|
||||
await expect(open(input)).resolves.toMatchObject({ _tag: "Success" });
|
||||
expect(openPreview).toHaveBeenCalledExactlyOnceWith({
|
||||
environmentId: threadRef.environmentId,
|
||||
input: {
|
||||
threadId: threadRef.threadId,
|
||||
url: input.url,
|
||||
viewport,
|
||||
profileId: "work",
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -6,12 +6,15 @@ import type {
|
||||
ScopedThreadRef,
|
||||
} from "@t3tools/contracts";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
browserDefaultOpenProfileId,
|
||||
browserDefaultOpenViewport,
|
||||
resolveBrowserDefaults,
|
||||
} from "~/browser/browserDefaults";
|
||||
import { BrowserSettingsReadError } from "~/browser/openFileInPreview";
|
||||
import { applyPreviewServerSnapshot, rememberPreviewUrl } from "~/previewStateStore";
|
||||
|
||||
interface OpenPreviewSessionInput<E> {
|
||||
@@ -29,10 +32,15 @@ interface OpenPreviewSessionInput<E> {
|
||||
|
||||
export async function openPreviewSession<E>(
|
||||
input: OpenPreviewSessionInput<E>,
|
||||
): Promise<AtomCommandResult<PreviewSessionSnapshot, E>> {
|
||||
): Promise<AtomCommandResult<PreviewSessionSnapshot, E | BrowserSettingsReadError>> {
|
||||
// Resolved once: a tab opened before client settings hydrate would otherwise
|
||||
// be born at the schema defaults and never corrected.
|
||||
const defaults = await resolveBrowserDefaults();
|
||||
const defaults = await resolveBrowserDefaults().catch(
|
||||
(cause: unknown) => new BrowserSettingsReadError({ cause }),
|
||||
);
|
||||
if (defaults instanceof BrowserSettingsReadError) {
|
||||
return AsyncResult.failure(Cause.fail(defaults));
|
||||
}
|
||||
const result = await input.openPreview({
|
||||
environmentId: input.threadRef.environmentId,
|
||||
input: {
|
||||
|
||||
@@ -68,6 +68,33 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("openTerminalLinkInPreview", () => {
|
||||
it.each(["target", "defaults"] as const)(
|
||||
"does not open either browser when reading %s fails",
|
||||
async (setting) => {
|
||||
const failure = new Error("Settings read failed");
|
||||
if (setting === "target") {
|
||||
linkTargetMocks.preference.mockImplementationOnce(() => {
|
||||
throw failure;
|
||||
});
|
||||
} else {
|
||||
browserDefaultsMocks.resolve.mockRejectedValueOnce(failure);
|
||||
}
|
||||
const fallbackToBrowser = vi.fn();
|
||||
const openPreview = vi.fn(async () => AsyncResult.success(snapshot));
|
||||
|
||||
await expect(
|
||||
openTerminalLinkInPreview({
|
||||
url: "https://example.com/docs",
|
||||
threadRef,
|
||||
openPreview,
|
||||
fallbackToBrowser,
|
||||
}),
|
||||
).rejects.toBe(failure);
|
||||
expect(fallbackToBrowser).not.toHaveBeenCalled();
|
||||
expect(openPreview).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("opens in the system browser while that is the configured target", async () => {
|
||||
linkTargetMocks.preference.mockReturnValue("system");
|
||||
const fallbackToBrowser = vi.fn();
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { getProviderSummary } from "./providerStatus";
|
||||
|
||||
const provider: ServerProvider = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated", label: "ChatGPT" },
|
||||
checkedAt: "2026-08-23T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
};
|
||||
|
||||
describe("getProviderSummary", () => {
|
||||
it("reports ready providers with unknown authentication as available", () => {
|
||||
expect(getProviderSummary({ ...provider, auth: { status: "unknown" } })).toEqual({
|
||||
headline: "Available",
|
||||
detail: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not hide a provider error behind a previous authenticated state", () => {
|
||||
expect(
|
||||
getProviderSummary({
|
||||
...provider,
|
||||
status: "error",
|
||||
message: "The provider process failed to start.",
|
||||
}),
|
||||
).toEqual({
|
||||
headline: "Unavailable",
|
||||
detail: "The provider process failed to start.",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not hide a provider warning behind an authenticated state", () => {
|
||||
expect(
|
||||
getProviderSummary({
|
||||
...provider,
|
||||
status: "warning",
|
||||
message: "The provider version is unsupported.",
|
||||
}),
|
||||
).toEqual({
|
||||
headline: "Needs attention",
|
||||
detail: "The provider version is unsupported.",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps authentication failures actionable when their provider status is error", () => {
|
||||
expect(
|
||||
getProviderSummary({
|
||||
...provider,
|
||||
status: "error",
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Run codex login.",
|
||||
}),
|
||||
).toEqual({
|
||||
headline: "Not authenticated",
|
||||
detail: "Run codex login.",
|
||||
});
|
||||
});
|
||||
|
||||
it("treats a disabled provider status as disabled even before its enabled flag updates", () => {
|
||||
expect(getProviderSummary({ ...provider, status: "disabled" }).headline).toBe("Disabled");
|
||||
});
|
||||
});
|
||||
@@ -26,7 +26,8 @@ export type ProviderStatusKey = keyof typeof PROVIDER_STATUS_STYLES;
|
||||
* settings page. Prefers `provider.message` for server-supplied detail and
|
||||
* falls back to generic phrasing when the server has not yet reported any
|
||||
* state — which happens before the first probe or when an instance names a
|
||||
* driver this build does not ship.
|
||||
* driver this build does not ship. A ready provider without account metadata
|
||||
* remains available and does not imply an authentication failure.
|
||||
*/
|
||||
export function getProviderSummary(provider: ServerProvider | undefined) {
|
||||
if (!provider) {
|
||||
@@ -35,7 +36,7 @@ export function getProviderSummary(provider: ServerProvider | undefined) {
|
||||
detail: "Waiting for the server to report installation and authentication details.",
|
||||
};
|
||||
}
|
||||
if (!provider.enabled) {
|
||||
if (!provider.enabled || provider.status === "disabled") {
|
||||
return {
|
||||
headline: "Disabled",
|
||||
detail:
|
||||
@@ -48,13 +49,6 @@ export function getProviderSummary(provider: ServerProvider | undefined) {
|
||||
detail: provider.message ?? "CLI not detected on PATH.",
|
||||
};
|
||||
}
|
||||
if (provider.auth.status === "authenticated") {
|
||||
const authLabel = provider.auth.label ?? provider.auth.type;
|
||||
return {
|
||||
headline: authLabel ? `Authenticated · ${authLabel}` : "Authenticated",
|
||||
detail: provider.message ?? null,
|
||||
};
|
||||
}
|
||||
if (provider.auth.status === "unauthenticated") {
|
||||
return {
|
||||
headline: "Not authenticated",
|
||||
@@ -74,9 +68,16 @@ export function getProviderSummary(provider: ServerProvider | undefined) {
|
||||
detail: provider.message ?? "The provider failed its startup checks.",
|
||||
};
|
||||
}
|
||||
if (provider.auth.status === "authenticated") {
|
||||
const authLabel = provider.auth.label ?? provider.auth.type;
|
||||
return {
|
||||
headline: authLabel ? `Authenticated · ${authLabel}` : "Authenticated",
|
||||
detail: provider.message ?? null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
headline: "Available",
|
||||
detail: provider.message ?? "Installed and ready, but authentication could not be verified.",
|
||||
detail: provider.message ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -353,6 +353,8 @@ export async function submitServerAuthCredential(credential: string): Promise<vo
|
||||
|
||||
resolvedAuthenticatedGateState = null;
|
||||
await exchangeBootstrapCredential(trimmedCredential);
|
||||
await waitForAuthenticatedSessionAfterBootstrap();
|
||||
resolvedAuthenticatedGateState = { status: "authenticated" };
|
||||
bootstrapPromise = null;
|
||||
stripPairingTokenFromUrl();
|
||||
}
|
||||
|
||||
@@ -55,9 +55,28 @@ describe("local storage errors", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves decode failure context", async () => {
|
||||
it("retries when access to browser storage becomes available", async () => {
|
||||
const storage = createStorage();
|
||||
storage.setItem("read-key", JSON.stringify("saved value"));
|
||||
let blocked = true;
|
||||
vi.stubGlobal("window", {
|
||||
get localStorage() {
|
||||
if (blocked) throw new Error("storage unavailable");
|
||||
return storage;
|
||||
},
|
||||
});
|
||||
const { getLocalStorageItem, LocalStorageOperationError } = await import("./useLocalStorage");
|
||||
|
||||
expect(() => getLocalStorageItem("read-key", Schema.String)).toThrow(
|
||||
LocalStorageOperationError,
|
||||
);
|
||||
blocked = false;
|
||||
expect(getLocalStorageItem("read-key", Schema.String)).toBe("saved value");
|
||||
});
|
||||
|
||||
it.each(["", "not-json"])("preserves decode failure context for %j", async (value) => {
|
||||
const { getLocalStorageItem, LocalStorageOperationError } = await loadWithStorage(
|
||||
createStorage({ getItem: () => "not-json" }),
|
||||
createStorage({ getItem: () => value }),
|
||||
);
|
||||
|
||||
try {
|
||||
|
||||
@@ -15,26 +15,26 @@ export class LocalStorageOperationError extends Schema.TaggedErrorClass<LocalSto
|
||||
}
|
||||
}
|
||||
|
||||
const isomorphicLocalStorage: Storage =
|
||||
typeof window !== "undefined"
|
||||
? window.localStorage
|
||||
: (function () {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
clear: () => store.clear(),
|
||||
getItem: (_) => store.get(_) ?? null,
|
||||
key: (_) => Record.keys(store).at(_) ?? null,
|
||||
get length() {
|
||||
return store.size;
|
||||
},
|
||||
removeItem: (_) => store.delete(_),
|
||||
setItem: (_, value) => store.set(_, value),
|
||||
};
|
||||
})();
|
||||
const fallbackStorage: Storage = (() => {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
clear: () => store.clear(),
|
||||
getItem: (_) => store.get(_) ?? null,
|
||||
key: (_) => Record.keys(store).at(_) ?? null,
|
||||
get length() {
|
||||
return store.size;
|
||||
},
|
||||
removeItem: (_) => store.delete(_),
|
||||
setItem: (_, value) => store.set(_, value),
|
||||
};
|
||||
})();
|
||||
|
||||
const getStorage = (): Storage =>
|
||||
typeof window !== "undefined" ? window.localStorage : fallbackStorage;
|
||||
|
||||
const read = (key: string) => {
|
||||
try {
|
||||
return isomorphicLocalStorage.getItem(key);
|
||||
return getStorage().getItem(key);
|
||||
} catch (cause) {
|
||||
throw new LocalStorageOperationError({ operation: "read", storageKey: key, cause });
|
||||
}
|
||||
@@ -58,13 +58,13 @@ const encode = <T, E>(key: string, schema: Schema.Codec<T, E>, value: T) => {
|
||||
|
||||
export const getLocalStorageItem = <T, E>(key: string, schema: Schema.Codec<T, E>): T | null => {
|
||||
const item = read(key);
|
||||
return item ? decode(key, schema, item) : null;
|
||||
return item === null ? null : decode(key, schema, item);
|
||||
};
|
||||
|
||||
export const setLocalStorageItem = <T, E>(key: string, value: T, schema: Schema.Codec<T, E>) => {
|
||||
const valueToSet = encode(key, schema, value);
|
||||
try {
|
||||
isomorphicLocalStorage.setItem(key, valueToSet);
|
||||
getStorage().setItem(key, valueToSet);
|
||||
} catch (cause) {
|
||||
throw new LocalStorageOperationError({ operation: "write", storageKey: key, cause });
|
||||
}
|
||||
@@ -72,7 +72,7 @@ export const setLocalStorageItem = <T, E>(key: string, value: T, schema: Schema.
|
||||
|
||||
export const removeLocalStorageItem = (key: string) => {
|
||||
try {
|
||||
isomorphicLocalStorage.removeItem(key);
|
||||
getStorage().removeItem(key);
|
||||
} catch (cause) {
|
||||
throw new LocalStorageOperationError({ operation: "remove", storageKey: key, cause });
|
||||
}
|
||||
|
||||
@@ -3,12 +3,22 @@ import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { DEFAULT_CLIENT_SETTINGS, type ClientSettings } from "@t3tools/contracts/settings";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const persistenceMocks = vi.hoisted(() => ({
|
||||
getClientSettings: vi.fn<() => Promise<ClientSettings | null>>(),
|
||||
setClientSettings: vi.fn<(settings: ClientSettings) => Promise<void>>(),
|
||||
}));
|
||||
|
||||
vi.mock("~/localApi", () => ({
|
||||
ensureLocalApi: () => ({ persistence: persistenceMocks }),
|
||||
}));
|
||||
|
||||
import {
|
||||
__resetClientSettingsPersistenceForTests,
|
||||
__setClientSettingsForTests,
|
||||
ensureClientSettingsHydrated,
|
||||
getClientSettings,
|
||||
mergeEnvironmentSettings,
|
||||
persistClientSettingsPatch,
|
||||
@@ -17,9 +27,138 @@ import {
|
||||
} from "./useSettings";
|
||||
|
||||
beforeEach(() => {
|
||||
persistenceMocks.getClientSettings.mockReset().mockResolvedValue(null);
|
||||
persistenceMocks.setClientSettings.mockReset().mockResolvedValue(undefined);
|
||||
__resetClientSettingsPersistenceForTests();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("client settings hydration", () => {
|
||||
const savedSettings = {
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
timestampFormat: "12-hour" as const,
|
||||
favorites: [{ provider: ProviderInstanceId.make("codex_work"), model: "gpt-5.6" }],
|
||||
};
|
||||
const onboardingCompletedAt = "2026-09-05T12:00:00.000Z";
|
||||
const complete = (current: ClientSettings) => ({ ...current, onboardingCompletedAt });
|
||||
|
||||
it("rejects completion after a failed read and preserves saved preferences on retry", async () => {
|
||||
const failure = new Error("storage unavailable");
|
||||
vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
persistenceMocks.getClientSettings
|
||||
.mockRejectedValueOnce(failure)
|
||||
.mockResolvedValue(savedSettings);
|
||||
|
||||
await expect(persistClientSettingsUpdate(complete)).rejects.toBe(failure);
|
||||
expect(persistenceMocks.setClientSettings).not.toHaveBeenCalled();
|
||||
expect(getClientSettings()).toBe(DEFAULT_CLIENT_SETTINGS);
|
||||
|
||||
const completedSettings = { ...savedSettings, onboardingCompletedAt };
|
||||
await expect(persistClientSettingsUpdate(complete)).resolves.toEqual(completedSettings);
|
||||
expect(persistenceMocks.setClientSettings).toHaveBeenCalledExactlyOnceWith(completedSettings);
|
||||
expect(persistenceMocks.getClientSettings).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("uses defaults only after storage confirms no saved settings exist", async () => {
|
||||
const completedSettings = { ...DEFAULT_CLIENT_SETTINGS, onboardingCompletedAt };
|
||||
|
||||
await expect(persistClientSettingsUpdate(complete)).resolves.toEqual(completedSettings);
|
||||
expect(persistenceMocks.getClientSettings).toHaveBeenCalledOnce();
|
||||
expect(persistenceMocks.setClientSettings).toHaveBeenCalledExactlyOnceWith(completedSettings);
|
||||
});
|
||||
|
||||
it("holds patches until a pending read supplies the saved preferences", async () => {
|
||||
let finishRead!: (settings: ClientSettings) => void;
|
||||
persistenceMocks.getClientSettings.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
finishRead = resolve;
|
||||
}),
|
||||
);
|
||||
const persisted = new Promise<ClientSettings>((resolve) => {
|
||||
persistenceMocks.setClientSettings.mockImplementationOnce(async (settings) => {
|
||||
resolve(settings);
|
||||
});
|
||||
});
|
||||
|
||||
const hydration = ensureClientSettingsHydrated();
|
||||
persistClientSettingsPatch({ wordWrap: false });
|
||||
expect(getClientSettings()).toBe(DEFAULT_CLIENT_SETTINGS);
|
||||
expect(persistenceMocks.setClientSettings).not.toHaveBeenCalled();
|
||||
|
||||
finishRead(savedSettings);
|
||||
await hydration;
|
||||
await expect(persisted).resolves.toEqual({ ...savedSettings, wordWrap: false });
|
||||
expect(persistenceMocks.getClientSettings).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("handles failed patch reads without writing and retries with the saved preferences", async () => {
|
||||
const failure = new Error("storage unavailable");
|
||||
vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
persistenceMocks.getClientSettings.mockRejectedValue(failure);
|
||||
|
||||
const hydration = ensureClientSettingsHydrated();
|
||||
persistClientSettingsPatch({ wordWrap: false });
|
||||
await expect(hydration).rejects.toBe(failure);
|
||||
expect(persistenceMocks.setClientSettings).not.toHaveBeenCalled();
|
||||
|
||||
persistenceMocks.getClientSettings.mockResolvedValue(savedSettings);
|
||||
const persisted = new Promise<ClientSettings>((resolve) => {
|
||||
persistenceMocks.setClientSettings.mockImplementationOnce(async (settings) => {
|
||||
resolve(settings);
|
||||
});
|
||||
});
|
||||
persistClientSettingsPatch({ wordWrap: false });
|
||||
|
||||
await expect(persisted).resolves.toEqual({ ...savedSettings, wordWrap: false });
|
||||
});
|
||||
|
||||
it("preserves patch order across hydration and a blocked completion write", async () => {
|
||||
let finishRead!: (settings: ClientSettings) => void;
|
||||
const read = new Promise<ClientSettings>((resolve) => {
|
||||
finishRead = resolve;
|
||||
});
|
||||
persistenceMocks.getClientSettings.mockReturnValue(read);
|
||||
let finishCompletionWrite!: () => void;
|
||||
const blockedWrite = new Promise<void>((resolve) => {
|
||||
finishCompletionWrite = resolve;
|
||||
});
|
||||
let signalCompletionWrite!: () => void;
|
||||
const completionWriteStarted = new Promise<void>((resolve) => {
|
||||
signalCompletionWrite = resolve;
|
||||
});
|
||||
let durableSettings: ClientSettings = savedSettings;
|
||||
const persist = vi
|
||||
.fn<(settings: ClientSettings) => Promise<void>>()
|
||||
.mockImplementationOnce(async (settings) => {
|
||||
signalCompletionWrite();
|
||||
await blockedWrite;
|
||||
durableSettings = settings;
|
||||
})
|
||||
.mockImplementation(async (settings) => {
|
||||
durableSettings = settings;
|
||||
});
|
||||
|
||||
const completion = persistClientSettingsUpdate(complete, persist);
|
||||
persistClientSettingsPatch({ wordWrap: false }, persist);
|
||||
finishRead(savedSettings);
|
||||
await completionWriteStarted;
|
||||
persistClientSettingsPatch({ wordWrap: true }, persist);
|
||||
const finalWrite = persistClientSettingsUpdate((current) => current, persist);
|
||||
|
||||
finishCompletionWrite();
|
||||
await completion;
|
||||
await finalWrite;
|
||||
|
||||
const expected = { ...savedSettings, onboardingCompletedAt, wordWrap: true };
|
||||
expect(getClientSettings()).toEqual(expected);
|
||||
expect(durableSettings).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe("persistClientSettingsUpdate", () => {
|
||||
it("publishes the update only after persistence succeeds", async () => {
|
||||
let finishPersistence!: () => void;
|
||||
@@ -245,3 +384,40 @@ describe("mergeEnvironmentSettings", () => {
|
||||
expect(settings.sidebarAutoSettleOnMerge).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("onboarding completion persistence", () => {
|
||||
it("keeps onboarding incomplete after a failed save and preserves preferences on retry", async () => {
|
||||
const failure = new Error("disk full");
|
||||
const persist = vi
|
||||
.fn<(settings: typeof DEFAULT_CLIENT_SETTINGS) => Promise<void>>()
|
||||
.mockRejectedValueOnce(failure)
|
||||
.mockResolvedValue(undefined);
|
||||
const existingSettings = {
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
timestampFormat: "12-hour" as const,
|
||||
favorites: [
|
||||
{
|
||||
provider: ProviderInstanceId.make("codex_work"),
|
||||
model: "gpt-5.6",
|
||||
},
|
||||
],
|
||||
};
|
||||
__setClientSettingsForTests(existingSettings);
|
||||
const onboardingCompletedAt = "2026-09-01T12:00:00.000Z";
|
||||
const complete = (current: typeof DEFAULT_CLIENT_SETTINGS) => ({
|
||||
...current,
|
||||
onboardingCompletedAt,
|
||||
});
|
||||
|
||||
await expect(persistClientSettingsUpdate(complete, persist)).rejects.toBe(failure);
|
||||
expect(getClientSettings()).toBe(existingSettings);
|
||||
expect(getClientSettings().onboardingCompletedAt).toBeNull();
|
||||
|
||||
const completedSettings = { ...existingSettings, onboardingCompletedAt };
|
||||
await expect(persistClientSettingsUpdate(complete, persist)).resolves.toEqual(
|
||||
completedSettings,
|
||||
);
|
||||
expect(getClientSettings()).toEqual(completedSettings);
|
||||
expect(persist).toHaveBeenLastCalledWith(completedSettings);
|
||||
});
|
||||
});
|
||||
@@ -54,11 +54,13 @@ type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
|
||||
|
||||
const clientSettingsListeners = new Set<() => void>();
|
||||
const clientSettingsHydrationListeners = new Set<() => void>();
|
||||
type ClientSettingsHydrationStatus = "pending" | "ready" | "failed" | "retrying";
|
||||
let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
|
||||
let clientSettingsHydrated = false;
|
||||
let clientSettingsHydrationStatus: ClientSettingsHydrationStatus = "pending";
|
||||
let clientSettingsHydrationPromise: Promise<void> | null = null;
|
||||
let clientSettingsHydrationGeneration = 0;
|
||||
let clientSettingsPersistenceQueue: Promise<void> = Promise.resolve();
|
||||
let deferredClientSettingsPatchCount = 0;
|
||||
|
||||
function emitClientSettingsChange() {
|
||||
for (const listener of clientSettingsListeners) {
|
||||
@@ -81,36 +83,40 @@ function replaceClientSettingsSnapshot(settings: ClientSettings): void {
|
||||
emitClientSettingsChange();
|
||||
}
|
||||
|
||||
function setClientSettingsHydrated(nextHydrated: boolean): void {
|
||||
if (clientSettingsHydrated === nextHydrated) {
|
||||
function setClientSettingsHydrationStatus(nextStatus: ClientSettingsHydrationStatus): void {
|
||||
if (clientSettingsHydrationStatus === nextStatus) {
|
||||
return;
|
||||
}
|
||||
clientSettingsHydrated = nextHydrated;
|
||||
clientSettingsHydrationStatus = nextStatus;
|
||||
emitClientSettingsHydrationChange();
|
||||
}
|
||||
|
||||
function subscribeClientSettings(listener: () => void): () => void {
|
||||
clientSettingsListeners.add(listener);
|
||||
void hydrateClientSettings();
|
||||
void hydrateClientSettings().catch(() => undefined);
|
||||
return () => {
|
||||
clientSettingsListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
function getClientSettingsHydratedSnapshot(): boolean {
|
||||
return clientSettingsHydrated;
|
||||
return clientSettingsHydrationStatus === "ready";
|
||||
}
|
||||
|
||||
function getClientSettingsHydrationStatusSnapshot(): ClientSettingsHydrationStatus {
|
||||
return clientSettingsHydrationStatus;
|
||||
}
|
||||
|
||||
function subscribeClientSettingsHydration(listener: () => void): () => void {
|
||||
clientSettingsHydrationListeners.add(listener);
|
||||
void hydrateClientSettings();
|
||||
void hydrateClientSettings().catch(() => undefined);
|
||||
return () => {
|
||||
clientSettingsHydrationListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
async function hydrateClientSettings(): Promise<void> {
|
||||
if (clientSettingsHydrated) {
|
||||
if (clientSettingsHydrationStatus === "ready") {
|
||||
return;
|
||||
}
|
||||
if (clientSettingsHydrationPromise) {
|
||||
@@ -118,6 +124,11 @@ async function hydrateClientSettings(): Promise<void> {
|
||||
}
|
||||
|
||||
const hydrationGeneration = clientSettingsHydrationGeneration;
|
||||
setClientSettingsHydrationStatus(
|
||||
clientSettingsHydrationStatus === "failed" || clientSettingsHydrationStatus === "retrying"
|
||||
? "retrying"
|
||||
: "pending",
|
||||
);
|
||||
const nextHydration = (async () => {
|
||||
try {
|
||||
const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
|
||||
@@ -127,15 +138,16 @@ async function hydrateClientSettings(): Promise<void> {
|
||||
if (persistedSettings) {
|
||||
replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
|
||||
}
|
||||
setClientSettingsHydrationStatus("ready");
|
||||
} catch (error) {
|
||||
if (hydrationGeneration === clientSettingsHydrationGeneration) {
|
||||
setClientSettingsHydrationStatus("failed");
|
||||
}
|
||||
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, {
|
||||
operation: "hydrate",
|
||||
...safeErrorLogAttributes(error),
|
||||
});
|
||||
} finally {
|
||||
if (hydrationGeneration === clientSettingsHydrationGeneration) {
|
||||
setClientSettingsHydrated(true);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -165,15 +177,32 @@ export function persistClientSettingsPatch(
|
||||
patch: ClientSettingsPatch,
|
||||
persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
|
||||
): void {
|
||||
replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
|
||||
void enqueueClientSettingsPersistence(() => persist(getClientSettingsSnapshot())).catch(
|
||||
(error) => {
|
||||
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
|
||||
operation: "persist",
|
||||
...safeErrorLogAttributes(error),
|
||||
});
|
||||
},
|
||||
);
|
||||
// Patches queued before hydration must publish before newer optimistic patches.
|
||||
const deferPatch =
|
||||
clientSettingsHydrationStatus !== "ready" || deferredClientSettingsPatchCount > 0;
|
||||
if (deferPatch) {
|
||||
deferredClientSettingsPatchCount += 1;
|
||||
} else {
|
||||
replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
|
||||
}
|
||||
void enqueueClientSettingsPersistence(async () => {
|
||||
if (deferPatch) {
|
||||
try {
|
||||
if (clientSettingsHydrationStatus !== "ready") {
|
||||
await hydrateClientSettings();
|
||||
}
|
||||
replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
|
||||
} finally {
|
||||
deferredClientSettingsPatchCount -= 1;
|
||||
}
|
||||
}
|
||||
await persist(getClientSettingsSnapshot());
|
||||
}).catch((error) => {
|
||||
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
|
||||
operation: "persist",
|
||||
...safeErrorLogAttributes(error),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -187,6 +216,9 @@ export async function persistClientSettingsUpdate(
|
||||
persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
|
||||
): Promise<ClientSettings> {
|
||||
return enqueueClientSettingsPersistence(async () => {
|
||||
if (clientSettingsHydrationStatus !== "ready") {
|
||||
await hydrateClientSettings();
|
||||
}
|
||||
for (;;) {
|
||||
const current = getClientSettingsSnapshot();
|
||||
const next = update(current);
|
||||
@@ -234,7 +266,9 @@ export function getClientSettings(): ClientSettings {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves once client settings have been read from disk.
|
||||
* Resolves after settings load or storage confirms no saved settings exist.
|
||||
* Failed reads reject and remain retryable. They must not allow defaults to
|
||||
* overwrite saved preferences.
|
||||
*
|
||||
* The pre-hydration snapshot is just the schema defaults, so imperative paths
|
||||
* that open a preview must await this or they bake the built-in viewport, zoom
|
||||
@@ -252,6 +286,14 @@ export function useClientSettingsHydrated(): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
export function useClientSettingsHydrationStatus(): ClientSettingsHydrationStatus {
|
||||
return useSyncExternalStore(
|
||||
subscribeClientSettingsHydration,
|
||||
getClientSettingsHydrationStatusSnapshot,
|
||||
() => "pending",
|
||||
);
|
||||
}
|
||||
|
||||
function useClientSettingsValue(): ClientSettings {
|
||||
return useSyncExternalStore(
|
||||
subscribeClientSettings,
|
||||
@@ -524,9 +566,10 @@ export function useUpdateClientSettings() {
|
||||
export function __resetClientSettingsPersistenceForTests(): void {
|
||||
clientSettingsHydrationGeneration += 1;
|
||||
clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
|
||||
clientSettingsHydrated = false;
|
||||
clientSettingsHydrationStatus = "pending";
|
||||
clientSettingsHydrationPromise = null;
|
||||
clientSettingsPersistenceQueue = Promise.resolve();
|
||||
deferredClientSettingsPatchCount = 0;
|
||||
clientSettingsListeners.clear();
|
||||
clientSettingsHydrationListeners.clear();
|
||||
}
|
||||
@@ -534,6 +577,6 @@ export function __resetClientSettingsPersistenceForTests(): void {
|
||||
export function __setClientSettingsForTests(settings: ClientSettings): void {
|
||||
clientSettingsHydrationGeneration += 1;
|
||||
clientSettingsSnapshot = settings;
|
||||
clientSettingsHydrated = true;
|
||||
clientSettingsHydrationStatus = "ready";
|
||||
clientSettingsHydrationPromise = null;
|
||||
}
|
||||
@@ -204,3 +204,200 @@ describe("theme failure handling", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("onboarding theme", () => {
|
||||
it("clears custom palettes and restores the latest selected theme", async () => {
|
||||
const storage = createStorage();
|
||||
const classes = new Set<string>();
|
||||
const styleValues = new Map<string, string>();
|
||||
const root = {
|
||||
classList: {
|
||||
add: (name: string) => classes.add(name),
|
||||
remove: (name: string) => classes.delete(name),
|
||||
toggle: (name: string, force?: boolean) => {
|
||||
const next = force ?? !classes.has(name);
|
||||
if (next) classes.add(name);
|
||||
else classes.delete(name);
|
||||
return next;
|
||||
},
|
||||
},
|
||||
dataset: {} as Record<string, string>,
|
||||
offsetHeight: 0,
|
||||
style: {
|
||||
backgroundColor: "",
|
||||
removeProperty: (name: string) => styleValues.delete(name),
|
||||
setProperty: (name: string, value: string) => styleValues.set(name, value),
|
||||
},
|
||||
};
|
||||
vi.doMock("react", () => ({
|
||||
useCallback: <A>(callback: A) => callback,
|
||||
useEffect: () => undefined,
|
||||
useSyncExternalStore: (
|
||||
subscribe: (listener: () => void) => () => void,
|
||||
getSnapshot: () => unknown,
|
||||
) => {
|
||||
subscribe(() => undefined);
|
||||
return getSnapshot();
|
||||
},
|
||||
}));
|
||||
vi.stubGlobal("window", {
|
||||
addEventListener: () => undefined,
|
||||
localStorage: storage,
|
||||
matchMedia: () => ({
|
||||
matches: false,
|
||||
addEventListener: () => undefined,
|
||||
removeEventListener: () => undefined,
|
||||
}),
|
||||
removeEventListener: () => undefined,
|
||||
});
|
||||
vi.stubGlobal("document", {
|
||||
body: { style: { backgroundColor: "" } },
|
||||
createElement: () => ({ name: "", setAttribute: () => undefined }),
|
||||
documentElement: root,
|
||||
head: { append: () => undefined },
|
||||
querySelector: () => null,
|
||||
querySelectorAll: () => [],
|
||||
});
|
||||
vi.stubGlobal("getComputedStyle", () => ({
|
||||
backgroundColor: "rgb(0, 0, 0)",
|
||||
getPropertyValue: () => "",
|
||||
}));
|
||||
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
|
||||
callback(0);
|
||||
return 0;
|
||||
});
|
||||
|
||||
const { EMBER_THEME, installCustomTheme } = await import("../themePalette");
|
||||
const firstTheme = installCustomTheme({
|
||||
...EMBER_THEME,
|
||||
id: "first-custom",
|
||||
label: "First Custom",
|
||||
});
|
||||
const secondTheme = installCustomTheme({
|
||||
...EMBER_THEME,
|
||||
id: "second-custom",
|
||||
label: "Second Custom",
|
||||
colors: { ...EMBER_THEME.colors, error: "#123456" },
|
||||
});
|
||||
storage.setItem("t3code:theme", firstTheme.id);
|
||||
|
||||
const { mountOnboardingTheme, useTheme } = await import("./useTheme");
|
||||
expect(root.dataset.themeId).toBe(firstTheme.id);
|
||||
expect(styleValues.get("--app-theme-error")).toBe(firstTheme.colors.error);
|
||||
|
||||
const cleanup = mountOnboardingTheme();
|
||||
expect(root.dataset.themeId).toBeUndefined();
|
||||
expect(styleValues.size).toBe(0);
|
||||
|
||||
expect(useTheme().setTheme(secondTheme.id)).toBe(true);
|
||||
expect(root.dataset.themeId).toBeUndefined();
|
||||
expect(styleValues.size).toBe(0);
|
||||
|
||||
cleanup();
|
||||
expect(root.dataset.themeId).toBe(secondTheme.id);
|
||||
expect(styleValues.get("--app-theme-error")).toBe(secondTheme.colors.error);
|
||||
});
|
||||
|
||||
it("stays dark during storage changes and restores the latest saved theme", async () => {
|
||||
const storage = createStorage();
|
||||
storage.setItem("t3code:theme", "light");
|
||||
const classes = new Set<string>();
|
||||
const styleValues = new Map<string, string>();
|
||||
const style = {
|
||||
backgroundColor: "",
|
||||
removeProperty: (name: string) => styleValues.delete(name),
|
||||
setProperty: (name: string, value: string) => styleValues.set(name, value),
|
||||
};
|
||||
const root = {
|
||||
classList: {
|
||||
add: (name: string) => classes.add(name),
|
||||
contains: (name: string) => classes.has(name),
|
||||
remove: (name: string) => classes.delete(name),
|
||||
toggle: (name: string, force?: boolean) => {
|
||||
const next = force ?? !classes.has(name);
|
||||
if (next) classes.add(name);
|
||||
else classes.delete(name);
|
||||
return next;
|
||||
},
|
||||
},
|
||||
dataset: {} as Record<string, string>,
|
||||
offsetHeight: 0,
|
||||
style,
|
||||
};
|
||||
const body = { style: { backgroundColor: "" } };
|
||||
let storageHandler: ((event: StorageEvent) => void) | undefined;
|
||||
const setDesktopTheme = vi.fn().mockResolvedValue(undefined);
|
||||
vi.doMock("react", () => ({
|
||||
useCallback: <A>(callback: A) => callback,
|
||||
useEffect: () => undefined,
|
||||
useSyncExternalStore: (
|
||||
subscribe: (listener: () => void) => () => void,
|
||||
getSnapshot: () => unknown,
|
||||
) => {
|
||||
subscribe(() => undefined);
|
||||
return getSnapshot();
|
||||
},
|
||||
}));
|
||||
vi.stubGlobal("window", {
|
||||
addEventListener: (type: string, listener: (event: StorageEvent) => void) => {
|
||||
if (type === "storage") storageHandler = listener;
|
||||
},
|
||||
localStorage: storage,
|
||||
matchMedia: () => ({
|
||||
matches: false,
|
||||
addEventListener: () => undefined,
|
||||
removeEventListener: () => undefined,
|
||||
}),
|
||||
removeEventListener: () => undefined,
|
||||
desktopBridge: { setTheme: setDesktopTheme },
|
||||
});
|
||||
vi.stubGlobal("document", {
|
||||
body,
|
||||
createElement: () => ({ name: "", setAttribute: () => undefined }),
|
||||
documentElement: root,
|
||||
head: { append: () => undefined },
|
||||
querySelector: () => null,
|
||||
querySelectorAll: () => [],
|
||||
});
|
||||
vi.stubGlobal("getComputedStyle", () => ({
|
||||
backgroundColor:
|
||||
root.dataset.onboardingSurface !== undefined
|
||||
? "rgb(0, 0, 0)"
|
||||
: classes.has("dark")
|
||||
? "rgb(10, 10, 10)"
|
||||
: "rgb(255, 255, 255)",
|
||||
getPropertyValue: () => "",
|
||||
}));
|
||||
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
|
||||
callback(0);
|
||||
return 0;
|
||||
});
|
||||
|
||||
const { mountOnboardingTheme, useTheme } = await import("./useTheme");
|
||||
expect(useTheme().resolvedTheme).toBe("light");
|
||||
const cleanup = mountOnboardingTheme();
|
||||
|
||||
expect(root.dataset.onboardingSurface).toBe("");
|
||||
expect(classes.has("dark")).toBe(true);
|
||||
expect(root.style.backgroundColor).toBe("#000");
|
||||
expect(body.style.backgroundColor).toBe("#000");
|
||||
expect(useTheme().resolvedTheme).toBe("dark");
|
||||
expect(setDesktopTheme).toHaveBeenLastCalledWith("dark");
|
||||
|
||||
storage.setItem("t3code:theme", "dark");
|
||||
storageHandler?.({ key: "t3code:theme" } as StorageEvent);
|
||||
storage.setItem("t3code:theme", "light");
|
||||
storageHandler?.({ key: "t3code:theme" } as StorageEvent);
|
||||
expect(classes.has("dark")).toBe(true);
|
||||
expect(useTheme().resolvedTheme).toBe("dark");
|
||||
|
||||
cleanup();
|
||||
expect(root.dataset.onboardingSurface).toBeUndefined();
|
||||
expect(classes.has("dark")).toBe(false);
|
||||
expect(root.style.backgroundColor).toBe("rgb(255, 255, 255)");
|
||||
expect(body.style.backgroundColor).toBe("rgb(255, 255, 255)");
|
||||
expect(storage.getItem("t3code:theme")).toBe("light");
|
||||
expect(useTheme().resolvedTheme).toBe("light");
|
||||
expect(setDesktopTheme).toHaveBeenLastCalledWith("light");
|
||||
});
|
||||
});
|
||||
@@ -98,6 +98,14 @@ function readStoredThemeHalvesRaw(): { light?: string; dark?: string } {
|
||||
function themeHalvesSignature(halves: ThemeHalves | null): string {
|
||||
return `${halves?.light ?? ""}|${halves?.dark ?? ""}`;
|
||||
}
|
||||
|
||||
function isOnboardingThemeActive(): boolean {
|
||||
return (
|
||||
typeof document !== "undefined" &&
|
||||
document.documentElement.dataset?.onboardingSurface !== undefined
|
||||
);
|
||||
}
|
||||
|
||||
const THEME_COLOR_META_NAME = "theme-color";
|
||||
const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;
|
||||
|
||||
@@ -292,15 +300,19 @@ function resolveBrowserChromeSurface(): HTMLElement {
|
||||
|
||||
export function syncBrowserChromeTheme() {
|
||||
if (typeof document === "undefined" || typeof getComputedStyle === "undefined") return;
|
||||
const onboardingActive = isOnboardingThemeActive();
|
||||
const rootStyles = getComputedStyle(document.documentElement);
|
||||
const themeChromeColor = document.documentElement.dataset.themeId
|
||||
? normalizeThemeColor(rootStyles.getPropertyValue("--app-chrome-background"))
|
||||
: null;
|
||||
const themeChromeColor =
|
||||
!onboardingActive && document.documentElement.dataset.themeId
|
||||
? normalizeThemeColor(rootStyles.getPropertyValue("--app-chrome-background"))
|
||||
: null;
|
||||
const surfaceColor = normalizeThemeColor(
|
||||
getComputedStyle(resolveBrowserChromeSurface()).backgroundColor,
|
||||
);
|
||||
const fallbackColor = normalizeThemeColor(getComputedStyle(document.body).backgroundColor);
|
||||
const backgroundColor = themeChromeColor ?? surfaceColor ?? fallbackColor;
|
||||
const backgroundColor = onboardingActive
|
||||
? "#000"
|
||||
: (themeChromeColor ?? surfaceColor ?? fallbackColor);
|
||||
if (!backgroundColor) return;
|
||||
|
||||
document.documentElement.style.backgroundColor = backgroundColor;
|
||||
@@ -321,8 +333,15 @@ export function syncBrowserChromeTheme() {
|
||||
|
||||
function applyTheme(theme: Theme, { suppressTransitions = false, preservePreview = true } = {}) {
|
||||
if (typeof document === "undefined" || typeof window === "undefined") return;
|
||||
const onboardingActive = isOnboardingThemeActive();
|
||||
// Keep the editor's draft visible until an explicit refresh restores the selection.
|
||||
if (preservePreview && document.documentElement.dataset?.themeId === THEME_PREVIEW_ID) return;
|
||||
if (
|
||||
preservePreview &&
|
||||
!onboardingActive &&
|
||||
document.documentElement.dataset?.themeId === THEME_PREVIEW_ID
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const appearanceMode = readAppearanceModePreference(theme);
|
||||
const followSystem = appearanceMode === "system";
|
||||
const systemDark = followSystem ? getSystemDark() : false;
|
||||
@@ -334,7 +353,13 @@ function applyTheme(theme: Theme, { suppressTransitions = false, preservePreview
|
||||
lastAppliedTheme.appearanceMode === appearanceMode &&
|
||||
themeHalvesSignature(lastAppliedTheme.themeHalves) === themeHalvesSignature(themeHalves)
|
||||
) {
|
||||
syncDesktopTheme(theme, followSystem, appearanceMode);
|
||||
if (onboardingActive) {
|
||||
document.documentElement.classList.add("dark");
|
||||
syncBrowserChromeTheme();
|
||||
syncDesktopTheme("dark", false, "dark");
|
||||
} else {
|
||||
syncDesktopTheme(theme, followSystem, appearanceMode);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -348,12 +373,19 @@ function applyTheme(theme: Theme, { suppressTransitions = false, preservePreview
|
||||
appearanceMode,
|
||||
themeHalves,
|
||||
);
|
||||
applyThemePalette(resolveThemeHalf(theme, themeHalves, resolvedAppearance), resolvedAppearance);
|
||||
const isDark = resolvedAppearance === "dark";
|
||||
document.documentElement.classList.toggle("dark", isDark);
|
||||
if (onboardingActive) {
|
||||
document.documentElement.classList.add("dark");
|
||||
} else {
|
||||
applyThemePalette(resolveThemeHalf(theme, themeHalves, resolvedAppearance), resolvedAppearance);
|
||||
document.documentElement.classList.toggle("dark", resolvedAppearance === "dark");
|
||||
}
|
||||
lastAppliedTheme = { theme, systemDark, followSystem, appearanceMode, themeHalves };
|
||||
syncBrowserChromeTheme();
|
||||
syncDesktopTheme(theme, followSystem, appearanceMode);
|
||||
if (onboardingActive) {
|
||||
syncDesktopTheme("dark", false, "dark");
|
||||
} else {
|
||||
syncDesktopTheme(theme, followSystem, appearanceMode);
|
||||
}
|
||||
if (suppressTransitions) {
|
||||
// Force a reflow so the no-transitions class takes effect before removal
|
||||
void document.documentElement.offsetHeight;
|
||||
@@ -363,6 +395,28 @@ function applyTheme(theme: Theme, { suppressTransitions = false, preservePreview
|
||||
}
|
||||
}
|
||||
|
||||
/** Own the document-wide dark palette used by the first-run wizard and its portals. */
|
||||
export function mountOnboardingTheme(): () => void {
|
||||
if (typeof document === "undefined" || typeof window === "undefined") return () => {};
|
||||
|
||||
const root = document.documentElement;
|
||||
applyThemePalette("dark", "dark");
|
||||
root.dataset.onboardingSurface = "";
|
||||
root.classList.add("dark");
|
||||
syncBrowserChromeTheme();
|
||||
syncDesktopTheme("dark", false, "dark");
|
||||
emitChange();
|
||||
|
||||
return () => {
|
||||
delete root.dataset.onboardingSurface;
|
||||
root.style.backgroundColor = "";
|
||||
document.body.style.backgroundColor = "";
|
||||
lastAppliedTheme = null;
|
||||
applyTheme(getStored(), { suppressTransitions: true, preservePreview: false });
|
||||
emitChange();
|
||||
};
|
||||
}
|
||||
|
||||
export async function syncDesktopThemePreference(
|
||||
bridge: DesktopThemeBridge,
|
||||
theme: Theme,
|
||||
@@ -424,13 +478,9 @@ function getSnapshot(): ThemeSnapshot {
|
||||
const systemDark = followSystem ? getSystemDark() : false;
|
||||
const themeHalves = readStoredThemeHalves();
|
||||
|
||||
const resolvedTheme = resolveThemeAppearance(
|
||||
theme,
|
||||
systemDark,
|
||||
followSystem,
|
||||
appearanceMode,
|
||||
themeHalves,
|
||||
);
|
||||
const resolvedTheme = isOnboardingThemeActive()
|
||||
? "dark"
|
||||
: resolveThemeAppearance(theme, systemDark, followSystem, appearanceMode, themeHalves);
|
||||
if (
|
||||
lastSnapshot &&
|
||||
lastSnapshot.theme === theme &&
|
||||
|
||||
+36
-4
@@ -1184,6 +1184,39 @@ html[data-theme-id]:not([data-theme-id=""]) {
|
||||
--terminal-selection-background: var(--app-theme-terminal-selection-background);
|
||||
}
|
||||
|
||||
/* The first-run flow owns the whole document so portaled menus and tooltips
|
||||
use the same fixed palette as the wizard. This follows the theme mapping so
|
||||
saved custom themes cannot override it while onboarding is mounted. */
|
||||
html[data-onboarding-surface]:root {
|
||||
color-scheme: dark;
|
||||
--accent: #262626;
|
||||
--accent-foreground: #fff;
|
||||
--appearance-contrast-target: #fff;
|
||||
--app-chrome-background: #000;
|
||||
--background: #000;
|
||||
--border: #262626;
|
||||
--card: #000;
|
||||
--card-foreground: #fff;
|
||||
--destructive: var(--color-red-400);
|
||||
--foreground: #fff;
|
||||
--icon-muted: #a1a1aa;
|
||||
--input: #262626;
|
||||
--muted: #171717;
|
||||
--muted-foreground: #a1a1aa;
|
||||
--placeholder: #71717a;
|
||||
--popover: #171717;
|
||||
--popover-foreground: #fff;
|
||||
--ring: #737373;
|
||||
--secondary: #171717;
|
||||
--secondary-foreground: #fff;
|
||||
--secondary-label: #a1a1aa;
|
||||
--success-foreground: var(--color-emerald-400);
|
||||
--terminal-background: #000;
|
||||
--terminal-cursor: #fff;
|
||||
--terminal-foreground: #fff;
|
||||
--terminal-selection-background: rgb(255 255 255 / 20%);
|
||||
}
|
||||
|
||||
/* Theme-token dependency probes are restored synchronously, before paint. Keep
|
||||
transitions from observing the temporary sentinel color in between. */
|
||||
html[data-theme-token-probe],
|
||||
@@ -1385,11 +1418,10 @@ html[data-theme-id="t3-chat"] [data-app-sidebar] {
|
||||
}
|
||||
}
|
||||
|
||||
/* Contrast stays in ordinary custom properties so both Tailwind utilities and
|
||||
global/imperative chrome styles resolve the same adjusted role. Redeclare on
|
||||
the sidebar because it owns a local semantic palette. */
|
||||
/* Recompute contrast wherever a subtree owns its own semantic color palette. */
|
||||
:root,
|
||||
[data-app-sidebar] {
|
||||
[data-app-sidebar],
|
||||
[data-onboarding-surface] {
|
||||
--contrast-toolbar-foreground: color-mix(
|
||||
in oklab,
|
||||
color-mix(
|
||||
|
||||
@@ -0,0 +1,514 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
isFirstRunWorkspaceProvenanceAuthoritative,
|
||||
isFreshFirstRunWorkspace,
|
||||
resolveFirstRunDecision,
|
||||
resolveHostedFirstRunDecision,
|
||||
transitionFirstRunGateState,
|
||||
} from "./firstRun.logic";
|
||||
|
||||
const freshWorkspace = {
|
||||
enabled: true,
|
||||
hydrated: true,
|
||||
completed: false,
|
||||
bootstrapped: true,
|
||||
authoritative: true,
|
||||
workspaceAuthoritative: true,
|
||||
workspaceProvenanceAuthoritative: true,
|
||||
catalogReady: true,
|
||||
serverConfigAvailable: true,
|
||||
workspaceFresh: true,
|
||||
projectCount: 1,
|
||||
threadCount: 1,
|
||||
} as const;
|
||||
|
||||
describe("resolveFirstRunDecision", () => {
|
||||
it("opens the wizard for an authoritative fresh workspace", () => {
|
||||
expect(resolveFirstRunDecision(freshWorkspace)).toEqual({
|
||||
decision: "wizard",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not permanently complete onboarding from cached project counts", () => {
|
||||
expect(
|
||||
resolveFirstRunDecision({
|
||||
...freshWorkspace,
|
||||
authoritative: false,
|
||||
projectCount: 3,
|
||||
workspaceFresh: false,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "app",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("backfills completion once existing projects are confirmed by the server", () => {
|
||||
expect(
|
||||
resolveFirstRunDecision({
|
||||
...freshWorkspace,
|
||||
projectCount: 3,
|
||||
workspaceFresh: false,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "app",
|
||||
persistCompletion: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not complete onboarding while another environment is still bootstrapping", () => {
|
||||
expect(
|
||||
resolveFirstRunDecision({
|
||||
...freshWorkspace,
|
||||
bootstrapped: false,
|
||||
projectCount: 3,
|
||||
workspaceFresh: false,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "app",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("waits for managed environments before treating a workspace as new", () => {
|
||||
expect(resolveFirstRunDecision({ ...freshWorkspace, catalogReady: false })).toEqual({
|
||||
decision: "pending",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not complete onboarding before the environment catalog is ready", () => {
|
||||
expect(
|
||||
resolveFirstRunDecision({
|
||||
...freshWorkspace,
|
||||
catalogReady: false,
|
||||
projectCount: 3,
|
||||
workspaceFresh: false,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "app",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not complete onboarding before the server configuration is available", () => {
|
||||
expect(
|
||||
resolveFirstRunDecision({
|
||||
...freshWorkspace,
|
||||
projectCount: 3,
|
||||
serverConfigAvailable: false,
|
||||
workspaceFresh: false,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "app",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not complete onboarding from cached remote projects", () => {
|
||||
expect(
|
||||
resolveFirstRunDecision({
|
||||
...freshWorkspace,
|
||||
projectCount: 3,
|
||||
workspaceAuthoritative: false,
|
||||
workspaceFresh: false,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "app",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not complete onboarding from a single cached remote project", () => {
|
||||
expect(
|
||||
resolveFirstRunDecision({
|
||||
...freshWorkspace,
|
||||
workspaceAuthoritative: false,
|
||||
workspaceFresh: false,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "app",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("waits for live data before judging a single cached project", () => {
|
||||
expect(
|
||||
resolveFirstRunDecision({
|
||||
...freshWorkspace,
|
||||
authoritative: false,
|
||||
workspaceFresh: false,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "pending",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("waits for the completed bootstrap welcome before judging a nonempty workspace", () => {
|
||||
expect(
|
||||
resolveFirstRunDecision({
|
||||
...freshWorkspace,
|
||||
workspaceProvenanceAuthoritative: false,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "pending",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("waits when the initial welcome is pending and opens the wizard after completion", () => {
|
||||
const pendingProvenance = isFirstRunWorkspaceProvenanceAuthoritative({
|
||||
welcomeReceived: true,
|
||||
bootstrapStatus: "pending",
|
||||
});
|
||||
expect(
|
||||
resolveFirstRunDecision({
|
||||
...freshWorkspace,
|
||||
workspaceProvenanceAuthoritative: pendingProvenance,
|
||||
}),
|
||||
).toEqual({ decision: "pending", persistCompletion: false });
|
||||
|
||||
const completedProvenance = isFirstRunWorkspaceProvenanceAuthoritative({
|
||||
welcomeReceived: true,
|
||||
bootstrapStatus: "complete",
|
||||
});
|
||||
expect(
|
||||
resolveFirstRunDecision({
|
||||
...freshWorkspace,
|
||||
workspaceProvenanceAuthoritative: completedProvenance,
|
||||
}),
|
||||
).toEqual({ decision: "wizard", persistCompletion: false });
|
||||
});
|
||||
|
||||
it("does not wait for server data after onboarding is already complete", () => {
|
||||
expect(
|
||||
resolveFirstRunDecision({
|
||||
...freshWorkspace,
|
||||
authoritative: false,
|
||||
bootstrapped: false,
|
||||
completed: true,
|
||||
serverConfigAvailable: false,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "app",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("isFirstRunWorkspaceProvenanceAuthoritative", () => {
|
||||
it("waits for cwd bootstrap when the initial catalog is empty", () => {
|
||||
expect(
|
||||
isFirstRunWorkspaceProvenanceAuthoritative({
|
||||
welcomeReceived: true,
|
||||
bootstrapStatus: "pending",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts an empty catalog after cwd bootstrap completes", () => {
|
||||
expect(
|
||||
isFirstRunWorkspaceProvenanceAuthoritative({
|
||||
welcomeReceived: true,
|
||||
bootstrapStatus: "complete",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("waits for a welcome before treating an empty catalog as final", () => {
|
||||
expect(
|
||||
isFirstRunWorkspaceProvenanceAuthoritative({
|
||||
welcomeReceived: false,
|
||||
bootstrapStatus: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a legacy welcome without bootstrap status", () => {
|
||||
expect(
|
||||
isFirstRunWorkspaceProvenanceAuthoritative({
|
||||
welcomeReceived: true,
|
||||
bootstrapStatus: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("transitionFirstRunGateState", () => {
|
||||
it("shows recovery without mounting the app when evidence stalls", () => {
|
||||
expect(
|
||||
transitionFirstRunGateState({ decision: "pending", stalled: false }, { type: "timeout" }),
|
||||
).toEqual({ decision: "pending", stalled: true });
|
||||
});
|
||||
|
||||
it.each(["app", "wizard"] as const)(
|
||||
"resolves stalled recovery to %s only after authoritative evidence",
|
||||
(decision) => {
|
||||
expect(
|
||||
transitionFirstRunGateState(
|
||||
{ decision: "pending", stalled: true },
|
||||
{ type: "evidence", decision },
|
||||
),
|
||||
).toEqual({ decision, stalled: false });
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps recovery visible while evidence remains pending", () => {
|
||||
const state = { decision: "pending", stalled: true } as const;
|
||||
expect(transitionFirstRunGateState(state, { type: "evidence", decision: "pending" })).toBe(
|
||||
state,
|
||||
);
|
||||
});
|
||||
|
||||
it("allows authoritative wizard evidence to replace an app decision", () => {
|
||||
expect(
|
||||
transitionFirstRunGateState(
|
||||
{ decision: "app", stalled: false },
|
||||
{ type: "evidence", decision: "wizard" },
|
||||
),
|
||||
).toEqual({ decision: "wizard", stalled: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveHostedFirstRunDecision", () => {
|
||||
it("keeps the shell hidden until client settings are hydrated", () => {
|
||||
expect(
|
||||
resolveHostedFirstRunDecision({
|
||||
hydrated: false,
|
||||
completed: false,
|
||||
catalogReady: true,
|
||||
environmentCount: 0,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "pending",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("waits for the saved environment catalog before judging a hosted install", () => {
|
||||
expect(
|
||||
resolveHostedFirstRunDecision({
|
||||
hydrated: true,
|
||||
completed: false,
|
||||
catalogReady: false,
|
||||
environmentCount: 0,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "pending",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("opens onboarding when a hosted install has no saved environments", () => {
|
||||
expect(
|
||||
resolveHostedFirstRunDecision({
|
||||
hydrated: true,
|
||||
completed: false,
|
||||
catalogReady: true,
|
||||
environmentCount: 0,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "wizard",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("backfills onboarding for a hosted install with saved environments", () => {
|
||||
expect(
|
||||
resolveHostedFirstRunDecision({
|
||||
hydrated: true,
|
||||
completed: false,
|
||||
catalogReady: true,
|
||||
environmentCount: 1,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "app",
|
||||
persistCompletion: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("opens the app immediately after hosted onboarding is complete", () => {
|
||||
expect(
|
||||
resolveHostedFirstRunDecision({
|
||||
hydrated: true,
|
||||
completed: true,
|
||||
catalogReady: false,
|
||||
environmentCount: 0,
|
||||
}),
|
||||
).toEqual({
|
||||
decision: "app",
|
||||
persistCompletion: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const primaryEnvironmentId = "primary-environment";
|
||||
const bootstrapProject = {
|
||||
id: "bootstrap-project",
|
||||
environmentId: primaryEnvironmentId,
|
||||
workspaceRoot: "/projects/current",
|
||||
};
|
||||
const bootstrapThread = {
|
||||
id: "bootstrap-thread",
|
||||
projectId: bootstrapProject.id,
|
||||
environmentId: primaryEnvironmentId,
|
||||
latestTurn: null,
|
||||
latestUserMessageAt: null,
|
||||
session: null,
|
||||
};
|
||||
|
||||
describe("isFreshFirstRunWorkspace", () => {
|
||||
it("accepts an empty workspace", () => {
|
||||
expect(
|
||||
isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd: "/projects/current",
|
||||
projects: [],
|
||||
threads: [],
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts only the unused project and thread created from the server cwd", () => {
|
||||
expect(
|
||||
isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd: "/projects/current/",
|
||||
bootstrapProjectId: bootstrapProject.id,
|
||||
bootstrapThreadId: bootstrapThread.id,
|
||||
bootstrapProjectCreated: true,
|
||||
bootstrapThreadCreated: true,
|
||||
projects: [bootstrapProject],
|
||||
threads: [bootstrapThread],
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an existing unused cwd project and thread reused by startup", () => {
|
||||
expect(
|
||||
isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd: "/projects/current",
|
||||
bootstrapProjectId: bootstrapProject.id,
|
||||
bootstrapThreadId: bootstrapThread.id,
|
||||
bootstrapProjectCreated: false,
|
||||
bootstrapThreadCreated: false,
|
||||
projects: [bootstrapProject],
|
||||
threads: [bootstrapThread],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a nonempty workspace when an older server omits creation provenance", () => {
|
||||
expect(
|
||||
isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd: "/projects/current",
|
||||
bootstrapProjectId: bootstrapProject.id,
|
||||
bootstrapThreadId: bootstrapThread.id,
|
||||
projects: [bootstrapProject],
|
||||
threads: [bootstrapThread],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("normalizes Windows project paths before checking the bootstrap workspace", () => {
|
||||
expect(
|
||||
isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd: "C:\\Projects\\Current\\",
|
||||
bootstrapProjectId: bootstrapProject.id,
|
||||
bootstrapThreadId: bootstrapThread.id,
|
||||
bootstrapProjectCreated: true,
|
||||
bootstrapThreadCreated: true,
|
||||
projects: [{ ...bootstrapProject, workspaceRoot: "c:/projects/current" }],
|
||||
threads: [bootstrapThread],
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects projects from another environment even when their paths match", () => {
|
||||
expect(
|
||||
isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd: "/projects/current",
|
||||
projects: [{ ...bootstrapProject, environmentId: "remote-environment" }],
|
||||
threads: [],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects threads from another environment", () => {
|
||||
expect(
|
||||
isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd: "/projects/current",
|
||||
projects: [bootstrapProject],
|
||||
threads: [{ ...bootstrapThread, environmentId: "remote-environment" }],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a thread that does not belong to the bootstrap project", () => {
|
||||
expect(
|
||||
isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd: "/projects/current",
|
||||
projects: [bootstrapProject],
|
||||
threads: [{ ...bootstrapThread, projectId: "another-project" }],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a thread when there is no bootstrap project", () => {
|
||||
expect(
|
||||
isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd: "/projects/current",
|
||||
projects: [],
|
||||
threads: [bootstrapThread],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a bootstrap thread that already has a user message", () => {
|
||||
expect(
|
||||
isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd: "/projects/current",
|
||||
projects: [bootstrapProject],
|
||||
threads: [
|
||||
{
|
||||
...bootstrapThread,
|
||||
latestUserMessageAt: "2026-08-23T12:00:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a bootstrap thread that has started a turn", () => {
|
||||
expect(
|
||||
isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd: "/projects/current",
|
||||
projects: [bootstrapProject],
|
||||
threads: [{ ...bootstrapThread, latestTurn: { id: "first-turn" } }],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a bootstrap thread that has a provider session", () => {
|
||||
expect(
|
||||
isFreshFirstRunWorkspace({
|
||||
primaryEnvironmentId,
|
||||
serverCwd: "/projects/current",
|
||||
projects: [bootstrapProject],
|
||||
threads: [{ ...bootstrapThread, session: { status: "ready" } }],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
|
||||
|
||||
export type FirstRunDecision = "pending" | "app" | "wizard";
|
||||
|
||||
export interface FirstRunGateState {
|
||||
readonly decision: FirstRunDecision;
|
||||
readonly stalled: boolean;
|
||||
}
|
||||
|
||||
type FirstRunGateEvent =
|
||||
| { readonly type: "evidence"; readonly decision: FirstRunDecision }
|
||||
| { readonly type: "timeout" };
|
||||
|
||||
interface FirstRunWorkspaceInput {
|
||||
readonly primaryEnvironmentId: string | null;
|
||||
readonly serverCwd: string | null;
|
||||
readonly bootstrapProjectId?: string | undefined;
|
||||
readonly bootstrapThreadId?: string | undefined;
|
||||
readonly bootstrapProjectCreated?: boolean | undefined;
|
||||
readonly bootstrapThreadCreated?: boolean | undefined;
|
||||
readonly projects: ReadonlyArray<{
|
||||
readonly id: string;
|
||||
readonly environmentId: string;
|
||||
readonly workspaceRoot: string;
|
||||
}>;
|
||||
readonly threads: ReadonlyArray<{
|
||||
readonly id: string;
|
||||
readonly projectId: string;
|
||||
readonly environmentId: string;
|
||||
readonly latestTurn: unknown;
|
||||
readonly latestUserMessageAt: string | null;
|
||||
readonly session: unknown;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface FirstRunDecisionInput {
|
||||
readonly enabled: boolean;
|
||||
readonly hydrated: boolean;
|
||||
readonly completed: boolean;
|
||||
readonly bootstrapped: boolean;
|
||||
readonly authoritative: boolean;
|
||||
readonly workspaceAuthoritative: boolean;
|
||||
readonly workspaceProvenanceAuthoritative: boolean;
|
||||
readonly catalogReady: boolean;
|
||||
readonly serverConfigAvailable: boolean;
|
||||
readonly workspaceFresh: boolean;
|
||||
readonly projectCount: number;
|
||||
readonly threadCount: number;
|
||||
}
|
||||
|
||||
interface HostedFirstRunDecisionInput {
|
||||
readonly hydrated: boolean;
|
||||
readonly completed: boolean;
|
||||
readonly catalogReady: boolean;
|
||||
readonly environmentCount: number;
|
||||
}
|
||||
|
||||
export function isFirstRunWorkspaceProvenanceAuthoritative(input: {
|
||||
readonly welcomeReceived: boolean;
|
||||
readonly bootstrapStatus: "pending" | "complete" | null;
|
||||
}): boolean {
|
||||
// An empty catalog is not final while cwd auto-bootstrap is pending. Older
|
||||
// servers omit bootstrapStatus, so a received welcome with null stays valid.
|
||||
return input.welcomeReceived && input.bootstrapStatus !== "pending";
|
||||
}
|
||||
|
||||
/** Keeps the authenticated app unmounted until workspace evidence settles. */
|
||||
export function transitionFirstRunGateState(
|
||||
state: FirstRunGateState,
|
||||
event: FirstRunGateEvent,
|
||||
): FirstRunGateState {
|
||||
if (event.type === "timeout") {
|
||||
return state.decision === "pending" && !state.stalled ? { ...state, stalled: true } : state;
|
||||
}
|
||||
|
||||
if (
|
||||
state.decision === "wizard" ||
|
||||
event.decision === "pending" ||
|
||||
(state.decision === "app" && event.decision !== "wizard")
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
|
||||
return { decision: event.decision, stalled: false };
|
||||
}
|
||||
|
||||
/** Only a project and thread created by this startup count as a fresh nonempty workspace. */
|
||||
export function isFreshFirstRunWorkspace(input: FirstRunWorkspaceInput): boolean {
|
||||
if (input.projects.length > 1 || input.threads.length > 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const bootstrapProject = input.projects[0];
|
||||
if (bootstrapProject !== undefined) {
|
||||
if (
|
||||
input.bootstrapProjectCreated !== true ||
|
||||
input.bootstrapProjectId !== bootstrapProject.id ||
|
||||
input.serverCwd === null ||
|
||||
bootstrapProject.environmentId !== input.primaryEnvironmentId ||
|
||||
normalizeProjectPathForComparison(bootstrapProject.workspaceRoot) !==
|
||||
normalizeProjectPathForComparison(input.serverCwd)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const bootstrapThread = input.threads[0];
|
||||
if (bootstrapThread === undefined) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
bootstrapProject !== undefined &&
|
||||
input.bootstrapThreadCreated === true &&
|
||||
input.bootstrapThreadId === bootstrapThread.id &&
|
||||
bootstrapThread.environmentId === input.primaryEnvironmentId &&
|
||||
bootstrapThread.projectId === bootstrapProject.id &&
|
||||
bootstrapThread.latestTurn === null &&
|
||||
bootstrapThread.latestUserMessageAt === null &&
|
||||
bootstrapThread.session === null
|
||||
);
|
||||
}
|
||||
|
||||
/** Cached projects may open the app, but only live workspace data may complete onboarding. */
|
||||
export function resolveFirstRunDecision(input: FirstRunDecisionInput): {
|
||||
readonly decision: FirstRunDecision;
|
||||
readonly persistCompletion: boolean;
|
||||
} {
|
||||
if (!input.enabled || (input.hydrated && input.completed)) {
|
||||
return { decision: "app", persistCompletion: false };
|
||||
}
|
||||
|
||||
if (!input.hydrated) {
|
||||
return { decision: "pending", persistCompletion: false };
|
||||
}
|
||||
|
||||
if (input.projectCount > 1 || input.threadCount > 1) {
|
||||
return {
|
||||
decision: "app",
|
||||
persistCompletion:
|
||||
input.bootstrapped &&
|
||||
input.authoritative &&
|
||||
input.workspaceAuthoritative &&
|
||||
input.catalogReady &&
|
||||
input.serverConfigAvailable,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
!input.bootstrapped ||
|
||||
!input.authoritative ||
|
||||
!input.workspaceProvenanceAuthoritative ||
|
||||
!input.catalogReady ||
|
||||
!input.serverConfigAvailable
|
||||
) {
|
||||
return { decision: "pending", persistCompletion: false };
|
||||
}
|
||||
|
||||
return input.workspaceFresh
|
||||
? { decision: "wizard", persistCompletion: false }
|
||||
: { decision: "app", persistCompletion: input.workspaceAuthoritative };
|
||||
}
|
||||
|
||||
/** Hosted onboarding depends on saved environments because there is no primary server. */
|
||||
export function resolveHostedFirstRunDecision(input: HostedFirstRunDecisionInput): {
|
||||
readonly decision: FirstRunDecision;
|
||||
readonly persistCompletion: boolean;
|
||||
} {
|
||||
if (!input.hydrated) {
|
||||
return { decision: "pending", persistCompletion: false };
|
||||
}
|
||||
|
||||
if (input.completed) {
|
||||
return { decision: "app", persistCompletion: false };
|
||||
}
|
||||
|
||||
if (!input.catalogReady) {
|
||||
return { decision: "pending", persistCompletion: false };
|
||||
}
|
||||
|
||||
return input.environmentCount === 0
|
||||
? { decision: "wizard", persistCompletion: false }
|
||||
: { decision: "app", persistCompletion: true };
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { ensureClientSettingsHydrated, persistClientSettingsUpdate } from "../hooks/useSettings";
|
||||
|
||||
/**
|
||||
* Marks first-run onboarding finished (or skipped) so FirstRunGate never
|
||||
* routes to the welcome wizard again. The gate itself lives in
|
||||
* `components/onboarding/FirstRunGate.tsx`.
|
||||
*/
|
||||
export function useCompleteOnboarding(): () => Promise<void> {
|
||||
return useCallback(async () => {
|
||||
await ensureClientSettingsHydrated();
|
||||
const onboardingCompletedAt = new Date().toISOString();
|
||||
await persistClientSettingsUpdate((current) => ({ ...current, onboardingCompletedAt }));
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
import { EnvironmentId, ProjectId, type AgentSessionProjectCandidate } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
partitionOnboardingProjects,
|
||||
resolveOnboardingLandingProject,
|
||||
resolveOnboardingProjectId,
|
||||
} from "./projectImport.logic";
|
||||
|
||||
const now = Date.parse("2026-08-22T12:00:00.000Z");
|
||||
|
||||
function candidate(
|
||||
path: string,
|
||||
overrides: Partial<AgentSessionProjectCandidate> = {},
|
||||
): AgentSessionProjectCandidate {
|
||||
return {
|
||||
title: path.split("/").at(-1) ?? path,
|
||||
path,
|
||||
sources: ["codex"],
|
||||
threadCount: 1,
|
||||
lastActiveAt: "2026-08-20T12:00:00.000Z",
|
||||
alreadyImported: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("partitionOnboardingProjects", () => {
|
||||
it("keeps existing projects available for thread history import", () => {
|
||||
const imported = candidate("/projects/current", { alreadyImported: true });
|
||||
const available = candidate("/projects/other");
|
||||
|
||||
expect(partitionOnboardingProjects([imported, available], now)).toEqual({
|
||||
available: [imported, available],
|
||||
recent: [imported, available],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps projects older than 30 days out of the default selection", () => {
|
||||
const recent = candidate("/projects/recent");
|
||||
const older = candidate("/projects/older", {
|
||||
lastActiveAt: "2026-07-01T12:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(partitionOnboardingProjects([recent, older], now)).toEqual({
|
||||
available: [recent, older],
|
||||
recent: [recent],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps future activity out of the default selection", () => {
|
||||
const recent = candidate("/projects/recent");
|
||||
const future = candidate("/projects/future", {
|
||||
lastActiveAt: "2026-08-23T12:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(partitionOnboardingProjects([recent, future], now)).toEqual({
|
||||
available: [recent, future],
|
||||
recent: [recent],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveOnboardingProjectId", () => {
|
||||
const localEnvironmentId = EnvironmentId.make("local");
|
||||
const remoteEnvironmentId = EnvironmentId.make("remote");
|
||||
const localProjectId = ProjectId.make("local-project");
|
||||
|
||||
it("uses the scanned project ID before the project reaches the client", () => {
|
||||
expect(
|
||||
resolveOnboardingProjectId(
|
||||
[],
|
||||
localEnvironmentId,
|
||||
candidate("/projects/repo", { projectId: localProjectId }),
|
||||
),
|
||||
).toBe(localProjectId);
|
||||
});
|
||||
|
||||
it("uses the scanned project ID when the client still has an older project at that root", () => {
|
||||
expect(
|
||||
resolveOnboardingProjectId(
|
||||
[
|
||||
{
|
||||
id: ProjectId.make("stale-project"),
|
||||
environmentId: localEnvironmentId,
|
||||
workspaceRoot: "/projects/repo",
|
||||
},
|
||||
],
|
||||
localEnvironmentId,
|
||||
candidate("/projects/repo", { projectId: localProjectId }),
|
||||
),
|
||||
).toBe(localProjectId);
|
||||
});
|
||||
|
||||
it("returns null to create a project when neither the scan nor the client has a project ID", () => {
|
||||
expect(
|
||||
resolveOnboardingProjectId([], localEnvironmentId, candidate("/projects/new")),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("finds an existing project by normalized root in the target environment", () => {
|
||||
expect(
|
||||
resolveOnboardingProjectId(
|
||||
[
|
||||
{
|
||||
id: ProjectId.make("remote-project"),
|
||||
environmentId: remoteEnvironmentId,
|
||||
workspaceRoot: "C:\\Work\\Repo",
|
||||
},
|
||||
{
|
||||
id: localProjectId,
|
||||
environmentId: localEnvironmentId,
|
||||
workspaceRoot: "C:\\Work\\Repo\\",
|
||||
},
|
||||
],
|
||||
localEnvironmentId,
|
||||
candidate("c:/work/repo"),
|
||||
),
|
||||
).toBe(localProjectId);
|
||||
});
|
||||
|
||||
it("does not reuse a project from another environment", () => {
|
||||
expect(
|
||||
resolveOnboardingProjectId(
|
||||
[
|
||||
{
|
||||
id: ProjectId.make("remote-project"),
|
||||
environmentId: remoteEnvironmentId,
|
||||
workspaceRoot: "/projects/repo",
|
||||
},
|
||||
],
|
||||
localEnvironmentId,
|
||||
candidate("/projects/repo"),
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("finds an alias after the scanner returns its persisted project root", () => {
|
||||
expect(
|
||||
resolveOnboardingProjectId(
|
||||
[
|
||||
{
|
||||
id: localProjectId,
|
||||
environmentId: localEnvironmentId,
|
||||
workspaceRoot: "/real/projects/repo",
|
||||
},
|
||||
],
|
||||
localEnvironmentId,
|
||||
candidate("/real/projects/repo"),
|
||||
),
|
||||
).toBe(localProjectId);
|
||||
});
|
||||
|
||||
it("finds the current root owner when the scan has no project ID", () => {
|
||||
const recreatedProjectId = ProjectId.make("recreated-project");
|
||||
expect(
|
||||
resolveOnboardingProjectId(
|
||||
[
|
||||
{
|
||||
id: localProjectId,
|
||||
environmentId: localEnvironmentId,
|
||||
workspaceRoot: "/projects/other",
|
||||
},
|
||||
{
|
||||
id: recreatedProjectId,
|
||||
environmentId: localEnvironmentId,
|
||||
workspaceRoot: "/projects/repo",
|
||||
},
|
||||
],
|
||||
localEnvironmentId,
|
||||
candidate("/projects/repo"),
|
||||
),
|
||||
).toBe(recreatedProjectId);
|
||||
});
|
||||
|
||||
it("does not reuse a moved project when the scan has no project ID", () => {
|
||||
expect(
|
||||
resolveOnboardingProjectId(
|
||||
[
|
||||
{
|
||||
id: localProjectId,
|
||||
environmentId: localEnvironmentId,
|
||||
workspaceRoot: "/projects/moved",
|
||||
},
|
||||
],
|
||||
localEnvironmentId,
|
||||
candidate("/projects/repo"),
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveOnboardingLandingProject", () => {
|
||||
it("skips a failed first project for a later project with imported history", () => {
|
||||
expect(
|
||||
resolveOnboardingLandingProject(
|
||||
["/projects/failed", "/projects/imported"],
|
||||
new Map([["/projects/imported", "imported"]]),
|
||||
new Map([["/projects/imported", "imported"]]),
|
||||
),
|
||||
).toBe("imported");
|
||||
});
|
||||
|
||||
it("prefers a partial first import that added history", () => {
|
||||
expect(
|
||||
resolveOnboardingLandingProject(
|
||||
["/projects/partial", "/projects/complete"],
|
||||
new Map([["/projects/partial", "partial"]]),
|
||||
new Map([["/projects/complete", "complete"]]),
|
||||
),
|
||||
).toBe("partial");
|
||||
});
|
||||
|
||||
it("uses a completed zero-history project when no import added history", () => {
|
||||
expect(
|
||||
resolveOnboardingLandingProject(
|
||||
["/projects/empty", "/projects/failed"],
|
||||
new Map(),
|
||||
new Map([["/projects/empty", "empty"]]),
|
||||
),
|
||||
).toBe("empty");
|
||||
});
|
||||
|
||||
it("keeps an earlier successful import available on retry", () => {
|
||||
expect(
|
||||
resolveOnboardingLandingProject(
|
||||
["/projects/imported", "/projects/retry"],
|
||||
new Map([["/projects/imported", "imported"]]),
|
||||
new Map([["/projects/imported", "imported"]]),
|
||||
),
|
||||
).toBe("imported");
|
||||
});
|
||||
|
||||
it("ignores cached successes outside the current retry selection", () => {
|
||||
expect(
|
||||
resolveOnboardingLandingProject(
|
||||
["/projects/current"],
|
||||
new Map([["/projects/previous", "previous"]]),
|
||||
new Map([
|
||||
["/projects/previous", "previous"],
|
||||
["/projects/current", "current"],
|
||||
]),
|
||||
),
|
||||
).toBe("current");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { findProjectByPath } from "@t3tools/client-runtime/state/projects";
|
||||
import type { AgentSessionProjectCandidate, EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
const RECENT_PROJECT_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/** Existing projects still need their agent history imported, so every scan candidate is offered. */
|
||||
export function partitionOnboardingProjects(
|
||||
candidates: ReadonlyArray<AgentSessionProjectCandidate>,
|
||||
now = Date.now(),
|
||||
) {
|
||||
const cutoff = now - RECENT_PROJECT_WINDOW_MS;
|
||||
|
||||
return {
|
||||
available: candidates,
|
||||
recent: candidates.filter((candidate) => {
|
||||
if (candidate.lastActiveAt === null) return false;
|
||||
const lastActiveAt = Date.parse(candidate.lastActiveAt);
|
||||
return lastActiveAt >= cutoff && lastActiveAt <= now;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Use the server's project match before the client snapshot, which can lag behind the scan. */
|
||||
export function resolveOnboardingProjectId(
|
||||
projects: ReadonlyArray<{
|
||||
readonly id: ProjectId;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly workspaceRoot: string;
|
||||
}>,
|
||||
environmentId: EnvironmentId,
|
||||
candidate: Pick<AgentSessionProjectCandidate, "path" | "projectId">,
|
||||
): ProjectId | null {
|
||||
if (candidate.projectId !== undefined) return candidate.projectId;
|
||||
const environmentProjects = projects.filter((project) => project.environmentId === environmentId);
|
||||
const currentRootMatch = findProjectByPath(environmentProjects, candidate.path);
|
||||
if (currentRootMatch !== undefined) return currentRootMatch.id;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Prefer a selected project with imported history, then a completed empty import. */
|
||||
export function resolveOnboardingLandingProject<T>(
|
||||
selection: ReadonlyArray<string>,
|
||||
projectsWithImportedHistory: ReadonlyMap<string, T>,
|
||||
completedProjects: ReadonlyMap<string, T>,
|
||||
): T | undefined {
|
||||
for (const path of selection) {
|
||||
const project = projectsWithImportedHistory.get(path);
|
||||
if (project !== undefined) return project;
|
||||
}
|
||||
for (const path of selection) {
|
||||
const project = completedProjects.get(path);
|
||||
if (project !== undefined) return project;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
getOnboardingProviderState,
|
||||
resolveOnboardingProviderLoginCommand,
|
||||
selectOnboardingProvidersByDriver,
|
||||
} from "./providerReadiness.logic";
|
||||
|
||||
const readyCodex: ServerProvider = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-08-23T00:00:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
};
|
||||
|
||||
describe("getOnboardingProviderState", () => {
|
||||
it("treats an enabled Codex provider with ready status and unknown authentication as ready", () => {
|
||||
expect(getOnboardingProviderState(readyCodex)).toBe("ready");
|
||||
});
|
||||
|
||||
it("treats authenticated providers as ready only when their provider status is ready", () => {
|
||||
expect(getOnboardingProviderState({ ...readyCodex, auth: { status: "authenticated" } })).toBe(
|
||||
"ready",
|
||||
);
|
||||
expect(
|
||||
getOnboardingProviderState({
|
||||
...readyCodex,
|
||||
auth: { status: "authenticated" },
|
||||
status: "error",
|
||||
}),
|
||||
).toBe("attention");
|
||||
expect(
|
||||
getOnboardingProviderState({
|
||||
...readyCodex,
|
||||
auth: { status: "authenticated" },
|
||||
status: "warning",
|
||||
}),
|
||||
).toBe("attention");
|
||||
});
|
||||
|
||||
it("offers sign-in only when the server reports an authentication failure", () => {
|
||||
expect(
|
||||
getOnboardingProviderState({
|
||||
...readyCodex,
|
||||
status: "error",
|
||||
auth: { status: "unauthenticated" },
|
||||
}),
|
||||
).toBe("signIn");
|
||||
expect(getOnboardingProviderState({ ...readyCodex, status: "error" })).toBe("attention");
|
||||
expect(getOnboardingProviderState({ ...readyCodex, status: "warning" })).toBe("attention");
|
||||
});
|
||||
|
||||
it("does not offer installation or sign-in for disabled providers", () => {
|
||||
expect(getOnboardingProviderState({ ...readyCodex, enabled: false, installed: false })).toBe(
|
||||
"disabled",
|
||||
);
|
||||
expect(getOnboardingProviderState({ ...readyCodex, status: "disabled" })).toBe("disabled");
|
||||
});
|
||||
|
||||
it("offers installation only when an enabled provider is missing", () => {
|
||||
expect(getOnboardingProviderState({ ...readyCodex, installed: false, status: "error" })).toBe(
|
||||
"install",
|
||||
);
|
||||
});
|
||||
|
||||
it("waits for a provider snapshot before offering an action", () => {
|
||||
expect(getOnboardingProviderState(undefined)).toBe("checking");
|
||||
});
|
||||
});
|
||||
|
||||
describe("selectOnboardingProvidersByDriver", () => {
|
||||
it("prefers a ready instance with unknown authentication to an unauthenticated instance", () => {
|
||||
const signedOutCodex: ServerProvider = {
|
||||
...readyCodex,
|
||||
instanceId: ProviderInstanceId.make("codex_work"),
|
||||
status: "error",
|
||||
auth: { status: "unauthenticated" },
|
||||
};
|
||||
|
||||
expect(selectOnboardingProvidersByDriver([signedOutCodex, readyCodex]).get("codex")).toBe(
|
||||
readyCodex,
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers a provider with an actionable sign-in over a failed provider", () => {
|
||||
const failedCodex: ServerProvider = { ...readyCodex, status: "error" };
|
||||
const signedOutCodex: ServerProvider = {
|
||||
...readyCodex,
|
||||
instanceId: ProviderInstanceId.make("codex_work"),
|
||||
status: "error",
|
||||
auth: { status: "unauthenticated" },
|
||||
};
|
||||
|
||||
expect(selectOnboardingProvidersByDriver([failedCodex, signedOutCodex]).get("codex")).toBe(
|
||||
signedOutCodex,
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers installed providers over missing or disabled instances", () => {
|
||||
const disabledCodex: ServerProvider = { ...readyCodex, enabled: false };
|
||||
const missingCodex: ServerProvider = {
|
||||
...readyCodex,
|
||||
instanceId: ProviderInstanceId.make("codex_work"),
|
||||
installed: false,
|
||||
status: "error",
|
||||
};
|
||||
|
||||
expect(
|
||||
selectOnboardingProvidersByDriver([disabledCodex, missingCodex, readyCodex]).get("codex"),
|
||||
).toBe(readyCodex);
|
||||
});
|
||||
|
||||
it("handles provider snapshots that have not arrived", () => {
|
||||
expect(selectOnboardingProvidersByDriver(undefined).size).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps a ready custom account when the default account is signed out", () => {
|
||||
const signedOutDefault: ServerProvider = {
|
||||
...readyCodex,
|
||||
status: "error",
|
||||
auth: { status: "unauthenticated" },
|
||||
};
|
||||
const readyCustom: ServerProvider = {
|
||||
...readyCodex,
|
||||
instanceId: ProviderInstanceId.make("codex_work"),
|
||||
};
|
||||
|
||||
expect(selectOnboardingProvidersByDriver([signedOutDefault, readyCustom]).get("codex")).toBe(
|
||||
readyCustom,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveOnboardingProviderLoginCommand", () => {
|
||||
it("uses the selected Codex account binary", () => {
|
||||
const provider = { ...readyCodex, instanceId: ProviderInstanceId.make("codex_work") };
|
||||
|
||||
expect(
|
||||
resolveOnboardingProviderLoginCommand(
|
||||
provider,
|
||||
{
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providerInstances: {
|
||||
[provider.instanceId]: {
|
||||
driver: provider.driver,
|
||||
config: { binaryPath: "/opt/codex-work/bin/codex" },
|
||||
},
|
||||
},
|
||||
},
|
||||
"linux",
|
||||
),
|
||||
).toBe("/opt/codex-work/bin/codex login");
|
||||
});
|
||||
|
||||
it("uses the selected Claude account binary", () => {
|
||||
const provider: ServerProvider = {
|
||||
...readyCodex,
|
||||
driver: ProviderDriverKind.make("claudeAgent"),
|
||||
instanceId: ProviderInstanceId.make("claude_work"),
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveOnboardingProviderLoginCommand(
|
||||
provider,
|
||||
{
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providerInstances: {
|
||||
[provider.instanceId]: {
|
||||
driver: provider.driver,
|
||||
config: { binaryPath: "/opt/claude-work/bin/claude" },
|
||||
},
|
||||
},
|
||||
},
|
||||
"linux",
|
||||
),
|
||||
).toBe("/opt/claude-work/bin/claude auth login");
|
||||
});
|
||||
|
||||
it("quotes a Codex path with spaces for PowerShell", () => {
|
||||
expect(
|
||||
resolveOnboardingProviderLoginCommand(
|
||||
readyCodex,
|
||||
{
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providers: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
codex: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.codex,
|
||||
binaryPath: "C:\\Program Files\\Codex & Tools\\codex.exe",
|
||||
},
|
||||
},
|
||||
},
|
||||
"windows",
|
||||
),
|
||||
).toBe("& 'C:\\Program Files\\Codex & Tools\\codex.exe' login");
|
||||
});
|
||||
|
||||
it("quotes a Claude path with shell metacharacters on POSIX", () => {
|
||||
const provider: ServerProvider = {
|
||||
...readyCodex,
|
||||
driver: ProviderDriverKind.make("claudeAgent"),
|
||||
instanceId: ProviderInstanceId.make("claude"),
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveOnboardingProviderLoginCommand(
|
||||
provider,
|
||||
{
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providers: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
claudeAgent: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.claudeAgent,
|
||||
binaryPath: "/opt/Claude Tools/$current/claude",
|
||||
},
|
||||
},
|
||||
},
|
||||
"linux",
|
||||
),
|
||||
).toBe("'/opt/Claude Tools/$current/claude' auth login");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["~/my tools/codex", "~/'my tools/codex' login"],
|
||||
["~\\my tools/codex", "~/'my tools/codex' login"],
|
||||
["~/tools/codex's build", `~/'tools/codex'"'"'s build' login`],
|
||||
["~\\tools\\codex's build", `~/'tools\\codex'"'"'s build' login`],
|
||||
["~/tools/codex; echo unsafe", "~/'tools/codex; echo unsafe' login"],
|
||||
])("keeps the home prefix expandable while quoting %s", (binaryPath, expectedCommand) => {
|
||||
expect(
|
||||
resolveOnboardingProviderLoginCommand(
|
||||
readyCodex,
|
||||
{
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providers: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
codex: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.codex,
|
||||
binaryPath,
|
||||
},
|
||||
},
|
||||
},
|
||||
"linux",
|
||||
),
|
||||
).toBe(expectedCommand);
|
||||
});
|
||||
|
||||
it.each(["darwin", "linux"] as const)("quotes backslashes in a Codex path on %s", (platform) => {
|
||||
expect(
|
||||
resolveOnboardingProviderLoginCommand(
|
||||
readyCodex,
|
||||
{
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providers: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
codex: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.codex,
|
||||
binaryPath: "/opt/codex\\work/codex",
|
||||
},
|
||||
},
|
||||
},
|
||||
platform,
|
||||
),
|
||||
).toBe("'/opt/codex\\work/codex' login");
|
||||
});
|
||||
|
||||
it("keeps a plain Windows path unquoted", () => {
|
||||
expect(
|
||||
resolveOnboardingProviderLoginCommand(
|
||||
readyCodex,
|
||||
{
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providers: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
codex: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.codex,
|
||||
binaryPath: "C:\\Tools\\codex.exe",
|
||||
},
|
||||
},
|
||||
},
|
||||
"windows",
|
||||
),
|
||||
).toBe("C:\\Tools\\codex.exe login");
|
||||
});
|
||||
|
||||
it("uses the default command when an old server reports an unknown shell", () => {
|
||||
expect(
|
||||
resolveOnboardingProviderLoginCommand(
|
||||
readyCodex,
|
||||
{
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
providers: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers,
|
||||
codex: {
|
||||
...DEFAULT_SERVER_SETTINGS.providers.codex,
|
||||
binaryPath: "/opt/Codex Tools/codex",
|
||||
},
|
||||
},
|
||||
},
|
||||
"unknown",
|
||||
),
|
||||
).toBe("codex login");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import {
|
||||
ClaudeSettings,
|
||||
CodexSettings,
|
||||
type ExecutionEnvironmentPlatformOs,
|
||||
type ServerProvider,
|
||||
type ServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
|
||||
const decodeCodexSettings = Schema.decodeUnknownOption(CodexSettings);
|
||||
const SAFE_SHELL_BINARY_PATTERN = /^[A-Za-z0-9_./:\\-]+$/;
|
||||
|
||||
function quoteProviderBinary(
|
||||
binaryPath: string,
|
||||
fallback: string,
|
||||
platform: ExecutionEnvironmentPlatformOs,
|
||||
): string {
|
||||
if (
|
||||
SAFE_SHELL_BINARY_PATTERN.test(binaryPath) &&
|
||||
(platform === "windows" || !binaryPath.includes("\\"))
|
||||
) {
|
||||
return binaryPath;
|
||||
}
|
||||
if (platform === "windows") return `& '${binaryPath.replaceAll("'", "''")}'`;
|
||||
if (platform === "darwin" || platform === "linux") {
|
||||
if (binaryPath.startsWith("~/") || binaryPath.startsWith("~\\")) {
|
||||
return `~/'${binaryPath.slice(2).replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
return `'${binaryPath.replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function getOnboardingProviderState(provider: ServerProvider | undefined) {
|
||||
if (provider === undefined) return "checking";
|
||||
if (!provider.enabled || provider.status === "disabled") return "disabled";
|
||||
if (!provider.installed) return "install";
|
||||
if (provider.auth.status === "unauthenticated") return "signIn";
|
||||
if (provider.status === "ready") return "ready";
|
||||
return "attention";
|
||||
}
|
||||
|
||||
const PROVIDER_STATE_PRIORITY = {
|
||||
checking: 0,
|
||||
disabled: 1,
|
||||
install: 2,
|
||||
attention: 3,
|
||||
signIn: 4,
|
||||
ready: 5,
|
||||
} as const;
|
||||
|
||||
/** Select the most usable configured instance for each provider driver. */
|
||||
export function selectOnboardingProvidersByDriver(
|
||||
providers: ReadonlyArray<ServerProvider> | null | undefined,
|
||||
) {
|
||||
const providersByDriver = new Map<string, ServerProvider>();
|
||||
|
||||
for (const provider of providers ?? []) {
|
||||
const existing = providersByDriver.get(provider.driver);
|
||||
if (
|
||||
existing === undefined ||
|
||||
PROVIDER_STATE_PRIORITY[getOnboardingProviderState(provider)] >
|
||||
PROVIDER_STATE_PRIORITY[getOnboardingProviderState(existing)]
|
||||
) {
|
||||
providersByDriver.set(provider.driver, provider);
|
||||
}
|
||||
}
|
||||
|
||||
return providersByDriver;
|
||||
}
|
||||
|
||||
/** Use the selected provider instance's binary when the setup terminal opens its login flow. */
|
||||
export function resolveOnboardingProviderLoginCommand(
|
||||
provider: ServerProvider,
|
||||
settings: ServerSettings,
|
||||
platform: ExecutionEnvironmentPlatformOs,
|
||||
): string {
|
||||
const instance = settings.providerInstances[provider.instanceId];
|
||||
|
||||
if (provider.driver === "claudeAgent") {
|
||||
const config = decodeClaudeSettings(
|
||||
instance ? (instance.config ?? {}) : settings.providers.claudeAgent,
|
||||
);
|
||||
const binaryPath = Option.isSome(config) ? config.value.binaryPath : "claude";
|
||||
return `${quoteProviderBinary(binaryPath, "claude", platform)} auth login`;
|
||||
}
|
||||
|
||||
if (provider.driver === "codex") {
|
||||
const config = decodeCodexSettings(
|
||||
instance ? (instance.config ?? {}) : settings.providers.codex,
|
||||
);
|
||||
const binaryPath = Option.isSome(config) ? config.value.binaryPath : "codex";
|
||||
return `${quoteProviderBinary(binaryPath, "codex", platform)} login`;
|
||||
}
|
||||
|
||||
return provider.driver;
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import {
|
||||
BearerConnectionTarget,
|
||||
PrimaryConnectionTarget,
|
||||
RelayConnectionTarget,
|
||||
SshConnectionTarget,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
isOnboardingRelayEnvironment,
|
||||
resolveOnboardingTargetEnvironment,
|
||||
} from "./targetEnvironment.logic";
|
||||
|
||||
const primaryEnvironment = {
|
||||
environmentId: EnvironmentId.make("primary"),
|
||||
connection: { phase: "connected" },
|
||||
entry: {
|
||||
target: new PrimaryConnectionTarget({
|
||||
environmentId: EnvironmentId.make("primary"),
|
||||
label: "This computer",
|
||||
httpBaseUrl: "http://127.0.0.1:3773",
|
||||
wsBaseUrl: "ws://127.0.0.1:3773",
|
||||
}),
|
||||
},
|
||||
label: "This computer",
|
||||
} as const;
|
||||
|
||||
const olderRelay = {
|
||||
environmentId: EnvironmentId.make("older-remote"),
|
||||
connection: { phase: "connected" },
|
||||
entry: {
|
||||
target: new RelayConnectionTarget({
|
||||
environmentId: EnvironmentId.make("older-remote"),
|
||||
label: "Older computer",
|
||||
}),
|
||||
},
|
||||
label: "Older computer",
|
||||
} as const;
|
||||
|
||||
const newerRelay = {
|
||||
environmentId: EnvironmentId.make("newer-relay"),
|
||||
connection: { phase: "connected" },
|
||||
entry: {
|
||||
target: new RelayConnectionTarget({
|
||||
environmentId: EnvironmentId.make("newer-relay"),
|
||||
label: "New computer",
|
||||
}),
|
||||
},
|
||||
label: "New computer",
|
||||
} as const;
|
||||
|
||||
const pairedRemote = {
|
||||
environmentId: EnvironmentId.make("paired-remote"),
|
||||
connection: { phase: "connected" },
|
||||
entry: {
|
||||
target: new BearerConnectionTarget({
|
||||
environmentId: EnvironmentId.make("paired-remote"),
|
||||
label: "Direct computer",
|
||||
connectionId: "paired-remote",
|
||||
}),
|
||||
},
|
||||
label: "Direct computer",
|
||||
} as const;
|
||||
|
||||
const sshEnvironment = {
|
||||
environmentId: EnvironmentId.make("ssh-remote"),
|
||||
connection: { phase: "connected" },
|
||||
entry: {
|
||||
target: new SshConnectionTarget({
|
||||
environmentId: EnvironmentId.make("ssh-remote"),
|
||||
label: "SSH computer",
|
||||
connectionId: "ssh-remote",
|
||||
}),
|
||||
},
|
||||
label: "SSH computer",
|
||||
} as const;
|
||||
|
||||
const desktopLocalEnvironment = {
|
||||
environmentId: EnvironmentId.make("desktop-local-wsl"),
|
||||
connection: { phase: "connected" },
|
||||
entry: {
|
||||
target: new BearerConnectionTarget({
|
||||
environmentId: EnvironmentId.make("desktop-local-wsl"),
|
||||
label: "WSL",
|
||||
connectionId: "local:wsl:Ubuntu",
|
||||
}),
|
||||
},
|
||||
label: "WSL",
|
||||
} as const;
|
||||
|
||||
describe("resolveOnboardingTargetEnvironment", () => {
|
||||
it("waits for the exact paired machine instead of using an older connected machine", () => {
|
||||
const pendingPairedRemote = { ...pairedRemote, connection: { phase: "connecting" } };
|
||||
|
||||
expect(
|
||||
resolveOnboardingTargetEnvironment({
|
||||
mode: "direct",
|
||||
environments: [primaryEnvironment, olderRelay, pendingPairedRemote],
|
||||
primaryEnvironment,
|
||||
pairedEnvironmentId: pairedRemote.environmentId,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the exact paired machine once it connects", () => {
|
||||
expect(
|
||||
resolveOnboardingTargetEnvironment({
|
||||
mode: "direct",
|
||||
environments: [primaryEnvironment, olderRelay, pairedRemote],
|
||||
primaryEnvironment,
|
||||
pairedEnvironmentId: pairedRemote.environmentId,
|
||||
}),
|
||||
).toBe(pairedRemote);
|
||||
});
|
||||
|
||||
it("waits for a newly paired machine that has not appeared in the catalog", () => {
|
||||
expect(
|
||||
resolveOnboardingTargetEnvironment({
|
||||
mode: "direct",
|
||||
environments: [primaryEnvironment, olderRelay],
|
||||
primaryEnvironment,
|
||||
pairedEnvironmentId: pairedRemote.environmentId,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the primary machine for local onboarding", () => {
|
||||
expect(
|
||||
resolveOnboardingTargetEnvironment({
|
||||
mode: "local",
|
||||
environments: [primaryEnvironment, olderRelay],
|
||||
primaryEnvironment,
|
||||
pairedEnvironmentId: null,
|
||||
}),
|
||||
).toBe(primaryEnvironment);
|
||||
});
|
||||
|
||||
it("does not substitute a remote machine when the local primary is offline", () => {
|
||||
const offlinePrimary = { ...primaryEnvironment, connection: { phase: "disconnected" } };
|
||||
|
||||
expect(
|
||||
resolveOnboardingTargetEnvironment({
|
||||
mode: "local",
|
||||
environments: [offlinePrimary, olderRelay],
|
||||
primaryEnvironment: offlinePrimary,
|
||||
pairedEnvironmentId: null,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the newest connected remote when no exact machine was selected", () => {
|
||||
expect(
|
||||
resolveOnboardingTargetEnvironment({
|
||||
mode: "connect",
|
||||
environments: [primaryEnvironment, olderRelay, newerRelay],
|
||||
primaryEnvironment,
|
||||
pairedEnvironmentId: null,
|
||||
}),
|
||||
).toBe(newerRelay);
|
||||
});
|
||||
|
||||
it("ignores direct, SSH, and desktop-managed connections in Connect mode", () => {
|
||||
expect(
|
||||
resolveOnboardingTargetEnvironment({
|
||||
mode: "connect",
|
||||
environments: [
|
||||
primaryEnvironment,
|
||||
olderRelay,
|
||||
pairedRemote,
|
||||
sshEnvironment,
|
||||
desktopLocalEnvironment,
|
||||
],
|
||||
primaryEnvironment,
|
||||
pairedEnvironmentId: null,
|
||||
}),
|
||||
).toBe(olderRelay);
|
||||
});
|
||||
|
||||
it("uses the primary computer when no relay connection exists", () => {
|
||||
expect(
|
||||
resolveOnboardingTargetEnvironment({
|
||||
mode: "connect",
|
||||
environments: [primaryEnvironment, pairedRemote, sshEnvironment, desktopLocalEnvironment],
|
||||
primaryEnvironment,
|
||||
pairedEnvironmentId: null,
|
||||
}),
|
||||
).toBe(primaryEnvironment);
|
||||
});
|
||||
|
||||
it("falls back to the connected primary when no remote is available", () => {
|
||||
expect(
|
||||
resolveOnboardingTargetEnvironment({
|
||||
mode: "connect",
|
||||
environments: [primaryEnvironment],
|
||||
primaryEnvironment,
|
||||
pairedEnvironmentId: null,
|
||||
}),
|
||||
).toBe(primaryEnvironment);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isOnboardingRelayEnvironment", () => {
|
||||
it("includes only T3 Connect relay targets", () => {
|
||||
expect(
|
||||
[olderRelay, pairedRemote, sshEnvironment, desktopLocalEnvironment].filter(
|
||||
isOnboardingRelayEnvironment,
|
||||
),
|
||||
).toEqual([olderRelay]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { ConnectionTarget } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
interface OnboardingEnvironment {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly connection: { readonly phase: string };
|
||||
readonly entry: { readonly target: ConnectionTarget };
|
||||
}
|
||||
|
||||
export function isOnboardingRelayEnvironment(
|
||||
environment: Pick<OnboardingEnvironment, "entry">,
|
||||
): boolean {
|
||||
return environment.entry.target._tag === "RelayConnectionTarget";
|
||||
}
|
||||
|
||||
/** Keep a directly paired machine pinned while its initial connection completes. */
|
||||
export function resolveOnboardingTargetEnvironment<TEnvironment extends OnboardingEnvironment>({
|
||||
mode,
|
||||
environments,
|
||||
primaryEnvironment,
|
||||
pairedEnvironmentId,
|
||||
}: {
|
||||
readonly mode: "local" | "connect" | "direct";
|
||||
readonly environments: ReadonlyArray<TEnvironment>;
|
||||
readonly primaryEnvironment: TEnvironment | null;
|
||||
readonly pairedEnvironmentId: EnvironmentId | null;
|
||||
}): TEnvironment | null {
|
||||
if (mode === "direct" && pairedEnvironmentId !== null) {
|
||||
const pairedEnvironment = environments.find(
|
||||
(environment) => environment.environmentId === pairedEnvironmentId,
|
||||
);
|
||||
return pairedEnvironment?.connection.phase === "connected" ? pairedEnvironment : null;
|
||||
}
|
||||
|
||||
const connectedRelayEnvironments = environments.filter(
|
||||
(environment) =>
|
||||
environment.connection.phase === "connected" && isOnboardingRelayEnvironment(environment),
|
||||
);
|
||||
|
||||
if (mode === "connect" && connectedRelayEnvironments.length > 0) {
|
||||
return connectedRelayEnvironments[connectedRelayEnvironments.length - 1] ?? null;
|
||||
}
|
||||
|
||||
if (primaryEnvironment?.connection.phase === "connected") {
|
||||
return primaryEnvironment;
|
||||
}
|
||||
|
||||
return mode === "local" ? null : (connectedRelayEnvironments[0] ?? null);
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as WelcomeRouteImport } from './routes/welcome'
|
||||
import { Route as UsageRouteImport } from './routes/usage'
|
||||
import { Route as SettingsRouteImport } from './routes/settings'
|
||||
import { Route as PairRouteImport } from './routes/pair'
|
||||
@@ -30,6 +31,11 @@ import { Route as ChatPullRequestsRouteImport } from './routes/_chat.pull-reques
|
||||
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
|
||||
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
|
||||
|
||||
const WelcomeRoute = WelcomeRouteImport.update({
|
||||
id: '/welcome',
|
||||
path: '/welcome',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const UsageRoute = UsageRouteImport.update({
|
||||
id: '/usage',
|
||||
path: '/usage',
|
||||
@@ -137,6 +143,7 @@ export interface FileRoutesByFullPath {
|
||||
'/pair': typeof PairRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/usage': typeof UsageRoute
|
||||
'/welcome': typeof WelcomeRoute
|
||||
'/pull-requests': typeof ChatPullRequestsRoute
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/projects/$projectKey': typeof ProjectsProjectKeyRoute
|
||||
@@ -157,6 +164,7 @@ export interface FileRoutesByTo {
|
||||
'/pair': typeof PairRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/usage': typeof UsageRoute
|
||||
'/welcome': typeof WelcomeRoute
|
||||
'/pull-requests': typeof ChatPullRequestsRoute
|
||||
'/connect/callback': typeof ConnectCallbackRoute
|
||||
'/projects/$projectKey': typeof ProjectsProjectKeyRoute
|
||||
@@ -180,6 +188,7 @@ export interface FileRoutesById {
|
||||
'/pair': typeof PairRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/usage': typeof UsageRoute
|
||||
'/welcome': typeof WelcomeRoute
|
||||
'/_chat/pull-requests': typeof ChatPullRequestsRoute
|
||||
'/connect_/callback': typeof ConnectCallbackRoute
|
||||
'/projects/$projectKey': typeof ProjectsProjectKeyRoute
|
||||
@@ -204,6 +213,7 @@ export interface FileRouteTypes {
|
||||
| '/pair'
|
||||
| '/settings'
|
||||
| '/usage'
|
||||
| '/welcome'
|
||||
| '/pull-requests'
|
||||
| '/connect/callback'
|
||||
| '/projects/$projectKey'
|
||||
@@ -224,6 +234,7 @@ export interface FileRouteTypes {
|
||||
| '/pair'
|
||||
| '/settings'
|
||||
| '/usage'
|
||||
| '/welcome'
|
||||
| '/pull-requests'
|
||||
| '/connect/callback'
|
||||
| '/projects/$projectKey'
|
||||
@@ -246,6 +257,7 @@ export interface FileRouteTypes {
|
||||
| '/pair'
|
||||
| '/settings'
|
||||
| '/usage'
|
||||
| '/welcome'
|
||||
| '/_chat/pull-requests'
|
||||
| '/connect_/callback'
|
||||
| '/projects/$projectKey'
|
||||
@@ -269,12 +281,20 @@ export interface RootRouteChildren {
|
||||
PairRoute: typeof PairRoute
|
||||
SettingsRoute: typeof SettingsRouteWithChildren
|
||||
UsageRoute: typeof UsageRoute
|
||||
WelcomeRoute: typeof WelcomeRoute
|
||||
ConnectCallbackRoute: typeof ConnectCallbackRoute
|
||||
ProjectsProjectKeyRoute: typeof ProjectsProjectKeyRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface FileRoutesByPath {
|
||||
'/welcome': {
|
||||
id: '/welcome'
|
||||
path: '/welcome'
|
||||
fullPath: '/welcome'
|
||||
preLoaderRoute: typeof WelcomeRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/usage': {
|
||||
id: '/usage'
|
||||
path: '/usage'
|
||||
@@ -468,6 +488,7 @@ const rootRouteChildren: RootRouteChildren = {
|
||||
PairRoute: PairRoute,
|
||||
SettingsRoute: SettingsRouteWithChildren,
|
||||
UsageRoute: UsageRoute,
|
||||
WelcomeRoute: WelcomeRoute,
|
||||
ConnectCallbackRoute: ConnectCallbackRoute,
|
||||
ProjectsProjectKeyRoute: ProjectsProjectKeyRoute,
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import { resolveServerBackedAppDisplayName } from "../branding.logic";
|
||||
import { AppSidebarLayout } from "../components/AppSidebarLayout";
|
||||
import { CommandPalette } from "../components/CommandPalette";
|
||||
import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
|
||||
import { FirstRunGate } from "../components/onboarding/FirstRunGate";
|
||||
import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
|
||||
import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
|
||||
import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
|
||||
@@ -97,6 +98,13 @@ function RootRouteView() {
|
||||
const pathname = useLocation({ select: (location) => location.pathname });
|
||||
const { authGateState } = Route.useRouteContext();
|
||||
const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
|
||||
const returningFromWelcomeRef = useRef(pathname === "/welcome");
|
||||
|
||||
useEffect(() => {
|
||||
if (pathname === "/welcome") {
|
||||
returningFromWelcomeRef.current = true;
|
||||
}
|
||||
}, [pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
@@ -116,6 +124,19 @@ function RootRouteView() {
|
||||
);
|
||||
}
|
||||
|
||||
// The welcome wizard is full-screen like /pair, but keeps toasts so its
|
||||
// connect/import actions can report failures.
|
||||
if (pathname === "/welcome") {
|
||||
return (
|
||||
<ToastProvider>
|
||||
<DocumentTitleSync />
|
||||
<ContrastAppearanceSync />
|
||||
<FontAppearanceSync />
|
||||
<Outlet />
|
||||
</ToastProvider>
|
||||
);
|
||||
}
|
||||
|
||||
if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
|
||||
return (
|
||||
<>
|
||||
@@ -133,6 +154,10 @@ function RootRouteView() {
|
||||
</CommandPalette>
|
||||
);
|
||||
|
||||
// FirstRunGate holds back everything below it — including EventRouter,
|
||||
// whose welcome payload navigates into a thread — until the first-run
|
||||
// decision is known, so a fresh install renders nothing (not the shell,
|
||||
// not a flash of threads) before landing on the welcome wizard.
|
||||
return (
|
||||
<ToastProvider>
|
||||
<AnchoredToastProvider>
|
||||
@@ -141,21 +166,28 @@ function RootRouteView() {
|
||||
<EnvironmentThemeSync />
|
||||
<GlassAppearanceSync />
|
||||
<FontAppearanceSync />
|
||||
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
|
||||
<RelayClientInstallDialog />
|
||||
<ConnectOnboardingDialog />
|
||||
<SshPasswordPromptDialog />
|
||||
<ConfirmDialogHost />
|
||||
<SlowRpcRequestToastCoordinator />
|
||||
<HostedStaticEnvironmentBootstrap />
|
||||
{primaryEnvironmentAuthenticated ? <EventRouter /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <PlanAgentSelectionHeal /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
|
||||
{appShell}
|
||||
{/* Above the router: a theme draft is judged by walking the app, so the
|
||||
editor has to survive navigation away from settings. */}
|
||||
<ThemeEditorHost />
|
||||
<FirstRunGate
|
||||
enabled={primaryEnvironmentAuthenticated}
|
||||
hostedStatic={authGateState.status === "hosted-static"}
|
||||
>
|
||||
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
|
||||
<RelayClientInstallDialog />
|
||||
<ConnectOnboardingDialog />
|
||||
<SshPasswordPromptDialog />
|
||||
<ConfirmDialogHost />
|
||||
<SlowRpcRequestToastCoordinator />
|
||||
<HostedStaticEnvironmentBootstrap />
|
||||
{primaryEnvironmentAuthenticated ? (
|
||||
<EventRouter skipInitialBootstrapNavigation={returningFromWelcomeRef.current} />
|
||||
) : null}
|
||||
{primaryEnvironmentAuthenticated ? <PlanAgentSelectionHeal /> : null}
|
||||
{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
|
||||
{appShell}
|
||||
{/* Above the router: a theme draft is judged by walking the app, so the
|
||||
editor has to survive navigation away from settings. */}
|
||||
<ThemeEditorHost />
|
||||
</FirstRunGate>
|
||||
</AnchoredToastProvider>
|
||||
</ToastProvider>
|
||||
);
|
||||
@@ -381,7 +413,11 @@ function AuthenticatedTracingBootstrap() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function EventRouter() {
|
||||
function EventRouter({
|
||||
skipInitialBootstrapNavigation,
|
||||
}: {
|
||||
readonly skipInitialBootstrapNavigation: boolean;
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const pathname = useLocation({ select: (loc) => loc.pathname });
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
@@ -394,6 +430,7 @@ function EventRouter() {
|
||||
const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
|
||||
const readPathname = useEffectEvent(() => pathname);
|
||||
const handledBootstrapThreadIdRef = useRef<string | null>(null);
|
||||
const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
|
||||
const handledConfigEventRef = useRef(serverConfigEvent);
|
||||
const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
|
||||
createKeybindingsUpdateToastController({}),
|
||||
@@ -425,6 +462,11 @@ function EventRouter() {
|
||||
if (readPathname() !== "/") {
|
||||
return;
|
||||
}
|
||||
if (skipInitialBootstrapNavigationRef.current) {
|
||||
skipInitialBootstrapNavigationRef.current = false;
|
||||
handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
|
||||
return;
|
||||
}
|
||||
if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
|
||||
return;
|
||||
}
|
||||
|
||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user