Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d7849fa702 |
No files matched your search
@@ -48,9 +48,7 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
|
||||
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
|
||||
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
|
||||
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
|
||||
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
|
||||
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
|
||||
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
|
||||
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
|
||||
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
|
||||
@@ -58,9 +56,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
|
||||
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
|
||||
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
|
||||
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
|
||||
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
|
||||
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
|
||||
|
||||
## File layout and migrations
|
||||
|
||||
@@ -78,6 +73,4 @@ Review changed TypeScript and directly affected call sites for the conventions b
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
|
||||
|
||||
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
|
||||
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
|
||||
@@ -18,6 +18,7 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
@@ -28,7 +29,6 @@ const clientSettings: ClientSettings = {
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
|
||||
|
||||
@@ -18,7 +18,8 @@ export const LEGACY_CONNECTIONS_KEY = "t3code.connections";
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
detail: `Could not ${operation} the local connection catalog.`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -58,23 +58,8 @@ const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
function shellPersistenceError(
|
||||
operation:
|
||||
| "load-shell"
|
||||
| "save-shell"
|
||||
| "load-thread"
|
||||
| "save-thread"
|
||||
| "remove-thread"
|
||||
| "clear-environment",
|
||||
cause: unknown,
|
||||
) {
|
||||
return new ConnectionPersistenceError({
|
||||
operation,
|
||||
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
|
||||
detail: `Could not ${operation} the local connection catalog.`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -100,7 +85,7 @@ const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapsh
|
||||
}
|
||||
return directory;
|
||||
},
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -117,16 +102,6 @@ const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFil
|
||||
);
|
||||
});
|
||||
|
||||
function targetPersistenceError(
|
||||
operation: "list-targets" | "register-connection" | "remove-connection",
|
||||
error: ConnectionTransientError,
|
||||
) {
|
||||
return new ConnectionPersistenceError({
|
||||
operation,
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
const secureCatalogStorage: SecureCatalogStorage = {
|
||||
getItem: (key) =>
|
||||
Effect.tryPromise({
|
||||
@@ -163,7 +138,7 @@ const shellSnapshotFileInDirectory = Effect.fn(
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
return new File(directory, shellSnapshotFileName(environmentId));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation, cause }),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -184,18 +159,29 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
const targetStore = ConnectionTargetStore.of({
|
||||
list: catalog.read.pipe(
|
||||
Effect.map((document) => document.targets),
|
||||
Effect.mapError((error) => targetPersistenceError("list-targets", error)),
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
|
||||
),
|
||||
),
|
||||
});
|
||||
const registrationStore = ConnectionRegistrationStore.of({
|
||||
register: (registration) =>
|
||||
catalog
|
||||
.update((document) => registerConnectionInCatalog(document, registration))
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({ operation: "register-connection", cause }),
|
||||
),
|
||||
),
|
||||
remove: (target) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
|
||||
),
|
||||
),
|
||||
});
|
||||
const profileStore = ProfileStore.make({
|
||||
get: (connectionId) =>
|
||||
@@ -283,15 +269,19 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (file.exists) {
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
);
|
||||
return stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
@@ -303,15 +293,19 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
const legacyRaw = yield* Effect.tryPromise({
|
||||
try: () => legacyFile.text(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
});
|
||||
const legacyParsed = yield* Effect.try({
|
||||
try: () => JSON.parse(legacyRaw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
});
|
||||
const legacyStored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
);
|
||||
return legacyStored.environmentId === environmentId
|
||||
? Option.some(legacyStored.snapshot)
|
||||
: Option.none();
|
||||
@@ -326,7 +320,11 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
} as const;
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
),
|
||||
);
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -334,7 +332,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("save-shell", cause),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
});
|
||||
}),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
@@ -345,15 +343,19 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
),
|
||||
);
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none();
|
||||
@@ -368,7 +370,11 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
}),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
),
|
||||
);
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -376,7 +382,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("save-thread", cause),
|
||||
catch: (cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
});
|
||||
}),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
@@ -389,7 +395,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: shellPersistenceError("remove-thread", cause),
|
||||
: new ConnectionPersistenceError({ operation: "remove-thread", cause }),
|
||||
),
|
||||
),
|
||||
clear: (environmentId) =>
|
||||
@@ -398,14 +404,16 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (file.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => file.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
});
|
||||
}
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
|
||||
if (legacyFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
});
|
||||
}
|
||||
const threadDirectory = yield* threadSnapshotDirectory(
|
||||
@@ -415,7 +423,8 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (threadDirectory.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => threadDirectory.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
catch: (cause) =>
|
||||
new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -30,9 +30,7 @@ import {
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { buildThreadRoutePath } from "../../lib/routes";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import { getComposerDraftSnapshot } from "../../state/use-composer-drafts";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
@@ -65,7 +63,6 @@ export function NewTaskDraftScreen(props: {
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
const promptInputRef = useRef<ComposerEditorHandle>(null);
|
||||
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
|
||||
|
||||
const borderColor = useThemeColor("--color-border");
|
||||
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
|
||||
@@ -81,12 +78,6 @@ export function NewTaskDraftScreen(props: {
|
||||
) ?? null;
|
||||
|
||||
if (directProject) {
|
||||
if (
|
||||
selectedProject?.environmentId === directProject.environmentId &&
|
||||
selectedProject.id === directProject.id
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setProject(directProject);
|
||||
return;
|
||||
}
|
||||
@@ -114,16 +105,10 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
loadedBranchesProjectKeyRef.current = null;
|
||||
return;
|
||||
}
|
||||
const projectKey = `${selectedProject.environmentId}:${selectedProject.id}`;
|
||||
if (loadedBranchesProjectKeyRef.current === projectKey) {
|
||||
return;
|
||||
}
|
||||
loadedBranchesProjectKeyRef.current = projectKey;
|
||||
void flow.loadBranches();
|
||||
}, [flow.loadBranches, selectedProject]);
|
||||
}, [flow, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedProject) {
|
||||
@@ -307,7 +292,11 @@ export function NewTaskDraftScreen(props: {
|
||||
if (!event.startsWith("model:")) {
|
||||
return;
|
||||
}
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
// Defer state update so the native menu dismiss animation completes
|
||||
// before re-rendering the menu actions (prevents submenu jump).
|
||||
setTimeout(() => {
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}, 150);
|
||||
}
|
||||
|
||||
function handleEnvironmentMenuAction(event: string) {
|
||||
@@ -377,42 +366,27 @@ export function NewTaskDraftScreen(props: {
|
||||
);
|
||||
|
||||
async function handleStart(): Promise<void> {
|
||||
const selectedProject = flow.selectedProject;
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
const draft = getComposerDraftSnapshot(
|
||||
`new-task:${scopedProjectKey(selectedProject.environmentId, selectedProject.id)}`,
|
||||
);
|
||||
const modelSelection = draft.modelSelection ?? flow.selectedModel;
|
||||
const workspaceMode = draft.workspaceSelection?.mode ?? flow.workspaceMode;
|
||||
const selectedBranchName = draft.workspaceSelection?.branch ?? flow.selectedBranchName;
|
||||
const selectedWorktreePath =
|
||||
draft.workspaceSelection?.worktreePath ?? flow.selectedWorktreePath;
|
||||
const runtimeMode = draft.runtimeMode ?? flow.runtimeMode;
|
||||
const interactionMode = draft.interactionMode ?? flow.interactionMode;
|
||||
const initialMessageText = draft.text.trim();
|
||||
|
||||
if (
|
||||
!modelSelection ||
|
||||
initialMessageText.length === 0 ||
|
||||
!flow.selectedProject ||
|
||||
!flow.selectedModel ||
|
||||
flow.prompt.trim().length === 0 ||
|
||||
flow.submitting ||
|
||||
(workspaceMode === "worktree" && !selectedBranchName)
|
||||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
flow.setSubmitting(true);
|
||||
const result = await createProjectThread({
|
||||
project: selectedProject,
|
||||
modelSelection,
|
||||
envMode: workspaceMode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
initialMessageText,
|
||||
initialAttachments: draft.attachments,
|
||||
project: flow.selectedProject,
|
||||
modelSelection: flow.selectedModel,
|
||||
envMode: flow.workspaceMode,
|
||||
branch: flow.selectedBranchName,
|
||||
worktreePath: flow.workspaceMode === "worktree" ? null : flow.selectedWorktreePath,
|
||||
runtimeMode: flow.runtimeMode,
|
||||
interactionMode: flow.interactionMode,
|
||||
initialMessageText: flow.prompt.trim(),
|
||||
initialAttachments: flow.attachments,
|
||||
});
|
||||
flow.setSubmitting(false);
|
||||
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
|
||||
import {
|
||||
EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProjectScript,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Pressable, ScrollView, Text as RNText, View } from "react-native";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -73,6 +79,18 @@ export function ThreadRouteScreen() {
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
const requests = useSelectedThreadRequests();
|
||||
const updateThreadMetadata = useAtomCommand(
|
||||
threadEnvironment.updateMetadata,
|
||||
"thread metadata update",
|
||||
);
|
||||
const setThreadRuntimeMode = useAtomCommand(
|
||||
threadEnvironment.setRuntimeMode,
|
||||
"thread runtime mode",
|
||||
);
|
||||
const setThreadInteractionMode = useAtomCommand(
|
||||
threadEnvironment.setInteractionMode,
|
||||
"thread interaction mode",
|
||||
);
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
|
||||
const router = useRouter();
|
||||
const params = useLocalSearchParams<{
|
||||
@@ -87,18 +105,6 @@ export function ThreadRouteScreen() {
|
||||
const routeConnectionState =
|
||||
routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
|
||||
const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
|
||||
const selectedThreadWithDraftSettings = useMemo(
|
||||
() =>
|
||||
selectedThread
|
||||
? {
|
||||
...selectedThread,
|
||||
modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
|
||||
runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
|
||||
interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
|
||||
}
|
||||
: null,
|
||||
[composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
|
||||
);
|
||||
|
||||
/* ─── Native header theming ──────────────────────────────────────── */
|
||||
const iconColor = String(useThemeColor("--color-icon"));
|
||||
@@ -151,6 +157,51 @@ export function ThreadRouteScreen() {
|
||||
const handleOpenConnectionEditor = useCallback(() => {
|
||||
void router.push("/connections");
|
||||
}, [router]);
|
||||
const handleUpdateThreadModelSelection = useCallback(
|
||||
(modelSelection: ModelSelection) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return updateThreadMetadata({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
modelSelection,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, updateThreadMetadata],
|
||||
);
|
||||
const handleUpdateThreadRuntimeMode = useCallback(
|
||||
(runtimeMode: RuntimeMode) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return setThreadRuntimeMode({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
runtimeMode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, setThreadRuntimeMode],
|
||||
);
|
||||
const handleUpdateThreadInteractionMode = useCallback(
|
||||
(interactionMode: ProviderInteractionMode) => {
|
||||
if (!selectedThread) {
|
||||
return;
|
||||
}
|
||||
return setThreadInteractionMode({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
interactionMode,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedThread, setThreadInteractionMode],
|
||||
);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (
|
||||
!selectedThread ||
|
||||
@@ -384,7 +435,7 @@ export function ThreadRouteScreen() {
|
||||
|
||||
<View className="flex-1 bg-screen">
|
||||
<ThreadDetailScreen
|
||||
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
|
||||
selectedThread={selectedThread}
|
||||
contentPresentation={contentPresentation}
|
||||
screenTone={connectionTone(routeConnectionState)}
|
||||
connectionError={routeConnectionError}
|
||||
@@ -415,9 +466,9 @@ export function ThreadRouteScreen() {
|
||||
onStopThread={handleStopThread}
|
||||
onSendMessage={composer.onSendMessage}
|
||||
onReconnectEnvironment={handleReconnectEnvironment}
|
||||
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
|
||||
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
|
||||
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
|
||||
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
|
||||
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
|
||||
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
|
||||
onRespondToApproval={requests.onRespondToApproval}
|
||||
onSelectUserInputOption={requests.onSelectUserInputOption}
|
||||
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import React, { useCallback, useMemo, useRef, useState } from "react";
|
||||
|
||||
import type {
|
||||
EnvironmentId,
|
||||
@@ -23,7 +23,6 @@ import {
|
||||
removeComposerDraftAttachment,
|
||||
replaceComposerDraftAttachments,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useBranches } from "../../state/queries";
|
||||
@@ -159,15 +158,34 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
? selectedEnvironmentIdOverride
|
||||
: (projects[0]?.environmentId ?? null);
|
||||
const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
|
||||
const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
|
||||
const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>("local");
|
||||
const [selectedBranchName, setSelectedBranchName] = useState<string | null>(null);
|
||||
const [selectedWorktreePath, setSelectedWorktreePath] = useState<string | null>(null);
|
||||
const branchLoadVersionRef = useRef(0);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [branchQuery, setBranchQuery] = useState("");
|
||||
const [runtimeMode, setRuntimeMode] = useState<RuntimeMode>(DEFAULT_RUNTIME_MODE);
|
||||
const [interactionMode, setInteractionMode] = useState<ProviderInteractionMode>(
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
);
|
||||
const [modelSelectionOverrides, setModelSelectionOverrides] = useState<
|
||||
Record<string, ModelSelection>
|
||||
>({});
|
||||
const [expandedProvider, setExpandedProvider] = useState<string | null>(null);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setSelectedEnvironmentId(null);
|
||||
setSelectedProjectKey(null);
|
||||
setSelectedModelKey(null);
|
||||
setWorkspaceMode("local");
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setSubmitting(false);
|
||||
setBranchQuery("");
|
||||
setRuntimeMode(DEFAULT_RUNTIME_MODE);
|
||||
setInteractionMode(DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
setModelSelectionOverrides({});
|
||||
setExpandedProvider(null);
|
||||
}, []);
|
||||
|
||||
@@ -229,33 +247,33 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
|
||||
const prompt = selectedProjectDraft.text;
|
||||
const attachments = selectedProjectDraft.attachments;
|
||||
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
|
||||
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
|
||||
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
const modelOptions = useMemo(
|
||||
() =>
|
||||
buildModelOptions(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
|
||||
selectedProject?.defaultModelSelection ?? null,
|
||||
),
|
||||
[
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection,
|
||||
selectedProjectDraft.modelSelection,
|
||||
],
|
||||
[selectedEnvironmentServerConfig, selectedProject?.defaultModelSelection],
|
||||
);
|
||||
|
||||
const selectedModel =
|
||||
selectedProjectDraft.modelSelection ??
|
||||
const defaultModelKey = selectedProject?.defaultModelSelection
|
||||
? `${selectedProject.defaultModelSelection.instanceId}:${selectedProject.defaultModelSelection.model}`
|
||||
: null;
|
||||
const baseSelectedModel =
|
||||
modelOptions.find((option) => option.key === selectedModelKey)?.selection ??
|
||||
(defaultModelKey
|
||||
? modelOptions.find((option) => option.key === defaultModelKey)?.selection
|
||||
: null) ??
|
||||
selectedProject?.defaultModelSelection ??
|
||||
modelOptions[0]?.selection ??
|
||||
null;
|
||||
const selectedModelKey = selectedModel
|
||||
? `${selectedModel.instanceId}:${selectedModel.model}`
|
||||
const selectedModelIdentity = baseSelectedModel
|
||||
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
|
||||
: null;
|
||||
const selectedModel =
|
||||
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
|
||||
baseSelectedModel;
|
||||
|
||||
const selectedModelOption =
|
||||
modelOptions.find(
|
||||
@@ -264,31 +282,13 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
option.selection.instanceId === selectedModel.instanceId &&
|
||||
option.selection.model === selectedModel.model,
|
||||
) ?? null;
|
||||
const selectedProviderSkills = useMemo(
|
||||
() =>
|
||||
selectedEnvironmentServerConfig?.providers.find(
|
||||
(provider) => provider.instanceId === selectedModel?.instanceId,
|
||||
)?.skills ?? [],
|
||||
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
|
||||
);
|
||||
const setSelectedModelKey = useCallback(
|
||||
(key: string | null) => {
|
||||
if (!key || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
const option = modelOptions.find((candidate) => candidate.key === key);
|
||||
if (!option) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: option.selection,
|
||||
});
|
||||
},
|
||||
[modelOptions, selectedProjectDraftKey],
|
||||
);
|
||||
const selectedProviderSkills =
|
||||
selectedEnvironmentServerConfig?.providers.find(
|
||||
(provider) => provider.instanceId === selectedModel?.instanceId,
|
||||
)?.skills ?? [];
|
||||
const setSelectedModelOptions = useCallback(
|
||||
(options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
|
||||
if (!selectedModel || !selectedProjectDraftKey) {
|
||||
if (!selectedModel || !selectedModelIdentity) {
|
||||
return;
|
||||
}
|
||||
const nextSelection: ModelSelection = options
|
||||
@@ -297,11 +297,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
instanceId: selectedModel.instanceId,
|
||||
model: selectedModel.model,
|
||||
};
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: nextSelection,
|
||||
});
|
||||
setModelSelectionOverrides((current) => ({
|
||||
...current,
|
||||
[selectedModelIdentity]: nextSelection,
|
||||
}));
|
||||
},
|
||||
[selectedModel, selectedProjectDraftKey],
|
||||
[selectedModel, selectedModelIdentity],
|
||||
);
|
||||
|
||||
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
|
||||
@@ -380,85 +381,62 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
|
||||
const setProject = useCallback((project: EnvironmentProject) => {
|
||||
const nextProjectKey = scopedProjectKey(project.environmentId, project.id);
|
||||
branchLoadVersionRef.current += 1;
|
||||
setSelectedEnvironmentId(project.environmentId);
|
||||
setSelectedProjectKey(nextProjectKey);
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setModelSelectionOverrides({});
|
||||
}, []);
|
||||
|
||||
const selectEnvironment = useCallback((environmentId: EnvironmentId) => {
|
||||
branchLoadVersionRef.current += 1;
|
||||
setSelectedEnvironmentId(environmentId);
|
||||
setSelectedProjectKey(null);
|
||||
setSelectedBranchName(null);
|
||||
setSelectedWorktreePath(null);
|
||||
setModelSelectionOverrides({});
|
||||
}, []);
|
||||
|
||||
const setWorkspaceMode = useCallback(
|
||||
(mode: WorkspaceMode) => {
|
||||
if (!selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: selectedWorktreePath,
|
||||
},
|
||||
});
|
||||
},
|
||||
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
|
||||
);
|
||||
|
||||
const selectBranch = useCallback(
|
||||
(branch: VcsRef) => {
|
||||
if (!selectedProject || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
workspaceSelection: {
|
||||
mode: workspaceMode,
|
||||
branch: branch.name,
|
||||
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
|
||||
},
|
||||
});
|
||||
setSelectedBranchName(branch.name);
|
||||
setSelectedWorktreePath(
|
||||
selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null,
|
||||
);
|
||||
},
|
||||
[selectedProject, selectedProjectDraftKey, workspaceMode],
|
||||
[selectedProject],
|
||||
);
|
||||
|
||||
const refreshBranches = branchState.refresh;
|
||||
const loadBranches = useCallback(async () => {
|
||||
if (!selectedProject) {
|
||||
return;
|
||||
}
|
||||
setPendingConnectionError(null);
|
||||
refreshBranches();
|
||||
}, [refreshBranches, selectedProject]);
|
||||
|
||||
useEffect(() => {
|
||||
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
|
||||
const loadVersion = ++branchLoadVersionRef.current;
|
||||
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
|
||||
branchState.refresh();
|
||||
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
|
||||
return;
|
||||
}
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current) ??
|
||||
availableBranches.find((branch) => branch.isDefault) ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
selectBranch(preferredBranch);
|
||||
setPendingConnectionError(null);
|
||||
if (workspaceMode === "worktree" && !selectedBranchName) {
|
||||
const preferredBranch =
|
||||
availableBranches.find((branch) => branch.current)?.name ??
|
||||
availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
if (preferredBranch) {
|
||||
setSelectedBranchName(preferredBranch);
|
||||
}
|
||||
}
|
||||
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
|
||||
|
||||
const setRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
if (selectedProjectDraftKey) {
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, { runtimeMode: value });
|
||||
}
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
const setInteractionMode = useCallback(
|
||||
(value: ProviderInteractionMode) => {
|
||||
if (selectedProjectDraftKey) {
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, { interactionMode: value });
|
||||
}
|
||||
},
|
||||
[selectedProjectDraftKey],
|
||||
);
|
||||
}, [
|
||||
availableBranches,
|
||||
branchState,
|
||||
selectedBranchName,
|
||||
selectedProject,
|
||||
selectedProjectKey,
|
||||
workspaceMode,
|
||||
]);
|
||||
|
||||
const value = useMemo<NewTaskFlowContextValue>(
|
||||
() => ({
|
||||
@@ -535,11 +513,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
setProject,
|
||||
selectBranch,
|
||||
selectEnvironment,
|
||||
setInteractionMode,
|
||||
setPrompt,
|
||||
setRuntimeMode,
|
||||
setSelectedModelKey,
|
||||
setWorkspaceMode,
|
||||
submitting,
|
||||
workspaceMode,
|
||||
appendAttachments,
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
previewUri: Schema.String,
|
||||
type: Schema.Literal("image"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
@@ -1,38 +1,32 @@
|
||||
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
|
||||
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
type ModelSelection as ModelSelectionType,
|
||||
type ProviderInteractionMode as ProviderInteractionModeType,
|
||||
type RuntimeMode as RuntimeModeType,
|
||||
} from "@t3tools/contracts";
|
||||
import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { scopedThreadKey } from "../lib/scopedEntities";
|
||||
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 2;
|
||||
const THREAD_OUTBOX_SCHEMA_VERSION = 1;
|
||||
const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000;
|
||||
|
||||
const DraftComposerImageAttachmentSchema = Schema.Struct({
|
||||
id: Schema.String,
|
||||
previewUri: Schema.String,
|
||||
type: Schema.Literal("image"),
|
||||
name: Schema.String,
|
||||
mimeType: Schema.String,
|
||||
sizeBytes: Schema.Number,
|
||||
dataUrl: Schema.String,
|
||||
});
|
||||
|
||||
export const QueuedThreadMessageSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literals([1, THREAD_OUTBOX_SCHEMA_VERSION]),
|
||||
schemaVersion: Schema.Literal(THREAD_OUTBOX_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
commandId: CommandId,
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
runtimeMode: Schema.optional(RuntimeMode),
|
||||
interactionMode: Schema.optional(ProviderInteractionMode),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -46,37 +40,9 @@ export interface QueuedThreadMessage {
|
||||
readonly commandId: CommandId;
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection?: ModelSelectionType;
|
||||
readonly runtimeMode?: RuntimeModeType;
|
||||
readonly interactionMode?: ProviderInteractionModeType;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
export interface ThreadSettingsSnapshot {
|
||||
readonly modelSelection: ModelSelectionType;
|
||||
readonly runtimeMode: RuntimeModeType;
|
||||
readonly interactionMode: ProviderInteractionModeType;
|
||||
}
|
||||
|
||||
export function resolveQueuedThreadSettings(
|
||||
message: QueuedThreadMessage,
|
||||
thread: ThreadSettingsSnapshot,
|
||||
): ThreadSettingsSnapshot {
|
||||
return {
|
||||
modelSelection: message.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: message.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: message.interactionMode ?? thread.interactionMode,
|
||||
};
|
||||
}
|
||||
|
||||
export function modelSelectionsEqual(left: ModelSelectionType, right: ModelSelectionType): boolean {
|
||||
return (
|
||||
left.instanceId === right.instanceId &&
|
||||
left.model === right.model &&
|
||||
JSON.stringify(left.options ?? null) === JSON.stringify(right.options ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
export function encodeQueuedThreadMessage(message: QueuedThreadMessage): unknown {
|
||||
return encodeStoredQueuedThreadMessage({
|
||||
schemaVersion: THREAD_OUTBOX_SCHEMA_VERSION,
|
||||
@@ -153,21 +119,3 @@ export function shouldRetryThreadOutboxDelivery(error: unknown): boolean {
|
||||
}
|
||||
return isTransportConnectionErrorMessage(errorMessage(error));
|
||||
}
|
||||
|
||||
export type ThreadOutboxCommandStage = "settings-sync" | "start-turn";
|
||||
export type ThreadOutboxFailureAction = "retry" | "discard";
|
||||
|
||||
export function resolveThreadOutboxFailureAction(input: {
|
||||
readonly stage: ThreadOutboxCommandStage;
|
||||
readonly error: unknown;
|
||||
readonly interrupted: boolean;
|
||||
}): ThreadOutboxFailureAction {
|
||||
if (
|
||||
input.stage === "settings-sync" ||
|
||||
input.interrupted ||
|
||||
shouldRetryThreadOutboxDelivery(input.error)
|
||||
) {
|
||||
return "retry";
|
||||
}
|
||||
return "discard";
|
||||
}
|
||||
@@ -1,21 +1,11 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
decodeQueuedThreadMessage,
|
||||
encodeQueuedThreadMessage,
|
||||
groupQueuedThreadMessages,
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadMessage,
|
||||
@@ -76,54 +66,6 @@ describe("thread outbox", () => {
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("persists the exact selector snapshot while remaining compatible with v1 messages", () => {
|
||||
const legacyMessage = queuedMessage({
|
||||
messageId: "message-1",
|
||||
createdAt: "2026-06-08T10:00:01.000Z",
|
||||
});
|
||||
const selectedMessage = {
|
||||
...legacyMessage,
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
} satisfies QueuedThreadMessage;
|
||||
|
||||
expect(decodeQueuedThreadMessage(encodeQueuedThreadMessage(selectedMessage))).toEqual(
|
||||
selectedMessage,
|
||||
);
|
||||
expect(
|
||||
resolveQueuedThreadSettings(legacyMessage, {
|
||||
modelSelection: selectedMessage.modelSelection,
|
||||
runtimeMode: selectedMessage.runtimeMode,
|
||||
interactionMode: selectedMessage.interactionMode,
|
||||
}),
|
||||
).toEqual({
|
||||
modelSelection: selectedMessage.modelSelection,
|
||||
runtimeMode: selectedMessage.runtimeMode,
|
||||
interactionMode: selectedMessage.interactionMode,
|
||||
});
|
||||
});
|
||||
|
||||
it("compares model options as part of the queued settings change", () => {
|
||||
const base = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "medium" }],
|
||||
} as const;
|
||||
|
||||
expect(modelSelectionsEqual(base, base)).toBe(true);
|
||||
expect(
|
||||
modelSelectionsEqual(base, {
|
||||
...base,
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("backs off queued delivery retries and caps them at sixteen seconds", () => {
|
||||
expect([1, 2, 3, 4, 5, 6].map(threadOutboxRetryDelayMs)).toEqual([
|
||||
1_000, 2_000, 4_000, 8_000, 16_000, 16_000,
|
||||
@@ -329,23 +271,4 @@ describe("thread outbox", () => {
|
||||
).toBe(true);
|
||||
expect(shouldRetryThreadOutboxDelivery(new Error("Thread no longer exists"))).toBe(false);
|
||||
});
|
||||
|
||||
it("retains queued messages when settings synchronization fails before startTurn", () => {
|
||||
const deterministicFailure = new Error("Thread no longer exists");
|
||||
|
||||
expect(
|
||||
resolveThreadOutboxFailureAction({
|
||||
stage: "settings-sync",
|
||||
error: deterministicFailure,
|
||||
interrupted: false,
|
||||
}),
|
||||
).toBe("retry");
|
||||
expect(
|
||||
resolveThreadOutboxFailureAction({
|
||||
stage: "start-turn",
|
||||
error: deterministicFailure,
|
||||
interrupted: false,
|
||||
}),
|
||||
).toBe("discard");
|
||||
});
|
||||
});
|
||||
@@ -1,136 +1,14 @@
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import {
|
||||
clearComposerDraftContentState,
|
||||
composerDraftsAtom,
|
||||
decodePersistedComposerDrafts,
|
||||
type ComposerDraft,
|
||||
getComposerDraftSnapshot,
|
||||
removeComposerDraftsForEnvironment,
|
||||
} from "./use-composer-drafts";
|
||||
import { type ComposerDraft, removeComposerDraftsForEnvironment } from "./use-composer-drafts";
|
||||
|
||||
const DRAFT: ComposerDraft = {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
appAtomRegistry.set(composerDraftsAtom, {});
|
||||
});
|
||||
|
||||
describe("mobile composer drafts", () => {
|
||||
it("hydrates selector state even when the message content is empty", () => {
|
||||
expect(
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"new-task:environment-1:project-1": {
|
||||
text: "",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
"new-task:environment-1:project-1": {
|
||||
text: "",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "plan",
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps legacy content-only drafts and rejects invalid selector state", () => {
|
||||
expect(
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"environment-1:thread-1": DRAFT,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
"environment-1:thread-1": DRAFT,
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
decodePersistedComposerDrafts({
|
||||
schemaVersion: 1,
|
||||
drafts: {
|
||||
"environment-1:thread-1": {
|
||||
...DRAFT,
|
||||
runtimeMode: "sometimes-safe",
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("clears sent content without clearing the selected model or workspace", () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
const draft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
workspaceSelection: {
|
||||
mode: "worktree",
|
||||
branch: "main",
|
||||
worktreePath: null,
|
||||
},
|
||||
};
|
||||
|
||||
expect(clearComposerDraftContentState({ [draftKey]: draft }, draftKey)).toEqual({
|
||||
[draftKey]: {
|
||||
...draft,
|
||||
text: "",
|
||||
attachments: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reads the latest selector state synchronously for send", () => {
|
||||
const draftKey = "environment-1:thread-1";
|
||||
const selectedDraft: ComposerDraft = {
|
||||
text: "send this",
|
||||
attachments: [],
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
options: [{ id: "reasoningEffort", value: "xhigh" }],
|
||||
},
|
||||
};
|
||||
appAtomRegistry.set(composerDraftsAtom, { [draftKey]: selectedDraft });
|
||||
|
||||
expect(getComposerDraftSnapshot(draftKey)).toEqual(selectedDraft);
|
||||
});
|
||||
|
||||
it("removes only drafts owned by the selected environment", () => {
|
||||
const environmentId = EnvironmentId.make("environment-cloud");
|
||||
const retainedEnvironmentId = EnvironmentId.make("environment-local");
|
||||
@@ -139,15 +17,12 @@ describe("mobile composer drafts", () => {
|
||||
removeComposerDraftsForEnvironment(
|
||||
{
|
||||
[`${environmentId}:thread-cloud`]: DRAFT,
|
||||
[`new-task:${environmentId}:project-cloud`]: DRAFT,
|
||||
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
|
||||
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
|
||||
},
|
||||
environmentId,
|
||||
),
|
||||
).toEqual({
|
||||
[`${retainedEnvironmentId}:thread-local`]: DRAFT,
|
||||
[`new-task:${retainedEnvironmentId}:project-local`]: DRAFT,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,18 +1,9 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import {
|
||||
ModelSelection as ModelSelectionSchema,
|
||||
ProviderInteractionMode as ProviderInteractionModeSchema,
|
||||
RuntimeMode as RuntimeModeSchema,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useEffect } from "react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { DraftComposerImageAttachmentSchema } from "../lib/composer-image-schema";
|
||||
import type { DraftComposerImageAttachment } from "../lib/composerImages";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
|
||||
@@ -38,47 +29,13 @@ export class ComposerDraftPersistenceError extends Schema.TaggedErrorClass<Compo
|
||||
export interface ComposerDraft {
|
||||
readonly text: string;
|
||||
readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
readonly interactionMode?: ProviderInteractionMode;
|
||||
readonly workspaceSelection?: ComposerDraftWorkspaceSelection;
|
||||
}
|
||||
|
||||
export interface ComposerDraftWorkspaceSelection {
|
||||
readonly mode: "local" | "worktree";
|
||||
readonly branch: string | null;
|
||||
readonly worktreePath: string | null;
|
||||
interface PersistedComposerDrafts {
|
||||
readonly schemaVersion: typeof COMPOSER_DRAFTS_SCHEMA_VERSION;
|
||||
readonly drafts: Record<string, ComposerDraft>;
|
||||
}
|
||||
|
||||
export type ComposerDraftSettingsUpdate = Pick<
|
||||
ComposerDraft,
|
||||
"modelSelection" | "runtimeMode" | "interactionMode" | "workspaceSelection"
|
||||
>;
|
||||
|
||||
const ComposerDraftWorkspaceSelectionSchema = Schema.Struct({
|
||||
mode: Schema.Literals(["local", "worktree"]),
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
});
|
||||
|
||||
const ComposerDraftSchema = Schema.Struct({
|
||||
text: Schema.String,
|
||||
attachments: Schema.Array(DraftComposerImageAttachmentSchema),
|
||||
modelSelection: Schema.optional(ModelSelectionSchema),
|
||||
runtimeMode: Schema.optional(RuntimeModeSchema),
|
||||
interactionMode: Schema.optional(ProviderInteractionModeSchema),
|
||||
workspaceSelection: Schema.optional(ComposerDraftWorkspaceSelectionSchema),
|
||||
});
|
||||
|
||||
const PersistedComposerDraftsSchema = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(COMPOSER_DRAFTS_SCHEMA_VERSION),
|
||||
drafts: Schema.Record(Schema.String, ComposerDraftSchema),
|
||||
});
|
||||
|
||||
const decodePersistedComposerDraftsDocument = Schema.decodeUnknownSync(
|
||||
PersistedComposerDraftsSchema,
|
||||
);
|
||||
|
||||
const EMPTY_DRAFT: ComposerDraft = {
|
||||
text: "",
|
||||
attachments: [],
|
||||
@@ -97,32 +54,13 @@ function normalizeDraft(draft: ComposerDraft | undefined): ComposerDraft {
|
||||
return EMPTY_DRAFT;
|
||||
}
|
||||
return {
|
||||
...draft,
|
||||
text: draft.text,
|
||||
attachments: draft.attachments,
|
||||
};
|
||||
}
|
||||
|
||||
export function getComposerDraftSnapshot(draftKey: string): ComposerDraft {
|
||||
return normalizeDraft(appAtomRegistry.get(composerDraftsAtom)[draftKey]);
|
||||
}
|
||||
|
||||
function isEmptyDraft(draft: ComposerDraft): boolean {
|
||||
return (
|
||||
draft.text.length === 0 &&
|
||||
draft.attachments.length === 0 &&
|
||||
draft.modelSelection === undefined &&
|
||||
draft.runtimeMode === undefined &&
|
||||
draft.interactionMode === undefined &&
|
||||
draft.workspaceSelection === undefined
|
||||
);
|
||||
}
|
||||
|
||||
export function decodePersistedComposerDrafts(value: unknown): Record<string, ComposerDraft> {
|
||||
const parsed = decodePersistedComposerDraftsDocument(value);
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed.drafts).filter(([, draft]) => !isEmptyDraft(draft)),
|
||||
);
|
||||
return draft.text.length === 0 && draft.attachments.length === 0;
|
||||
}
|
||||
|
||||
async function getComposerDraftsFile() {
|
||||
@@ -142,7 +80,20 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
|
||||
operation = "read";
|
||||
const raw = await file.text();
|
||||
operation = "decode";
|
||||
return decodePersistedComposerDrafts(JSON.parse(raw) as unknown);
|
||||
const parsed = JSON.parse(raw) as Partial<PersistedComposerDrafts>;
|
||||
if (parsed.schemaVersion !== COMPOSER_DRAFTS_SCHEMA_VERSION || !parsed.drafts) {
|
||||
return {};
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed.drafts).filter((entry): entry is [string, ComposerDraft] => {
|
||||
const draft = entry[1];
|
||||
return (
|
||||
typeof draft?.text === "string" &&
|
||||
Array.isArray(draft.attachments) &&
|
||||
!isEmptyDraft(draft)
|
||||
);
|
||||
}),
|
||||
);
|
||||
} catch (cause) {
|
||||
console.warn(
|
||||
"[composer-drafts] ignored persisted draft failure",
|
||||
@@ -165,10 +116,10 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
|
||||
const nonEmptyDrafts = Object.fromEntries(
|
||||
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
|
||||
);
|
||||
const document = {
|
||||
const document: PersistedComposerDrafts = {
|
||||
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
|
||||
drafts: nonEmptyDrafts,
|
||||
} as const;
|
||||
};
|
||||
const encoded = JSON.stringify(document);
|
||||
operation = "write";
|
||||
if (!file.exists) {
|
||||
@@ -331,55 +282,6 @@ export function removeComposerDraftAttachment(draftKey: string, imageId: string)
|
||||
});
|
||||
}
|
||||
|
||||
export function updateComposerDraftSettings(
|
||||
draftKey: string,
|
||||
settings: Partial<ComposerDraftSettingsUpdate>,
|
||||
): void {
|
||||
updateComposerDrafts((current) => {
|
||||
const draft = {
|
||||
...normalizeDraft(current[draftKey]),
|
||||
...settings,
|
||||
};
|
||||
if (isEmptyDraft(draft)) {
|
||||
const next = { ...current };
|
||||
delete next[draftKey];
|
||||
return next;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: draft,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function clearComposerDraftContentState(
|
||||
current: Record<string, ComposerDraft>,
|
||||
draftKey: string,
|
||||
): Record<string, ComposerDraft> {
|
||||
const existing = current[draftKey];
|
||||
if (!existing) {
|
||||
return current;
|
||||
}
|
||||
const draft = {
|
||||
...existing,
|
||||
text: "",
|
||||
attachments: [],
|
||||
};
|
||||
if (isEmptyDraft(draft)) {
|
||||
const next = { ...current };
|
||||
delete next[draftKey];
|
||||
return next;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[draftKey]: draft,
|
||||
};
|
||||
}
|
||||
|
||||
export function clearComposerDraftContent(draftKey: string): void {
|
||||
updateComposerDrafts((current) => clearComposerDraftContentState(current, draftKey));
|
||||
}
|
||||
|
||||
export function clearComposerDraft(draftKey: string): void {
|
||||
updateComposerDrafts((current) => {
|
||||
if (!current[draftKey]) {
|
||||
@@ -396,12 +298,8 @@ export function removeComposerDraftsForEnvironment(
|
||||
environmentId: EnvironmentId,
|
||||
): Record<string, ComposerDraft> {
|
||||
const environmentPrefix = `${environmentId}:`;
|
||||
const newTaskPrefix = `new-task:${environmentId}:`;
|
||||
return Object.fromEntries(
|
||||
Object.entries(drafts).filter(
|
||||
([draftKey]) =>
|
||||
!draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
|
||||
),
|
||||
Object.entries(drafts).filter(([draftKey]) => !draftKey.startsWith(environmentPrefix)),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type EnvironmentId,
|
||||
type ModelSelection,
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
|
||||
|
||||
@@ -26,13 +18,11 @@ import { appAtomRegistry } from "../state/atom-registry";
|
||||
import {
|
||||
appendComposerDraftAttachments,
|
||||
appendComposerDraftText,
|
||||
clearComposerDraftContent,
|
||||
clearComposerDraft,
|
||||
composerDraftsAtom,
|
||||
ensureComposerDraftsLoaded,
|
||||
getComposerDraftSnapshot,
|
||||
removeComposerDraftAttachment,
|
||||
setComposerDraftText,
|
||||
updateComposerDraftSettings,
|
||||
useComposerDraft,
|
||||
} from "./use-composer-drafts";
|
||||
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
|
||||
@@ -108,10 +98,6 @@ export function useThreadComposerState() {
|
||||
const draftMessage = selectedDraft?.text ?? "";
|
||||
const draftAttachments = selectedDraft?.attachments ?? [];
|
||||
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
|
||||
const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
|
||||
const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
|
||||
|
||||
const selectedThreadSessionActivity = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
@@ -144,6 +130,7 @@ export function useThreadComposerState() {
|
||||
selectedThreadShell,
|
||||
]);
|
||||
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const activeThreadBusy =
|
||||
!!selectedThread &&
|
||||
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
|
||||
@@ -154,10 +141,9 @@ export function useThreadComposerState() {
|
||||
}
|
||||
|
||||
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
|
||||
const draft = getComposerDraftSnapshot(threadKey);
|
||||
const thread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const text = draft.text.trim();
|
||||
const attachments = draft.attachments;
|
||||
const draft = composerDrafts[threadKey];
|
||||
const text = (draft?.text ?? "").trim();
|
||||
const attachments = draft?.attachments ?? [];
|
||||
if (text.length === 0 && attachments.length === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -171,18 +157,15 @@ export function useThreadComposerState() {
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
text,
|
||||
attachments,
|
||||
modelSelection: draft.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
|
||||
interactionMode: draft.interactionMode ?? thread.interactionMode,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
clearComposerDraftContent(threadKey);
|
||||
clearComposerDraft(threadKey);
|
||||
} catch (error) {
|
||||
setPendingConnectionError(
|
||||
error instanceof Error ? error.message : "Failed to save the queued message.",
|
||||
);
|
||||
}
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
}, [composerDrafts, selectedThreadShell]);
|
||||
|
||||
const onChangeDraftMessage = useCallback(
|
||||
(value: string) => {
|
||||
@@ -272,45 +255,12 @@ export function useThreadComposerState() {
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
const onUpdateModelSelection = useCallback(
|
||||
(value: ModelSelection) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { modelSelection: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
const onUpdateRuntimeMode = useCallback(
|
||||
(value: RuntimeMode) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
const onUpdateInteractionMode = useCallback(
|
||||
(value: ProviderInteractionMode) => {
|
||||
if (!selectedThreadKey) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedThreadKey, { interactionMode: value });
|
||||
},
|
||||
[selectedThreadKey],
|
||||
);
|
||||
|
||||
return {
|
||||
selectedThreadFeed,
|
||||
selectedThreadQueueCount,
|
||||
activeWorkStartedAt,
|
||||
draftMessage,
|
||||
draftAttachments,
|
||||
modelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
activeThreadBusy,
|
||||
onChangeDraftMessage,
|
||||
onPickDraftImages,
|
||||
@@ -318,8 +268,5 @@ export function useThreadComposerState() {
|
||||
onNativePasteImages,
|
||||
onRemoveDraftImage,
|
||||
onSendMessage,
|
||||
onUpdateModelSelection,
|
||||
onUpdateRuntimeMode,
|
||||
onUpdateInteractionMode,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import { CommandId, type MessageId } from "@t3tools/contracts";
|
||||
import { type MessageId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
@@ -11,13 +10,10 @@ import { appAtomRegistry } from "./atom-registry";
|
||||
import { useThreadShells } from "./entities";
|
||||
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
|
||||
import {
|
||||
modelSelectionsEqual,
|
||||
resolveThreadOutboxDeliveryAction,
|
||||
resolveThreadOutboxFailureAction,
|
||||
resolveQueuedThreadSettings,
|
||||
shouldRetryThreadOutboxDelivery,
|
||||
threadOutboxRetryDelayMs,
|
||||
type QueuedThreadMessage,
|
||||
type ThreadOutboxCommandStage,
|
||||
} from "./thread-outbox-model";
|
||||
import { threadEnvironment } from "./threads";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
@@ -48,21 +44,8 @@ function findThread(
|
||||
);
|
||||
}
|
||||
|
||||
function settingsCommandId(message: QueuedThreadMessage, setting: string): CommandId {
|
||||
return CommandId.make(`${message.commandId}:${setting}`);
|
||||
}
|
||||
|
||||
export function useThreadOutboxDrain(): void {
|
||||
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
const shellStatuses = useThreadOutboxShellStatuses();
|
||||
@@ -85,98 +68,6 @@ export function useThreadOutboxDrain(): void {
|
||||
|
||||
const sendQueuedMessage = useCallback(
|
||||
async (queuedMessage: QueuedThreadMessage, thread: EnvironmentThreadShell) => {
|
||||
const settings = resolveQueuedThreadSettings(queuedMessage, thread);
|
||||
const reportFailure = (
|
||||
commandResult: AtomCommandResult<unknown, unknown>,
|
||||
stage: ThreadOutboxCommandStage,
|
||||
): boolean => {
|
||||
if (!AsyncResult.isFailure(commandResult)) {
|
||||
return false;
|
||||
}
|
||||
const action = resolveThreadOutboxFailureAction({
|
||||
stage,
|
||||
error: Cause.squash(commandResult.cause),
|
||||
interrupted: Cause.hasInterruptsOnly(commandResult.cause),
|
||||
});
|
||||
const retry = action === "retry";
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
stage,
|
||||
cause: commandResult.cause,
|
||||
retry,
|
||||
});
|
||||
return retry;
|
||||
};
|
||||
const completeDelivery = async (
|
||||
deliveryResult: AtomCommandResult<unknown, unknown>,
|
||||
): Promise<boolean> => {
|
||||
if (reportFailure(deliveryResult, "start-turn")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
if (!modelSelectionsEqual(settings.modelSelection, thread.modelSelection)) {
|
||||
const updateResult = await updateThreadMetadata({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "model-selection"),
|
||||
threadId: queuedMessage.threadId,
|
||||
modelSelection: settings.modelSelection,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(updateResult)) {
|
||||
reportFailure(updateResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.runtimeMode !== thread.runtimeMode) {
|
||||
const runtimeResult = await setThreadRuntimeMode({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "runtime-mode"),
|
||||
threadId: queuedMessage.threadId,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(runtimeResult)) {
|
||||
reportFailure(runtimeResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (settings.interactionMode !== thread.interactionMode) {
|
||||
const interactionResult = await setThreadInteractionMode({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: settingsCommandId(queuedMessage, "interaction-mode"),
|
||||
threadId: queuedMessage.threadId,
|
||||
interactionMode: settings.interactionMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
if (AsyncResult.isFailure(interactionResult)) {
|
||||
reportFailure(interactionResult, "settings-sync");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const deliveryResult = await startTurn({
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
@@ -188,15 +79,41 @@ export function useThreadOutboxDrain(): void {
|
||||
text: queuedMessage.text,
|
||||
attachments: queuedMessage.attachments,
|
||||
},
|
||||
modelSelection: settings.modelSelection,
|
||||
runtimeMode: settings.runtimeMode,
|
||||
interactionMode: settings.interactionMode,
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
},
|
||||
});
|
||||
return completeDelivery(deliveryResult);
|
||||
if (AsyncResult.isFailure(deliveryResult)) {
|
||||
const error = Cause.squash(deliveryResult.cause);
|
||||
const retry =
|
||||
Cause.hasInterruptsOnly(deliveryResult.cause) || shouldRetryThreadOutboxDelivery(error);
|
||||
console.warn("[thread-outbox] queued message delivery failed", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
cause: deliveryResult.cause,
|
||||
retry,
|
||||
});
|
||||
if (retry) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await removeThreadOutboxMessage(queuedMessage);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn("[thread-outbox] failed to remove delivered queued message", {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
threadId: queuedMessage.threadId,
|
||||
messageId: queuedMessage.messageId,
|
||||
error,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
|
||||
[startTurn],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -44,8 +44,8 @@ const failingSessionLookupRepositoryLayer = Layer.succeed(AuthSessions.AuthSessi
|
||||
create: () => Effect.void,
|
||||
getById: () => Effect.fail(repositoryFailure),
|
||||
listActive: () => Effect.succeed([]),
|
||||
revoke: () => Effect.fail(repositoryFailure),
|
||||
revokeAllExcept: () => Effect.fail(repositoryFailure),
|
||||
revoke: () => Effect.succeed(false),
|
||||
revokeAllExcept: () => Effect.succeed([]),
|
||||
setLastConnectedAt: () => Effect.void,
|
||||
});
|
||||
|
||||
@@ -104,29 +104,11 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
|
||||
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
|
||||
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
const revokeError = yield* Effect.flip(sessions.revoke(issued.sessionId));
|
||||
const revokeOthersError = yield* Effect.flip(sessions.revokeAllExcept(issued.sessionId));
|
||||
|
||||
expect(sessionError._tag).toBe("SessionCredentialVerificationError");
|
||||
expect(websocketError._tag).toBe("WebSocketTokenVerificationError");
|
||||
expect(sessionError.cause).toBe(repositoryFailure);
|
||||
expect(websocketError.cause).toBe(repositoryFailure);
|
||||
if (sessionError._tag === "SessionCredentialVerificationError") {
|
||||
expect(sessionError.sessionId).toBe(issued.sessionId);
|
||||
}
|
||||
if (websocketError._tag === "WebSocketTokenVerificationError") {
|
||||
expect(websocketError.sessionId).toBe(issued.sessionId);
|
||||
}
|
||||
expect(revokeError).toMatchObject({
|
||||
_tag: "SessionRevocationError",
|
||||
sessionId: issued.sessionId,
|
||||
cause: repositoryFailure,
|
||||
});
|
||||
expect(revokeOthersError).toMatchObject({
|
||||
_tag: "OtherSessionsRevocationError",
|
||||
currentSessionId: issued.sessionId,
|
||||
cause: repositoryFailure,
|
||||
});
|
||||
}).pipe(Effect.provide(failingSessionLookupCredentialLayer)),
|
||||
);
|
||||
it.effect("verifies session tokens against the Effect clock", () =>
|
||||
@@ -163,52 +145,7 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
expect(error._tag).toBe("WebSocketSessionExpiredError");
|
||||
if (error._tag === "WebSocketSessionExpiredError") {
|
||||
expect(error.sessionId).toBe(issued.sessionId);
|
||||
expect(error.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
|
||||
expect(error.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
error.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("includes expiry context when session and websocket tokens expire", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* SessionStore.SessionStore;
|
||||
const issued = yield* sessions.issue({
|
||||
method: "bearer-access-token",
|
||||
subject: "short-lived-token",
|
||||
ttl: Duration.seconds(1),
|
||||
});
|
||||
const websocket = yield* sessions.issueWebSocketToken(issued.sessionId, {
|
||||
ttl: Duration.seconds(1),
|
||||
});
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(2));
|
||||
|
||||
const sessionError = yield* Effect.flip(sessions.verify(issued.token));
|
||||
const websocketError = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token));
|
||||
|
||||
expect(sessionError._tag).toBe("SessionTokenExpiredError");
|
||||
if (sessionError._tag === "SessionTokenExpiredError") {
|
||||
expect(sessionError.sessionId).toBe(issued.sessionId);
|
||||
expect(sessionError.expiresAt.epochMilliseconds).toBe(issued.expiresAt.epochMilliseconds);
|
||||
expect(sessionError.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
sessionError.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
expect(websocketError._tag).toBe("WebSocketTokenExpiredError");
|
||||
if (websocketError._tag === "WebSocketTokenExpiredError") {
|
||||
expect(websocketError.sessionId).toBe(issued.sessionId);
|
||||
expect(websocketError.expiresAt.epochMilliseconds).toBe(
|
||||
websocket.expiresAt.epochMilliseconds,
|
||||
);
|
||||
expect(websocketError.observedAt.epochMilliseconds).toBeGreaterThan(
|
||||
websocketError.expiresAt.epochMilliseconds,
|
||||
);
|
||||
}
|
||||
expect(error.message).toContain("expired");
|
||||
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
|
||||
);
|
||||
|
||||
@@ -236,16 +173,12 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
ipAddress: "192.168.1.88",
|
||||
},
|
||||
});
|
||||
const clientWebSocket = yield* sessions.issueWebSocketToken(client.sessionId);
|
||||
|
||||
yield* sessions.markConnected(client.sessionId);
|
||||
const beforeRevoke = yield* sessions.listActive();
|
||||
const revokedCount = yield* sessions.revokeAllExcept(administrative.sessionId);
|
||||
const afterRevoke = yield* sessions.listActive();
|
||||
const revokedClient = yield* Effect.flip(sessions.verify(client.token));
|
||||
const revokedClientWebSocket = yield* Effect.flip(
|
||||
sessions.verifyWebSocketToken(clientWebSocket.token),
|
||||
);
|
||||
|
||||
expect(beforeRevoke).toHaveLength(2);
|
||||
expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe(
|
||||
@@ -261,16 +194,7 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
|
||||
expect(revokedCount).toBe(1);
|
||||
expect(afterRevoke).toHaveLength(1);
|
||||
expect(afterRevoke[0]?.sessionId).toBe(administrative.sessionId);
|
||||
expect(revokedClient._tag).toBe("SessionTokenRevokedError");
|
||||
if (revokedClient._tag === "SessionTokenRevokedError") {
|
||||
expect(revokedClient.sessionId).toBe(client.sessionId);
|
||||
expect(revokedClient.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
expect(revokedClientWebSocket._tag).toBe("WebSocketSessionRevokedError");
|
||||
if (revokedClientWebSocket._tag === "WebSocketSessionRevokedError") {
|
||||
expect(revokedClientWebSocket.sessionId).toBe(client.sessionId);
|
||||
expect(revokedClientWebSocket.revokedAt.epochMilliseconds).toBeGreaterThanOrEqual(0);
|
||||
}
|
||||
expect(revokedClient.message).toContain("revoked");
|
||||
}).pipe(Effect.provide(makeSessionStoreLayer())),
|
||||
);
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type AuthEnvironmentScope,
|
||||
type ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -92,11 +93,7 @@ export class InvalidSessionTokenPayloadError extends Schema.TaggedErrorClass<Inv
|
||||
|
||||
export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTokenExpiredError>()(
|
||||
"SessionTokenExpiredError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Session token expired.";
|
||||
@@ -105,9 +102,7 @@ export class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTok
|
||||
|
||||
export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSessionTokenError>()(
|
||||
"UnknownSessionTokenError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Unknown session token.";
|
||||
@@ -116,10 +111,7 @@ export class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSes
|
||||
|
||||
export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTokenRevokedError>()(
|
||||
"SessionTokenRevokedError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Session token revoked.";
|
||||
@@ -128,10 +120,7 @@ export class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTok
|
||||
|
||||
export class InvalidSessionExpirationClaimError extends Schema.TaggedErrorClass<InvalidSessionExpirationClaimError>()(
|
||||
"InvalidSessionExpirationClaimError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expirationClaim: Schema.Number,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Invalid `exp` claim";
|
||||
@@ -169,11 +158,7 @@ export class InvalidWebSocketTokenPayloadError extends Schema.TaggedErrorClass<I
|
||||
|
||||
export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocketTokenExpiredError>()(
|
||||
"WebSocketTokenExpiredError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket token expired.";
|
||||
@@ -182,9 +167,7 @@ export class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocke
|
||||
|
||||
export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<UnknownWebSocketSessionError>()(
|
||||
"UnknownWebSocketSessionError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Unknown websocket session.";
|
||||
@@ -193,11 +176,7 @@ export class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<Unknow
|
||||
|
||||
export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSocketSessionExpiredError>()(
|
||||
"WebSocketSessionExpiredError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
expiresAt: Schema.DateTimeUtc,
|
||||
observedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket session expired.";
|
||||
@@ -206,10 +185,7 @@ export class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSoc
|
||||
|
||||
export class WebSocketSessionRevokedError extends Schema.TaggedErrorClass<WebSocketSessionRevokedError>()(
|
||||
"WebSocketSessionRevokedError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
revokedAt: Schema.DateTimeUtc,
|
||||
},
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Websocket session revoked.";
|
||||
@@ -242,7 +218,6 @@ const sessionCredentialInternalErrorContext = {
|
||||
export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionClaimsEncodingError>()(
|
||||
"SessionClaimsEncodingError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
operation: Schema.Literals(["encode_session_claims", "encode_websocket_claims"]),
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
@@ -255,7 +230,6 @@ export class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionC
|
||||
export class SessionCredentialIssueError extends Schema.TaggedErrorClass<SessionCredentialIssueError>()(
|
||||
"SessionCredentialIssueError",
|
||||
{
|
||||
sessionId: Schema.optional(AuthSessionId),
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -267,7 +241,6 @@ export class SessionCredentialIssueError extends Schema.TaggedErrorClass<Session
|
||||
export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<SessionCredentialVerificationError>()(
|
||||
"SessionCredentialVerificationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -279,7 +252,6 @@ export class SessionCredentialVerificationError extends Schema.TaggedErrorClass<
|
||||
export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketTokenIssueError>()(
|
||||
"WebSocketTokenIssueError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -291,7 +263,6 @@ export class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketT
|
||||
export class WebSocketTokenVerificationError extends Schema.TaggedErrorClass<WebSocketTokenVerificationError>()(
|
||||
"WebSocketTokenVerificationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -314,7 +285,6 @@ export class ActiveSessionsListError extends Schema.TaggedErrorClass<ActiveSessi
|
||||
export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevocationError>()(
|
||||
"SessionRevocationError",
|
||||
{
|
||||
sessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -326,7 +296,6 @@ export class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevoc
|
||||
export class OtherSessionsRevocationError extends Schema.TaggedErrorClass<OtherSessionsRevocationError>()(
|
||||
"OtherSessionsRevocationError",
|
||||
{
|
||||
currentSessionId: AuthSessionId,
|
||||
...sessionCredentialInternalErrorContext,
|
||||
},
|
||||
) {
|
||||
@@ -570,11 +539,7 @@ export const make = Effect.gen(function* () {
|
||||
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
|
||||
const issue: SessionStore["Service"]["issue"] = Effect.fn("SessionStore.issue")(
|
||||
function* (input) {
|
||||
const sessionId = AuthSessionId.make(
|
||||
yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
|
||||
),
|
||||
);
|
||||
const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
||||
@@ -594,37 +559,27 @@ export const make = Effect.gen(function* () {
|
||||
const encodedPayload = yield* encodeClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionCredentialIssueError({
|
||||
sessionId,
|
||||
cause: new SessionClaimsEncodingError({
|
||||
sessionId,
|
||||
operation: "encode_session_claims",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
(cause) => new SessionClaimsEncodingError({ operation: "encode_session_claims", cause }),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
const client = input?.client ?? createDefaultClientMetadata();
|
||||
yield* authSessions
|
||||
.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
scopes: claims.scopes,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));
|
||||
yield* authSessions.create({
|
||||
sessionId,
|
||||
subject: claims.sub,
|
||||
scopes: claims.scopes,
|
||||
method: claims.method,
|
||||
client: {
|
||||
label: client.label ?? null,
|
||||
ipAddress: client.ipAddress ?? null,
|
||||
userAgent: client.userAgent ?? null,
|
||||
deviceType: client.deviceType,
|
||||
os: client.os ?? null,
|
||||
browser: client.browser ?? null,
|
||||
},
|
||||
issuedAt,
|
||||
expiresAt,
|
||||
});
|
||||
yield* emitUpsert(
|
||||
toAuthClientSession({
|
||||
sessionId,
|
||||
@@ -649,6 +604,7 @@ export const make = Effect.gen(function* () {
|
||||
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
|
||||
} satisfies IssuedSession;
|
||||
},
|
||||
Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),
|
||||
);
|
||||
|
||||
const verify: SessionStore["Service"]["verify"] = Effect.fn("SessionStore.verify")(
|
||||
@@ -667,37 +623,22 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),
|
||||
);
|
||||
|
||||
const observedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({
|
||||
sessionId: claims.sid,
|
||||
expirationClaim: claims.exp,
|
||||
});
|
||||
}
|
||||
if (claims.exp <= observedAt.epochMilliseconds) {
|
||||
return yield* new SessionTokenExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: expiresAt.value,
|
||||
observedAt,
|
||||
});
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new SessionTokenExpiredError({});
|
||||
}
|
||||
|
||||
const row = yield* authSessions
|
||||
.getById({ sessionId: claims.sid })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),
|
||||
),
|
||||
);
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownSessionTokenError({ sessionId: claims.sid });
|
||||
return yield* new UnknownSessionTokenError({});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new SessionTokenRevokedError({
|
||||
sessionId: claims.sid,
|
||||
revokedAt: row.value.revokedAt,
|
||||
});
|
||||
return yield* new SessionTokenRevokedError({});
|
||||
}
|
||||
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({});
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -711,111 +652,95 @@ export const make = Effect.gen(function* () {
|
||||
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
|
||||
} satisfies VerifiedSession;
|
||||
},
|
||||
Effect.mapError((cause) =>
|
||||
isSessionCredentialInvalidError(cause)
|
||||
? cause
|
||||
: new SessionCredentialVerificationError({ cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
|
||||
const issueWebSocketToken: SessionStore["Service"]["issueWebSocketToken"] = Effect.fn(
|
||||
"SessionStore.issueWebSocketToken",
|
||||
)(function* (sessionId, input) {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = yield* encodeWsClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new WebSocketTokenIssueError({
|
||||
sessionId,
|
||||
cause: new SessionClaimsEncodingError({
|
||||
sessionId,
|
||||
operation: "encode_websocket_claims",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
});
|
||||
)(
|
||||
function* (sessionId, input) {
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),
|
||||
});
|
||||
const claims: WebSocketClaims = {
|
||||
v: 1,
|
||||
kind: "websocket",
|
||||
sid: sessionId,
|
||||
iat: issuedAt.epochMilliseconds,
|
||||
exp: expiresAt.epochMilliseconds,
|
||||
};
|
||||
const encodedPayload = yield* encodeWsClaims(claims).pipe(
|
||||
Effect.map(base64UrlEncode),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SessionClaimsEncodingError({ operation: "encode_websocket_claims", cause }),
|
||||
),
|
||||
);
|
||||
const signature = signPayload(encodedPayload, signingSecret);
|
||||
return {
|
||||
token: `${encodedPayload}.${signature}`,
|
||||
expiresAt,
|
||||
};
|
||||
},
|
||||
Effect.mapError((cause) => new WebSocketTokenIssueError({ cause })),
|
||||
);
|
||||
|
||||
const verifyWebSocketToken: SessionStore["Service"]["verifyWebSocketToken"] = Effect.fn(
|
||||
"SessionStore.verifyWebSocketToken",
|
||||
)(function* (token) {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new MalformedWebSocketTokenError({});
|
||||
}
|
||||
)(
|
||||
function* (token) {
|
||||
const [encodedPayload, signature] = token.split(".");
|
||||
if (!encodedPayload || !signature) {
|
||||
return yield* new MalformedWebSocketTokenError({});
|
||||
}
|
||||
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new InvalidWebSocketTokenSignatureError({});
|
||||
}
|
||||
const expectedSignature = signPayload(encodedPayload, signingSecret);
|
||||
if (!timingSafeEqualBase64Url(signature, expectedSignature)) {
|
||||
return yield* new InvalidWebSocketTokenSignatureError({});
|
||||
}
|
||||
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
|
||||
);
|
||||
|
||||
const observedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.make(claims.exp);
|
||||
if (Option.isNone(expiresAt)) {
|
||||
return yield* new InvalidSessionExpirationClaimError({
|
||||
sessionId: claims.sid,
|
||||
expirationClaim: claims.exp,
|
||||
});
|
||||
}
|
||||
if (claims.exp <= observedAt.epochMilliseconds) {
|
||||
return yield* new WebSocketTokenExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: expiresAt.value,
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
|
||||
const row = yield* authSessions
|
||||
.getById({ sessionId: claims.sid })
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),
|
||||
),
|
||||
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
|
||||
Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),
|
||||
);
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {
|
||||
return yield* new WebSocketSessionExpiredError({
|
||||
sessionId: claims.sid,
|
||||
expiresAt: row.value.expiresAt,
|
||||
observedAt,
|
||||
});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new WebSocketSessionRevokedError({
|
||||
sessionId: claims.sid,
|
||||
revokedAt: row.value.revokedAt,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
scopes: row.value.scopes,
|
||||
} satisfies VerifiedSession;
|
||||
});
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
if (claims.exp <= now) {
|
||||
return yield* new WebSocketTokenExpiredError({});
|
||||
}
|
||||
|
||||
const row = yield* authSessions.getById({ sessionId: claims.sid });
|
||||
if (Option.isNone(row)) {
|
||||
return yield* new UnknownWebSocketSessionError({});
|
||||
}
|
||||
if (row.value.expiresAt.epochMilliseconds <= now) {
|
||||
return yield* new WebSocketSessionExpiredError({});
|
||||
}
|
||||
if (row.value.revokedAt !== null) {
|
||||
return yield* new WebSocketSessionRevokedError({});
|
||||
}
|
||||
|
||||
return {
|
||||
sessionId: row.value.sessionId,
|
||||
token,
|
||||
method: row.value.method,
|
||||
client: toClientMetadata(row.value.client),
|
||||
expiresAt: row.value.expiresAt,
|
||||
subject: row.value.subject,
|
||||
scopes: row.value.scopes,
|
||||
} satisfies VerifiedSession;
|
||||
},
|
||||
Effect.mapError((cause) =>
|
||||
isSessionCredentialInvalidError(cause)
|
||||
? cause
|
||||
: new WebSocketTokenVerificationError({ cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const listActive: SessionStore["Service"]["listActive"] = Effect.fn("SessionStore.listActive")(
|
||||
function* () {
|
||||
@@ -843,12 +768,10 @@ export const make = Effect.gen(function* () {
|
||||
const revoke: SessionStore["Service"]["revoke"] = Effect.fn("SessionStore.revoke")(
|
||||
function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revoked = yield* authSessions
|
||||
.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
})
|
||||
.pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));
|
||||
const revoked = yield* authSessions.revoke({
|
||||
sessionId,
|
||||
revokedAt,
|
||||
});
|
||||
if (revoked) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
@@ -859,41 +782,39 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
return revoked;
|
||||
},
|
||||
Effect.mapError((cause) => new SessionRevocationError({ cause })),
|
||||
);
|
||||
|
||||
const revokeAllExcept: SessionStore["Service"]["revokeAllExcept"] = Effect.fn(
|
||||
"SessionStore.revokeAllExcept",
|
||||
)(function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions
|
||||
.revokeAllExcept({
|
||||
)(
|
||||
function* (sessionId) {
|
||||
const revokedAt = yield* DateTime.now;
|
||||
const revokedSessionIds = yield* authSessions.revokeAllExcept({
|
||||
currentSessionId: sessionId,
|
||||
revokedAt,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),
|
||||
),
|
||||
);
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
});
|
||||
if (revokedSessionIds.length > 0) {
|
||||
yield* Ref.update(connectedSessionsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
for (const revokedSessionId of revokedSessionIds) {
|
||||
next.delete(revokedSessionId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
revokedSessionIds,
|
||||
(revokedSessionId) => emitRemoved(revokedSessionId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
return revokedSessionIds.length;
|
||||
},
|
||||
Effect.mapError((cause) => new OtherSessionsRevocationError({ cause })),
|
||||
);
|
||||
|
||||
return SessionStore.of({
|
||||
cookieName,
|
||||
|
||||
@@ -3,8 +3,7 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Option from "effect/Option";
|
||||
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
|
||||
import {
|
||||
ServerAuthDpopReplayKeyCalculationError,
|
||||
@@ -14,6 +13,22 @@ import {
|
||||
} from "./EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "./ServerSecretStore.ts";
|
||||
|
||||
function firstHeaderValue(value: string | undefined): string | undefined {
|
||||
const first = value?.split(",")[0]?.trim();
|
||||
return first && first.length > 0 ? first : undefined;
|
||||
}
|
||||
|
||||
export function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string {
|
||||
try {
|
||||
return new URL(request.originalUrl).href;
|
||||
} catch {
|
||||
const host = firstHeaderValue(request.headers.host) ?? "127.0.0.1";
|
||||
const forwardedProto = firstHeaderValue(request.headers["x-forwarded-proto"]);
|
||||
const proto = forwardedProto === "https" || forwardedProto === "http" ? forwardedProto : "http";
|
||||
return new URL(request.originalUrl, `${proto}://${host}`).href;
|
||||
}
|
||||
}
|
||||
|
||||
export const mapDpopReplayStoreError = (
|
||||
error: ServerSecretStore.SecretStoreError,
|
||||
): ServerAuthInvalidCredentialError | ServerAuthInternalError =>
|
||||
@@ -33,17 +48,11 @@ export const verifyRequestDpopProof = (input: {
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const proof = input.request.headers.dpop;
|
||||
const url = HttpServerRequest.toURL(input.request);
|
||||
if (Option.isNone(url)) {
|
||||
return yield* new ServerAuthInvalidCredentialError({
|
||||
diagnostic: "Invalid DPoP request URL.",
|
||||
});
|
||||
}
|
||||
const now = yield* DateTime.now;
|
||||
const result = verifyDpopProof({
|
||||
proof,
|
||||
method: input.request.method,
|
||||
url: url.value.href,
|
||||
url: requestAbsoluteUrl(input.request),
|
||||
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
|
||||
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
|
||||
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
|
||||
|
||||
@@ -2,11 +2,7 @@ import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { EnvironmentInternalError } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
ProjectLiveServerDeclaredResponseError,
|
||||
ProjectLiveServerRequestError,
|
||||
projectCommandErrorFromLiveServerRequest,
|
||||
} from "./project.ts";
|
||||
import { ProjectCommandError } from "./project.ts";
|
||||
|
||||
it("maps declared server failures into structural project command errors", () => {
|
||||
const cause = new EnvironmentInternalError({
|
||||
@@ -15,9 +11,8 @@ it("maps declared server failures into structural project command errors", () =>
|
||||
traceId: "trace-123",
|
||||
});
|
||||
|
||||
const error = projectCommandErrorFromLiveServerRequest(cause);
|
||||
const error = ProjectCommandError.fromLiveServerRequest(cause);
|
||||
|
||||
assert.instanceOf(error, ProjectLiveServerDeclaredResponseError);
|
||||
assert.strictEqual(error.operation, "callLiveServer");
|
||||
assert.strictEqual(error.code, "internal_error");
|
||||
assert.strictEqual(error.traceId, "trace-123");
|
||||
@@ -28,10 +23,10 @@ it("maps declared server failures into structural project command errors", () =>
|
||||
it("preserves unexpected server failures without deriving the message from them", () => {
|
||||
const cause = new Error("credential abc123 was rejected");
|
||||
|
||||
const error = projectCommandErrorFromLiveServerRequest(cause);
|
||||
const error = ProjectCommandError.fromLiveServerRequest(cause);
|
||||
|
||||
assert.instanceOf(error, ProjectLiveServerRequestError);
|
||||
assert.strictEqual(error.operation, "callLiveServer");
|
||||
assert.strictEqual(error.detail, "Failed to call the running server.");
|
||||
assert.strictEqual(error.message, "Failed to call the running server.");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
});
|
||||
+49
-138
@@ -51,148 +51,62 @@ type ProjectCliDispatchCommand = Extract<
|
||||
>;
|
||||
|
||||
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
|
||||
const ProjectCommandOperation = Schema.Literals([
|
||||
"generateProjectCommandId",
|
||||
"callLiveServer",
|
||||
"validateProjectTitle",
|
||||
"resolveProjectTarget",
|
||||
"addProject",
|
||||
]);
|
||||
|
||||
export class ProjectCommandIdGenerationError extends Schema.TaggedErrorClass<ProjectCommandIdGenerationError>()(
|
||||
"ProjectCommandIdGenerationError",
|
||||
export class ProjectCommandError extends Schema.TaggedErrorClass<ProjectCommandError>()(
|
||||
"ProjectCommandError",
|
||||
{
|
||||
operation: Schema.Literal("generateProjectCommandId"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to generate a project command identifier.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectLiveServerDeclaredResponseError extends Schema.TaggedErrorClass<ProjectLiveServerDeclaredResponseError>()(
|
||||
"ProjectLiveServerDeclaredResponseError",
|
||||
{
|
||||
operation: Schema.Literal("callLiveServer"),
|
||||
code: Schema.String,
|
||||
traceId: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Server request failed (${this.code}, trace ${this.traceId}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedErrorClass<ProjectLiveServerUndeclaredStatusError>()(
|
||||
"ProjectLiveServerUndeclaredStatusError",
|
||||
{
|
||||
operation: Schema.Literal("callLiveServer"),
|
||||
status: Schema.Int,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Server request failed with undeclared status ${this.status}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectLiveServerRequestError extends Schema.TaggedErrorClass<ProjectLiveServerRequestError>()(
|
||||
"ProjectLiveServerRequestError",
|
||||
{
|
||||
operation: Schema.Literal("callLiveServer"),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Failed to call the running server.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectTitleEmptyError extends Schema.TaggedErrorClass<ProjectTitleEmptyError>()(
|
||||
"ProjectTitleEmptyError",
|
||||
{
|
||||
operation: Schema.Literal("validateProjectTitle"),
|
||||
title: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Project title cannot be empty.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectIdentifierEmptyError extends Schema.TaggedErrorClass<ProjectIdentifierEmptyError>()(
|
||||
"ProjectIdentifierEmptyError",
|
||||
{
|
||||
operation: Schema.Literal("resolveProjectTarget"),
|
||||
identifier: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Project identifier cannot be empty.";
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(
|
||||
"ProjectNotFoundError",
|
||||
{
|
||||
operation: Schema.Literal("resolveProjectTarget"),
|
||||
identifier: Schema.String,
|
||||
normalizedWorkspaceRoot: Schema.optional(Schema.String),
|
||||
activeProjectCount: Schema.Number,
|
||||
operation: ProjectCommandOperation,
|
||||
detail: Schema.String,
|
||||
code: Schema.optional(Schema.String),
|
||||
traceId: Schema.optional(Schema.String),
|
||||
status: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `No active project found for '${this.identifier}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ProjectAlreadyExistsError extends Schema.TaggedErrorClass<ProjectAlreadyExistsError>()(
|
||||
"ProjectAlreadyExistsError",
|
||||
{
|
||||
operation: Schema.Literal("addProject"),
|
||||
projectId: ProjectId,
|
||||
workspaceRoot: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `An active project already exists for '${this.workspaceRoot}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const ProjectCommandError = Schema.Union([
|
||||
ProjectCommandIdGenerationError,
|
||||
ProjectLiveServerDeclaredResponseError,
|
||||
ProjectLiveServerUndeclaredStatusError,
|
||||
ProjectLiveServerRequestError,
|
||||
ProjectTitleEmptyError,
|
||||
ProjectIdentifierEmptyError,
|
||||
ProjectNotFoundError,
|
||||
ProjectAlreadyExistsError,
|
||||
]);
|
||||
export type ProjectCommandError = typeof ProjectCommandError.Type;
|
||||
|
||||
export function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {
|
||||
if (isEnvironmentHttpCommonError(cause)) {
|
||||
return new ProjectLiveServerDeclaredResponseError({
|
||||
static fromLiveServerRequest(cause: unknown): ProjectCommandError {
|
||||
if (isEnvironmentHttpCommonError(cause)) {
|
||||
return new ProjectCommandError({
|
||||
operation: "callLiveServer",
|
||||
detail: `Server request failed (${cause.code}, trace ${cause.traceId}).`,
|
||||
code: cause.code,
|
||||
traceId: cause.traceId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
|
||||
return new ProjectCommandError({
|
||||
operation: "callLiveServer",
|
||||
detail: `Server request failed with undeclared status ${cause.response.status}.`,
|
||||
status: cause.response.status,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
return new ProjectCommandError({
|
||||
operation: "callLiveServer",
|
||||
code: cause.code,
|
||||
traceId: cause.traceId,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {
|
||||
return new ProjectLiveServerUndeclaredStatusError({
|
||||
operation: "callLiveServer",
|
||||
status: cause.response.status,
|
||||
detail: "Failed to call the running server.",
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
return new ProjectLiveServerRequestError({ operation: "callLiveServer", cause });
|
||||
override get message(): string {
|
||||
return this.detail;
|
||||
}
|
||||
}
|
||||
|
||||
const projectCommandUuid = Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProjectCommandIdGenerationError({
|
||||
new ProjectCommandError({
|
||||
operation: "generateProjectCommandId",
|
||||
detail: "Failed to generate a project command identifier.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -244,9 +158,9 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
|
||||
if (trimmed.length > 0) {
|
||||
return trimmed;
|
||||
}
|
||||
return yield* new ProjectTitleEmptyError({
|
||||
return yield* new ProjectCommandError({
|
||||
operation: "validateProjectTitle",
|
||||
title: explicitTitle,
|
||||
detail: "Project title cannot be empty.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -261,9 +175,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
|
||||
}) {
|
||||
const trimmedIdentifier = input.identifier.trim();
|
||||
if (trimmedIdentifier.length === 0) {
|
||||
return yield* new ProjectIdentifierEmptyError({
|
||||
return yield* new ProjectCommandError({
|
||||
operation: "resolveProjectTarget",
|
||||
identifier: input.identifier,
|
||||
detail: "Project identifier cannot be empty.",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -290,11 +204,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
|
||||
|
||||
const resolved = exactWorkspaceMatch;
|
||||
if (!resolved) {
|
||||
return yield* new ProjectNotFoundError({
|
||||
return yield* new ProjectCommandError({
|
||||
operation: "resolveProjectTarget",
|
||||
identifier: trimmedIdentifier,
|
||||
activeProjectCount: activeProjects.length,
|
||||
...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),
|
||||
detail: `No active project found for '${trimmedIdentifier}'.`,
|
||||
...(normalizedWorkspaceRootResult._tag === "Failure"
|
||||
? { cause: normalizedWorkspaceRootResult.failure }
|
||||
: {}),
|
||||
@@ -316,7 +228,7 @@ const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
|
||||
});
|
||||
}).pipe(
|
||||
withProjectCliLiveServerTimeout,
|
||||
Effect.mapError(projectCommandErrorFromLiveServerRequest),
|
||||
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
|
||||
);
|
||||
|
||||
const dispatchLiveOrchestrationCommand = (
|
||||
@@ -332,7 +244,7 @@ const dispatchLiveOrchestrationCommand = (
|
||||
} as Parameters<typeof client.orchestration.dispatch>[0]);
|
||||
}).pipe(
|
||||
withProjectCliLiveServerTimeout,
|
||||
Effect.mapError(projectCommandErrorFromLiveServerRequest),
|
||||
Effect.mapError(ProjectCommandError.fromLiveServerRequest),
|
||||
);
|
||||
|
||||
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
|
||||
@@ -464,10 +376,9 @@ const projectAddCommand = Command.make("add", {
|
||||
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
|
||||
);
|
||||
if (existingProject) {
|
||||
return yield* new ProjectAlreadyExistsError({
|
||||
return yield* new ProjectCommandError({
|
||||
operation: "addProject",
|
||||
projectId: existingProject.id,
|
||||
workspaceRoot,
|
||||
detail: `An active project already exists for '${workspaceRoot}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -171,8 +171,20 @@ function runGitSyncForFakeGh(cwd: string, args: readonly string[]): void {
|
||||
if (result.status === 0) {
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
`Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
|
||||
throw new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd,
|
||||
detail: `Failed to simulate gh checkout with git ${args.join(" ")}: ${result.stderr?.trim() || "unknown error"}`,
|
||||
});
|
||||
}
|
||||
|
||||
function isGitHubCliError(error: unknown): error is GitHubCli.GitHubCliError {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
(error as { _tag?: unknown })._tag === "GitHubCliError"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -466,12 +478,16 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
return fakeGhOutput("");
|
||||
},
|
||||
catch: (error) =>
|
||||
GitHubCli.isGitHubCliError(error)
|
||||
isGitHubCliError(error)
|
||||
? error
|
||||
: new GitHubCli.GitHubCliCommandError({
|
||||
: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: error,
|
||||
detail:
|
||||
error instanceof Error
|
||||
? `Failed to simulate gh checkout: ${error.message}`
|
||||
: "Failed to simulate gh checkout.",
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -482,10 +498,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
const cloneUrls = scenario.repositoryCloneUrls?.[repository];
|
||||
if (!cloneUrls) {
|
||||
return Effect.fail(
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: new Error(`Unexpected repository lookup: ${repository}`),
|
||||
detail: `Unexpected repository lookup: ${repository}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -503,10 +520,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}
|
||||
|
||||
return Effect.fail(
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: new Error(`Unexpected gh command: ${args.join(" ")}`),
|
||||
detail: `Unexpected gh command: ${args.join(" ")}`,
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -583,10 +601,11 @@ function createGitHubCliWithFakeGh(scenario: FakeGhScenario = {}): {
|
||||
}).pipe(Effect.map((result) => JSON.parse(result.stdout))),
|
||||
createRepository: (input) =>
|
||||
Effect.fail(
|
||||
new GitHubCli.GitHubCliCommandError({
|
||||
new GitHubCli.GitHubCliError({
|
||||
operation: "createRepository",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause: new Error(`Unexpected repository create: ${input.repository}`),
|
||||
detail: `Unexpected repository create: ${input.repository}`,
|
||||
}),
|
||||
),
|
||||
checkoutPullRequest: (input) =>
|
||||
@@ -1322,10 +1341,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("gh is not available on PATH"),
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -2463,10 +2483,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliUnavailableError({
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("gh is not available on PATH"),
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -2493,10 +2514,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
failWith: new GitHubCli.GitHubCliAuthenticationError({
|
||||
failWith: new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: repoDir,
|
||||
cause: new Error("gh is not authenticated"),
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -198,7 +198,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
|
||||
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
|
||||
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
|
||||
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
PreviewAutomationUnavailableError,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as McpInvocationContext from "./McpInvocationContext.ts";
|
||||
|
||||
it.effect("reports the scoped credential context when preview capability is unavailable", () => {
|
||||
const invocation: McpInvocationContext.McpInvocationScope = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
providerSessionId: "provider-session-1",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(),
|
||||
issuedAt: 1,
|
||||
expiresAt: 2,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const error = yield* McpInvocationContext.requireMcpCapability("preview").pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(PreviewAutomationUnavailableError);
|
||||
expect(error).toMatchObject({
|
||||
capability: "preview",
|
||||
environmentId: invocation.environmentId,
|
||||
threadId: invocation.threadId,
|
||||
providerSessionId: invocation.providerSessionId,
|
||||
providerInstanceId: invocation.providerInstanceId,
|
||||
});
|
||||
expect(error.message).toBe("MCP credential does not grant the preview capability.");
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,5 @@
|
||||
import {
|
||||
type EnvironmentId,
|
||||
PreviewAutomationUnavailableError,
|
||||
type ProviderInstanceId,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { PreviewAutomationUnavailableError } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
@@ -30,11 +26,7 @@ export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function*
|
||||
const invocation = yield* McpInvocationContext;
|
||||
if (!invocation.capabilities.has(capability)) {
|
||||
return yield* new PreviewAutomationUnavailableError({
|
||||
capability,
|
||||
environmentId: invocation.environmentId,
|
||||
threadId: invocation.threadId,
|
||||
providerSessionId: invocation.providerSessionId,
|
||||
providerInstanceId: invocation.providerInstanceId,
|
||||
message: `MCP credential does not grant the ${capability} capability.`,
|
||||
});
|
||||
}
|
||||
return invocation;
|
||||
|
||||
@@ -4,7 +4,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import type * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type { CursorSettings } from "@t3tools/contracts";
|
||||
@@ -25,11 +24,7 @@ import {
|
||||
} from "./CursorProvider.ts";
|
||||
|
||||
const runNode = <A, E>(
|
||||
effect: Effect.Effect<
|
||||
A,
|
||||
E,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
>,
|
||||
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
|
||||
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
|
||||
|
||||
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
|
||||
@@ -298,18 +293,6 @@ const baseCursorSettings: CursorSettings = {
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
};
|
||||
const cursorAcpDiscoveryFailedMessage = [
|
||||
"Cursor ACP model discovery failed.",
|
||||
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
|
||||
"See https://cursor.com/docs/cli/installation.",
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent";
|
||||
const cursorCliCommandMissingMessage = [
|
||||
`Cursor CLI command \`${missingCursorBinaryPath}\` was not found.`,
|
||||
`Install or enable the Cursor CLI, make sure \`${missingCursorBinaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
"See https://cursor.com/docs/cli/installation.",
|
||||
].join(" ");
|
||||
|
||||
describe("getCursorFallbackModels", () => {
|
||||
it("does not publish any built-in cursor models before ACP discovery", () => {
|
||||
@@ -355,11 +338,12 @@ describe("buildCursorProviderSnapshot", () => {
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
|
||||
},
|
||||
discoveryWarning: cursorAcpDiscoveryFailedMessage,
|
||||
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "error",
|
||||
message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
|
||||
message:
|
||||
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
@@ -427,28 +411,10 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
|
||||
});
|
||||
|
||||
describe("checkCursorProviderStatus", () => {
|
||||
it("reports the install docs when the Cursor CLI command is missing", async () => {
|
||||
const provider = await runNode(
|
||||
checkCursorProviderStatus({
|
||||
enabled: true,
|
||||
binaryPath: missingCursorBinaryPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(provider).toMatchObject({
|
||||
installed: false,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: cursorCliCommandMissingMessage,
|
||||
});
|
||||
});
|
||||
|
||||
it("passes the injected environment to ACP model discovery", async () => {
|
||||
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
|
||||
|
||||
const provider = await runNode(
|
||||
const provider = await Effect.runPromise(
|
||||
checkCursorProviderStatus(
|
||||
{
|
||||
enabled: true,
|
||||
@@ -460,7 +426,7 @@ describe("checkCursorProviderStatus", () => {
|
||||
...process.env,
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
},
|
||||
),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
expect(provider.models.map((model) => model.slug)).toEqual([
|
||||
@@ -477,13 +443,13 @@ describe("discoverCursorModelsViaAcp", () => {
|
||||
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
|
||||
const wrapperPath = await runNode(makeMockAgentWrapper());
|
||||
|
||||
const models = await runNode(
|
||||
const models = await Effect.runPromise(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.scoped),
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
expect(models.map((model) => model.slug)).toEqual([
|
||||
@@ -499,13 +465,13 @@ describe("discoverCursorModelsViaAcp", () => {
|
||||
makeExitLogFixture("cursor-provider-exit-log-"),
|
||||
);
|
||||
|
||||
await runNode(
|
||||
await Effect.runPromise(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}),
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
const exitLog = await runNode(waitForFileContent(exitLogPath));
|
||||
|
||||
@@ -62,13 +62,6 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
|
||||
|
||||
const CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
|
||||
const CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;
|
||||
const CURSOR_CLI_INSTALLATION_DOCS_URL = "https://cursor.com/docs/cli/installation";
|
||||
const CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [
|
||||
"Cursor ACP model discovery failed.",
|
||||
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
|
||||
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
|
||||
"Check server logs for ACP details.",
|
||||
].join(" ");
|
||||
export const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
@@ -615,14 +608,6 @@ function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): s
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function buildCursorCliCommandMissingMessage(binaryPath: string): string {
|
||||
return [
|
||||
`Cursor CLI command \`${binaryPath}\` was not found.`,
|
||||
`Install or enable the Cursor CLI, make sure \`${binaryPath}\` is on PATH, then restart T3 Code.`,
|
||||
`See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
export function buildCursorProviderSnapshot(input: {
|
||||
readonly checkedAt: string;
|
||||
readonly cursorSettings: CursorSettings;
|
||||
@@ -1035,7 +1020,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: isCommandMissingCause(error)
|
||||
? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
|
||||
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
|
||||
: "Failed to execute Cursor Agent CLI health check.",
|
||||
},
|
||||
});
|
||||
@@ -1094,7 +1079,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
|
||||
yield* Effect.logWarning("Cursor ACP model discovery failed", {
|
||||
errorTag: causeErrorTag(discoveryExit.cause),
|
||||
});
|
||||
discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
|
||||
discoveryWarning = "Cursor ACP model discovery failed. Check server logs for details.";
|
||||
} else if (Option.isNone(discoveryExit.value)) {
|
||||
discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
|
||||
} else if (discoveryExit.value.value.length === 0) {
|
||||
|
||||
@@ -4,9 +4,8 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
|
||||
@@ -346,63 +345,11 @@ describe("AzureDevOpsCli.layer", () => {
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const error = yield* az.execute({ cwd: "/repo", args: ["repos", "list"] }).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
|
||||
assert.strictEqual(error.operation, "execute");
|
||||
assert.strictEqual(error.command, "az");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.argumentCount, 2);
|
||||
assert.strictEqual(error.detail, "Azure DevOps CLI command failed.");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes("sensitive-upstream-detail"), false);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("does not report a missing working directory as a missing Azure CLI", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = "/missing/repo";
|
||||
const platformCause = PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "ChildProcess",
|
||||
method: "spawn",
|
||||
syscall: "chdir",
|
||||
pathOrDescriptor: cwd,
|
||||
});
|
||||
const cause = new VcsProcessSpawnError({
|
||||
operation: "AzureDevOpsCli.execute",
|
||||
command: "az",
|
||||
cwd,
|
||||
argumentCount: 2,
|
||||
cause: platformCause,
|
||||
});
|
||||
mockRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const error = yield* az.execute({ cwd, args: ["repos", "list"] }).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsCommandFailedError);
|
||||
assert.strictEqual(error.cwd, cwd);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
it.effect("keeps invalid pull request output diagnostics structured", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(Effect.succeed(processOutput("not-json")));
|
||||
|
||||
const az = yield* AzureDevOpsCli.AzureDevOpsCli;
|
||||
const error = yield* az.getPullRequest({ cwd: "/repo", reference: "42" }).pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, AzureDevOpsCli.AzureDevOpsPullRequestDecodeError);
|
||||
assert.strictEqual(error.operation, "getPullRequest");
|
||||
assert.strictEqual(error.command, "az");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.outputLength, 8);
|
||||
assert.strictEqual(error.detail, "Azure DevOps CLI returned invalid pull request JSON.");
|
||||
assert.exists(error.cause);
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Azure DevOps CLI failed in getPullRequest: Azure DevOps CLI returned invalid pull request JSON.",
|
||||
);
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,11 +1,9 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
NonNegativeInt,
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlRepositoryVisibility,
|
||||
type VcsError,
|
||||
@@ -21,61 +19,16 @@ import * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
const azureDevOpsCommandErrorFields = {
|
||||
operation: Schema.Literal("execute"),
|
||||
command: Schema.Literal("az"),
|
||||
cwd: Schema.String,
|
||||
argumentCount: NonNegativeInt,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class AzureDevOpsCliUnavailableError extends Schema.TaggedErrorClass<AzureDevOpsCliUnavailableError>()(
|
||||
"AzureDevOpsCliUnavailableError",
|
||||
azureDevOpsCommandErrorFields,
|
||||
export class AzureDevOpsCliError extends Schema.TaggedErrorClass<AzureDevOpsCliError>()(
|
||||
"AzureDevOpsCliError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
cwd: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AzureDevOpsCliAuthenticationError extends Schema.TaggedErrorClass<AzureDevOpsCliAuthenticationError>()(
|
||||
"AzureDevOpsCliAuthenticationError",
|
||||
azureDevOpsCommandErrorFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestNotFoundError>()(
|
||||
"AzureDevOpsPullRequestNotFoundError",
|
||||
azureDevOpsCommandErrorFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Pull request not found. Check the PR number or URL and try again.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<AzureDevOpsCommandFailedError>()(
|
||||
"AzureDevOpsCommandFailedError",
|
||||
azureDevOpsCommandErrorFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI command failed.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
@@ -85,109 +38,53 @@ export class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<Azure
|
||||
readonly operation: "execute";
|
||||
readonly command: "az";
|
||||
readonly cwd: string;
|
||||
readonly argumentCount: number;
|
||||
},
|
||||
cause: VcsError,
|
||||
error: VcsError | unknown,
|
||||
): AzureDevOpsCliError {
|
||||
const fields = { ...context, cause };
|
||||
const lower = errorText(error).toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: az") || lower.includes("enoent")) {
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail:
|
||||
"Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
cause._tag === "VcsProcessSpawnError" &&
|
||||
cause.cause instanceof PlatformError.PlatformError &&
|
||||
cause.cause.reason._tag === "NotFound" &&
|
||||
cause.cause.reason.pathOrDescriptor !== context.cwd &&
|
||||
cause.cause.reason.syscall !== "chdir"
|
||||
lower.includes("az devops login") ||
|
||||
lower.includes("please run az login") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("unauthorized")
|
||||
) {
|
||||
return new AzureDevOpsCliUnavailableError(fields);
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Azure DevOps CLI is not authenticated. Run `az devops login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (cause._tag === "VcsProcessExitError") {
|
||||
if (cause.failureKind === "authentication") {
|
||||
return new AzureDevOpsCliAuthenticationError(fields);
|
||||
}
|
||||
if (cause.failureKind === "not-found") {
|
||||
return new AzureDevOpsPullRequestNotFoundError(fields);
|
||||
}
|
||||
if (
|
||||
lower.includes("pull request") &&
|
||||
(lower.includes("not found") || lower.includes("does not exist"))
|
||||
) {
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new AzureDevOpsCommandFailedError(fields);
|
||||
return new AzureDevOpsCliError({
|
||||
...context,
|
||||
detail: "Azure DevOps CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const azureDevOpsDecodeErrorFields = {
|
||||
command: Schema.Literal("az"),
|
||||
cwd: Schema.String,
|
||||
outputLength: NonNegativeInt,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class AzureDevOpsPullRequestListDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestListDecodeError>()(
|
||||
"AzureDevOpsPullRequestListDecodeError",
|
||||
{
|
||||
operation: Schema.Literal("listPullRequests"),
|
||||
...azureDevOpsDecodeErrorFields,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI returned invalid PR list JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AzureDevOpsPullRequestDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestDecodeError>()(
|
||||
"AzureDevOpsPullRequestDecodeError",
|
||||
{
|
||||
operation: Schema.Literal("getPullRequest"),
|
||||
...azureDevOpsDecodeErrorFields,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI returned invalid pull request JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
const AzureDevOpsRepositoryDecodeOperation = Schema.Literals([
|
||||
"getRepositoryCloneUrls",
|
||||
"getDefaultBranch",
|
||||
"createRepository",
|
||||
]);
|
||||
|
||||
export class AzureDevOpsRepositoryDecodeError extends Schema.TaggedErrorClass<AzureDevOpsRepositoryDecodeError>()(
|
||||
"AzureDevOpsRepositoryDecodeError",
|
||||
{
|
||||
operation: AzureDevOpsRepositoryDecodeOperation,
|
||||
...azureDevOpsDecodeErrorFields,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Azure DevOps CLI returned invalid repository JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const AzureDevOpsCliError = Schema.Union([
|
||||
AzureDevOpsCliUnavailableError,
|
||||
AzureDevOpsCliAuthenticationError,
|
||||
AzureDevOpsPullRequestNotFoundError,
|
||||
AzureDevOpsCommandFailedError,
|
||||
AzureDevOpsPullRequestListDecodeError,
|
||||
AzureDevOpsPullRequestDecodeError,
|
||||
AzureDevOpsRepositoryDecodeError,
|
||||
]);
|
||||
export type AzureDevOpsCliError = typeof AzureDevOpsCliError.Type;
|
||||
|
||||
export const isAzureDevOpsCliError = Schema.is(AzureDevOpsCliError);
|
||||
|
||||
export interface AzureDevOpsRepositoryCloneUrls {
|
||||
readonly nameWithOwner: string;
|
||||
readonly url: string;
|
||||
@@ -249,6 +146,17 @@ export class AzureDevOpsCli extends Context.Service<
|
||||
}
|
||||
>()("t3/sourceControl/AzureDevOpsCli") {}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
|
||||
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
|
||||
const message = "message" in error && typeof error.message === "string" ? error.message : "";
|
||||
return [tag, detail, message].filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function normalizeChangeRequestId(reference: string): string {
|
||||
const trimmed = reference.trim().replace(/^#/, "");
|
||||
const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed);
|
||||
@@ -317,18 +225,19 @@ function parseRepositorySpecifier(repository: string): {
|
||||
function decodeAzureDevOpsJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
cwd: string,
|
||||
): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> {
|
||||
): Effect.Effect<S["Type"], AzureDevOpsCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AzureDevOpsRepositoryDecodeError({
|
||||
(error) =>
|
||||
new AzureDevOpsCliError({
|
||||
operation,
|
||||
command: "az",
|
||||
cwd,
|
||||
outputLength: raw.length,
|
||||
cause,
|
||||
detail: invalidDetail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -348,13 +257,8 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
AzureDevOpsCommandFailedError.fromVcsError(
|
||||
{
|
||||
operation: "execute",
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
argumentCount: input.args.length,
|
||||
},
|
||||
AzureDevOpsCliError.fromVcsError(
|
||||
{ operation: "execute", command: "az", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
),
|
||||
@@ -393,11 +297,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsPullRequestListDecodeError({
|
||||
new AzureDevOpsCliError({
|
||||
operation: "listPullRequests",
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
outputLength: raw.length,
|
||||
detail: "Azure DevOps CLI returned invalid PR list JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -427,11 +331,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new AzureDevOpsPullRequestDecodeError({
|
||||
new AzureDevOpsCliError({
|
||||
operation: "getPullRequest",
|
||||
command: "az",
|
||||
cwd: input.cwd,
|
||||
outputLength: raw.length,
|
||||
detail: "Azure DevOps CLI returned invalid pull request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -453,6 +357,7 @@ export const make = Effect.gen(function* () {
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
@@ -478,7 +383,13 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd),
|
||||
decodeAzureDevOpsJson(
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"createRepository",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
);
|
||||
@@ -510,7 +421,13 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd),
|
||||
decodeAzureDevOpsJson(
|
||||
raw,
|
||||
RawAzureDevOpsRepositorySchema,
|
||||
"getDefaultBranch",
|
||||
"Azure DevOps CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),
|
||||
),
|
||||
|
||||
@@ -48,11 +48,11 @@ it.effect("maps Azure DevOps PR summaries into provider-neutral change requests"
|
||||
|
||||
it.effect("adds change-request context while retaining Azure CLI causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new AzureDevOpsCli.AzureDevOpsCommandFailedError({
|
||||
const cause = new AzureDevOpsCli.AzureDevOpsCliError({
|
||||
operation: "execute",
|
||||
command: "az",
|
||||
cwd: "/repo",
|
||||
argumentCount: 2,
|
||||
detail: "Azure DevOps CLI command failed.",
|
||||
cause: new Error("raw upstream detail that should remain in the cause"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
|
||||
@@ -533,8 +533,8 @@ it.effect("preserves the HTTP client failure without deriving the domain message
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketRequestError);
|
||||
assert.strictEqual(error.operation, "getPullRequest");
|
||||
assert.strictEqual(error.detail, "Failed to send the Bitbucket request.");
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in getPullRequest: Failed to send the Bitbucket request.",
|
||||
@@ -544,61 +544,6 @@ it.effect("preserves the HTTP client failure without deriving the domain message
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("keeps Bitbucket response bodies out of checkout diagnostics", () => {
|
||||
const responseBody = '{"error":{"message":"credential=secret-value"}}';
|
||||
const { layer } = makeLayer({
|
||||
response: () => new Response(responseBody, { status: 403 }),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const error = yield* bitbucket
|
||||
.checkoutPullRequest({ cwd: "/repo", reference: "42" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketResponseError);
|
||||
assert.strictEqual(error.operation, "getPullRequest");
|
||||
assert.strictEqual(error.status, 403);
|
||||
assert.strictEqual(error.responseBodyLength, responseBody.length);
|
||||
assert.notProperty(error, "responseBody");
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 403.",
|
||||
);
|
||||
assert.notInclude(error.message, "secret-value");
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("preserves Bitbucket response body read failures as their immediate cause", () => {
|
||||
const cause = new Error("response stream failed");
|
||||
const { layer } = makeLayer({
|
||||
response: () =>
|
||||
new Response(
|
||||
new ReadableStream<Uint8Array>({
|
||||
start: (controller) => controller.error(cause),
|
||||
}),
|
||||
{ status: 502 },
|
||||
),
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const bitbucket = yield* BitbucketApi.BitbucketApi;
|
||||
const error = yield* bitbucket
|
||||
.getPullRequest({ cwd: "/repo", reference: "42" })
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketResponseBodyReadError);
|
||||
assert.strictEqual(error.operation, "getPullRequest");
|
||||
assert.strictEqual(error.status, 502);
|
||||
assert.instanceOf(error.cause, HttpClientError.HttpClientError);
|
||||
assert.strictEqual(error.cause.cause, cause);
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 502.",
|
||||
);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect("checks out same-repository pull requests with the existing Bitbucket remote", () => {
|
||||
const { git, layer } = makeLayer({
|
||||
response: () =>
|
||||
@@ -685,9 +630,8 @@ it.effect("preserves Git checkout failures without deriving the domain message f
|
||||
}),
|
||||
);
|
||||
|
||||
assert.instanceOf(error, BitbucketApi.BitbucketCheckoutError);
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.reference, "42");
|
||||
assert.strictEqual(error.operation, "checkoutPullRequest");
|
||||
assert.strictEqual(error.detail, "Failed to check out the Bitbucket pull request.");
|
||||
assert.strictEqual(
|
||||
error.message,
|
||||
"Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.",
|
||||
|
||||
@@ -6,7 +6,6 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import {
|
||||
NonNegativeInt,
|
||||
TrimmedNonEmptyString,
|
||||
type SourceControlProviderAuth,
|
||||
type SourceControlRepositoryCloneUrls,
|
||||
@@ -37,156 +36,20 @@ const BitbucketApiEnvConfig = Config.all({
|
||||
apiToken: Config.string("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
|
||||
});
|
||||
|
||||
const BitbucketApiOperation = Schema.Literals([
|
||||
"resolveRepository",
|
||||
"getRepository",
|
||||
"getBranchingModel",
|
||||
"getPullRequest",
|
||||
"listPullRequests",
|
||||
"createRepository",
|
||||
"createPullRequest",
|
||||
"probeAuth",
|
||||
"checkoutPullRequest",
|
||||
]);
|
||||
type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
|
||||
|
||||
export class BitbucketRepositoryLocatorError extends Schema.TaggedErrorClass<BitbucketRepositoryLocatorError>()(
|
||||
"BitbucketRepositoryLocatorError",
|
||||
export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError>()(
|
||||
"BitbucketApiError",
|
||||
{
|
||||
repository: Schema.String,
|
||||
operation: Schema.String,
|
||||
detail: Schema.String,
|
||||
status: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Bitbucket API failed in createRepository: Bitbucket repositories must be specified as workspace/repository.";
|
||||
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketRequestError extends Schema.TaggedErrorClass<BitbucketRequestError>()(
|
||||
"BitbucketRequestError",
|
||||
{
|
||||
operation: BitbucketApiOperation,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Failed to send the Bitbucket request.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketResponseError extends Schema.TaggedErrorClass<BitbucketResponseError>()(
|
||||
"BitbucketResponseError",
|
||||
{
|
||||
operation: BitbucketApiOperation,
|
||||
status: Schema.Int,
|
||||
responseBodyLength: NonNegativeInt,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketResponseBodyReadError extends Schema.TaggedErrorClass<BitbucketResponseBodyReadError>()(
|
||||
"BitbucketResponseBodyReadError",
|
||||
{
|
||||
operation: BitbucketApiOperation,
|
||||
status: Schema.Int,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketResponseDecodeError extends Schema.TaggedErrorClass<BitbucketResponseDecodeError>()(
|
||||
"BitbucketResponseDecodeError",
|
||||
{
|
||||
operation: BitbucketApiOperation,
|
||||
status: Schema.Int,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in ${this.operation}: Bitbucket returned invalid JSON for the requested resource.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketRepositoryVcsResolveError extends Schema.TaggedErrorClass<BitbucketRepositoryVcsResolveError>()(
|
||||
"BitbucketRepositoryVcsResolveError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in resolveRepository: Failed to resolve VCS repository for ${this.cwd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketRepositoryRemotesListError extends Schema.TaggedErrorClass<BitbucketRepositoryRemotesListError>()(
|
||||
"BitbucketRepositoryRemotesListError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in resolveRepository: Failed to list remotes for ${this.cwd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedErrorClass<BitbucketRepositoryRemoteNotFoundError>()(
|
||||
"BitbucketRepositoryRemoteNotFoundError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in resolveRepository: No Bitbucket repository remote was detected for ${this.cwd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketPullRequestBodyReadError extends Schema.TaggedErrorClass<BitbucketPullRequestBodyReadError>()(
|
||||
"BitbucketPullRequestBodyReadError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
bodyFile: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Bitbucket API failed in createPullRequest: Failed to read pull request body file ${this.bodyFile}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class BitbucketCheckoutError extends Schema.TaggedErrorClass<BitbucketCheckoutError>()(
|
||||
"BitbucketCheckoutError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
reference: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.";
|
||||
}
|
||||
}
|
||||
|
||||
export const BitbucketApiError = Schema.Union([
|
||||
BitbucketRepositoryLocatorError,
|
||||
BitbucketRequestError,
|
||||
BitbucketResponseError,
|
||||
BitbucketResponseBodyReadError,
|
||||
BitbucketResponseDecodeError,
|
||||
BitbucketRepositoryVcsResolveError,
|
||||
BitbucketRepositoryRemotesListError,
|
||||
BitbucketRepositoryRemoteNotFoundError,
|
||||
BitbucketPullRequestBodyReadError,
|
||||
BitbucketCheckoutError,
|
||||
]);
|
||||
export type BitbucketApiError = typeof BitbucketApiError.Type;
|
||||
export const isBitbucketApiError = Schema.is(BitbucketApiError);
|
||||
const isBitbucketApiError = Schema.is(BitbucketApiError);
|
||||
|
||||
const RawBitbucketRepositorySchema = Schema.Struct({
|
||||
full_name: TrimmedNonEmptyString,
|
||||
@@ -346,14 +209,16 @@ function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator
|
||||
}
|
||||
|
||||
function requireRepositoryLocator(
|
||||
operation: string,
|
||||
repository: string,
|
||||
): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
|
||||
const locator = parseBitbucketRepositorySlug(repository);
|
||||
return locator
|
||||
? Effect.succeed(locator)
|
||||
: Effect.fail(
|
||||
new BitbucketRepositoryLocatorError({
|
||||
repository,
|
||||
new BitbucketApiError({
|
||||
operation,
|
||||
detail: "Bitbucket repositories must be specified as workspace/repository.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -474,24 +339,20 @@ function authFromConfig(
|
||||
}
|
||||
|
||||
function responseError(
|
||||
operation: BitbucketApiOperation,
|
||||
operation: string,
|
||||
response: HttpClientResponse.HttpClientResponse,
|
||||
): Effect.Effect<never, BitbucketApiError> {
|
||||
return response.text.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketResponseBodyReadError({
|
||||
operation,
|
||||
status: response.status,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.orElseSucceed(() => ""),
|
||||
Effect.flatMap((body) =>
|
||||
Effect.fail(
|
||||
new BitbucketResponseError({
|
||||
new BitbucketApiError({
|
||||
operation,
|
||||
status: response.status,
|
||||
responseBodyLength: body.length,
|
||||
detail:
|
||||
body.trim().length > 0
|
||||
? `Bitbucket returned HTTP ${response.status}: ${body.trim()}`
|
||||
: `Bitbucket returned HTTP ${response.status}.`,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -518,7 +379,7 @@ export const make = Effect.gen(function* () {
|
||||
};
|
||||
|
||||
const decodeResponse = <S extends Schema.Top>(
|
||||
operation: BitbucketApiOperation,
|
||||
operation: string,
|
||||
schema: S,
|
||||
response: HttpClientResponse.HttpClientResponse,
|
||||
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
|
||||
@@ -527,9 +388,9 @@ export const make = Effect.gen(function* () {
|
||||
HttpClientResponse.schemaBodyJson(schema)(success).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketResponseDecodeError({
|
||||
new BitbucketApiError({
|
||||
operation,
|
||||
status: success.status,
|
||||
detail: "Bitbucket returned invalid JSON for the requested resource.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -538,15 +399,16 @@ export const make = Effect.gen(function* () {
|
||||
})(response);
|
||||
|
||||
const executeJson = <S extends Schema.Top>(
|
||||
operation: BitbucketApiOperation,
|
||||
operation: string,
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
schema: S,
|
||||
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
|
||||
httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketRequestError({
|
||||
new BitbucketApiError({
|
||||
operation,
|
||||
detail: "Failed to send the Bitbucket request.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -571,8 +433,9 @@ export const make = Effect.gen(function* () {
|
||||
const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketRepositoryVcsResolveError({
|
||||
cwd: input.cwd,
|
||||
new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `Failed to resolve VCS repository for ${input.cwd}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -580,8 +443,9 @@ export const make = Effect.gen(function* () {
|
||||
const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketRepositoryRemotesListError({
|
||||
cwd: input.cwd,
|
||||
new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `Failed to list remotes for ${input.cwd}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -593,8 +457,9 @@ export const make = Effect.gen(function* () {
|
||||
if (parsed) return parsed;
|
||||
}
|
||||
|
||||
return yield* new BitbucketRepositoryRemoteNotFoundError({
|
||||
cwd: input.cwd,
|
||||
return yield* new BitbucketApiError({
|
||||
operation: "resolveRepository",
|
||||
detail: `No Bitbucket repository remote was detected for ${input.cwd}.`,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -735,7 +600,7 @@ export const make = Effect.gen(function* () {
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
|
||||
createRepository: (input) =>
|
||||
requireRepositoryLocator(input.repository).pipe(
|
||||
requireRepositoryLocator("createRepository", input.repository).pipe(
|
||||
Effect.flatMap((repository) =>
|
||||
executeJson(
|
||||
"createRepository",
|
||||
@@ -760,9 +625,9 @@ export const make = Effect.gen(function* () {
|
||||
const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new BitbucketPullRequestBodyReadError({
|
||||
cwd: input.cwd,
|
||||
bodyFile: input.bodyFile,
|
||||
new BitbucketApiError({
|
||||
operation: "createPullRequest",
|
||||
detail: `Failed to read pull request body file ${input.bodyFile}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
@@ -878,9 +743,9 @@ export const make = Effect.gen(function* () {
|
||||
Effect.mapError((cause) =>
|
||||
isBitbucketApiError(cause)
|
||||
? cause
|
||||
: new BitbucketCheckoutError({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
: new BitbucketApiError({
|
||||
operation: "checkoutPullRequest",
|
||||
detail: "Failed to check out the Bitbucket pull request.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -53,10 +53,11 @@ it.effect("maps Bitbucket PR summaries into provider-neutral change requests", (
|
||||
|
||||
it.effect("adds repository context while retaining Bitbucket API causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const upstreamCause = new Error("raw upstream failure");
|
||||
const cause = new BitbucketApi.BitbucketRequestError({
|
||||
const cause = new BitbucketApi.BitbucketApiError({
|
||||
operation: "getRepository",
|
||||
cause: upstreamCause,
|
||||
detail: "upstream detail that should remain in the cause",
|
||||
status: 503,
|
||||
cause: new Error("raw upstream failure"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
getRepositoryCloneUrls: () => Effect.fail(cause),
|
||||
@@ -85,7 +86,7 @@ it.effect("adds repository context while retaining Bitbucket API causes", () =>
|
||||
},
|
||||
);
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes(upstreamCause.message), false);
|
||||
assert.equal(error.message.includes(cause.detail), false);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { assert, it, afterEach, describe, expect, vi } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import * as GitHubCli from "./GitHubCli.ts";
|
||||
@@ -31,27 +30,6 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("GitHubCli.layer", () => {
|
||||
it("does not classify a missing cwd as an unavailable gh executable", () => {
|
||||
const context = { command: "gh", cwd: "/repo" } as const;
|
||||
const missingCwd = new VcsProcessSpawnError({
|
||||
operation: "GitHubCli.execute",
|
||||
command: "gh",
|
||||
cwd: context.cwd,
|
||||
cause: PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "access",
|
||||
pathOrDescriptor: context.cwd,
|
||||
}),
|
||||
});
|
||||
|
||||
const commandFailure = GitHubCli.fromVcsError(context, missingCwd);
|
||||
|
||||
assert.equal(commandFailure._tag, "GitHubCliCommandError");
|
||||
assert.strictEqual(commandFailure.cause, missingCwd);
|
||||
assert.notProperty(commandFailure, "operation");
|
||||
});
|
||||
|
||||
it.effect("parses pull request view output", () =>
|
||||
Effect.gen(function* () {
|
||||
mockRun.mockReturnValueOnce(
|
||||
@@ -296,7 +274,6 @@ describe("GitHubCli.layer", () => {
|
||||
command: "gh pr view",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
failureKind: "not-found",
|
||||
detail:
|
||||
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
|
||||
});
|
||||
@@ -311,7 +288,6 @@ describe("GitHubCli.layer", () => {
|
||||
.pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Pull request not found"), true);
|
||||
assert.strictEqual(error._tag, "GitHubPullRequestNotFoundError");
|
||||
assert.strictEqual(error.command, "gh");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
@@ -19,163 +18,67 @@ import {
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
const gitHubCliFailureFields = {
|
||||
command: Schema.Literal("gh"),
|
||||
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
} as const;
|
||||
|
||||
export class GitHubCliUnavailableError extends Schema.TaggedErrorClass<GitHubCliUnavailableError>()(
|
||||
"GitHubCliUnavailableError",
|
||||
gitHubCliFailureFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI (`gh`) is required but not available on PATH.";
|
||||
}
|
||||
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in execute: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubCliAuthenticationError extends Schema.TaggedErrorClass<GitHubCliAuthenticationError>()(
|
||||
"GitHubCliAuthenticationError",
|
||||
gitHubCliFailureFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI is not authenticated. Run `gh auth login` and retry.";
|
||||
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in execute: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
static fromVcsError(
|
||||
context: {
|
||||
readonly operation: "execute";
|
||||
readonly command: "gh";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError | unknown,
|
||||
): GitHubCliError {
|
||||
const lower = errorText(error).toLowerCase();
|
||||
|
||||
export class GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(
|
||||
"GitHubPullRequestNotFoundError",
|
||||
gitHubCliFailureFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "Pull request not found. Check the PR number or URL and try again.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in execute: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubCliCommandError extends Schema.TaggedErrorClass<GitHubCliCommandError>()(
|
||||
"GitHubCliCommandError",
|
||||
gitHubCliFailureFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI command failed.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in execute: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
const gitHubCliDecodeFields = {
|
||||
command: Schema.Literal("gh"),
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
} as const;
|
||||
|
||||
export class GitHubPullRequestListDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestListDecodeError>()(
|
||||
"GitHubPullRequestListDecodeError",
|
||||
gitHubCliDecodeFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI returned invalid PR list JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubChangeRequestListDecodeError extends Schema.TaggedErrorClass<GitHubChangeRequestListDecodeError>()(
|
||||
"GitHubChangeRequestListDecodeError",
|
||||
gitHubCliDecodeFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI returned invalid change request JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in listChangeRequests: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubPullRequestDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestDecodeError>()(
|
||||
"GitHubPullRequestDecodeError",
|
||||
gitHubCliDecodeFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI returned invalid pull request JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in getPullRequest: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubRepositoryDecodeError>()(
|
||||
"GitHubRepositoryDecodeError",
|
||||
gitHubCliDecodeFields,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitHub CLI returned invalid repository JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const GitHubCliError = Schema.Union([
|
||||
GitHubCliUnavailableError,
|
||||
GitHubCliAuthenticationError,
|
||||
GitHubPullRequestNotFoundError,
|
||||
GitHubCliCommandError,
|
||||
GitHubPullRequestListDecodeError,
|
||||
GitHubChangeRequestListDecodeError,
|
||||
GitHubPullRequestDecodeError,
|
||||
GitHubRepositoryDecodeError,
|
||||
]);
|
||||
export type GitHubCliError = typeof GitHubCliError.Type;
|
||||
|
||||
export const isGitHubCliError = Schema.is(GitHubCliError);
|
||||
|
||||
export function fromVcsError(
|
||||
context: {
|
||||
readonly command: "gh";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError,
|
||||
): GitHubCliError {
|
||||
if (
|
||||
error._tag === "VcsProcessSpawnError" &&
|
||||
error.cause instanceof PlatformError.PlatformError &&
|
||||
error.cause.reason._tag === "NotFound" &&
|
||||
error.cause.reason.module === "ChildProcess" &&
|
||||
error.cause.reason.method === "spawn"
|
||||
) {
|
||||
return new GitHubCliUnavailableError({ ...context, cause: error });
|
||||
}
|
||||
|
||||
if (error._tag === "VcsProcessExitError") {
|
||||
if (error.failureKind === "authentication") {
|
||||
return new GitHubCliAuthenticationError({ ...context, cause: error });
|
||||
if (lower.includes("command not found: gh") || lower.includes("enoent")) {
|
||||
return new GitHubCliError({
|
||||
...context,
|
||||
detail: "GitHub CLI (`gh`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
if (error.failureKind === "not-found") {
|
||||
return new GitHubPullRequestNotFoundError({ ...context, cause: error });
|
||||
}
|
||||
}
|
||||
|
||||
return new GitHubCliCommandError({ ...context, cause: error });
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("gh auth login") ||
|
||||
lower.includes("no oauth token")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
...context,
|
||||
detail: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("could not resolve to a pullrequest") ||
|
||||
lower.includes("repository.pullrequest") ||
|
||||
lower.includes("no pull requests found for branch") ||
|
||||
lower.includes("pull request not found")
|
||||
) {
|
||||
return new GitHubCliError({
|
||||
...context,
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return new GitHubCliError({
|
||||
...context,
|
||||
detail: "GitHub CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface GitHubPullRequestSummary {
|
||||
@@ -247,14 +150,22 @@ export class GitHubCli extends Context.Service<
|
||||
}
|
||||
>()("t3/sourceControl/GitHubCli") {}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
|
||||
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
|
||||
const message = "message" in error && typeof error.message === "string" ? error.message : "";
|
||||
return [tag, detail, message].filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
nameWithOwner: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
sshUrl: TrimmedNonEmptyString,
|
||||
});
|
||||
const decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),
|
||||
);
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
|
||||
@@ -303,6 +214,27 @@ function deriveRepositoryCloneUrlsFromCreateOutput(
|
||||
};
|
||||
}
|
||||
|
||||
function decodeGitHubJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
|
||||
invalidDetail: string,
|
||||
cwd: string,
|
||||
): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new GitHubCliError({
|
||||
operation,
|
||||
command: "gh",
|
||||
cwd,
|
||||
detail: invalidDetail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
|
||||
@@ -315,7 +247,14 @@ export const make = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError((error) => fromVcsError({ command: "gh", cwd: input.cwd }, error)));
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
GitHubCliError.fromVcsError(
|
||||
{ operation: "execute", command: "gh", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return GitHubCli.of({
|
||||
execute,
|
||||
@@ -343,9 +282,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubPullRequestListDecodeError({
|
||||
new GitHubCliError({
|
||||
operation: "listOpenPullRequests",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: "GitHub CLI returned invalid PR list JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -375,9 +316,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubPullRequestDecodeError({
|
||||
new GitHubCliError({
|
||||
operation: "getPullRequest",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
detail: "GitHub CLI returned invalid pull request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -397,15 +340,12 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeRawGitHubRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitHubRepositoryDecodeError({
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
decodeGitHubJson(
|
||||
raw,
|
||||
RawGitHubRepositoryCloneUrlsSchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"GitHub CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
|
||||
@@ -70,9 +70,11 @@ it.effect("maps GitHub PR summaries into provider-neutral change requests", () =
|
||||
|
||||
it.effect("adds safe request context while retaining GitHub CLI causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new GitHubCli.GitHubPullRequestNotFoundError({
|
||||
const cause = new GitHubCli.GitHubCliError({
|
||||
operation: "execute",
|
||||
command: "gh",
|
||||
cwd: "/repo",
|
||||
detail: "Pull request not found. Check the PR number or URL and try again.",
|
||||
cause: new Error("raw upstream detail that should remain in the cause"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
|
||||
@@ -158,17 +158,23 @@ export const make = Effect.gen(function* () {
|
||||
})),
|
||||
)
|
||||
: Effect.fail(
|
||||
new GitHubCli.GitHubChangeRequestListDecodeError({
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
command: "gh",
|
||||
cwd: input.cwd,
|
||||
reference: SourceControlProvider.transportSafeSourceControlErrorValue(
|
||||
input.headSelector,
|
||||
),
|
||||
detail: "GitHub CLI returned invalid change request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
Effect.catchTags({
|
||||
GitHubCliError: (error) =>
|
||||
new SourceControlProviderError({
|
||||
provider: "github",
|
||||
operation: "listChangeRequests",
|
||||
@@ -180,7 +186,7 @@ export const make = Effect.gen(function* () {
|
||||
detail: error.detail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -315,11 +315,10 @@ layer("GitLabCli.layer", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab",
|
||||
command: "glab mr view 4888",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 merge request not found",
|
||||
failureKind: "not-found",
|
||||
});
|
||||
mockedRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
@@ -331,37 +330,11 @@ layer("GitLabCli.layer", (it) => {
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.equal(error.message.includes("Merge request 4888 was not found"), true);
|
||||
assert.strictEqual(error._tag, "GitLabMergeRequestNotFoundError");
|
||||
assert.equal(error.message.includes("Merge request not found"), true);
|
||||
assert.strictEqual(error.command, "glab");
|
||||
assert.strictEqual(error.cwd, "/repo");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
assert.equal(error.message.includes(cause.detail), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps non-merge-request not-found failures generic", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new VcsProcessExitError({
|
||||
operation: "GitLabCli.execute",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
exitCode: 1,
|
||||
detail: "GET 404 project not found",
|
||||
failureKind: "not-found",
|
||||
});
|
||||
mockedRun.mockReturnValueOnce(Effect.fail(cause));
|
||||
|
||||
const error = yield* Effect.gen(function* () {
|
||||
const glab = yield* GitLabCli.GitLabCli;
|
||||
return yield* glab.getRepositoryCloneUrls({
|
||||
cwd: "/repo",
|
||||
repository: "missing/project",
|
||||
});
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
assert.strictEqual(error._tag, "GitLabCliCommandError");
|
||||
assert.strictEqual(error.cause, cause);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Match from "effect/Match";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -22,56 +21,13 @@ import type * as SourceControlProvider from "./SourceControlProvider.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
const gitLabCliExecutionErrorContext = {
|
||||
operation: Schema.Literal("execute"),
|
||||
command: Schema.Literal("glab"),
|
||||
export class GitLabCliError extends Schema.TaggedErrorClass<GitLabCliError>()("GitLabCliError", {
|
||||
operation: Schema.String,
|
||||
command: Schema.String,
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
const gitLabCliDecodeErrorContext = {
|
||||
command: Schema.Literal("glab"),
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
};
|
||||
|
||||
export class GitLabCliUnavailableError extends Schema.TaggedErrorClass<GitLabCliUnavailableError>()(
|
||||
"GitLabCliUnavailableError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI (`glab`) is required but not available on PATH.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabCliAuthenticationError extends Schema.TaggedErrorClass<GitLabCliAuthenticationError>()(
|
||||
"GitLabCliAuthenticationError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI is not authenticated. Run `glab auth login` and retry.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<GitLabMergeRequestNotFoundError>()(
|
||||
"GitLabMergeRequestNotFoundError",
|
||||
{
|
||||
...gitLabCliExecutionErrorContext,
|
||||
reference: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return `Merge request ${this.reference} was not found. Check the MR number or URL and try again.`;
|
||||
}
|
||||
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
@@ -81,148 +37,52 @@ export class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<Git
|
||||
readonly operation: "execute";
|
||||
readonly command: "glab";
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
},
|
||||
error: VcsError,
|
||||
error: VcsError | unknown,
|
||||
): GitLabCliError {
|
||||
if (error._tag === "VcsProcessExitError" && error.failureKind === "not-found") {
|
||||
return new GitLabMergeRequestNotFoundError({ ...context, cause: error });
|
||||
const lower = errorText(error).toLowerCase();
|
||||
|
||||
if (lower.includes("command not found: glab") || isVcsProcessSpawnError(error)) {
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI (`glab`) is required but not available on PATH.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
return GitLabCliCommandError.fromVcsError(
|
||||
{
|
||||
operation: context.operation,
|
||||
command: context.command,
|
||||
cwd: context.cwd,
|
||||
},
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (
|
||||
lower.includes("authentication failed") ||
|
||||
lower.includes("not logged in") ||
|
||||
lower.includes("glab auth login") ||
|
||||
lower.includes("token")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI is not authenticated. Run `glab auth login` and retry.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
export class GitLabCliCommandError extends Schema.TaggedErrorClass<GitLabCliCommandError>()(
|
||||
"GitLabCliCommandError",
|
||||
gitLabCliExecutionErrorContext,
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI command failed.";
|
||||
}
|
||||
if (
|
||||
lower.includes("merge request not found") ||
|
||||
lower.includes("not found") ||
|
||||
lower.includes("404")
|
||||
) {
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "Merge request not found. Check the MR number or URL and try again.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
|
||||
static fromVcsError(
|
||||
context: {
|
||||
readonly operation: "execute";
|
||||
readonly command: "glab";
|
||||
readonly cwd: string;
|
||||
},
|
||||
error: VcsError,
|
||||
): GitLabCliError {
|
||||
return Match.valueTags(error, {
|
||||
VcsProcessSpawnError: (cause) => new GitLabCliUnavailableError({ ...context, cause }),
|
||||
VcsProcessExitError: (cause) => {
|
||||
switch (cause.failureKind) {
|
||||
case "authentication":
|
||||
return new GitLabCliAuthenticationError({ ...context, cause });
|
||||
case "not-found":
|
||||
case "command-failed":
|
||||
case undefined:
|
||||
return new GitLabCliCommandError({ ...context, cause });
|
||||
}
|
||||
},
|
||||
VcsProcessTimeoutError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsProcessStdinWriteError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsProcessOutputReadError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsProcessOutputLimitError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsProcessMissingExitCodeError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsRepositoryDetectionError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
VcsUnsupportedOperationError: (cause) => new GitLabCliCommandError({ ...context, cause }),
|
||||
return new GitLabCliError({
|
||||
...context,
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabMergeRequestListDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestListDecodeError>()(
|
||||
"GitLabMergeRequestListDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literal("listMergeRequests"),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid MR list JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabMergeRequestDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestDecodeError>()(
|
||||
"GitLabMergeRequestDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literal("getMergeRequest"),
|
||||
reference: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid merge request JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabRepositoryDecodeError extends Schema.TaggedErrorClass<GitLabRepositoryDecodeError>()(
|
||||
"GitLabRepositoryDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literals(["getRepositoryCloneUrls", "createRepository", "getDefaultBranch"]),
|
||||
repository: Schema.optional(Schema.String),
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid repository JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class GitLabNamespaceDecodeError extends Schema.TaggedErrorClass<GitLabNamespaceDecodeError>()(
|
||||
"GitLabNamespaceDecodeError",
|
||||
{
|
||||
...gitLabCliDecodeErrorContext,
|
||||
operation: Schema.Literal("createRepository"),
|
||||
namespacePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
get detail(): string {
|
||||
return "GitLab CLI returned invalid namespace JSON.";
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `GitLab CLI failed in ${this.operation}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const GitLabCliError = Schema.Union([
|
||||
GitLabCliUnavailableError,
|
||||
GitLabCliAuthenticationError,
|
||||
GitLabMergeRequestNotFoundError,
|
||||
GitLabCliCommandError,
|
||||
GitLabMergeRequestListDecodeError,
|
||||
GitLabMergeRequestDecodeError,
|
||||
GitLabRepositoryDecodeError,
|
||||
GitLabNamespaceDecodeError,
|
||||
]);
|
||||
export type GitLabCliError = typeof GitLabCliError.Type;
|
||||
export const isGitLabCliError = Schema.is(GitLabCliError);
|
||||
|
||||
export interface GitLabMergeRequestSummary {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
@@ -242,6 +102,17 @@ export interface GitLabRepositoryCloneUrls {
|
||||
readonly sshUrl: string;
|
||||
}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
if (typeof error === "object" && error !== null) {
|
||||
const tag = "_tag" in error && typeof error._tag === "string" ? error._tag : "";
|
||||
const detail = "detail" in error && typeof error.detail === "string" ? error.detail : "";
|
||||
const message = "message" in error && typeof error.message === "string" ? error.message : "";
|
||||
return [tag, detail, message].filter(Boolean).join("\n");
|
||||
}
|
||||
|
||||
return String(error);
|
||||
}
|
||||
|
||||
export class GitLabCli extends Context.Service<
|
||||
GitLabCli,
|
||||
{
|
||||
@@ -297,6 +168,15 @@ export class GitLabCli extends Context.Service<
|
||||
}
|
||||
>()("t3/sourceControl/GitLabCli") {}
|
||||
|
||||
function isVcsProcessSpawnError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "VcsProcessSpawnError"
|
||||
);
|
||||
}
|
||||
|
||||
const RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
path_with_namespace: TrimmedNonEmptyString,
|
||||
web_url: TrimmedNonEmptyString,
|
||||
@@ -312,14 +192,6 @@ const RawGitLabNamespaceSchema = Schema.Struct({
|
||||
id: Schema.Number,
|
||||
});
|
||||
|
||||
const decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),
|
||||
);
|
||||
const decodeGitLabDefaultBranch = Schema.decodeEffect(
|
||||
Schema.fromJsonString(RawGitLabDefaultBranchSchema),
|
||||
);
|
||||
const decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,
|
||||
): GitLabRepositoryCloneUrls {
|
||||
@@ -330,6 +202,27 @@ function normalizeRepositoryCloneUrls(
|
||||
};
|
||||
}
|
||||
|
||||
function decodeGitLabJson<S extends Schema.Top>(
|
||||
raw: string,
|
||||
schema: S,
|
||||
operation: "getRepositoryCloneUrls" | "getDefaultBranch" | "createRepository",
|
||||
invalidDetail: string,
|
||||
cwd: string,
|
||||
): Effect.Effect<S["Type"], GitLabCliError, S["DecodingServices"]> {
|
||||
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
|
||||
Effect.mapError(
|
||||
(error) =>
|
||||
new GitLabCliError({
|
||||
operation,
|
||||
command: "glab",
|
||||
cwd,
|
||||
detail: invalidDetail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function stateArgs(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
|
||||
switch (state) {
|
||||
case "open":
|
||||
@@ -390,10 +283,7 @@ function parseRepositoryPath(repository: string): {
|
||||
export const make = Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
|
||||
const run = (
|
||||
input: Parameters<GitLabCli["Service"]["execute"]>[0],
|
||||
mapError: (error: VcsError) => GitLabCliError,
|
||||
) =>
|
||||
const execute: GitLabCli["Service"]["execute"] = (input) =>
|
||||
process
|
||||
.run({
|
||||
operation: "GitLabCli.execute",
|
||||
@@ -402,32 +292,14 @@ export const make = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.mapError(mapError));
|
||||
|
||||
const execute: GitLabCli["Service"]["execute"] = (input) =>
|
||||
run(input, (error) =>
|
||||
GitLabCliCommandError.fromVcsError(
|
||||
{ operation: "execute", command: "glab", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
);
|
||||
|
||||
const executeMergeRequest = (input: {
|
||||
readonly cwd: string;
|
||||
readonly reference: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) =>
|
||||
run(input, (error) =>
|
||||
GitLabMergeRequestNotFoundError.fromVcsError(
|
||||
{
|
||||
operation: "execute",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
},
|
||||
error,
|
||||
),
|
||||
);
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
GitLabCliError.fromVcsError(
|
||||
{ operation: "execute", command: "glab", cwd: input.cwd },
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return GitLabCli.of({
|
||||
execute,
|
||||
@@ -454,10 +326,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabMergeRequestListDecodeError({
|
||||
new GitLabCliError({
|
||||
operation: "listMergeRequests",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
detail: "GitLab CLI returned invalid MR list JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -469,9 +342,8 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
getMergeRequest: (input) =>
|
||||
executeMergeRequest({
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
args: ["mr", "view", input.reference, "--output", "json"],
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
@@ -480,11 +352,11 @@ export const make = Effect.gen(function* () {
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitLabMergeRequestDecodeError({
|
||||
new GitLabCliError({
|
||||
operation: "getMergeRequest",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
detail: "GitLab CLI returned invalid merge request JSON.",
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
@@ -502,17 +374,12 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "getRepositoryCloneUrls",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"getRepositoryCloneUrls",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
@@ -526,17 +393,12 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabNamespace(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabNamespaceDecodeError({
|
||||
operation: "createRepository",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
namespacePath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabNamespaceSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid namespace JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map((namespace) => namespace.id),
|
||||
@@ -566,17 +428,12 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabRepositoryCloneUrls(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "createRepository",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
repository: input.repository,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabRepositoryCloneUrlsSchema,
|
||||
"createRepository",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map(normalizeRepositoryCloneUrls),
|
||||
@@ -610,24 +467,19 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
decodeGitLabDefaultBranch(raw).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitLabRepositoryDecodeError({
|
||||
operation: "getDefaultBranch",
|
||||
command: "glab",
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
decodeGitLabJson(
|
||||
raw,
|
||||
RawGitLabDefaultBranchSchema,
|
||||
"getDefaultBranch",
|
||||
"GitLab CLI returned invalid repository JSON.",
|
||||
input.cwd,
|
||||
),
|
||||
),
|
||||
Effect.map((value) => value.default_branch ?? null),
|
||||
),
|
||||
checkoutMergeRequest: (input) =>
|
||||
executeMergeRequest({
|
||||
execute({
|
||||
cwd: input.cwd,
|
||||
reference: input.reference,
|
||||
args: ["mr", "checkout", input.reference],
|
||||
}).pipe(Effect.asVoid),
|
||||
});
|
||||
|
||||
@@ -54,10 +54,11 @@ it.effect("maps GitLab MR summaries into provider-neutral change requests", () =
|
||||
|
||||
it.effect("adds repository context while retaining GitLab CLI causes", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new GitLabCli.GitLabCliCommandError({
|
||||
const cause = new GitLabCli.GitLabCliError({
|
||||
operation: "execute",
|
||||
command: "glab",
|
||||
cwd: "/repo",
|
||||
detail: "GitLab CLI command failed.",
|
||||
cause: new Error("raw upstream detail that should remain in the cause"),
|
||||
});
|
||||
const provider = yield* makeProvider({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { OpenCodeSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
|
||||
import { OpenCodeSettings, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -11,8 +11,8 @@ import { beforeEach, expect } from "vite-plus/test";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
|
||||
import * as OpenCodeTextGeneration from "./OpenCodeTextGeneration.ts";
|
||||
import * as TextGeneration from "./TextGeneration.ts";
|
||||
import { makeOpenCodeTextGeneration } from "./OpenCodeTextGeneration.ts";
|
||||
|
||||
const runtimeMock = {
|
||||
state: {
|
||||
@@ -20,11 +20,8 @@ const runtimeMock = {
|
||||
promptUrls: [] as string[],
|
||||
authHeaders: [] as Array<string | null>,
|
||||
closeCalls: [] as string[],
|
||||
sessionCreateError: undefined as unknown,
|
||||
sessionResult: undefined as { data?: { id: string } } | undefined,
|
||||
promptRequestError: undefined as unknown,
|
||||
promptResult: undefined as
|
||||
| { data?: { info?: { error?: unknown }; parts?: Array<unknown> } }
|
||||
| { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
|
||||
| undefined,
|
||||
},
|
||||
reset() {
|
||||
@@ -32,9 +29,6 @@ const runtimeMock = {
|
||||
this.state.promptUrls.length = 0;
|
||||
this.state.authHeaders.length = 0;
|
||||
this.state.closeCalls.length = 0;
|
||||
this.state.sessionCreateError = undefined;
|
||||
this.state.sessionResult = undefined;
|
||||
this.state.promptRequestError = undefined;
|
||||
this.state.promptResult = undefined;
|
||||
},
|
||||
};
|
||||
@@ -67,20 +61,12 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
|
||||
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
|
||||
({
|
||||
session: {
|
||||
create: async () => {
|
||||
if (runtimeMock.state.sessionCreateError !== undefined) {
|
||||
throw runtimeMock.state.sessionCreateError;
|
||||
}
|
||||
return runtimeMock.state.sessionResult ?? { data: { id: `${baseUrl}/session` } };
|
||||
},
|
||||
create: async () => ({ data: { id: `${baseUrl}/session` } }),
|
||||
prompt: async () => {
|
||||
runtimeMock.state.promptUrls.push(baseUrl);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
if (runtimeMock.state.promptRequestError !== undefined) {
|
||||
throw runtimeMock.state.promptRequestError;
|
||||
}
|
||||
return (
|
||||
runtimeMock.state.promptResult ?? {
|
||||
data: {
|
||||
@@ -113,13 +99,6 @@ const DEFAULT_TEST_MODEL_SELECTION = {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "openai/gpt-5",
|
||||
};
|
||||
const DEFAULT_COMMIT_MESSAGE_INPUT = {
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
};
|
||||
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
|
||||
|
||||
@@ -163,7 +142,7 @@ function withOpenCodeTextGeneration<A, E, R>(
|
||||
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings);
|
||||
const textGeneration = yield* makeOpenCodeTextGeneration(settings);
|
||||
return yield* effectFn(textGeneration);
|
||||
}).pipe(Effect.scoped);
|
||||
}
|
||||
@@ -242,99 +221,22 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
|
||||
).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("preserves the SDK cause when session creation fails", () =>
|
||||
it.effect("returns a typed empty-output error when OpenCode returns no text parts", () =>
|
||||
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const sdkCause = new Error("session endpoint unavailable");
|
||||
runtimeMock.state.sessionCreateError = sdkCause;
|
||||
runtimeMock.state.promptResult = { data: {} };
|
||||
|
||||
const error = yield* textGeneration
|
||||
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(TextGenerationError);
|
||||
expect(error.message).toContain("OpenCode session.create request failed.");
|
||||
expect(error.cause).toMatchObject({
|
||||
_tag: "OpenCodeTextGenerationSessionRequestError",
|
||||
operation: "generateCommitMessage",
|
||||
cwd: process.cwd(),
|
||||
cause: sdkCause,
|
||||
});
|
||||
expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reports a missing session payload without manufacturing a cause", () =>
|
||||
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.sessionResult = {};
|
||||
|
||||
const error = yield* textGeneration
|
||||
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("OpenCode session.create returned no session payload.");
|
||||
expect(error.cause).toMatchObject({
|
||||
_tag: "OpenCodeTextGenerationSessionPayloadError",
|
||||
operation: "generateCommitMessage",
|
||||
cwd: process.cwd(),
|
||||
});
|
||||
expect(error.cause).not.toHaveProperty("cause");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("preserves the SDK cause and request context when prompting fails", () =>
|
||||
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const sdkCause = new Error("prompt endpoint unavailable");
|
||||
runtimeMock.state.promptRequestError = sdkCause;
|
||||
|
||||
const error = yield* textGeneration
|
||||
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("OpenCode session.prompt request failed.");
|
||||
expect(error.cause).toMatchObject({
|
||||
_tag: "OpenCodeTextGenerationPromptRequestError",
|
||||
operation: "generateCommitMessage",
|
||||
cwd: process.cwd(),
|
||||
sessionId: "http://127.0.0.1:4301/session",
|
||||
providerId: "openai",
|
||||
modelId: "gpt-5",
|
||||
cause: sdkCause,
|
||||
});
|
||||
expect((error.cause as { cause: unknown }).cause).toBe(sdkCause);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns a typed empty-output error for malformed and blank response parts", () =>
|
||||
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.promptResult = {
|
||||
data: {
|
||||
parts: [null, { type: "tool" }, { type: "text", text: " " }],
|
||||
},
|
||||
};
|
||||
|
||||
const error = yield* textGeneration
|
||||
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
|
||||
.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("OpenCode returned empty output.");
|
||||
expect(error.cause).toMatchObject({
|
||||
_tag: "OpenCodeTextGenerationEmptyOutputError",
|
||||
operation: "generateCommitMessage",
|
||||
cwd: process.cwd(),
|
||||
sessionId: "http://127.0.0.1:4301/session",
|
||||
providerId: "openai",
|
||||
modelId: "gpt-5",
|
||||
responsePartCount: 3,
|
||||
textPartCount: 1,
|
||||
});
|
||||
expect(error.cause).not.toHaveProperty("cause");
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -387,21 +289,16 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
|
||||
};
|
||||
|
||||
const error = yield* textGeneration
|
||||
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
|
||||
.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("Model did not produce structured output");
|
||||
expect(error.cause).toMatchObject({
|
||||
_tag: "OpenCodeTextGenerationPromptResponseError",
|
||||
operation: "generateCommitMessage",
|
||||
cwd: process.cwd(),
|
||||
sessionId: "http://127.0.0.1:4301/session",
|
||||
providerId: "openai",
|
||||
modelId: "gpt-5",
|
||||
providerErrorName: "StructuredOutputError",
|
||||
providerMessage: "Model did not produce structured output",
|
||||
});
|
||||
expect(error.cause).not.toHaveProperty("cause");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -6,7 +6,6 @@ import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import {
|
||||
NonNegativeInt,
|
||||
TextGenerationError,
|
||||
type ChatAttachment,
|
||||
type ModelSelection,
|
||||
@@ -34,106 +33,11 @@ import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
|
||||
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
|
||||
|
||||
const OpenCodeTextGenerationOperation = Schema.Literals([
|
||||
"generateCommitMessage",
|
||||
"generatePrContent",
|
||||
"generateBranchName",
|
||||
"generateThreadTitle",
|
||||
]);
|
||||
|
||||
type OpenCodeTextGenerationOperation = typeof OpenCodeTextGenerationOperation.Type;
|
||||
|
||||
const openCodeTextGenerationErrorContext = {
|
||||
operation: OpenCodeTextGenerationOperation,
|
||||
cwd: Schema.String,
|
||||
};
|
||||
|
||||
export class OpenCodeTextGenerationSessionRequestError extends Schema.TaggedErrorClass<OpenCodeTextGenerationSessionRequestError>()(
|
||||
"OpenCodeTextGenerationSessionRequestError",
|
||||
{
|
||||
...openCodeTextGenerationErrorContext,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `OpenCode session creation request failed for ${this.operation} in ${this.cwd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class OpenCodeTextGenerationSessionPayloadError extends Schema.TaggedErrorClass<OpenCodeTextGenerationSessionPayloadError>()(
|
||||
"OpenCodeTextGenerationSessionPayloadError",
|
||||
openCodeTextGenerationErrorContext,
|
||||
) {
|
||||
override get message(): string {
|
||||
return `OpenCode session.create returned no session payload for ${this.operation} in ${this.cwd}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const openCodePromptErrorContext = {
|
||||
...openCodeTextGenerationErrorContext,
|
||||
sessionId: Schema.String,
|
||||
providerId: Schema.String,
|
||||
modelId: Schema.String,
|
||||
};
|
||||
|
||||
export class OpenCodeTextGenerationPromptRequestError extends Schema.TaggedErrorClass<OpenCodeTextGenerationPromptRequestError>()(
|
||||
"OpenCodeTextGenerationPromptRequestError",
|
||||
{
|
||||
...openCodePromptErrorContext,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `OpenCode prompt request failed for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}).`;
|
||||
}
|
||||
}
|
||||
|
||||
export class OpenCodeTextGenerationPromptResponseError extends Schema.TaggedErrorClass<OpenCodeTextGenerationPromptResponseError>()(
|
||||
"OpenCodeTextGenerationPromptResponseError",
|
||||
{
|
||||
...openCodePromptErrorContext,
|
||||
providerErrorName: Schema.optional(Schema.String),
|
||||
providerMessage: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const providerError = this.providerErrorName ? ` ${this.providerErrorName}` : "";
|
||||
return `OpenCode prompt${providerError} failed for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}): ${this.providerMessage}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class OpenCodeTextGenerationEmptyOutputError extends Schema.TaggedErrorClass<OpenCodeTextGenerationEmptyOutputError>()(
|
||||
"OpenCodeTextGenerationEmptyOutputError",
|
||||
{
|
||||
...openCodePromptErrorContext,
|
||||
responsePartCount: NonNegativeInt,
|
||||
textPartCount: NonNegativeInt,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `OpenCode returned empty output for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}, ${this.responsePartCount} response parts, ${this.textPartCount} text parts).`;
|
||||
}
|
||||
}
|
||||
|
||||
interface OpenCodePromptFailure {
|
||||
readonly name?: string;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
interface OpenCodeTextPart {
|
||||
readonly type: "text";
|
||||
readonly text: string;
|
||||
}
|
||||
|
||||
function getOpenCodePromptFailure(error: unknown): OpenCodePromptFailure | null {
|
||||
function getOpenCodePromptErrorMessage(error: unknown): string | null {
|
||||
if (!error || typeof error !== "object") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const name =
|
||||
"name" in error && typeof error.name === "string" && error.name.trim().length > 0
|
||||
? error.name.trim()
|
||||
: undefined;
|
||||
const message =
|
||||
"data" in error &&
|
||||
error.data &&
|
||||
@@ -143,34 +47,31 @@ function getOpenCodePromptFailure(error: unknown): OpenCodePromptFailure | null
|
||||
? error.data.message.trim()
|
||||
: "";
|
||||
if (message.length > 0) {
|
||||
return {
|
||||
...(name ? { name } : {}),
|
||||
message,
|
||||
};
|
||||
return message;
|
||||
}
|
||||
|
||||
if (name) {
|
||||
return { name, message: name };
|
||||
if ("name" in error && typeof error.name === "string") {
|
||||
const name = error.name.trim();
|
||||
return name.length > 0 ? name : null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function isOpenCodeTextPart(part: unknown): part is OpenCodeTextPart {
|
||||
return (
|
||||
part !== null &&
|
||||
typeof part === "object" &&
|
||||
"type" in part &&
|
||||
part.type === "text" &&
|
||||
"text" in part &&
|
||||
typeof part.text === "string"
|
||||
);
|
||||
}
|
||||
|
||||
function getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): string {
|
||||
return (parts ?? [])
|
||||
.filter(isOpenCodeTextPart)
|
||||
.map((part) => part.text)
|
||||
.flatMap((part) => {
|
||||
if (!part || typeof part !== "object") {
|
||||
return [];
|
||||
}
|
||||
if (!("type" in part) || part.type !== "text") {
|
||||
return [];
|
||||
}
|
||||
if (!("text" in part) || typeof part.text !== "string") {
|
||||
return [];
|
||||
}
|
||||
return [part.text];
|
||||
})
|
||||
.join("")
|
||||
.trim();
|
||||
}
|
||||
@@ -359,7 +260,11 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
);
|
||||
|
||||
const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
|
||||
readonly operation: OpenCodeTextGenerationOperation;
|
||||
readonly operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
readonly cwd: string;
|
||||
readonly prompt: string;
|
||||
readonly outputSchemaJson: S;
|
||||
@@ -380,121 +285,54 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
|
||||
});
|
||||
|
||||
const runAgainstServer = Effect.fn("runOpenCodeJson.runAgainstServer")(
|
||||
function* (server: Pick<OpenCodeRuntime.OpenCodeServerConnection, "url">) {
|
||||
const client = openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
|
||||
? { serverPassword: openCodeSettings.serverPassword }
|
||||
: {}),
|
||||
});
|
||||
const session = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
client.session.create({
|
||||
title: `T3 Code ${input.operation}`,
|
||||
permission: [{ permission: "*", pattern: "*", action: "deny" }],
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new OpenCodeTextGenerationSessionRequestError({
|
||||
operation: input.operation,
|
||||
cwd: input.cwd,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
if (!session.data) {
|
||||
return yield* new OpenCodeTextGenerationSessionPayloadError({
|
||||
operation: input.operation,
|
||||
cwd: input.cwd,
|
||||
const runAgainstServer = (server: Pick<OpenCodeRuntime.OpenCodeServerConnection, "url">) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const client = openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
|
||||
? { serverPassword: openCodeSettings.serverPassword }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent");
|
||||
const selectedVariant = getModelSelectionStringOptionValue(input.modelSelection, "variant");
|
||||
const promptContext = {
|
||||
operation: input.operation,
|
||||
cwd: input.cwd,
|
||||
sessionId: session.data.id,
|
||||
providerId: parsedModel.providerID,
|
||||
modelId: parsedModel.modelID,
|
||||
};
|
||||
const session = await client.session.create({
|
||||
title: `T3 Code ${input.operation}`,
|
||||
permission: [{ permission: "*", pattern: "*", action: "deny" }],
|
||||
});
|
||||
if (!session.data) {
|
||||
throw new Error("OpenCode session.create returned no session payload.");
|
||||
}
|
||||
const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent");
|
||||
const selectedVariant = getModelSelectionStringOptionValue(
|
||||
input.modelSelection,
|
||||
"variant",
|
||||
);
|
||||
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
client.session.prompt({
|
||||
sessionID: session.data.id,
|
||||
model: parsedModel,
|
||||
...(selectedAgent ? { agent: selectedAgent } : {}),
|
||||
...(selectedVariant ? { variant: selectedVariant } : {}),
|
||||
parts: [{ type: "text", text: input.prompt }, ...fileParts],
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new OpenCodeTextGenerationPromptRequestError({
|
||||
...promptContext,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
const promptFailure = getOpenCodePromptFailure(result.data?.info?.error);
|
||||
if (promptFailure) {
|
||||
return yield* new OpenCodeTextGenerationPromptResponseError({
|
||||
...promptContext,
|
||||
...(promptFailure.name ? { providerErrorName: promptFailure.name } : {}),
|
||||
providerMessage: promptFailure.message,
|
||||
const result = await client.session.prompt({
|
||||
sessionID: session.data.id,
|
||||
model: parsedModel,
|
||||
...(selectedAgent ? { agent: selectedAgent } : {}),
|
||||
...(selectedVariant ? { variant: selectedVariant } : {}),
|
||||
parts: [{ type: "text", text: input.prompt }, ...fileParts],
|
||||
});
|
||||
}
|
||||
const responseParts = result.data?.parts ?? [];
|
||||
const rawText = getOpenCodeTextResponse(responseParts);
|
||||
if (rawText.length === 0) {
|
||||
return yield* new OpenCodeTextGenerationEmptyOutputError({
|
||||
...promptContext,
|
||||
responsePartCount: responseParts.length,
|
||||
textPartCount: responseParts.filter(isOpenCodeTextPart).length,
|
||||
});
|
||||
}
|
||||
return rawText;
|
||||
},
|
||||
Effect.catchTags({
|
||||
OpenCodeTextGenerationSessionRequestError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: cause.operation,
|
||||
detail: "OpenCode session.create request failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
OpenCodeTextGenerationSessionPayloadError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: cause.operation,
|
||||
detail: "OpenCode session.create returned no session payload.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
OpenCodeTextGenerationPromptRequestError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: cause.operation,
|
||||
detail: "OpenCode session.prompt request failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
OpenCodeTextGenerationPromptResponseError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: cause.operation,
|
||||
detail: cause.providerMessage,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
OpenCodeTextGenerationEmptyOutputError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: cause.operation,
|
||||
detail: "OpenCode returned empty output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
const info = result.data?.info;
|
||||
const errorMessage = getOpenCodePromptErrorMessage(info?.error);
|
||||
if (errorMessage) {
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
const rawText = getOpenCodeTextResponse(result.data?.parts);
|
||||
if (rawText.length === 0) {
|
||||
throw new Error("OpenCode returned empty output.");
|
||||
}
|
||||
return rawText;
|
||||
},
|
||||
catch: (cause) =>
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const rawOutput =
|
||||
openCodeSettings.serverUrl.length > 0
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
VcsProcessSpawnError,
|
||||
VcsProcessTimeoutError,
|
||||
} from "@t3tools/contracts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import * as VcsProcess from "./VcsProcess.ts";
|
||||
|
||||
const run = (input: VcsProcess.VcsProcessInput) =>
|
||||
@@ -25,25 +24,6 @@ const liveLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
|
||||
const provideLive = <A, E, R>(effect: Effect.Effect<A, E, R | VcsProcess.VcsProcess>) =>
|
||||
effect.pipe(Effect.provide(liveLayer));
|
||||
|
||||
const baseInput = {
|
||||
operation: "test.process-boundary",
|
||||
command: "git",
|
||||
args: ["status", "--short"],
|
||||
cwd: "/workspace",
|
||||
} satisfies VcsProcess.VcsProcessInput;
|
||||
|
||||
const captureProcessResult = (
|
||||
result: Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
|
||||
) =>
|
||||
VcsProcess.make.pipe(
|
||||
Effect.provideService(
|
||||
ProcessRunner.ProcessRunner,
|
||||
ProcessRunner.ProcessRunner.of({ run: () => result }),
|
||||
),
|
||||
Effect.flatMap((service) => service.run(baseInput)),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
describe("VcsProcess.run", () => {
|
||||
it.effect("collects stdout", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -161,51 +141,6 @@ describe("VcsProcess.run", () => {
|
||||
}).pipe(provideLive),
|
||||
);
|
||||
|
||||
it.effect("preserves real boundary causes without manufacturing structural ones", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("secret stdin failure");
|
||||
const error = yield* captureProcessResult(
|
||||
Effect.fail(
|
||||
new ProcessRunner.ProcessStdinError({
|
||||
command: baseInput.command,
|
||||
argumentCount: baseInput.args.length,
|
||||
cwd: baseInput.cwd,
|
||||
stdinBytes: 47,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "VcsProcessStdinWriteError",
|
||||
operation: baseInput.operation,
|
||||
stdinBytes: 47,
|
||||
cause,
|
||||
});
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
|
||||
const missingExitCodeError = yield* captureProcessResult(
|
||||
Effect.succeed({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
code: null,
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(missingExitCodeError).toMatchObject({
|
||||
_tag: "VcsProcessMissingExitCodeError",
|
||||
operation: baseInput.operation,
|
||||
command: baseInput.command,
|
||||
cwd: baseInput.cwd,
|
||||
argumentCount: baseInput.args.length,
|
||||
});
|
||||
expect(missingExitCodeError).not.toHaveProperty("cause");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns output when non-zero exits are allowed", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* run({
|
||||
|
||||
@@ -5,14 +5,11 @@ import * as Match from "effect/Match";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
VcsOutputDecodeError,
|
||||
type VcsError,
|
||||
VcsProcessExitError,
|
||||
type VcsProcessExitFailureKind,
|
||||
VcsProcessMissingExitCodeError,
|
||||
VcsProcessOutputLimitError,
|
||||
VcsProcessOutputReadError,
|
||||
VcsProcessSpawnError,
|
||||
VcsProcessStdinWriteError,
|
||||
VcsProcessTimeoutError,
|
||||
} from "@t3tools/contracts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
@@ -117,32 +114,19 @@ export const make = Effect.gen(function* () {
|
||||
ProcessSpawnError: (error) =>
|
||||
VcsProcessSpawnError.fromProcessSpawnError(baseError, error),
|
||||
ProcessOutputLimitError: (error) =>
|
||||
new VcsProcessOutputLimitError({
|
||||
...baseError,
|
||||
stream: error.stream,
|
||||
maxBytes: error.maxBytes,
|
||||
observedBytes: error.observedBytes,
|
||||
}),
|
||||
VcsOutputDecodeError.fromProcessOutputLimitError(baseError, error),
|
||||
ProcessTimeoutError: (error) =>
|
||||
VcsProcessTimeoutError.fromProcessTimeoutError(baseError, error),
|
||||
ProcessStdinError: (error) =>
|
||||
new VcsProcessStdinWriteError({
|
||||
...baseError,
|
||||
stdinBytes: error.stdinBytes,
|
||||
cause: error.cause,
|
||||
}),
|
||||
VcsOutputDecodeError.fromProcessStdinError(baseError, error),
|
||||
ProcessReadError: (error) =>
|
||||
new VcsProcessOutputReadError({
|
||||
...baseError,
|
||||
stream: error.stream,
|
||||
cause: error.cause,
|
||||
}),
|
||||
VcsOutputDecodeError.fromProcessReadError(baseError, error),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (result.code === null) {
|
||||
return yield* new VcsProcessMissingExitCodeError(baseError);
|
||||
return yield* VcsOutputDecodeError.missingExitCode(baseError);
|
||||
}
|
||||
|
||||
if (!input.allowNonZeroExit && result.code !== 0) {
|
||||
|
||||
@@ -96,19 +96,16 @@ describe("VcsProjectConfig", () => {
|
||||
const kind = yield* config.resolveKind({ cwd });
|
||||
|
||||
assert.equal(kind, "jj");
|
||||
const [message, context] = messages[0] as [string, Record<string, unknown>];
|
||||
const failedCandidate = path.join(cwd, ".t3code", "vcs.json");
|
||||
const [error] = messages[0] as ReadonlyArray<unknown>;
|
||||
assert.instanceOf(error, VcsProjectConfig.VcsProjectConfigError);
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Failed to inspect VCS project config at " + failedCandidate + ".",
|
||||
);
|
||||
assert.deepInclude(error, {
|
||||
assert.equal(message, "Failed to inspect VCS project config at " + failedCandidate + ".");
|
||||
assert.deepInclude(context, {
|
||||
operation: "inspect",
|
||||
cwd,
|
||||
configPath: failedCandidate,
|
||||
_tag: "VcsProjectConfigError",
|
||||
errorTag: "VcsProjectConfigError",
|
||||
});
|
||||
assert.equal("cause" in context, false);
|
||||
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||
});
|
||||
});
|
||||
@@ -149,19 +146,18 @@ describe("VcsProjectConfig", () => {
|
||||
const kind = yield* config.resolveKind({ cwd: root });
|
||||
|
||||
assert.equal(kind, "auto");
|
||||
const [error] = messages[0] as ReadonlyArray<unknown>;
|
||||
assert.instanceOf(error, VcsProjectConfig.VcsProjectConfigError);
|
||||
const [message, context] = messages[0] as [string, Record<string, unknown>];
|
||||
assert.equal(
|
||||
error.message,
|
||||
message,
|
||||
"Failed to decode VCS project config at " + path.join(configDir, "vcs.json") + ".",
|
||||
);
|
||||
assert.deepInclude(error.cause, { _tag: "SchemaError" });
|
||||
assert.deepInclude(error, {
|
||||
assert.deepInclude(context, {
|
||||
operation: "decode",
|
||||
cwd: root,
|
||||
configPath: path.join(configDir, "vcs.json"),
|
||||
_tag: "VcsProjectConfigError",
|
||||
errorTag: "VcsProjectConfigError",
|
||||
});
|
||||
assert.equal("cause" in context, false);
|
||||
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||
});
|
||||
});
|
||||
@@ -186,16 +182,15 @@ describe("VcsProjectConfig", () => {
|
||||
const kind = yield* config.resolveKind({ cwd: root });
|
||||
|
||||
assert.equal(kind, "auto");
|
||||
const [error] = messages[0] as ReadonlyArray<unknown>;
|
||||
assert.instanceOf(error, VcsProjectConfig.VcsProjectConfigError);
|
||||
assert.equal(error.message, "Failed to read VCS project config at " + configPath + ".");
|
||||
assert.deepInclude(error.cause, { _tag: "PlatformError" });
|
||||
assert.deepInclude(error, {
|
||||
const [message, context] = messages[0] as [string, Record<string, unknown>];
|
||||
assert.equal(message, "Failed to read VCS project config at " + configPath + ".");
|
||||
assert.deepInclude(context, {
|
||||
operation: "read",
|
||||
cwd: root,
|
||||
configPath,
|
||||
_tag: "VcsProjectConfigError",
|
||||
errorTag: "VcsProjectConfigError",
|
||||
});
|
||||
assert.equal("cause" in context, false);
|
||||
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -55,14 +55,13 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
|
||||
}
|
||||
|
||||
const logVcsProjectConfigError = (error: VcsProjectConfigError) =>
|
||||
Effect.logWarning(error).pipe(
|
||||
Effect.annotateLogs({
|
||||
operation: error.operation,
|
||||
cwd: error.cwd,
|
||||
configPath: error.configPath,
|
||||
errorTag: error._tag,
|
||||
}),
|
||||
);
|
||||
Effect.logWarning(error.message, {
|
||||
operation: error.operation,
|
||||
cwd: error.cwd,
|
||||
configPath: error.configPath,
|
||||
errorTag: error._tag,
|
||||
stack: error.stack,
|
||||
});
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -151,29 +151,20 @@ export const make = Effect.gen(function* () {
|
||||
if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, normalizedCwd))) {
|
||||
return;
|
||||
}
|
||||
const recoverRefreshFailure = (
|
||||
cause:
|
||||
| WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed
|
||||
| WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut
|
||||
| WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logWarning("Failed to refresh workspace search index", {
|
||||
cwd,
|
||||
cause,
|
||||
});
|
||||
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;
|
||||
yield* searchIndex.refresh();
|
||||
}).pipe(
|
||||
Effect.provide(workspaceSearchIndexes.get(normalizedCwd)),
|
||||
Effect.catchTags({
|
||||
WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,
|
||||
WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,
|
||||
WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,
|
||||
}),
|
||||
Effect.catch((cause) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logWarning("Failed to refresh workspace search index", {
|
||||
cwd,
|
||||
cause,
|
||||
});
|
||||
yield* workspaceSearchIndexes.invalidate(normalizedCwd);
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { FileFinder } from "@ff-labs/fff-node";
|
||||
import { afterEach, expect, it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";
|
||||
@@ -51,35 +49,6 @@ it.effect("keeps returned FileFinder creation diagnostics out of the cause chain
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves FileFinder destroy failures as structured defects", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("native destroy failed");
|
||||
const finder = {
|
||||
destroy: vi.fn(() => {
|
||||
throw cause;
|
||||
}),
|
||||
isScanning: vi.fn(() => false),
|
||||
} as unknown as FileFinder;
|
||||
vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder });
|
||||
|
||||
const exit = yield* Effect.scoped(WorkspaceSearchIndex.make("/workspace/project")).pipe(
|
||||
Effect.exit,
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasDies(exit.cause)).toBe(true);
|
||||
const error = Cause.squash(exit.cause);
|
||||
expect(error).toBeInstanceOf(WorkspaceSearchIndex.WorkspaceSearchIndexDestroyFailed);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "WorkspaceSearchIndexDestroyFailed",
|
||||
cwd: "/workspace/project",
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves search and refresh failures with operation context", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -71,18 +71,6 @@ export class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedErrorClass<W
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexDestroyFailed>()(
|
||||
"WorkspaceSearchIndexDestroyFailed",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to destroy the workspace search index for '${this.cwd}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export type WorkspaceSearchIndexError =
|
||||
| WorkspaceSearchIndexCreateFailed
|
||||
| WorkspaceSearchIndexScanTimedOut
|
||||
@@ -213,10 +201,7 @@ const waitForScan = <E>(cwd: string, finder: FileFinder, onFailure: (cause: unkn
|
||||
|
||||
export const make = Effect.fn("WorkspaceSearchIndex.make")(function* (cwd: string) {
|
||||
const finder = yield* Effect.acquireRelease(createFinder(cwd), (finder) =>
|
||||
Effect.try({
|
||||
try: () => finder.destroy(),
|
||||
catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),
|
||||
}).pipe(Effect.orDie),
|
||||
Effect.sync(() => finder.destroy()),
|
||||
);
|
||||
yield* waitForScan(
|
||||
cwd,
|
||||
|
||||
@@ -71,18 +71,6 @@ function installTestBrowser(url: string) {
|
||||
return testWindow;
|
||||
}
|
||||
|
||||
function installDesktopBootstrap() {
|
||||
const testWindow = installTestBrowser("http://localhost/");
|
||||
testWindow.desktopBridge = {
|
||||
getLocalEnvironmentBootstrap: () => ({
|
||||
label: "Local environment",
|
||||
httpBaseUrl: "http://localhost:3773",
|
||||
wsBaseUrl: "ws://localhost:3773",
|
||||
bootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
} as DesktopBridge;
|
||||
}
|
||||
|
||||
function sequence<A>(...values: ReadonlyArray<A>) {
|
||||
let index = 0;
|
||||
return () => values[Math.min(index++, values.length - 1)]!;
|
||||
@@ -143,7 +131,15 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
|
||||
});
|
||||
|
||||
installDesktopBootstrap();
|
||||
const testWindow = installTestBrowser("http://localhost/");
|
||||
testWindow.desktopBridge = {
|
||||
getLocalEnvironmentBootstrap: () => ({
|
||||
label: "Local environment",
|
||||
httpBaseUrl: "http://localhost:3773",
|
||||
wsBaseUrl: "ws://localhost:3773",
|
||||
bootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
} as DesktopBridge;
|
||||
|
||||
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
|
||||
|
||||
@@ -293,23 +289,6 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
expect(testApi.calls.session).toBe(2);
|
||||
});
|
||||
|
||||
it("rejects a blank pairing token with a structured validation error", async () => {
|
||||
const { PrimaryEnvironmentPairingCredentialRequiredError, submitServerAuthCredential } =
|
||||
await import("./environments/primary/auth");
|
||||
|
||||
const error = await submitServerAuthCredential(" ").then(
|
||||
() => null,
|
||||
(failure: unknown) => failure,
|
||||
);
|
||||
|
||||
expect(error).toBeInstanceOf(PrimaryEnvironmentPairingCredentialRequiredError);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PrimaryEnvironmentPairingCredentialRequiredError",
|
||||
providedLength: 3,
|
||||
message: "Enter a pairing token to continue.",
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces a friendly error message when an invalid pairing token is submitted", async () => {
|
||||
const cause = new EnvironmentAuthInvalidError({
|
||||
code: "auth_invalid",
|
||||
@@ -320,7 +299,7 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
browserSession: () => Effect.fail(cause),
|
||||
});
|
||||
|
||||
const { isPrimaryEnvironmentPairingCredentialRejectedError, submitServerAuthCredential } =
|
||||
const { isPrimaryEnvironmentRequestError, submitServerAuthCredential } =
|
||||
await import("./environments/primary");
|
||||
|
||||
const error = await submitServerAuthCredential("bad-token").then(
|
||||
@@ -328,13 +307,14 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
(failure: unknown) => failure,
|
||||
);
|
||||
expect(error).toMatchObject({
|
||||
_tag: "PrimaryEnvironmentPairingCredentialRejectedError",
|
||||
providedLength: 9,
|
||||
message: "Invalid pairing token. Check the token and try again.",
|
||||
_tag: "PrimaryEnvironmentRequestError",
|
||||
operation: "exchange-bootstrap-credential",
|
||||
status: 401,
|
||||
detail: "Invalid pairing token. Check the token and try again.",
|
||||
});
|
||||
expect(isPrimaryEnvironmentPairingCredentialRejectedError(error)).toBe(true);
|
||||
if (!isPrimaryEnvironmentPairingCredentialRejectedError(error)) {
|
||||
throw new Error("Expected a structured rejected pairing credential error.");
|
||||
expect(isPrimaryEnvironmentRequestError(error)).toBe(true);
|
||||
if (!isPrimaryEnvironmentRequestError(error)) {
|
||||
throw new Error("Expected a structured primary environment request error.");
|
||||
}
|
||||
expect(error.cause).toMatchObject({
|
||||
_tag: "EnvironmentAuthInvalidError",
|
||||
@@ -345,22 +325,6 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
expect(testApi.calls.browserSession).toEqual([{ credential: "bad-token" }]);
|
||||
});
|
||||
|
||||
it("derives primary request messages from structural request context", async () => {
|
||||
const cause = new Error("private transport detail");
|
||||
const { PrimaryEnvironmentRequestError } = await import("./environments/primary");
|
||||
const error = PrimaryEnvironmentRequestError.fromCause({
|
||||
operation: "list-pairing-links",
|
||||
cause,
|
||||
});
|
||||
|
||||
expect(error.status).toBe(500);
|
||||
expect(error.cause).toBe(cause);
|
||||
expect(error.message).toBe(
|
||||
"Primary environment request failed during list-pairing-links (HTTP 500).",
|
||||
);
|
||||
expect(error.message).not.toContain(cause.message);
|
||||
});
|
||||
|
||||
it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => {
|
||||
vi.useFakeTimers();
|
||||
const nextSession = sequence(
|
||||
@@ -373,7 +337,15 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
|
||||
});
|
||||
|
||||
installDesktopBootstrap();
|
||||
const testWindow = installTestBrowser("http://localhost/");
|
||||
testWindow.desktopBridge = {
|
||||
getLocalEnvironmentBootstrap: () => ({
|
||||
label: "Local environment",
|
||||
httpBaseUrl: "http://localhost:3773",
|
||||
wsBaseUrl: "ws://localhost:3773",
|
||||
bootstrapToken: "desktop-bootstrap-token",
|
||||
}),
|
||||
} as DesktopBridge;
|
||||
|
||||
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
|
||||
|
||||
@@ -384,28 +356,6 @@ describe("resolveInitialServerAuthGateState", () => {
|
||||
expect(testApi.calls.session).toBe(3);
|
||||
});
|
||||
|
||||
it("preserves the timeout message when a bootstrapped session never becomes observable", async () => {
|
||||
vi.useFakeTimers();
|
||||
const testApi = await installAuthApi({
|
||||
session: () => unauthenticatedSession(DESKTOP_AUTH),
|
||||
browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])),
|
||||
});
|
||||
|
||||
installDesktopBootstrap();
|
||||
|
||||
const { resolveInitialServerAuthGateState } = await import("./environments/primary");
|
||||
|
||||
const gateStatePromise = resolveInitialServerAuthGateState();
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
|
||||
await expect(gateStatePromise).resolves.toEqual({
|
||||
status: "requires-auth",
|
||||
auth: DESKTOP_AUTH,
|
||||
errorMessage: "Timed out waiting for authenticated session after bootstrap.",
|
||||
});
|
||||
expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]);
|
||||
});
|
||||
|
||||
it("memoizes the authenticated gate state after the first successful read", async () => {
|
||||
const testApi = await installAuthApi({
|
||||
session: sequence(authenticatedSession(LOOPBACK_AUTH), unauthenticatedSession(LOOPBACK_AUTH)),
|
||||
|
||||
@@ -47,14 +47,6 @@ describe("browser target resolver", () => {
|
||||
).toBe("http://localhost:3000/app");
|
||||
});
|
||||
|
||||
it("preserves localhost server-picker values when the prepared base is 127.0.0.1", async () => {
|
||||
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://127.0.0.1:3773" });
|
||||
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
|
||||
expect(
|
||||
resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "localhost:5173/app?x=1#top"),
|
||||
).toBe("http://localhost:5173/app?x=1#top");
|
||||
});
|
||||
|
||||
it("normalizes public URLs without treating them as environment ports", async () => {
|
||||
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
|
||||
expect(resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "example.com/app")).toBe(
|
||||
|
||||
@@ -24,11 +24,6 @@ const isPrivateNetworkHost = (host: string): boolean => {
|
||||
);
|
||||
};
|
||||
|
||||
const isLocalLoopbackHost = (host: string): boolean => {
|
||||
const normalized = host.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
|
||||
};
|
||||
|
||||
export function resolveBrowserNavigationTarget(
|
||||
environmentId: EnvironmentId,
|
||||
target: BrowserNavigationTarget,
|
||||
@@ -73,12 +68,6 @@ export function resolveDiscoveredServerUrl(environmentId: EnvironmentId, rawUrl:
|
||||
const normalizedUrl = normalizePreviewUrl(rawUrl);
|
||||
const parsed = new URL(normalizedUrl);
|
||||
if (!isLoopbackHost(parsed.hostname)) return normalizedUrl;
|
||||
const connection = readPreparedConnection(environmentId);
|
||||
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
|
||||
const environmentUrl = new URL(connection.httpBaseUrl);
|
||||
if (parsed.hostname !== "0.0.0.0" && isLocalLoopbackHost(environmentUrl.hostname)) {
|
||||
return normalizedUrl;
|
||||
}
|
||||
const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80));
|
||||
return resolveBrowserNavigationTarget(environmentId, {
|
||||
kind: "environment-port",
|
||||
|
||||
@@ -69,25 +69,4 @@ describe("clientPersistenceStorage", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("defaults word wrap on and discards obsolete wrapping preferences", async () => {
|
||||
const testWindow = getTestWindow();
|
||||
testWindow.localStorage.setItem(
|
||||
"t3code:client-settings:v1",
|
||||
JSON.stringify({
|
||||
chatWordWrap: false,
|
||||
diffWordWrap: false,
|
||||
}),
|
||||
);
|
||||
const { readBrowserClientSettings } = await import("./clientPersistenceStorage");
|
||||
const settings = readBrowserClientSettings();
|
||||
|
||||
expect(settings).toEqual(
|
||||
expect.objectContaining({
|
||||
wordWrap: true,
|
||||
}),
|
||||
);
|
||||
expect(settings).not.toHaveProperty("chatWordWrap");
|
||||
expect(settings).not.toHaveProperty("diffWordWrap");
|
||||
});
|
||||
});
|
||||
@@ -33,7 +33,6 @@ import {
|
||||
readPrimaryCloudLinkState,
|
||||
type CloudLinkTarget,
|
||||
unlinkPrimaryEnvironmentFromCloud,
|
||||
updatePrimaryCloudPreferences,
|
||||
} from "./linkEnvironment";
|
||||
|
||||
const TARGET: CloudLinkTarget = {
|
||||
@@ -253,38 +252,6 @@ describe("web cloud link environment client", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("updates agent activity publishing for the explicit primary target", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
Response.json({
|
||||
linked: true,
|
||||
cloudUserId: "user-1",
|
||||
relayUrl: "https://relay.example.test",
|
||||
relayIssuer: "https://relay.example.test",
|
||||
publishAgentActivity: true,
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const state = yield* withServices(
|
||||
updatePrimaryCloudPreferences({
|
||||
target: TARGET,
|
||||
publishAgentActivity: true,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(state.publishAgentActivity).toBe(true);
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
|
||||
"http://127.0.0.1:3000/api/connect/preferences",
|
||||
);
|
||||
expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
expect(JSON.parse(bodyText(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({
|
||||
publishAgentActivity: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("links an available primary environment without invoking installation", () =>
|
||||
Effect.gen(function* () {
|
||||
const fetchMock = vi
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
linkPrimaryEnvironmentToCloud,
|
||||
type CloudLinkTarget,
|
||||
unlinkPrimaryEnvironmentFromCloud,
|
||||
updatePrimaryCloudPreferences,
|
||||
} from "./linkEnvironment";
|
||||
|
||||
const cloudLinkScheduler = createAtomCommandScheduler();
|
||||
@@ -32,11 +31,3 @@ export const unlinkPrimaryEnvironment = createRuntimeCommand(connectionAtomRunti
|
||||
execute: (input: { readonly target: CloudLinkTarget; readonly clerkToken: string | null }) =>
|
||||
unlinkPrimaryEnvironmentFromCloud(input),
|
||||
});
|
||||
|
||||
export const updatePrimaryEnvironmentPreferences = createRuntimeCommand(connectionAtomRuntime, {
|
||||
label: "web:cloud:update-primary-environment-preferences",
|
||||
scheduler: cloudLinkScheduler,
|
||||
concurrency: cloudLinkConcurrency,
|
||||
execute: (input: { readonly target: CloudLinkTarget; readonly publishAgentActivity: boolean }) =>
|
||||
updatePrimaryCloudPreferences(input),
|
||||
});
|
||||
@@ -1,64 +1,14 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useEffect, type CSSProperties, type ReactNode } from "react";
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import { isElectron } from "../env";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import { Sidebar, SidebarProvider, SidebarRail, SidebarTrigger, useSidebar } from "./ui/sidebar";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
|
||||
import { Sidebar, SidebarProvider, SidebarRail } from "./ui/sidebar";
|
||||
|
||||
const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width";
|
||||
const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16;
|
||||
const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16;
|
||||
const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "90px";
|
||||
|
||||
function SidebarControl() {
|
||||
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
|
||||
const { toggleSidebar } = useSidebar();
|
||||
const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle");
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.defaultPrevented) return;
|
||||
if (resolveShortcutCommand(event, keybindings) !== "sidebar.toggle") return;
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleSidebar();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [keybindings, toggleSidebar]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="pointer-events-none fixed left-[var(--workspace-controls-left)] top-[var(--workspace-controls-top)] z-50 flex h-[var(--workspace-topbar-height)] items-center"
|
||||
data-sidebar-control=""
|
||||
>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<SidebarTrigger className="pointer-events-auto" aria-label="Toggle main sidebar" />
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
const macosWindowControlsStyle =
|
||||
isElectron && isMacPlatform(navigator.platform)
|
||||
? ({ "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET } as CSSProperties)
|
||||
: undefined;
|
||||
|
||||
useEffect(() => {
|
||||
const onMenuAction = window.desktopBridge?.onMenuAction;
|
||||
@@ -78,7 +28,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
}, [navigate]);
|
||||
|
||||
return (
|
||||
<SidebarProvider className="h-dvh! min-h-0!" defaultOpen style={macosWindowControlsStyle}>
|
||||
<SidebarProvider className="h-dvh! min-h-0!" defaultOpen>
|
||||
<Sidebar
|
||||
side="left"
|
||||
collapsible="offcanvas"
|
||||
@@ -94,7 +44,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
<SidebarRail />
|
||||
</Sidebar>
|
||||
{children}
|
||||
<SidebarControl />
|
||||
</SidebarProvider>
|
||||
);
|
||||
}
|
||||
@@ -54,7 +54,6 @@ import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { getClientSettings } from "../hooks/useSettings";
|
||||
import {
|
||||
chatMarkdownClipboardPayload,
|
||||
serializeTableElementToCsv,
|
||||
@@ -293,14 +292,10 @@ function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
return promise;
|
||||
}
|
||||
|
||||
function readInitialWordWrapSetting(): boolean {
|
||||
return getClientSettings().wordWrap;
|
||||
}
|
||||
|
||||
function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const tableRef = useRef<HTMLTableElement | null>(null);
|
||||
const [expanded, setExpanded] = useState(readInitialWordWrapSetting);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const expandLabel = expanded ? "Collapse table cells" : "Expand table cells";
|
||||
@@ -530,11 +525,10 @@ function MarkdownCodeBlock({
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [wrapped, setWrapped] = useState(readInitialWordWrapSetting);
|
||||
const [wrapped, setWrapped] = useState(false);
|
||||
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const wrapLabel = wrapped ? "Disable line wrap" : "Wrap lines";
|
||||
const copyLabel = copied ? "Copied" : "Copy code";
|
||||
|
||||
const handleCopy = useCallback(() => {
|
||||
if (typeof navigator === "undefined" || navigator.clipboard == null) {
|
||||
return;
|
||||
|
||||
@@ -128,7 +128,6 @@ import PlanSidebar from "./PlanSidebar";
|
||||
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
|
||||
import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
|
||||
import { cn, randomHex } from "~/lib/utils";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
|
||||
import { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
||||
@@ -4678,7 +4677,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
<header
|
||||
data-chat-header
|
||||
className={cn(
|
||||
"border-b border-border transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none",
|
||||
"border-b border-border",
|
||||
isElectron
|
||||
? cn(
|
||||
"workspace-topbar drag-region relative px-3 sm:px-5",
|
||||
@@ -4687,7 +4686,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
"wco:pr-[var(--workspace-native-controls-inset)]",
|
||||
)
|
||||
: "workspace-topbar pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)]",
|
||||
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
|
||||
)}
|
||||
>
|
||||
{!rightPanelOpen ? panelLayoutControls : null}
|
||||
@@ -4729,6 +4727,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
<MessagesTimeline
|
||||
key={activeThread.id}
|
||||
isWorking={isWorking}
|
||||
activeTurnInProgress={isWorking || !latestTurnSettled}
|
||||
activeTurnStartedAt={activeWorkStartedAt}
|
||||
listRef={legendListRef}
|
||||
timelineEntries={timelineEntries}
|
||||
|
||||
@@ -38,7 +38,7 @@ import { resolveThreadRouteRef } from "../threadRoutes";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
|
||||
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableFileDiff";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
import { Switch } from "./ui/switch";
|
||||
import {
|
||||
@@ -186,7 +186,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
const { resolvedTheme } = useTheme();
|
||||
const settings = useClientSettings();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [wordWrap, setWordWrap] = useState(settings.wordWrap);
|
||||
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
|
||||
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
|
||||
const [baseRefQuery, setBaseRefQuery] = useState("");
|
||||
const [collapsedDiffFiles, setCollapsedDiffFiles] = useState<CollapsedDiffFilesState>(() => ({
|
||||
@@ -194,7 +194,6 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
fileKeys: EMPTY_COLLAPSED_DIFF_FILE_KEYS,
|
||||
}));
|
||||
const codeViewRef = useRef<AnnotatableCodeViewHandle>(null);
|
||||
|
||||
const routeThreadRef = useParams({
|
||||
strict: false,
|
||||
select: (params) => resolveThreadRouteRef(params),
|
||||
@@ -696,12 +695,14 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
|
||||
aria-label={
|
||||
diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"
|
||||
}
|
||||
variant="outline"
|
||||
size="xs"
|
||||
pressed={wordWrap}
|
||||
pressed={diffWordWrap}
|
||||
onPressedChange={(pressed) => {
|
||||
setWordWrap(Boolean(pressed));
|
||||
setDiffWordWrap(Boolean(pressed));
|
||||
}}
|
||||
/>
|
||||
}
|
||||
@@ -709,7 +710,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
<TextWrapIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">
|
||||
{wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
|
||||
{diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
@@ -843,7 +844,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
options={{
|
||||
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
||||
lineDiffType: "none",
|
||||
overflow: wordWrap ? "wrap" : "scroll",
|
||||
overflow: diffWordWrap ? "wrap" : "scroll",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||
@@ -859,7 +860,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
<pre
|
||||
className={cn(
|
||||
"max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90",
|
||||
wordWrap
|
||||
diffWordWrap
|
||||
? "overflow-auto whitespace-pre-wrap wrap-break-word"
|
||||
: "overflow-auto",
|
||||
)}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "./ui/empty";
|
||||
import { SidebarInset } from "./ui/sidebar";
|
||||
import { SidebarInset, SidebarTrigger } from "./ui/sidebar";
|
||||
import { isElectron } from "../env";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
|
||||
export function NoActiveThreadState() {
|
||||
return (
|
||||
@@ -10,9 +9,8 @@ export function NoActiveThreadState() {
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
|
||||
<header
|
||||
className={cn(
|
||||
"border-b border-border px-3 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
|
||||
"border-b border-border px-3 sm:px-5",
|
||||
isElectron ? "workspace-topbar drag-region" : "workspace-topbar",
|
||||
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
|
||||
)}
|
||||
>
|
||||
{isElectron ? (
|
||||
@@ -21,6 +19,7 @@ export function NoActiveThreadState() {
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
<span className="text-sm font-medium text-foreground md:text-muted-foreground/60">
|
||||
No active thread
|
||||
</span>
|
||||
|
||||
@@ -70,7 +70,7 @@ import {
|
||||
type SidebarThreadSortOrder,
|
||||
} from "@t3tools/contracts/settings";
|
||||
import { isElectron } from "../env";
|
||||
import { APP_STAGE_LABEL } from "../branding";
|
||||
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
|
||||
import { useOpenPrLink } from "../lib/openPullRequestLink";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
@@ -187,12 +187,12 @@ import {
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadSeedContext,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
orderItemsByPreferredIds,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
resolveSidebarStageBadgeLabel,
|
||||
useThreadJumpHintVisibility,
|
||||
ThreadStatusPill,
|
||||
} from "./Sidebar.logic";
|
||||
@@ -2452,6 +2452,22 @@ const SidebarProjectListRow = memo(function SidebarProjectListRow(props: Sidebar
|
||||
);
|
||||
});
|
||||
|
||||
function T3Wordmark() {
|
||||
return (
|
||||
<svg
|
||||
aria-label="T3"
|
||||
className="h-2.5 w-auto shrink-0 text-foreground"
|
||||
viewBox="15.5309 37 94.3941 56.96"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
type SortableProjectHandleProps = Pick<
|
||||
ReturnType<typeof useSortable>,
|
||||
"attributes" | "listeners" | "setActivatorNodeRef"
|
||||
@@ -2648,64 +2664,48 @@ const SidebarChromeHeader = memo(function SidebarChromeHeader({
|
||||
}: {
|
||||
isElectron: boolean;
|
||||
}) {
|
||||
return isElectron ? (
|
||||
<SidebarHeader className="@container/sidebar-header drag-region h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center px-3 py-0 md:px-0">
|
||||
<SidebarTrigger className="md:hidden" />
|
||||
<SidebarBrand />
|
||||
</SidebarHeader>
|
||||
) : (
|
||||
<SidebarHeader className="@container/sidebar-header h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center px-3 py-0 md:px-0">
|
||||
<SidebarTrigger className="md:hidden" />
|
||||
<SidebarBrand />
|
||||
</SidebarHeader>
|
||||
);
|
||||
});
|
||||
|
||||
function SidebarBrand() {
|
||||
const stageLabel = useSidebarStageLabel();
|
||||
|
||||
return (
|
||||
<Link
|
||||
aria-label="Go to threads"
|
||||
className="sidebar-brand ml-[var(--workspace-titlebar-content-left)] h-7 w-fit min-w-0 shrink-0 items-center gap-1 overflow-hidden rounded-md text-foreground outline-hidden ring-ring focus-visible:ring-2"
|
||||
to="/"
|
||||
>
|
||||
<T3Wordmark />
|
||||
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
|
||||
Code
|
||||
</span>
|
||||
<span className="sidebar-brand-stage shrink-0 items-center whitespace-nowrap rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] font-medium uppercase tracking-[0.18em] text-muted-foreground/60">
|
||||
{stageLabel}
|
||||
</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
function useSidebarStageLabel() {
|
||||
const primaryServerVersion =
|
||||
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
|
||||
|
||||
return resolveSidebarStageBadgeLabel({
|
||||
const stageBadgeLabel = resolveSidebarStageBadgeLabel({
|
||||
primaryServerVersion,
|
||||
fallbackStageLabel: APP_STAGE_LABEL,
|
||||
});
|
||||
}
|
||||
|
||||
function T3Wordmark() {
|
||||
return (
|
||||
<svg
|
||||
aria-label="T3"
|
||||
className="h-2.5 w-auto shrink-0 text-foreground"
|
||||
viewBox="15.5309 37 94.3941 56.96"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
const wordmark = (
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="shrink-0 md:hidden" />
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Link
|
||||
aria-label="Go to threads"
|
||||
className="ml-1 flex min-w-0 flex-1 cursor-pointer items-center gap-1 rounded-md outline-hidden ring-ring transition-colors hover:text-foreground focus-visible:ring-2"
|
||||
to="/"
|
||||
>
|
||||
<T3Wordmark />
|
||||
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
|
||||
Code
|
||||
</span>
|
||||
<span className="rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] font-medium uppercase tracking-[0.18em] text-muted-foreground/60">
|
||||
{stageBadgeLabel}
|
||||
</span>
|
||||
</Link>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom" sideOffset={2}>
|
||||
Version {APP_VERSION}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return isElectron ? (
|
||||
<SidebarHeader className="drag-region h-[52px] flex-row items-center gap-2 px-4 py-0 pl-[90px] wco:h-[env(titlebar-area-height)] wco:pl-[calc(env(titlebar-area-x)+1em)]">
|
||||
{wordmark}
|
||||
</SidebarHeader>
|
||||
) : (
|
||||
<SidebarHeader className="gap-3 px-3 py-2 sm:gap-2.5 sm:px-4 sm:py-3">{wordmark}</SidebarHeader>
|
||||
);
|
||||
});
|
||||
|
||||
const SidebarChromeFooter = memo(function SidebarChromeFooter() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
@@ -78,7 +78,6 @@ import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
|
||||
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
|
||||
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
|
||||
import {
|
||||
getComposerPromptInjectionState,
|
||||
getComposerProviderState,
|
||||
renderProviderTraitsMenuContent,
|
||||
renderProviderTraitsPicker,
|
||||
@@ -792,22 +791,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
[selectedProviderEntry],
|
||||
);
|
||||
|
||||
const composerPromptInjectionState = useMemo(
|
||||
() => getComposerPromptInjectionState(prompt),
|
||||
[prompt],
|
||||
);
|
||||
const composerProviderState = useMemo(
|
||||
() =>
|
||||
getComposerProviderState({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
models: selectedProviderModels,
|
||||
promptInjectionState: composerPromptInjectionState,
|
||||
prompt,
|
||||
modelOptions: composerModelOptions?.[selectedInstanceId],
|
||||
}),
|
||||
[
|
||||
composerModelOptions,
|
||||
composerPromptInjectionState,
|
||||
prompt,
|
||||
selectedInstanceId,
|
||||
selectedModel,
|
||||
selectedProvider,
|
||||
|
||||
@@ -14,6 +14,7 @@ import ProjectScriptsControl, {
|
||||
type NewProjectScriptInput,
|
||||
type ProjectScriptActionResult,
|
||||
} from "../ProjectScriptsControl";
|
||||
import { SidebarTrigger } from "../ui/sidebar";
|
||||
import { OpenInPicker } from "./OpenInPicker";
|
||||
import { usePrimaryEnvironmentId } from "../../state/environments";
|
||||
import { cn } from "~/lib/utils";
|
||||
@@ -79,6 +80,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
return (
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
|
||||
@@ -208,17 +208,19 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<button
|
||||
<div
|
||||
key={`${activeQuestion.id}:${option.label}`}
|
||||
type="button"
|
||||
disabled={isResponding}
|
||||
role="button"
|
||||
tabIndex={isResponding ? -1 : 0}
|
||||
aria-disabled={isResponding}
|
||||
onClick={() => {
|
||||
if (isResponding) return;
|
||||
handleOptionSelection(activeQuestion.id, option.label);
|
||||
}}
|
||||
className={className}
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -879,69 +879,6 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
expect(assistantRow?.showAssistantMeta).toBe(false);
|
||||
expect(assistantRow?.showAssistantCopyButton).toBe(false);
|
||||
});
|
||||
|
||||
it("marks only the unsettled turn work row as in progress", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "old-work-entry",
|
||||
kind: "work",
|
||||
createdAt: "2026-01-01T00:00:08Z",
|
||||
entry: {
|
||||
id: "old-work",
|
||||
createdAt: "2026-01-01T00:00:08Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "Read files",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "user-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:12Z",
|
||||
message: {
|
||||
id: "user-message" as never,
|
||||
role: "user",
|
||||
text: "Continue",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:12Z",
|
||||
updatedAt: "2026-01-01T00:00:12Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "active-work-entry",
|
||||
kind: "work",
|
||||
createdAt: "2026-01-01T00:00:18Z",
|
||||
entry: {
|
||||
id: "active-work",
|
||||
createdAt: "2026-01-01T00:00:18Z",
|
||||
turnId: "turn-2" as never,
|
||||
label: "Run tests",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-2" as never,
|
||||
state: "running",
|
||||
startedAt: "2026-01-01T00:00:16Z",
|
||||
completedAt: null,
|
||||
},
|
||||
expandedTurnIds: new Set(["turn-1" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const workRows = rows.filter((row) => row.kind === "work");
|
||||
|
||||
expect(workRows.map((row) => [row.id, row.turnInProgress])).toEqual([
|
||||
["old-work-entry", false],
|
||||
["active-work-entry", true],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeStableMessagesTimelineRows", () => {
|
||||
@@ -1050,92 +987,6 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
expect(repeated.result[0]).toBe(initial.result[0]);
|
||||
});
|
||||
|
||||
it("reuses settled work rows when a different turn stops running", () => {
|
||||
const timelineEntries = [
|
||||
{
|
||||
id: "old-work-entry",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:08Z",
|
||||
entry: {
|
||||
id: "old-work",
|
||||
createdAt: "2026-01-01T00:00:08Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "Read files",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "user-entry",
|
||||
kind: "message" as const,
|
||||
createdAt: "2026-01-01T00:00:12Z",
|
||||
message: {
|
||||
id: "user-message" as never,
|
||||
role: "user" as const,
|
||||
text: "Continue",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:12Z",
|
||||
updatedAt: "2026-01-01T00:00:12Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "active-work-entry",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:18Z",
|
||||
entry: {
|
||||
id: "active-work",
|
||||
createdAt: "2026-01-01T00:00:18Z",
|
||||
turnId: "turn-2" as never,
|
||||
label: "Run tests",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const runningRows = deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
latestTurn: {
|
||||
turnId: "turn-2" as never,
|
||||
state: "running",
|
||||
startedAt: "2026-01-01T00:00:16Z",
|
||||
completedAt: null,
|
||||
},
|
||||
expandedTurnIds: new Set(["turn-1" as never, "turn-2" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
const initial = computeStableMessagesTimelineRows(runningRows, {
|
||||
byId: new Map(),
|
||||
result: [],
|
||||
});
|
||||
|
||||
const settledRows = deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
latestTurn: {
|
||||
turnId: "turn-2" as never,
|
||||
state: "completed",
|
||||
startedAt: "2026-01-01T00:00:16Z",
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
},
|
||||
expandedTurnIds: new Set(["turn-1" as never, "turn-2" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const repeated = computeStableMessagesTimelineRows(settledRows, initial);
|
||||
|
||||
expect(repeated.result.find((row) => row.id === "old-work-entry")).toBe(
|
||||
initial.result.find((row) => row.id === "old-work-entry"),
|
||||
);
|
||||
expect(repeated.result.find((row) => row.id === "active-work-entry")).not.toBe(
|
||||
initial.result.find((row) => row.id === "active-work-entry"),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns a new result when row order changes without content changes", () => {
|
||||
const firstUserMessage = {
|
||||
id: "user-1" as never,
|
||||
|
||||
@@ -41,7 +41,6 @@ export type MessagesTimelineRow =
|
||||
id: string;
|
||||
createdAt: string;
|
||||
groupedEntries: WorkLogEntry[];
|
||||
turnInProgress: boolean;
|
||||
}
|
||||
| {
|
||||
kind: "turn-fold";
|
||||
@@ -362,9 +361,6 @@ export function deriveMessagesTimelineRows(input: {
|
||||
id: timelineEntry.id,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
groupedEntries,
|
||||
turnInProgress:
|
||||
unsettledTurnId !== null &&
|
||||
groupedEntries.some((entry) => entry.turnId === unsettledTurnId),
|
||||
});
|
||||
index = cursor - 1;
|
||||
continue;
|
||||
@@ -464,10 +460,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
return a.proposedPlan === (b as typeof a).proposedPlan;
|
||||
|
||||
case "work":
|
||||
return (
|
||||
a.turnInProgress === (b as typeof a).turnInProgress &&
|
||||
Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries)
|
||||
);
|
||||
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
|
||||
|
||||
case "message": {
|
||||
const bm = b as typeof a;
|
||||
|
||||
@@ -93,6 +93,7 @@ const MESSAGE_CREATED_AT = "2026-03-17T19:12:28.000Z";
|
||||
function buildProps() {
|
||||
return {
|
||||
isWorking: false,
|
||||
activeTurnInProgress: false,
|
||||
activeTurnStartedAt: null,
|
||||
listRef: createRef<LegendListRef | null>(),
|
||||
latestTurn: null,
|
||||
@@ -192,33 +193,6 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).toContain("Show full message");
|
||||
}, 20_000);
|
||||
|
||||
it("renders chips for standalone element-pick context messages", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[
|
||||
buildUserTimelineEntry(
|
||||
[
|
||||
"<element_context>",
|
||||
"- <SubmitButton> (Button.tsx:12):",
|
||||
" url: https://example.com/dashboard",
|
||||
" selector: button.submit",
|
||||
" source: /repo/src/Button.tsx:12:5",
|
||||
" html:",
|
||||
' <button class="submit">Save</button>',
|
||||
"</element_context>",
|
||||
].join("\n"),
|
||||
),
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("SubmitButton");
|
||||
expect(markup).not.toContain("<element_context");
|
||||
expect(markup).not.toContain("<element_context");
|
||||
});
|
||||
|
||||
it("keeps the copy button for collapsed long user messages", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
|
||||
@@ -17,10 +17,8 @@ import {
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type Dispatch,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
type SetStateAction,
|
||||
} from "react";
|
||||
import { LegendList, type LegendListRef } from "@legendapp/list/react";
|
||||
import { FileDiff } from "@pierre/diffs/react";
|
||||
@@ -131,12 +129,14 @@ interface TimelineRowSharedState {
|
||||
onToggleTurnFold: (turnId: TurnId) => void;
|
||||
}
|
||||
|
||||
interface TimelineRevertControlsState {
|
||||
disabled: boolean;
|
||||
interface TimelineRowActivityState {
|
||||
isWorking: boolean;
|
||||
isRevertingCheckpoint: boolean;
|
||||
activeTurnInProgress: boolean;
|
||||
}
|
||||
|
||||
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
|
||||
const TimelineRevertControlsCtx = createContext<TimelineRevertControlsState>(null!);
|
||||
const TimelineRowActivityCtx = createContext<TimelineRowActivityState>(null!);
|
||||
const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
|
||||
const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
|
||||
const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
|
||||
@@ -147,6 +147,7 @@ const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "d
|
||||
|
||||
interface MessagesTimelineProps {
|
||||
isWorking: boolean;
|
||||
activeTurnInProgress: boolean;
|
||||
activeTurnStartedAt: string | null;
|
||||
listRef: React.RefObject<LegendListRef | null>;
|
||||
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
|
||||
@@ -173,6 +174,7 @@ interface MessagesTimelineProps {
|
||||
|
||||
export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
isWorking,
|
||||
activeTurnInProgress,
|
||||
activeTurnStartedAt,
|
||||
listRef,
|
||||
timelineEntries,
|
||||
@@ -213,11 +215,52 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
useFoldToggleSettlingReset(foldToggleSettling, setFoldToggleSettling);
|
||||
useEffect(() => {
|
||||
if (!foldToggleSettling) {
|
||||
return;
|
||||
}
|
||||
let secondFrameId: number | null = null;
|
||||
const firstFrameId = window.requestAnimationFrame(() => {
|
||||
secondFrameId = window.requestAnimationFrame(() => {
|
||||
setFoldToggleSettling(false);
|
||||
});
|
||||
});
|
||||
return () => {
|
||||
window.cancelAnimationFrame(firstFrameId);
|
||||
if (secondFrameId !== null) {
|
||||
window.cancelAnimationFrame(secondFrameId);
|
||||
}
|
||||
};
|
||||
}, [foldToggleSettling]);
|
||||
|
||||
// An in-session interrupt leaves its turn expanded so the user keeps their
|
||||
// place; the next turn (or a reload, since this is local state) folds it.
|
||||
useLatestTurnFoldState(latestTurn, setExpandedTurnIds);
|
||||
const previousLatestTurnRef = useRef(latestTurn);
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = latestTurn;
|
||||
if (!latestTurn || previous?.turnId === undefined) {
|
||||
return;
|
||||
}
|
||||
if (latestTurn.turnId === previous.turnId) {
|
||||
if (previous.state === "running" && latestTurn.state === "interrupted") {
|
||||
setExpandedTurnIds((existing) => {
|
||||
const next = new Set(existing);
|
||||
next.add(latestTurn.turnId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
setExpandedTurnIds((existing) => {
|
||||
if (!existing.has(previous.turnId)) {
|
||||
return existing;
|
||||
}
|
||||
const next = new Set(existing);
|
||||
next.delete(previous.turnId);
|
||||
return next;
|
||||
});
|
||||
}, [latestTurn]);
|
||||
|
||||
const rawRows = useMemo(
|
||||
() =>
|
||||
@@ -249,7 +292,23 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
}
|
||||
}, [listRef, onIsAtEndChange]);
|
||||
|
||||
useInitialTimelineEndScroll(rows.length, listRef, onIsAtEndChange);
|
||||
const previousRowCountRef = useRef(rows.length);
|
||||
useEffect(() => {
|
||||
const previousRowCount = previousRowCountRef.current;
|
||||
previousRowCountRef.current = rows.length;
|
||||
|
||||
if (previousRowCount > 0 || rows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
onIsAtEndChange(true);
|
||||
const frameId = window.requestAnimationFrame(() => {
|
||||
void listRef.current?.scrollToEnd?.({ animated: false });
|
||||
});
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frameId);
|
||||
};
|
||||
}, [listRef, onIsAtEndChange, rows.length]);
|
||||
|
||||
const sharedState = useMemo<TimelineRowSharedState>(
|
||||
() => ({
|
||||
@@ -280,11 +339,13 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onToggleTurnFold,
|
||||
],
|
||||
);
|
||||
const revertControlsState = useMemo<TimelineRevertControlsState>(
|
||||
const activityState = useMemo<TimelineRowActivityState>(
|
||||
() => ({
|
||||
disabled: isRevertingCheckpoint || isWorking,
|
||||
isWorking,
|
||||
isRevertingCheckpoint,
|
||||
activeTurnInProgress,
|
||||
}),
|
||||
[isRevertingCheckpoint, isWorking],
|
||||
[activeTurnInProgress, isRevertingCheckpoint, isWorking],
|
||||
);
|
||||
|
||||
// Stable renderItem — no closure deps. Row components read shared state
|
||||
@@ -310,7 +371,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
|
||||
return (
|
||||
<TimelineRowCtx value={sharedState}>
|
||||
<TimelineRevertControlsCtx value={revertControlsState}>
|
||||
<TimelineRowActivityCtx value={activityState}>
|
||||
<LegendList<MessagesTimelineRow>
|
||||
ref={listRef}
|
||||
data={rows}
|
||||
@@ -326,92 +387,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
ListHeaderComponent={TIMELINE_LIST_HEADER}
|
||||
ListFooterComponent={TIMELINE_LIST_FOOTER}
|
||||
/>
|
||||
</TimelineRevertControlsCtx>
|
||||
</TimelineRowActivityCtx>
|
||||
</TimelineRowCtx>
|
||||
);
|
||||
});
|
||||
|
||||
function useFoldToggleSettlingReset(
|
||||
foldToggleSettling: boolean,
|
||||
setFoldToggleSettling: Dispatch<SetStateAction<boolean>>,
|
||||
) {
|
||||
useEffect(() => {
|
||||
if (!foldToggleSettling) {
|
||||
return;
|
||||
}
|
||||
let secondFrameId: number | null = null;
|
||||
const firstFrameId = window.requestAnimationFrame(() => {
|
||||
secondFrameId = window.requestAnimationFrame(() => {
|
||||
setFoldToggleSettling(false);
|
||||
});
|
||||
});
|
||||
return () => {
|
||||
window.cancelAnimationFrame(firstFrameId);
|
||||
if (secondFrameId !== null) {
|
||||
window.cancelAnimationFrame(secondFrameId);
|
||||
}
|
||||
};
|
||||
}, [foldToggleSettling, setFoldToggleSettling]);
|
||||
}
|
||||
|
||||
function useLatestTurnFoldState(
|
||||
latestTurn: TimelineLatestTurn | null,
|
||||
setExpandedTurnIds: Dispatch<SetStateAction<ReadonlySet<TurnId>>>,
|
||||
) {
|
||||
const previousLatestTurnRef = useRef(latestTurn);
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = latestTurn;
|
||||
if (!latestTurn || previous?.turnId === undefined) {
|
||||
return;
|
||||
}
|
||||
if (latestTurn.turnId === previous.turnId) {
|
||||
if (previous.state === "running" && latestTurn.state === "interrupted") {
|
||||
setExpandedTurnIds((existing) => {
|
||||
const next = new Set(existing);
|
||||
next.add(latestTurn.turnId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
setExpandedTurnIds((existing) => {
|
||||
if (!existing.has(previous.turnId)) {
|
||||
return existing;
|
||||
}
|
||||
const next = new Set(existing);
|
||||
next.delete(previous.turnId);
|
||||
return next;
|
||||
});
|
||||
}, [latestTurn, setExpandedTurnIds]);
|
||||
}
|
||||
|
||||
function useInitialTimelineEndScroll(
|
||||
rowCount: number,
|
||||
listRef: React.RefObject<LegendListRef | null>,
|
||||
onIsAtEndChange: (isAtEnd: boolean) => void,
|
||||
) {
|
||||
const previousRowCountRef = useRef(rowCount);
|
||||
|
||||
useEffect(() => {
|
||||
const previousRowCount = previousRowCountRef.current;
|
||||
previousRowCountRef.current = rowCount;
|
||||
|
||||
if (previousRowCount > 0 || rowCount === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
onIsAtEndChange(true);
|
||||
const frameId = window.requestAnimationFrame(() => {
|
||||
void listRef.current?.scrollToEnd?.({ animated: false });
|
||||
});
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frameId);
|
||||
};
|
||||
}, [listRef, onIsAtEndChange, rowCount]);
|
||||
}
|
||||
|
||||
function keyExtractor(item: MessagesTimelineRow) {
|
||||
return item.id;
|
||||
}
|
||||
@@ -442,7 +422,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
data-message-id={row.kind === "message" ? row.message.id : undefined}
|
||||
data-message-role={row.kind === "message" ? row.message.role : undefined}
|
||||
>
|
||||
{row.kind === "work" ? <WorkGroupSection row={row} /> : null}
|
||||
{row.kind === "work" ? <WorkGroupSection groupedEntries={row.groupedEntries} /> : null}
|
||||
{row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
|
||||
{row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
|
||||
{row.kind === "message" && row.message.role === "assistant" ? (
|
||||
@@ -468,10 +448,6 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
visibleText = extracted.promptText;
|
||||
}
|
||||
const elementContextState = extractTrailingElementContexts(visibleText);
|
||||
const elementContexts = [
|
||||
...displayedUserMessage.elementContexts,
|
||||
...elementContextState.contexts,
|
||||
];
|
||||
const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
|
||||
const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
|
||||
const canRevertAgentWork = typeof row.revertTurnCount === "number";
|
||||
@@ -519,9 +495,9 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
image={previewImages[index] ?? null}
|
||||
/>
|
||||
))}
|
||||
{elementContexts.length > 0 ? (
|
||||
{elementContextState.contexts.length > 0 ? (
|
||||
<div className="mb-2 flex flex-wrap gap-1.5">
|
||||
{elementContexts.map((context) => (
|
||||
{elementContextState.contexts.map((context) => (
|
||||
<UserMessageElementContextChip
|
||||
key={`${context.header}:${context.body}`}
|
||||
context={context}
|
||||
@@ -560,7 +536,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
|
||||
function RevertUserMessageButton({ messageId }: { messageId: MessageId }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const controls = use(TimelineRevertControlsCtx);
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
@@ -570,7 +546,7 @@ function RevertUserMessageButton({ messageId }: { messageId: MessageId }) {
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
disabled={controls.disabled}
|
||||
disabled={activity.isRevertingCheckpoint || activity.isWorking}
|
||||
onClick={() => ctx.onRevertUserMessage(messageId)}
|
||||
aria-label="Revert to this message"
|
||||
/>
|
||||
@@ -711,16 +687,7 @@ function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "workin
|
||||
function WorkingTimer({ createdAt }: { createdAt: string }) {
|
||||
const textRef = useRef<HTMLSpanElement>(null);
|
||||
const initialText = formatWorkingTimerNow(createdAt);
|
||||
useWorkingTimerText(textRef, createdAt);
|
||||
|
||||
return (
|
||||
<span ref={textRef} className="tabular-nums">
|
||||
{initialText}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function useWorkingTimerText(textRef: React.RefObject<HTMLSpanElement | null>, createdAt: string) {
|
||||
useEffect(() => {
|
||||
const updateText = () => {
|
||||
if (textRef.current) {
|
||||
@@ -730,7 +697,13 @@ function useWorkingTimerText(textRef: React.RefObject<HTMLSpanElement | null>, c
|
||||
updateText();
|
||||
const id = setInterval(updateText, 1000);
|
||||
return () => clearInterval(id);
|
||||
}, [createdAt, textRef]);
|
||||
}, [createdAt]);
|
||||
|
||||
return (
|
||||
<span ref={textRef} className="tabular-nums">
|
||||
{initialText}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -740,15 +713,14 @@ function useWorkingTimerText(textRef: React.RefObject<HTMLSpanElement | null>, c
|
||||
|
||||
/** Collapsed state shows the earliest chunk so "Show more" only appends rows downward. */
|
||||
const WorkGroupSection = memo(function WorkGroupSection({
|
||||
row,
|
||||
groupedEntries,
|
||||
}: {
|
||||
row: Extract<MessagesTimelineRow, { kind: "work" }>;
|
||||
groupedEntries: Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"];
|
||||
}) {
|
||||
const { workspaceRoot } = use(TimelineRowCtx);
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const sectionRef = useRef<HTMLElement>(null);
|
||||
const anchorBottomBeforeToggleRef = useRef<number | null>(null);
|
||||
const { groupedEntries, turnInProgress } = row;
|
||||
const nonEmptyEntries = useMemo(
|
||||
() => groupedEntries.filter((entry) => !workEntryIndicatesToolNeutralStatus(entry)),
|
||||
[groupedEntries],
|
||||
@@ -766,7 +738,31 @@ const WorkGroupSection = memo(function WorkGroupSection({
|
||||
: `${nonEmptyEntries.length} tool calls`
|
||||
: "Work Log";
|
||||
|
||||
usePreserveWorkGroupAnchorOnExpand(isExpanded, sectionRef, anchorBottomBeforeToggleRef);
|
||||
useLayoutEffect(() => {
|
||||
const anchorBottomBeforeToggle = anchorBottomBeforeToggleRef.current;
|
||||
anchorBottomBeforeToggleRef.current = null;
|
||||
|
||||
if (anchorBottomBeforeToggle === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const section = sectionRef.current;
|
||||
if (!section) {
|
||||
return;
|
||||
}
|
||||
|
||||
const delta = section.getBoundingClientRect().bottom - anchorBottomBeforeToggle;
|
||||
if (Math.abs(delta) < 0.5) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scroller = findNearestVerticalScroller(section);
|
||||
if (scroller) {
|
||||
scroller.scrollTop += delta;
|
||||
} else {
|
||||
window.scrollBy(0, delta);
|
||||
}
|
||||
}, [isExpanded]);
|
||||
|
||||
const toggleExpanded = () => {
|
||||
anchorBottomBeforeToggleRef.current =
|
||||
@@ -788,7 +784,6 @@ const WorkGroupSection = memo(function WorkGroupSection({
|
||||
<SimpleWorkEntryRow
|
||||
key={workEntry.id}
|
||||
workEntry={workEntry}
|
||||
turnInProgress={turnInProgress}
|
||||
workspaceRoot={workspaceRoot}
|
||||
/>
|
||||
))}
|
||||
@@ -819,38 +814,6 @@ const WorkGroupSection = memo(function WorkGroupSection({
|
||||
);
|
||||
});
|
||||
|
||||
function usePreserveWorkGroupAnchorOnExpand(
|
||||
isExpanded: boolean,
|
||||
sectionRef: React.RefObject<HTMLElement | null>,
|
||||
anchorBottomBeforeToggleRef: React.RefObject<number | null>,
|
||||
) {
|
||||
useLayoutEffect(() => {
|
||||
const anchorBottomBeforeToggle = anchorBottomBeforeToggleRef.current;
|
||||
anchorBottomBeforeToggleRef.current = null;
|
||||
|
||||
if (anchorBottomBeforeToggle === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const section = sectionRef.current;
|
||||
if (!section) {
|
||||
return;
|
||||
}
|
||||
|
||||
const delta = section.getBoundingClientRect().bottom - anchorBottomBeforeToggle;
|
||||
if (Math.abs(delta) < 0.5) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scroller = findNearestVerticalScroller(section);
|
||||
if (scroller) {
|
||||
scroller.scrollTop += delta;
|
||||
} else {
|
||||
window.scrollBy(0, delta);
|
||||
}
|
||||
}, [anchorBottomBeforeToggleRef, isExpanded, sectionRef]);
|
||||
}
|
||||
|
||||
function findNearestVerticalScroller(element: HTMLElement): HTMLElement | null {
|
||||
let parent = element.parentElement;
|
||||
while (parent) {
|
||||
@@ -1578,10 +1541,10 @@ const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation(
|
||||
|
||||
const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
workEntry: TimelineWorkEntry;
|
||||
turnInProgress: boolean;
|
||||
workspaceRoot: string | undefined;
|
||||
}) {
|
||||
const { workEntry, turnInProgress, workspaceRoot } = props;
|
||||
const { workEntry, workspaceRoot } = props;
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const iconConfig = workToneIcon(workEntry.tone);
|
||||
const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning";
|
||||
@@ -1616,7 +1579,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
: showDestructiveRowStyle
|
||||
? "font-medium text-destructive"
|
||||
: "font-medium text-foreground/82";
|
||||
const turnSettled = !turnInProgress;
|
||||
const turnSettled = !activity.activeTurnInProgress;
|
||||
const showNeutralIndicator = !turnSettled && workEntryIndicatesToolNeutralStatus(workEntry);
|
||||
const showSuccessIndicator =
|
||||
workEntryIndicatesToolSuccess(workEntry) ||
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getComposerPromptInjectionState,
|
||||
getComposerProviderState,
|
||||
renderProviderTraitsMenuContent,
|
||||
renderProviderTraitsPicker,
|
||||
@@ -62,13 +61,6 @@ const ULTRATHINK_FRAME_CLASSES = {
|
||||
} as const;
|
||||
|
||||
describe("getComposerProviderState", () => {
|
||||
it("derives a stable prompt injection state for ordinary prompt edits", () => {
|
||||
expect(getComposerPromptInjectionState("Investigate this failure")).toBe("none");
|
||||
expect(getComposerPromptInjectionState("Ultrathink:\nInvestigate this failure")).toBe(
|
||||
"ultrathink",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns descriptor defaults when no selections are provided", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: PROVIDER,
|
||||
@@ -79,6 +71,7 @@ describe("getComposerProviderState", () => {
|
||||
{ id: "high", label: "High", isDefault: true },
|
||||
]),
|
||||
]),
|
||||
prompt: "",
|
||||
modelOptions: undefined,
|
||||
});
|
||||
|
||||
@@ -100,6 +93,7 @@ describe("getComposerProviderState", () => {
|
||||
]),
|
||||
booleanDescriptor("fastMode"),
|
||||
]),
|
||||
prompt: "",
|
||||
modelOptions: selections(["effort", "low"], ["fastMode", true]),
|
||||
});
|
||||
|
||||
@@ -118,6 +112,7 @@ describe("getComposerProviderState", () => {
|
||||
selectDescriptor("effort", [{ id: "high", label: "High", isDefault: true }]),
|
||||
booleanDescriptor("fastMode"),
|
||||
]),
|
||||
prompt: "",
|
||||
modelOptions: selections(["effort", "high"], ["fastMode", false]),
|
||||
});
|
||||
|
||||
@@ -131,6 +126,7 @@ describe("getComposerProviderState", () => {
|
||||
provider: PROVIDER,
|
||||
model: MODEL,
|
||||
models: modelWith([booleanDescriptor("thinking")]),
|
||||
prompt: "",
|
||||
modelOptions: selections(["effort", "max"], ["thinking", false]),
|
||||
});
|
||||
|
||||
@@ -156,6 +152,7 @@ describe("getComposerProviderState", () => {
|
||||
{ id: "plan", label: "Plan" },
|
||||
]),
|
||||
]),
|
||||
prompt: "",
|
||||
modelOptions: selections(["agent", "plan"]),
|
||||
});
|
||||
|
||||
@@ -170,6 +167,7 @@ describe("getComposerProviderState", () => {
|
||||
provider: PROVIDER,
|
||||
model: MODEL,
|
||||
models: modelWith([]),
|
||||
prompt: "",
|
||||
modelOptions: selections(["anything", "value"]),
|
||||
});
|
||||
|
||||
@@ -195,9 +193,7 @@ describe("getComposerProviderState", () => {
|
||||
["ultrathink"],
|
||||
),
|
||||
]),
|
||||
promptInjectionState: getComposerPromptInjectionState(
|
||||
"Ultrathink:\nInvestigate this failure",
|
||||
),
|
||||
prompt: "Ultrathink:\nInvestigate this failure",
|
||||
modelOptions: selections(["effort", "medium"]),
|
||||
});
|
||||
|
||||
@@ -216,9 +212,7 @@ describe("getComposerProviderState", () => {
|
||||
models: modelWith([
|
||||
selectDescriptor("effort", [{ id: "high", label: "High", isDefault: true }]),
|
||||
]),
|
||||
promptInjectionState: getComposerPromptInjectionState(
|
||||
"Ultrathink:\nInvestigate this failure",
|
||||
),
|
||||
prompt: "Ultrathink:\nInvestigate this failure",
|
||||
modelOptions: undefined,
|
||||
});
|
||||
|
||||
|
||||
@@ -21,12 +21,10 @@ export type ComposerProviderStateInput = {
|
||||
provider: ProviderDriverKind;
|
||||
model: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
promptInjectionState?: ComposerPromptInjectionState;
|
||||
prompt: string;
|
||||
modelOptions: ReadonlyArray<ProviderOptionSelection> | null | undefined;
|
||||
};
|
||||
|
||||
export type ComposerPromptInjectionState = "none" | "ultrathink";
|
||||
|
||||
export type ComposerProviderState = {
|
||||
provider: ProviderDriverKind;
|
||||
promptEffort: string | null;
|
||||
@@ -48,12 +46,8 @@ type TraitsRenderInput = {
|
||||
onPromptChange: (prompt: string) => void;
|
||||
};
|
||||
|
||||
export function getComposerPromptInjectionState(prompt: string): ComposerPromptInjectionState {
|
||||
return isClaudeUltrathinkPrompt(prompt) ? "ultrathink" : "none";
|
||||
}
|
||||
|
||||
export function getComposerProviderState(input: ComposerProviderStateInput): ComposerProviderState {
|
||||
const { provider, model, models, modelOptions, promptInjectionState = "none" } = input;
|
||||
const { provider, model, models, prompt, modelOptions } = input;
|
||||
const caps = getProviderModelCapabilities(models, model, provider);
|
||||
const descriptors = getProviderOptionDescriptors({ caps, selections: modelOptions });
|
||||
const primarySelectDescriptor = descriptors.find(
|
||||
@@ -64,7 +58,7 @@ export function getComposerProviderState(input: ComposerProviderStateInput): Com
|
||||
const promptEffort = typeof primaryValue === "string" ? primaryValue : null;
|
||||
const ultrathinkActive =
|
||||
(primarySelectDescriptor?.promptInjectedValues?.length ?? 0) > 0 &&
|
||||
promptInjectionState === "ultrathink";
|
||||
isClaudeUltrathinkPrompt(prompt);
|
||||
|
||||
return {
|
||||
provider,
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import type { RelayClientDeviceRecord } from "@t3tools/contracts/relay";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
mobileClientNotificationDetail,
|
||||
mobileClientPlatformLabel,
|
||||
mobileClientUpdatedAtLabel,
|
||||
} from "./MobileClientsUserProfilePage.logic";
|
||||
|
||||
function device(overrides: Partial<RelayClientDeviceRecord> = {}): RelayClientDeviceRecord {
|
||||
return {
|
||||
deviceId: "device-1",
|
||||
label: "Julius’s iPhone",
|
||||
platform: "ios",
|
||||
iosMajorVersion: 18,
|
||||
appVersion: "1.2.3",
|
||||
notifications: {
|
||||
enabled: true,
|
||||
notifyOnApproval: true,
|
||||
notifyOnInput: false,
|
||||
notifyOnCompletion: true,
|
||||
notifyOnFailure: false,
|
||||
},
|
||||
liveActivities: { enabled: true },
|
||||
updatedAt: "2026-06-21T12:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("mobile client presentation", () => {
|
||||
it("describes the client platform and enabled notification events", () => {
|
||||
const client = device();
|
||||
|
||||
expect(mobileClientPlatformLabel(client)).toBe("iOS 18 · T3 Code 1.2.3");
|
||||
expect(mobileClientNotificationDetail(client)).toBe(
|
||||
"Alerts enabled for approvals, completions.",
|
||||
);
|
||||
});
|
||||
|
||||
it("distinguishes disabled notifications from an empty event selection", () => {
|
||||
expect(
|
||||
mobileClientNotificationDetail(
|
||||
device({ notifications: { ...device().notifications, enabled: false } }),
|
||||
),
|
||||
).toBe("Push notifications are disabled on this device.");
|
||||
expect(
|
||||
mobileClientNotificationDetail(
|
||||
device({
|
||||
notifications: {
|
||||
enabled: true,
|
||||
notifyOnApproval: false,
|
||||
notifyOnInput: false,
|
||||
notifyOnCompletion: false,
|
||||
notifyOnFailure: false,
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe("Push notifications are enabled, but no alert types are selected.");
|
||||
});
|
||||
|
||||
it("handles missing app versions and invalid update timestamps", () => {
|
||||
expect(mobileClientPlatformLabel(device({ appVersion: null }))).toBe("iOS 18");
|
||||
expect(mobileClientUpdatedAtLabel("not-a-date")).toBe("Update time unavailable");
|
||||
});
|
||||
});
|
||||
@@ -1,39 +0,0 @@
|
||||
import type { RelayClientDeviceRecord } from "@t3tools/contracts/relay";
|
||||
|
||||
const mobileClientUpdatedAtFormatter = new Intl.DateTimeFormat(undefined, {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
});
|
||||
|
||||
const NOTIFICATION_PREFERENCES = [
|
||||
["notifyOnApproval", "approvals"],
|
||||
["notifyOnInput", "input requests"],
|
||||
["notifyOnCompletion", "completions"],
|
||||
["notifyOnFailure", "failures"],
|
||||
] as const satisfies ReadonlyArray<
|
||||
readonly [keyof RelayClientDeviceRecord["notifications"], string]
|
||||
>;
|
||||
|
||||
export function mobileClientPlatformLabel(device: RelayClientDeviceRecord): string {
|
||||
return `iOS ${device.iosMajorVersion}${device.appVersion ? ` · T3 Code ${device.appVersion}` : ""}`;
|
||||
}
|
||||
|
||||
export function mobileClientNotificationDetail(device: RelayClientDeviceRecord): string {
|
||||
if (!device.notifications.enabled) {
|
||||
return "Push notifications are disabled on this device.";
|
||||
}
|
||||
|
||||
const enabledPreferences = NOTIFICATION_PREFERENCES.flatMap(([preference, label]) =>
|
||||
device.notifications[preference] ? [label] : [],
|
||||
);
|
||||
return enabledPreferences.length > 0
|
||||
? `Alerts enabled for ${enabledPreferences.join(", ")}.`
|
||||
: "Push notifications are enabled, but no alert types are selected.";
|
||||
}
|
||||
|
||||
export function mobileClientUpdatedAtLabel(updatedAt: string): string {
|
||||
const date = new Date(updatedAt);
|
||||
return Number.isNaN(date.getTime())
|
||||
? "Update time unavailable"
|
||||
: `Updated ${mobileClientUpdatedAtFormatter.format(date)}`;
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
import type { RelayClientDeviceRecord } from "@t3tools/contracts/relay";
|
||||
import { RefreshCwIcon, SmartphoneIcon } from "lucide-react";
|
||||
|
||||
import { useManagedRelayDevices } from "../../cloud/managedRelayState";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Button } from "../ui/button";
|
||||
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";
|
||||
import { Skeleton } from "../ui/skeleton";
|
||||
import {
|
||||
mobileClientNotificationDetail,
|
||||
mobileClientPlatformLabel,
|
||||
mobileClientUpdatedAtLabel,
|
||||
} from "./MobileClientsUserProfilePage.logic";
|
||||
|
||||
const MOBILE_CLIENT_SKELETON_ROWS = ["primary", "secondary"] as const;
|
||||
|
||||
function MobileClientStatusBadge({
|
||||
enabled,
|
||||
label,
|
||||
}: {
|
||||
readonly enabled: boolean;
|
||||
readonly label: string;
|
||||
}) {
|
||||
return (
|
||||
<Badge variant={enabled ? "success" : "outline"}>
|
||||
{label}: {enabled ? "On" : "Off"}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileClientRow({ device }: { readonly device: RelayClientDeviceRecord }) {
|
||||
return (
|
||||
<li className="rounded-xl border bg-card p-4 text-card-foreground shadow-sm/4">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex size-9 shrink-0 items-center justify-center rounded-lg border bg-muted/40 text-muted-foreground">
|
||||
<SmartphoneIcon className="size-4" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between sm:gap-3">
|
||||
<div className="min-w-0">
|
||||
<h3 className="truncate text-sm font-semibold text-foreground">{device.label}</h3>
|
||||
<p className="text-xs text-muted-foreground">{mobileClientPlatformLabel(device)}</p>
|
||||
</div>
|
||||
<p className="shrink-0 text-[11px] text-muted-foreground/75">
|
||||
{mobileClientUpdatedAtLabel(device.updatedAt)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-1.5">
|
||||
<MobileClientStatusBadge
|
||||
enabled={device.notifications.enabled}
|
||||
label="Push notifications"
|
||||
/>
|
||||
<MobileClientStatusBadge
|
||||
enabled={device.liveActivities.enabled}
|
||||
label="Live Activities"
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-2 text-xs leading-relaxed text-muted-foreground/80">
|
||||
{mobileClientNotificationDetail(device)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileClientsSkeleton() {
|
||||
return (
|
||||
<div aria-label="Loading mobile clients" className="space-y-3" role="status">
|
||||
{MOBILE_CLIENT_SKELETON_ROWS.map((row) => (
|
||||
<div key={row} className="rounded-xl border p-4">
|
||||
<div className="flex gap-3">
|
||||
<Skeleton className="size-9 shrink-0 rounded-lg" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-36" />
|
||||
<Skeleton className="h-3 w-28" />
|
||||
<div className="flex gap-2 pt-1">
|
||||
<Skeleton className="h-5 w-28" />
|
||||
<Skeleton className="h-5 w-24" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyMobileClients() {
|
||||
return (
|
||||
<Empty className="min-h-72 rounded-xl border border-dashed bg-muted/15">
|
||||
<EmptyMedia variant="icon">
|
||||
<SmartphoneIcon />
|
||||
</EmptyMedia>
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>No mobile clients</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
Sign in to T3 Code on your iPhone to register it for push notifications and Live
|
||||
Activities.
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
);
|
||||
}
|
||||
|
||||
export function MobileClientsUserProfilePage() {
|
||||
const devicesState = useManagedRelayDevices();
|
||||
const devices = devicesState.data ?? [];
|
||||
const isInitialLoad =
|
||||
!devicesState.accountId || (devicesState.data === null && !devicesState.error);
|
||||
const hasErrorWithoutData = devicesState.error !== null && devicesState.data === null;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-[30rem] w-full flex-col bg-background text-foreground">
|
||||
<header className="flex flex-col gap-4 border-b px-6 py-5 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h2 className="text-base font-semibold tracking-[-0.01em]">Mobile clients</h2>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
Devices registered to receive T3 Connect activity from your environments.
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={devicesState.isPending}
|
||||
onClick={devicesState.refresh}
|
||||
>
|
||||
<RefreshCwIcon className={cn("size-3.5", devicesState.isPending && "animate-spin")} />
|
||||
Refresh
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 p-6">
|
||||
{devicesState.error ? (
|
||||
<div
|
||||
className="mb-4 flex flex-col gap-3 rounded-lg border border-destructive/25 bg-destructive/5 p-3 text-sm sm:flex-row sm:items-center sm:justify-between"
|
||||
role="alert"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium text-destructive-foreground">
|
||||
Could not load mobile clients
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">{devicesState.error}</p>
|
||||
</div>
|
||||
<Button size="xs" variant="outline" onClick={devicesState.refresh}>
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{isInitialLoad ? (
|
||||
<MobileClientsSkeleton />
|
||||
) : hasErrorWithoutData ? null : devices.length > 0 ? (
|
||||
<ul className="space-y-3">
|
||||
{devices.map((device) => (
|
||||
<MobileClientRow key={device.deviceId} device={device} />
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<EmptyMobileClients />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { UserButton, useAuth } from "@clerk/react";
|
||||
import { LogInIcon, SmartphoneIcon } from "lucide-react";
|
||||
import { LogInIcon } from "lucide-react";
|
||||
|
||||
import { hasCloudPublicConfig } from "../../cloud/publicConfig";
|
||||
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "../ui/sidebar";
|
||||
import { MobileClientsUserProfilePage } from "./MobileClientsUserProfilePage";
|
||||
import { useT3ConnectAuthPrompt } from "./useT3ConnectAuthPrompt";
|
||||
|
||||
export function T3ConnectSidebarSignIn() {
|
||||
@@ -31,15 +30,7 @@ function ConfiguredT3ConnectSidebarAvatar() {
|
||||
userButtonTrigger: "rounded-lg p-1 hover:bg-sidebar-accent",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<UserButton.UserProfilePage
|
||||
label="Mobile clients"
|
||||
labelIcon={<SmartphoneIcon className="size-4" />}
|
||||
url="mobile-clients"
|
||||
>
|
||||
<MobileClientsUserProfilePage />
|
||||
</UserButton.UserProfilePage>
|
||||
</UserButton>
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+179
-1
@@ -6,7 +6,13 @@ import type {
|
||||
FileDiffMetadata,
|
||||
SelectedLineRange,
|
||||
} from "@pierre/diffs";
|
||||
import { CodeView, type CodeViewHandle, type CodeViewProps } from "@pierre/diffs/react";
|
||||
import {
|
||||
CodeView,
|
||||
type CodeViewHandle,
|
||||
type CodeViewProps,
|
||||
FileDiff,
|
||||
type FileDiffProps,
|
||||
} from "@pierre/diffs/react";
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { useCallback, useMemo, useState, type ReactNode, type Ref } from "react";
|
||||
|
||||
@@ -70,6 +76,178 @@ function appendAnnotationEntry(
|
||||
);
|
||||
}
|
||||
|
||||
interface AnnotatableFileDiffProps {
|
||||
fileDiff: FileDiffMetadata;
|
||||
filePath: string;
|
||||
sectionId: string;
|
||||
sectionTitle: string;
|
||||
composerDraftTarget: ScopedThreadRef | DraftId;
|
||||
options: FileDiffProps<DiffCommentAnnotationGroup>["options"];
|
||||
renderHeaderPrefix: (fileDiff: FileDiffMetadata) => ReactNode;
|
||||
}
|
||||
|
||||
export function AnnotatableFileDiff({
|
||||
fileDiff,
|
||||
filePath,
|
||||
sectionId,
|
||||
sectionTitle,
|
||||
composerDraftTarget,
|
||||
options,
|
||||
renderHeaderPrefix,
|
||||
}: AnnotatableFileDiffProps) {
|
||||
const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
|
||||
const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
|
||||
const reviewComments = useComposerDraftStore(
|
||||
(store) => store.getComposerDraft(composerDraftTarget)?.reviewComments ?? EMPTY_REVIEW_COMMENTS,
|
||||
);
|
||||
const [selectedRange, setSelectedRange] = useState<SelectedLineRange | null>(null);
|
||||
const [draftAnnotation, setDraftAnnotation] = useState<DiffCommentLineAnnotation | null>(null);
|
||||
const persistedAnnotations = useMemo(
|
||||
() =>
|
||||
reviewComments
|
||||
.filter(
|
||||
(comment) =>
|
||||
comment.sectionId === sectionId &&
|
||||
comment.filePath === filePath &&
|
||||
(comment.fenceLanguage ?? "diff") === "diff",
|
||||
)
|
||||
.reduce<DiffCommentLineAnnotation[]>((annotations, comment) => {
|
||||
const range = restoreDiffReviewCommentRange(fileDiff, comment);
|
||||
if (!range) return annotations;
|
||||
return appendAnnotationEntry(annotations, range, {
|
||||
id: comment.id,
|
||||
kind: "comment",
|
||||
range,
|
||||
rangeLabel: comment.rangeLabel,
|
||||
text: comment.text,
|
||||
});
|
||||
}, []),
|
||||
[fileDiff, filePath, reviewComments, sectionId],
|
||||
);
|
||||
const lineAnnotations = useMemo(
|
||||
() => (draftAnnotation ? [...persistedAnnotations, draftAnnotation] : persistedAnnotations),
|
||||
[draftAnnotation, persistedAnnotations],
|
||||
);
|
||||
|
||||
const removeAnnotationEntry = useCallback(
|
||||
(entryId: string) => {
|
||||
setSelectedRange(null);
|
||||
if (
|
||||
draftAnnotation?.metadata.entries.some(
|
||||
(entry) => entry.id === entryId && entry.kind === "draft",
|
||||
)
|
||||
) {
|
||||
setDraftAnnotation(null);
|
||||
return;
|
||||
}
|
||||
removeReviewComment(composerDraftTarget, entryId);
|
||||
},
|
||||
[composerDraftTarget, draftAnnotation, removeReviewComment],
|
||||
);
|
||||
|
||||
const submitAnnotationEntry = useCallback(
|
||||
(entryId: string, text: string) => {
|
||||
const entry = draftAnnotation?.metadata.entries.find((candidate) => candidate.id === entryId);
|
||||
if (!entry) return;
|
||||
|
||||
const comment = buildDiffReviewComment({
|
||||
id: entry.id,
|
||||
sectionId,
|
||||
sectionTitle,
|
||||
filePath,
|
||||
fileDiff,
|
||||
range: entry.range,
|
||||
text,
|
||||
});
|
||||
if (comment) {
|
||||
addReviewComment(composerDraftTarget, comment);
|
||||
}
|
||||
setSelectedRange(null);
|
||||
setDraftAnnotation(null);
|
||||
},
|
||||
[
|
||||
addReviewComment,
|
||||
composerDraftTarget,
|
||||
fileDiff,
|
||||
filePath,
|
||||
draftAnnotation,
|
||||
sectionId,
|
||||
sectionTitle,
|
||||
],
|
||||
);
|
||||
|
||||
const beginComment = useCallback(
|
||||
(range: SelectedLineRange) => {
|
||||
const id = nextFileCommentId();
|
||||
const comment = buildDiffReviewComment({
|
||||
id,
|
||||
sectionId,
|
||||
sectionTitle,
|
||||
filePath,
|
||||
fileDiff,
|
||||
range,
|
||||
text: "",
|
||||
});
|
||||
if (!comment) return;
|
||||
|
||||
const draftEntry: DiffCommentAnnotationEntry = {
|
||||
id,
|
||||
kind: "draft",
|
||||
range,
|
||||
rangeLabel: comment.rangeLabel,
|
||||
text: "",
|
||||
};
|
||||
setDraftAnnotation({
|
||||
side: annotationSide(range),
|
||||
lineNumber: range.end,
|
||||
metadata: { entries: [draftEntry] },
|
||||
});
|
||||
},
|
||||
[fileDiff, filePath, sectionId, sectionTitle],
|
||||
);
|
||||
|
||||
const hasOpenCommentForm = draftAnnotation !== null;
|
||||
const handleLineSelectionEnd = useCallback(
|
||||
(range: SelectedLineRange | null) => {
|
||||
setSelectedRange(range);
|
||||
if (range) beginComment(range);
|
||||
},
|
||||
[beginComment],
|
||||
);
|
||||
|
||||
return (
|
||||
<FileDiff<DiffCommentAnnotationGroup>
|
||||
fileDiff={fileDiff}
|
||||
renderHeaderPrefix={renderHeaderPrefix}
|
||||
options={{
|
||||
...options,
|
||||
enableGutterUtility: !hasOpenCommentForm,
|
||||
enableLineSelection: !hasOpenCommentForm,
|
||||
onGutterUtilityClick: setSelectedRange,
|
||||
onLineSelectionChange: setSelectedRange,
|
||||
onLineSelectionEnd: handleLineSelectionEnd,
|
||||
}}
|
||||
selectedLines={selectedRange}
|
||||
lineAnnotations={lineAnnotations}
|
||||
renderAnnotation={(annotation) => (
|
||||
<div className="py-1">
|
||||
{annotation.metadata.entries.map((entry) => (
|
||||
<LocalCommentAnnotation
|
||||
key={entry.id}
|
||||
kind={entry.kind}
|
||||
rangeLabel={entry.rangeLabel}
|
||||
text={entry.text}
|
||||
onCancel={() => removeAnnotationEntry(entry.id)}
|
||||
onComment={(text) => submitAnnotationEntry(entry.id, text)}
|
||||
onDelete={() => removeAnnotationEntry(entry.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface AnnotatableCodeViewProps {
|
||||
files: ReadonlyArray<{
|
||||
fileDiff: FileDiffMetadata;
|
||||
@@ -18,7 +18,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview";
|
||||
import ChatMarkdown from "~/components/ChatMarkdown";
|
||||
import { OpenInPicker } from "~/components/chat/OpenInPicker";
|
||||
import { useClientSettings } from "~/hooks/useSettings";
|
||||
import { useTheme } from "~/hooks/useTheme";
|
||||
import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
|
||||
import { resolveDiffThemeName } from "~/lib/diffRendering";
|
||||
@@ -249,7 +248,6 @@ interface EditableFileSurfaceProps {
|
||||
contents: string;
|
||||
resolvedTheme: "light" | "dark";
|
||||
revealRequestId: number;
|
||||
wordWrap: boolean;
|
||||
onPostRender: FilePostRender;
|
||||
onPendingChange: (relativePath: string, pending: boolean) => void;
|
||||
}
|
||||
@@ -298,7 +296,6 @@ function EditableFileSurface({
|
||||
contents,
|
||||
resolvedTheme,
|
||||
revealRequestId,
|
||||
wordWrap,
|
||||
onPostRender,
|
||||
onPendingChange,
|
||||
}: EditableFileSurfaceProps) {
|
||||
@@ -519,7 +516,7 @@ function EditableFileSurface({
|
||||
onGutterUtilityClick: setSelectedRange,
|
||||
onLineSelectionChange: setSelectedRange,
|
||||
onLineSelectionEnd: handleLineSelectionEnd,
|
||||
overflow: wordWrap ? "wrap" : "scroll",
|
||||
overflow: "scroll",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme,
|
||||
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
|
||||
@@ -560,12 +557,7 @@ function RenderedMarkdownSurface({
|
||||
onPendingChange,
|
||||
}: Omit<
|
||||
EditableFileSurfaceProps,
|
||||
| "resolvedTheme"
|
||||
| "composerDraftTarget"
|
||||
| "revealLine"
|
||||
| "revealRequestId"
|
||||
| "wordWrap"
|
||||
| "onPostRender"
|
||||
"resolvedTheme" | "composerDraftTarget" | "revealLine" | "revealRequestId" | "onPostRender"
|
||||
> & {
|
||||
threadRef: ScopedThreadRef;
|
||||
}) {
|
||||
@@ -621,7 +613,6 @@ export default function FilePreviewPanel({
|
||||
onPendingChange,
|
||||
}: FilePreviewPanelProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const wordWrap = useClientSettings((settings) => settings.wordWrap);
|
||||
const primaryEnvironmentId = usePrimaryEnvironmentId();
|
||||
const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
|
||||
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
|
||||
@@ -853,7 +844,7 @@ export default function FilePreviewPanel({
|
||||
}}
|
||||
options={{
|
||||
disableFileHeader: true,
|
||||
overflow: wordWrap ? "wrap" : "scroll",
|
||||
overflow: "scroll",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme,
|
||||
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
|
||||
@@ -872,7 +863,6 @@ export default function FilePreviewPanel({
|
||||
contents={file.data.contents}
|
||||
resolvedTheme={resolvedTheme}
|
||||
revealRequestId={revealRequestId}
|
||||
wordWrap={wordWrap}
|
||||
onPostRender={onFilePostRender}
|
||||
onPendingChange={onPendingChange}
|
||||
/>
|
||||
|
||||
@@ -118,7 +118,6 @@ import { hasCloudPublicConfig } from "~/cloud/publicConfig";
|
||||
import {
|
||||
linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,
|
||||
unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,
|
||||
updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,
|
||||
} from "~/cloud/linkEnvironmentAtoms";
|
||||
import { authEnvironment } from "~/state/auth";
|
||||
import { environmentCatalog } from "~/connection/catalog";
|
||||
@@ -1424,31 +1423,6 @@ function SavedBackendListRow({
|
||||
: "bg-muted-foreground/40";
|
||||
const statusTooltip = connectionStatusText(environment.connection);
|
||||
const errorTraceId = environment.connection.traceId;
|
||||
const { copyToClipboard: copyTraceIdToClipboard } = useCopyToClipboard<{ traceId: string }>({
|
||||
target: "trace ID",
|
||||
onCopy: ({ traceId }) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Trace ID copied",
|
||||
description: traceId,
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not copy trace ID",
|
||||
description: error.message,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
const copyTraceId = useCallback(
|
||||
(traceId: string) => {
|
||||
copyTraceIdToClipboard(traceId, { traceId });
|
||||
},
|
||||
[copyTraceIdToClipboard],
|
||||
);
|
||||
const versionMismatch = resolveServerConfigVersionMismatch(environment.serverConfig);
|
||||
const sshTarget =
|
||||
environment.entry.target._tag === "SshConnectionTarget" &&
|
||||
@@ -1458,7 +1432,7 @@ function SavedBackendListRow({
|
||||
: null;
|
||||
const metadataBits = [
|
||||
sshTarget ? `SSH ${formatDesktopSshTarget(sshTarget)}` : null,
|
||||
environment.relayManaged ? "T3 Connect" : null,
|
||||
environment.relayManaged ? "T3 Cloud" : null,
|
||||
].filter((value): value is string => value !== null);
|
||||
|
||||
return (
|
||||
@@ -1494,7 +1468,7 @@ function SavedBackendListRow({
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 underline underline-offset-2"
|
||||
onClick={() => copyTraceId(errorTraceId)}
|
||||
onClick={() => void navigator.clipboard.writeText(errorTraceId)}
|
||||
>
|
||||
Copy trace ID
|
||||
</button>
|
||||
@@ -1576,7 +1550,7 @@ function CloudLinkSwitch({
|
||||
}) {
|
||||
const control = (
|
||||
<Switch
|
||||
aria-label="Enable T3 Connect"
|
||||
aria-label="Enable T3 Cloud"
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
{...(onCheckedChange ? { onCheckedChange } : {})}
|
||||
@@ -1603,23 +1577,18 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
|
||||
const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {
|
||||
reportFailure: false,
|
||||
});
|
||||
const updatePrimaryEnvironmentPreferences = useAtomCommand(
|
||||
updatePrimaryEnvironmentPreferencesAtom,
|
||||
{ reportFailure: false },
|
||||
);
|
||||
const primaryCloudLinkState = usePrimaryCloudLinkState();
|
||||
const [operationError, setOperationError] = useState<string | null>(null);
|
||||
const [isUpdating, setIsUpdating] = useState(false);
|
||||
const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
|
||||
|
||||
const reportUpdateFailure = (cause: unknown) => {
|
||||
const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
|
||||
const message = cause instanceof Error ? cause.message : "Could not update T3 Cloud access.";
|
||||
const traceId = findErrorTraceId(cause);
|
||||
console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
|
||||
console.error("[t3-cloud] Could not update T3 Cloud", { message, traceId, cause });
|
||||
setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not update T3 Connect",
|
||||
title: "Could not update T3 Cloud",
|
||||
description: message,
|
||||
data: traceId
|
||||
? {
|
||||
@@ -1649,7 +1618,9 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
|
||||
return;
|
||||
}
|
||||
if (enabled && !tokenResult.value) {
|
||||
reportUpdateFailure(new Error("Sign in to T3 Connect before linking this environment."));
|
||||
reportUpdateFailure(
|
||||
new Error("Sign in from T3 Cloud settings before linking this environment."),
|
||||
);
|
||||
setIsUpdating(false);
|
||||
return;
|
||||
}
|
||||
@@ -1684,95 +1655,38 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
|
||||
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: enabled ? "T3 Connect linked" : "T3 Connect unlinked",
|
||||
title: enabled ? "T3 Cloud linked" : "T3 Cloud unlinked",
|
||||
description: enabled
|
||||
? "This environment is available through T3 Connect."
|
||||
: "This environment is no longer available through T3 Connect.",
|
||||
? "This environment is available through T3 Cloud."
|
||||
: "This environment is no longer available through T3 Cloud.",
|
||||
});
|
||||
setIsUpdating(false);
|
||||
};
|
||||
|
||||
const updatePublishAgentActivity = async (enabled: boolean) => {
|
||||
const target = primaryCloudLinkState.target;
|
||||
if (!target) {
|
||||
reportUpdateFailure(new Error("Local environment is not ready yet."));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsUpdatingPreference(true);
|
||||
setOperationError(null);
|
||||
const updateResult = await updatePrimaryEnvironmentPreferences({
|
||||
target,
|
||||
publishAgentActivity: enabled,
|
||||
});
|
||||
if (updateResult._tag === "Failure") {
|
||||
if (!isAtomCommandInterrupted(updateResult)) {
|
||||
reportUpdateFailure(squashAtomCommandFailure(updateResult));
|
||||
}
|
||||
setIsUpdatingPreference(false);
|
||||
return;
|
||||
}
|
||||
|
||||
primaryCloudLinkState.refresh();
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: enabled ? "Agent activity enabled" : "Agent activity disabled",
|
||||
description: enabled
|
||||
? "This environment can publish agent activity to your mobile clients."
|
||||
: "This environment will stop publishing agent activity.",
|
||||
});
|
||||
setIsUpdatingPreference(false);
|
||||
};
|
||||
const disabledReason = !isSignedIn
|
||||
? "Sign in to T3 Connect to manage this environment."
|
||||
? "Sign in from T3 Cloud settings to manage this environment."
|
||||
: !canManageRelay
|
||||
? "Your session does not have permission to manage T3 Connect access."
|
||||
? "Your session does not have permission to manage T3 Cloud access."
|
||||
: null;
|
||||
const linked = primaryCloudLinkState.data?.linked ?? false;
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsRow
|
||||
title="T3 Connect"
|
||||
description={
|
||||
linked
|
||||
? "This environment is available to your other devices through T3 Connect."
|
||||
: "Make this environment available to your other devices through T3 Connect."
|
||||
}
|
||||
status={operationError ?? primaryCloudLinkState.error}
|
||||
control={
|
||||
<CloudLinkSwitch
|
||||
checked={linked}
|
||||
disabled={
|
||||
!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isUpdating
|
||||
}
|
||||
disabledReason={disabledReason}
|
||||
onCheckedChange={(enabled) => void updateLink(enabled)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{linked ? (
|
||||
<SettingsRow
|
||||
title="Publish agent activity"
|
||||
description="Send activity from this environment to your mobile clients for push notifications and Live Activities."
|
||||
className="bg-muted/20 pl-7 sm:pl-8"
|
||||
control={
|
||||
<Switch
|
||||
aria-label="Publish agent activity to mobile clients"
|
||||
checked={primaryCloudLinkState.data?.publishAgentActivity ?? false}
|
||||
disabled={
|
||||
!canManageRelay ||
|
||||
!isSignedIn ||
|
||||
primaryCloudLinkState.isPending ||
|
||||
isUpdating ||
|
||||
isUpdatingPreference
|
||||
}
|
||||
onCheckedChange={(enabled) => void updatePublishAgentActivity(enabled)}
|
||||
/>
|
||||
}
|
||||
<SettingsRow
|
||||
title="T3 Cloud"
|
||||
description={
|
||||
linked
|
||||
? "This environment is available to your other devices through T3 Cloud."
|
||||
: "Make this environment available to your other devices through T3 Cloud."
|
||||
}
|
||||
status={operationError ?? primaryCloudLinkState.error}
|
||||
control={
|
||||
<CloudLinkSwitch
|
||||
checked={linked}
|
||||
disabled={!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isUpdating}
|
||||
disabledReason={disabledReason}
|
||||
onCheckedChange={(enabled) => void updateLink(enabled)}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1790,7 +1704,7 @@ function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnable
|
||||
<EmptyTitle>No saved remote environments</EmptyTitle>
|
||||
<EmptyDescription>
|
||||
{cloudEnabled
|
||||
? "Click “Add environment” to pair another environment, or connect one from T3 Connect."
|
||||
? "Click “Add environment” to pair another environment, or connect one from T3 Cloud."
|
||||
: "Click “Add environment” to pair another environment."}
|
||||
</EmptyDescription>
|
||||
</EmptyHeader>
|
||||
@@ -1855,7 +1769,7 @@ function ConfiguredCloudRemoteEnvironmentRows({
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Environment connected",
|
||||
description: `${environment.label} is available through T3 Connect.`,
|
||||
description: `${environment.label} is available through T3 Cloud.`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -1864,9 +1778,9 @@ function ConfiguredCloudRemoteEnvironmentRows({
|
||||
}
|
||||
const cause = squashAtomCommandFailure(result);
|
||||
const message =
|
||||
cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.";
|
||||
cause instanceof Error ? cause.message : "Could not connect the T3 Cloud environment.";
|
||||
const traceId = findErrorTraceId(cause);
|
||||
console.error("[t3-connect] Could not connect environment", { message, traceId, cause });
|
||||
console.error("[t3-cloud] Could not connect environment", { message, traceId, cause });
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not connect environment",
|
||||
|
||||
@@ -391,7 +391,9 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.sidebarThreadPreviewCount !== DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount
|
||||
? ["Visible threads"]
|
||||
: []),
|
||||
...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []),
|
||||
...(settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap
|
||||
? ["Diff line wrapping"]
|
||||
: []),
|
||||
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
|
||||
? ["Diff whitespace changes"]
|
||||
: []),
|
||||
@@ -432,11 +434,11 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.newWorktreesStartFromOrigin,
|
||||
settings.diffIgnoreWhitespace,
|
||||
settings.diffWordWrap,
|
||||
settings.automaticGitFetchInterval,
|
||||
settings.enableAssistantStreaming,
|
||||
settings.sidebarThreadPreviewCount,
|
||||
settings.timestampFormat,
|
||||
settings.wordWrap,
|
||||
theme,
|
||||
],
|
||||
);
|
||||
@@ -454,7 +456,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
setTheme("system");
|
||||
updateSettings({
|
||||
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
|
||||
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
|
||||
diffWordWrap: DEFAULT_UNIFIED_SETTINGS.diffWordWrap,
|
||||
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
|
||||
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
|
||||
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
|
||||
@@ -592,15 +594,15 @@ export function GeneralSettingsPanel() {
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Word wrap"
|
||||
description="Wrap long lines in code blocks, tables, diffs, and file previews by default."
|
||||
title="Diff line wrapping"
|
||||
description="Set the default wrap state when the diff panel opens."
|
||||
resetAction={
|
||||
settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? (
|
||||
settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap ? (
|
||||
<SettingResetButton
|
||||
label="word wrapping"
|
||||
label="diff line wrapping"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
|
||||
diffWordWrap: DEFAULT_UNIFIED_SETTINGS.diffWordWrap,
|
||||
})
|
||||
}
|
||||
/>
|
||||
@@ -608,9 +610,9 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.wordWrap}
|
||||
onCheckedChange={(checked) => updateSettings({ wordWrap: Boolean(checked) })}
|
||||
aria-label="Wrap code, tables, diffs, and file previews by default"
|
||||
checked={settings.diffWordWrap}
|
||||
onCheckedChange={(checked) => updateSettings({ diffWordWrap: Boolean(checked) })}
|
||||
aria-label="Wrap diff lines by default"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -6,9 +6,7 @@ import {
|
||||
SidebarMenuButton,
|
||||
SidebarMenuSubButton,
|
||||
SidebarProvider,
|
||||
SidebarTrigger,
|
||||
} from "./sidebar";
|
||||
import { resolveSidebarState } from "./sidebarState";
|
||||
|
||||
function renderSidebarButton(className?: string) {
|
||||
return renderToStaticMarkup(
|
||||
@@ -19,37 +17,6 @@ function renderSidebarButton(className?: string) {
|
||||
}
|
||||
|
||||
describe("sidebar interactive cursors", () => {
|
||||
it("uses mobile sheet visibility for the shared responsive state", () => {
|
||||
expect(resolveSidebarState({ isMobile: true, open: true, openMobile: false })).toBe(
|
||||
"collapsed",
|
||||
);
|
||||
expect(resolveSidebarState({ isMobile: true, open: false, openMobile: true })).toBe("expanded");
|
||||
expect(resolveSidebarState({ isMobile: false, open: true, openMobile: false })).toBe(
|
||||
"expanded",
|
||||
);
|
||||
});
|
||||
|
||||
it("exposes collapsed state for shared titlebar inset styling", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SidebarProvider defaultOpen={false}>
|
||||
<div />
|
||||
</SidebarProvider>,
|
||||
);
|
||||
|
||||
expect(html).toContain('data-sidebar-state="collapsed"');
|
||||
});
|
||||
|
||||
it("keeps the sidebar trigger interactive inside Electron drag regions", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SidebarProvider>
|
||||
<SidebarTrigger />
|
||||
</SidebarProvider>,
|
||||
);
|
||||
|
||||
expect(html).toContain("[-webkit-app-region:no-drag]");
|
||||
expect(html).toContain("size-[var(--workspace-titlebar-control-size)]!");
|
||||
});
|
||||
|
||||
it("uses a pointer cursor for menu buttons by default", () => {
|
||||
const html = renderSidebarButton();
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ import { Skeleton } from "~/components/ui/skeleton";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
|
||||
import { useIsMobile } from "~/hooks/useMediaQuery";
|
||||
import { getLocalStorageItem, setLocalStorageItem } from "~/hooks/useLocalStorage";
|
||||
import { resolveSidebarState, type ResponsiveSidebarState } from "./sidebarState";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state";
|
||||
@@ -30,7 +29,7 @@ const SIDEBAR_WIDTH_ICON = "3rem";
|
||||
const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16;
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: ResponsiveSidebarState;
|
||||
state: "expanded" | "collapsed";
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
openMobile: boolean;
|
||||
@@ -86,11 +85,6 @@ function useSidebar() {
|
||||
return context;
|
||||
}
|
||||
|
||||
function useSidebarVisibility() {
|
||||
const { isMobile, open, openMobile } = useSidebar();
|
||||
return isMobile ? openMobile : open;
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
defaultOpen = true,
|
||||
open: openProp,
|
||||
@@ -138,7 +132,7 @@ function SidebarProvider({
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = resolveSidebarState({ isMobile, open, openMobile });
|
||||
const state = open ? "expanded" : "collapsed";
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
@@ -160,7 +154,6 @@ function SidebarProvider({
|
||||
"group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
|
||||
className,
|
||||
)}
|
||||
data-sidebar-state={state}
|
||||
data-slot="sidebar-wrapper"
|
||||
style={
|
||||
{
|
||||
@@ -317,18 +310,13 @@ function Sidebar({
|
||||
}
|
||||
|
||||
function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar();
|
||||
const isOpen = useSidebarVisibility();
|
||||
const { toggleSidebar, openMobile } = useSidebar();
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={cn(
|
||||
"size-[var(--workspace-titlebar-control-size)]! [-webkit-app-region:no-drag]",
|
||||
className,
|
||||
)}
|
||||
className={cn("size-7", className)}
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
aria-pressed={isOpen}
|
||||
onClick={(event) => {
|
||||
onClick?.(event);
|
||||
toggleSidebar();
|
||||
@@ -337,7 +325,7 @@ function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<t
|
||||
variant="ghost"
|
||||
{...props}
|
||||
>
|
||||
{isOpen ? <PanelLeftCloseIcon /> : <PanelLeftIcon />}
|
||||
{openMobile ? <PanelLeftCloseIcon /> : <PanelLeftIcon />}
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
);
|
||||
@@ -1016,5 +1004,4 @@ export {
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
useSidebarVisibility,
|
||||
};
|
||||
@@ -1,9 +0,0 @@
|
||||
export type ResponsiveSidebarState = "expanded" | "collapsed";
|
||||
|
||||
export function resolveSidebarState(input: {
|
||||
isMobile: boolean;
|
||||
open: boolean;
|
||||
openMobile: boolean;
|
||||
}): ResponsiveSidebarState {
|
||||
return (input.isMobile ? input.openMobile : input.open) ? "expanded" : "collapsed";
|
||||
}
|
||||
@@ -70,7 +70,10 @@ describe("makeCatalogBackend", () => {
|
||||
const error = yield* backend.write("{}").pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(ConnectionTransientError);
|
||||
expect(error.message).toContain("Desktop secure storage is unavailable");
|
||||
expect(error.message).toBe("Could not save the local connection catalog.");
|
||||
expect(error.cause).toEqual(
|
||||
new Error("Desktop secure storage is unavailable in this system context."),
|
||||
);
|
||||
expect(setConnectionCatalog).toHaveBeenCalledWith("{}");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -63,26 +63,8 @@ const encodeStoredThreadSnapshot = Schema.encodeEffect(StoredThreadSnapshotJson)
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
function persistenceError(
|
||||
operation:
|
||||
| "list-targets"
|
||||
| "register-connection"
|
||||
| "remove-connection"
|
||||
| "load-shell"
|
||||
| "save-shell"
|
||||
| "load-thread"
|
||||
| "save-thread"
|
||||
| "remove-thread"
|
||||
| "clear-environment",
|
||||
cause: unknown,
|
||||
) {
|
||||
return new ConnectionPersistenceError({
|
||||
operation,
|
||||
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
|
||||
detail: `Could not ${operation} the local connection catalog.`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -233,7 +215,7 @@ export function makeCatalogBackend(database: IDBDatabase): CatalogBackend {
|
||||
: Effect.fail(
|
||||
catalogError(
|
||||
"save",
|
||||
"Desktop secure storage is unavailable in this system context.",
|
||||
new Error("Desktop secure storage is unavailable in this system context."),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -330,18 +312,29 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
const targetStore = ConnectionTargetStore.of({
|
||||
list: catalog.read.pipe(
|
||||
Effect.map((document) => document.targets),
|
||||
Effect.mapError((cause) => persistenceError("list-targets", cause)),
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "list-targets", cause }),
|
||||
),
|
||||
),
|
||||
});
|
||||
const registrationStore = ConnectionRegistrationStore.of({
|
||||
register: (registration) =>
|
||||
catalog
|
||||
.update((document) => registerConnectionInCatalog(document, registration))
|
||||
.pipe(Effect.mapError((cause) => persistenceError("register-connection", cause))),
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ConnectionPersistenceError({ operation: "register-connection", cause }),
|
||||
),
|
||||
),
|
||||
remove: (target) =>
|
||||
catalog
|
||||
.update((document) => removeConnectionFromCatalog(document, target))
|
||||
.pipe(Effect.mapError((cause) => persistenceError("remove-connection", cause))),
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "remove-connection", cause }),
|
||||
),
|
||||
),
|
||||
});
|
||||
const profileStore = ProfileStore.make({
|
||||
get: (connectionId) =>
|
||||
@@ -430,7 +423,9 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return decodeStoredShellSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-shell", cause)),
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
@@ -441,7 +436,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: persistenceError("load-shell", cause),
|
||||
: new ConnectionPersistenceError({ operation: "load-shell", cause }),
|
||||
),
|
||||
),
|
||||
saveShell: (environmentId, snapshot) =>
|
||||
@@ -450,13 +445,17 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
),
|
||||
);
|
||||
yield* writeDatabaseValue(database, SHELL_STORE_NAME, environmentId, encoded);
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: persistenceError("save-shell", cause),
|
||||
: new ConnectionPersistenceError({ operation: "save-shell", cause }),
|
||||
),
|
||||
),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
@@ -470,7 +469,9 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return decodeStoredThreadSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-thread", cause)),
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
@@ -481,7 +482,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: persistenceError("load-thread", cause),
|
||||
: new ConnectionPersistenceError({ operation: "load-thread", cause }),
|
||||
),
|
||||
),
|
||||
saveThread: (environmentId, thread) =>
|
||||
@@ -491,7 +492,11 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
thread,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
),
|
||||
);
|
||||
yield* writeDatabaseValue(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
@@ -502,7 +507,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: persistenceError("save-thread", cause),
|
||||
: new ConnectionPersistenceError({ operation: "save-thread", cause }),
|
||||
),
|
||||
),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
@@ -510,7 +515,11 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
threadCacheKey(environmentId, threadId),
|
||||
).pipe(Effect.mapError((cause) => persistenceError("remove-thread", cause))),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "remove-thread", cause }),
|
||||
),
|
||||
),
|
||||
clear: (environmentId) =>
|
||||
Effect.all(
|
||||
[
|
||||
@@ -522,7 +531,11 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
).pipe(Effect.mapError((cause) => persistenceError("clear-environment", cause))),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new ConnectionPersistenceError({ operation: "clear-environment", cause }),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
return Context.make(ConnectionTargetStore, targetStore).pipe(
|
||||
|
||||
@@ -40,6 +40,7 @@ export class PrimaryEnvironmentRequestError extends Schema.TaggedErrorClass<Prim
|
||||
{
|
||||
operation: PrimaryEnvironmentRequestOperation,
|
||||
status: Schema.Number,
|
||||
detail: Schema.String,
|
||||
pairingLinkId: Schema.optional(Schema.String),
|
||||
sessionId: Schema.optional(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
@@ -48,13 +49,17 @@ export class PrimaryEnvironmentRequestError extends Schema.TaggedErrorClass<Prim
|
||||
static fromCause(input: {
|
||||
readonly operation: PrimaryEnvironmentRequestOperation;
|
||||
readonly cause: unknown;
|
||||
readonly fallbackMessage: (status: number) => string;
|
||||
readonly formatDetail?: (detail: string, status: number) => string;
|
||||
readonly pairingLinkId?: string;
|
||||
readonly sessionId?: string;
|
||||
}): PrimaryEnvironmentRequestError {
|
||||
const status = readHttpApiStatus(input.cause) ?? 500;
|
||||
const rawDetail = readHttpApiErrorMessage(input.cause, input.fallbackMessage(status));
|
||||
return new PrimaryEnvironmentRequestError({
|
||||
operation: input.operation,
|
||||
status,
|
||||
detail: input.formatDetail?.(rawDetail, status) ?? rawDetail,
|
||||
...(input.pairingLinkId !== undefined ? { pairingLinkId: input.pairingLinkId } : {}),
|
||||
...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),
|
||||
cause: input.cause,
|
||||
@@ -62,59 +67,11 @@ export class PrimaryEnvironmentRequestError extends Schema.TaggedErrorClass<Prim
|
||||
}
|
||||
|
||||
override get message(): string {
|
||||
return `Primary environment request failed during ${this.operation} (HTTP ${this.status}).`;
|
||||
return this.detail;
|
||||
}
|
||||
}
|
||||
|
||||
export const isPrimaryEnvironmentRequestError = Schema.is(PrimaryEnvironmentRequestError);
|
||||
|
||||
export class PrimaryEnvironmentPairingCredentialRejectedError extends Schema.TaggedErrorClass<PrimaryEnvironmentPairingCredentialRejectedError>()(
|
||||
"PrimaryEnvironmentPairingCredentialRejectedError",
|
||||
{
|
||||
providedLength: Schema.Number,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Invalid pairing token. Check the token and try again.";
|
||||
}
|
||||
}
|
||||
|
||||
export const isPrimaryEnvironmentPairingCredentialRejectedError = Schema.is(
|
||||
PrimaryEnvironmentPairingCredentialRejectedError,
|
||||
);
|
||||
|
||||
export class PrimaryEnvironmentAuthSessionTimeoutError extends Schema.TaggedErrorClass<PrimaryEnvironmentAuthSessionTimeoutError>()(
|
||||
"PrimaryEnvironmentAuthSessionTimeoutError",
|
||||
{
|
||||
timeoutMs: Schema.Number,
|
||||
elapsedMs: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Timed out waiting for authenticated session after bootstrap.";
|
||||
}
|
||||
}
|
||||
|
||||
export const isPrimaryEnvironmentAuthSessionTimeoutError = Schema.is(
|
||||
PrimaryEnvironmentAuthSessionTimeoutError,
|
||||
);
|
||||
|
||||
export class PrimaryEnvironmentPairingCredentialRequiredError extends Schema.TaggedErrorClass<PrimaryEnvironmentPairingCredentialRequiredError>()(
|
||||
"PrimaryEnvironmentPairingCredentialRequiredError",
|
||||
{
|
||||
providedLength: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Enter a pairing token to continue.";
|
||||
}
|
||||
}
|
||||
|
||||
export const isPrimaryEnvironmentPairingCredentialRequiredError = Schema.is(
|
||||
PrimaryEnvironmentPairingCredentialRequiredError,
|
||||
);
|
||||
|
||||
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
|
||||
|
||||
export interface ServerPairingLinkRecord {
|
||||
@@ -194,6 +151,7 @@ export async function fetchSessionState(): Promise<AuthSessionState> {
|
||||
throw PrimaryEnvironmentRequestError.fromCause({
|
||||
operation: "fetch-session-state",
|
||||
cause: error,
|
||||
fallbackMessage: (status) => `Failed to load server auth session state (${status}).`,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -222,6 +180,42 @@ function readEnvironmentHttpErrorStatus(error: EnvironmentHttpCommonErrorType):
|
||||
}
|
||||
}
|
||||
|
||||
function readHttpApiErrorMessage(error: unknown, fallbackMessage: string): string {
|
||||
if (!isEnvironmentHttpCommonError(error)) {
|
||||
return fallbackMessage;
|
||||
}
|
||||
switch (error._tag) {
|
||||
case "EnvironmentAuthInvalidError":
|
||||
return error.reason === "missing_credential"
|
||||
? "Authentication required."
|
||||
: "Invalid bootstrap credential.";
|
||||
case "EnvironmentRequestInvalidError":
|
||||
return error.reason === "invalid_scope"
|
||||
? "Requested token scope is invalid."
|
||||
: "Requested scope exceeds the bootstrap credential grant.";
|
||||
case "EnvironmentScopeRequiredError":
|
||||
return `The authenticated token is missing required scope: ${error.requiredScope}.`;
|
||||
case "EnvironmentOperationForbiddenError":
|
||||
return "This operation is not allowed for the current session.";
|
||||
case "EnvironmentInternalError":
|
||||
return fallbackMessage;
|
||||
}
|
||||
}
|
||||
|
||||
const INVALID_BOOTSTRAP_CREDENTIAL_MESSAGES = new Set([
|
||||
"Invalid bootstrap credential.",
|
||||
"Unknown bootstrap credential.",
|
||||
]);
|
||||
|
||||
function toFriendlyBootstrapErrorMessage(status: number, message: string): string {
|
||||
const trimmedMessage = message.trim();
|
||||
if (status === 401 && INVALID_BOOTSTRAP_CREDENTIAL_MESSAGES.has(trimmedMessage)) {
|
||||
return "Invalid pairing token. Check the token and try again.";
|
||||
}
|
||||
|
||||
return trimmedMessage;
|
||||
}
|
||||
|
||||
async function exchangeBootstrapCredential(credential: string): Promise<AuthBrowserSessionResult> {
|
||||
return retryTransientBootstrap(async () => {
|
||||
try {
|
||||
@@ -231,19 +225,11 @@ async function exchangeBootstrapCredential(credential: string): Promise<AuthBrow
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
if (
|
||||
isEnvironmentHttpCommonError(error) &&
|
||||
error._tag === "EnvironmentAuthInvalidError" &&
|
||||
error.reason === "invalid_credential"
|
||||
) {
|
||||
throw new PrimaryEnvironmentPairingCredentialRejectedError({
|
||||
providedLength: credential.length,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
throw PrimaryEnvironmentRequestError.fromCause({
|
||||
operation: "exchange-bootstrap-credential",
|
||||
cause: error,
|
||||
fallbackMessage: (status) => `Failed to bootstrap auth session (${status}).`,
|
||||
formatDetail: (detail, status) => toFriendlyBootstrapErrorMessage(status, detail),
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -258,12 +244,8 @@ async function waitForAuthenticatedSessionAfterBootstrap(): Promise<AuthSessionS
|
||||
return session;
|
||||
}
|
||||
|
||||
const elapsedMs = Date.now() - startedAt;
|
||||
if (elapsedMs >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
|
||||
throw new PrimaryEnvironmentAuthSessionTimeoutError({
|
||||
timeoutMs: AUTH_SESSION_ESTABLISH_TIMEOUT_MS,
|
||||
elapsedMs,
|
||||
});
|
||||
if (Date.now() - startedAt >= AUTH_SESSION_ESTABLISH_TIMEOUT_MS) {
|
||||
throw new Error("Timed out waiting for authenticated session after bootstrap.");
|
||||
}
|
||||
|
||||
await waitForBootstrapRetry(AUTH_SESSION_ESTABLISH_STEP_MS);
|
||||
@@ -341,9 +323,7 @@ async function bootstrapServerAuth(): Promise<ServerAuthGateState> {
|
||||
export async function submitServerAuthCredential(credential: string): Promise<void> {
|
||||
const trimmedCredential = credential.trim();
|
||||
if (!trimmedCredential) {
|
||||
throw new PrimaryEnvironmentPairingCredentialRequiredError({
|
||||
providedLength: credential.length,
|
||||
});
|
||||
throw new Error("Enter a pairing token to continue.");
|
||||
}
|
||||
|
||||
resolvedAuthenticatedGateState = null;
|
||||
@@ -375,6 +355,7 @@ export async function createServerPairingCredential(input?: {
|
||||
throw PrimaryEnvironmentRequestError.fromCause({
|
||||
operation: "create-pairing-credential",
|
||||
cause: error,
|
||||
fallbackMessage: (status) => `Failed to create pairing credential (${status}).`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -415,6 +396,7 @@ export async function listServerPairingLinks(): Promise<ReadonlyArray<ServerPair
|
||||
throw PrimaryEnvironmentRequestError.fromCause({
|
||||
operation: "list-pairing-links",
|
||||
cause: error,
|
||||
fallbackMessage: (status) => `Failed to load pairing links (${status}).`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -431,6 +413,7 @@ export async function revokeServerPairingLink(id: string): Promise<void> {
|
||||
operation: "revoke-pairing-link",
|
||||
pairingLinkId: id,
|
||||
cause: error,
|
||||
fallbackMessage: (status) => `Failed to revoke pairing link (${status}).`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -463,6 +446,7 @@ export async function listServerClientSessions(): Promise<
|
||||
throw PrimaryEnvironmentRequestError.fromCause({
|
||||
operation: "list-client-sessions",
|
||||
cause: error,
|
||||
fallbackMessage: (status) => `Failed to load paired clients (${status}).`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -481,6 +465,7 @@ export async function revokeServerClientSession(sessionId: AuthSessionId): Promi
|
||||
operation: "revoke-client-session",
|
||||
sessionId,
|
||||
cause: error,
|
||||
fallbackMessage: (status) => `Failed to revoke client session (${status}).`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -497,6 +482,7 @@ export async function revokeOtherServerClientSessions(): Promise<number> {
|
||||
throw PrimaryEnvironmentRequestError.fromCause({
|
||||
operation: "revoke-other-client-sessions",
|
||||
cause: error,
|
||||
fallbackMessage: (status) => `Failed to revoke other client sessions (${status}).`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ async function fetchPrimaryEnvironmentDescriptor(): Promise<ExecutionEnvironment
|
||||
throw PrimaryEnvironmentRequestError.fromCause({
|
||||
operation: "fetch-environment-descriptor",
|
||||
cause: error,
|
||||
fallbackMessage: (status) => `Failed to load server environment descriptor (${status}).`,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -16,12 +16,10 @@ export {
|
||||
export {
|
||||
createServerPairingCredential,
|
||||
fetchSessionState,
|
||||
isPrimaryEnvironmentPairingCredentialRejectedError,
|
||||
isPrimaryEnvironmentRequestError,
|
||||
listServerClientSessions,
|
||||
listServerPairingLinks,
|
||||
peekPairingTokenFromUrl,
|
||||
PrimaryEnvironmentPairingCredentialRejectedError,
|
||||
PrimaryEnvironmentRequestError,
|
||||
resolveInitialServerAuthGateState,
|
||||
revokeOtherServerClientSessions,
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
function createStorage(overrides: Partial<Storage> = {}): Storage {
|
||||
const store = new Map<string, string>();
|
||||
return {
|
||||
clear: () => store.clear(),
|
||||
getItem: (key) => store.get(key) ?? null,
|
||||
key: (index) => [...store.keys()][index] ?? null,
|
||||
get length() {
|
||||
return store.size;
|
||||
},
|
||||
removeItem: (key) => {
|
||||
store.delete(key);
|
||||
},
|
||||
setItem: (key, value) => {
|
||||
store.set(key, value);
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.doUnmock("react");
|
||||
vi.resetModules();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("theme failure handling", () => {
|
||||
it("preserves exact storage causes and operation context", async () => {
|
||||
const readCause = new Error("storage read blocked");
|
||||
const writeCause = new Error("storage quota exceeded");
|
||||
vi.stubGlobal("window", {
|
||||
localStorage: createStorage({
|
||||
getItem: () => {
|
||||
throw readCause;
|
||||
},
|
||||
setItem: () => {
|
||||
throw writeCause;
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const { readThemePreference, ThemeStorageError, writeThemePreference } =
|
||||
await import("./useTheme");
|
||||
|
||||
try {
|
||||
readThemePreference();
|
||||
expect.unreachable("expected the theme read to fail");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ThemeStorageError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "read",
|
||||
storageKey: "t3code:theme",
|
||||
cause: readCause,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
writeThemePreference("dark");
|
||||
expect.unreachable("expected the theme write to fail");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ThemeStorageError);
|
||||
expect(error).toMatchObject({
|
||||
operation: "write",
|
||||
storageKey: "t3code:theme",
|
||||
theme: "dark",
|
||||
cause: writeCause,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back during initial theme application and logs only safe attributes", async () => {
|
||||
const cause = new Error("private browsing storage failure");
|
||||
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
vi.stubGlobal("window", {
|
||||
localStorage: createStorage({
|
||||
getItem: () => {
|
||||
throw cause;
|
||||
},
|
||||
}),
|
||||
matchMedia: () => ({ matches: false }),
|
||||
});
|
||||
vi.stubGlobal("document", {
|
||||
documentElement: {
|
||||
classList: { toggle: vi.fn() },
|
||||
},
|
||||
});
|
||||
|
||||
await expect(import("./useTheme")).resolves.toBeDefined();
|
||||
|
||||
expect(errorLog).toHaveBeenCalledWith(
|
||||
"Failed to read theme preference for t3code:theme.",
|
||||
expect.objectContaining({
|
||||
operation: "read",
|
||||
storageKey: "t3code:theme",
|
||||
errorTag: "ThemeStorageError",
|
||||
}),
|
||||
);
|
||||
const attributes = errorLog.mock.calls[0]?.[1];
|
||||
expect(attributes).not.toHaveProperty("cause");
|
||||
expect(JSON.stringify(attributes)).not.toContain(cause.message);
|
||||
});
|
||||
|
||||
it("retries a failed storage read only after a relevant storage event", async () => {
|
||||
const cause = new Error("persistent storage failure");
|
||||
const getItem = vi.fn(() => {
|
||||
throw cause;
|
||||
});
|
||||
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
let readSnapshot: (() => unknown) | undefined;
|
||||
let subscribeToTheme: ((listener: () => void) => () => void) | undefined;
|
||||
let storageHandler: ((event: StorageEvent) => void) | undefined;
|
||||
vi.doMock("react", () => ({
|
||||
useCallback: <A>(callback: A) => callback,
|
||||
useEffect: () => undefined,
|
||||
useSyncExternalStore: (
|
||||
subscribe: (listener: () => void) => () => void,
|
||||
getSnapshot: () => unknown,
|
||||
) => {
|
||||
subscribeToTheme = subscribe;
|
||||
readSnapshot = getSnapshot;
|
||||
return getSnapshot();
|
||||
},
|
||||
}));
|
||||
vi.stubGlobal("window", {
|
||||
addEventListener: (type: string, listener: (event: StorageEvent) => void) => {
|
||||
if (type === "storage") storageHandler = listener;
|
||||
},
|
||||
localStorage: createStorage({ getItem }),
|
||||
matchMedia: () => ({
|
||||
matches: false,
|
||||
addEventListener: () => undefined,
|
||||
removeEventListener: () => undefined,
|
||||
}),
|
||||
removeEventListener: () => undefined,
|
||||
});
|
||||
|
||||
const { useTheme } = await import("./useTheme");
|
||||
useTheme();
|
||||
readSnapshot?.();
|
||||
readSnapshot?.();
|
||||
|
||||
expect(getItem).toHaveBeenCalledTimes(1);
|
||||
expect(errorLog).toHaveBeenCalledTimes(1);
|
||||
|
||||
const unsubscribe = subscribeToTheme?.(() => undefined);
|
||||
storageHandler?.({ key: "t3code:theme" } as StorageEvent);
|
||||
readSnapshot?.();
|
||||
|
||||
expect(getItem).toHaveBeenCalledTimes(2);
|
||||
expect(errorLog).toHaveBeenCalledTimes(2);
|
||||
unsubscribe?.();
|
||||
});
|
||||
|
||||
it("preserves desktop sync causes and retries after a failed cosmetic sync", async () => {
|
||||
const cause = new Error("desktop IPC unavailable");
|
||||
const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const setTheme = vi.fn().mockRejectedValue(cause);
|
||||
vi.stubGlobal("window", { desktopBridge: { setTheme } });
|
||||
|
||||
const { DesktopThemeSyncError, syncDesktopTheme, syncDesktopThemePreference } =
|
||||
await import("./useTheme");
|
||||
|
||||
const error = await syncDesktopThemePreference({ setTheme }, "dark").then(
|
||||
() => undefined,
|
||||
(failure: unknown) => failure,
|
||||
);
|
||||
expect(error).toBeInstanceOf(DesktopThemeSyncError);
|
||||
expect(error).toMatchObject({ theme: "dark", cause });
|
||||
|
||||
setTheme.mockClear();
|
||||
syncDesktopTheme("dark");
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
syncDesktopTheme("dark");
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(setTheme).toHaveBeenCalledTimes(2);
|
||||
expect(errorLog).toHaveBeenCalledWith(
|
||||
"Failed to sync the dark theme to the desktop shell.",
|
||||
expect.objectContaining({
|
||||
theme: "dark",
|
||||
errorTag: "DesktopThemeSyncError",
|
||||
}),
|
||||
);
|
||||
for (const [, attributes] of errorLog.mock.calls) {
|
||||
expect(attributes).not.toHaveProperty("cause");
|
||||
expect(JSON.stringify(attributes)).not.toContain(cause.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
+14
-132
@@ -1,17 +1,11 @@
|
||||
import type { DesktopBridge } from "@t3tools/contracts";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
|
||||
const ThemePreference = Schema.Literals(["light", "dark", "system"]);
|
||||
type Theme = typeof ThemePreference.Type;
|
||||
type Theme = "light" | "dark" | "system";
|
||||
type ThemeSnapshot = {
|
||||
theme: Theme;
|
||||
systemDark: boolean;
|
||||
};
|
||||
|
||||
type DesktopThemeBridge = Pick<DesktopBridge, "setTheme">;
|
||||
|
||||
const STORAGE_KEY = "t3code:theme";
|
||||
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
|
||||
const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
|
||||
@@ -21,46 +15,19 @@ const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
|
||||
const THEME_COLOR_META_NAME = "theme-color";
|
||||
const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;
|
||||
|
||||
export class ThemeStorageError extends Schema.TaggedErrorClass<ThemeStorageError>()(
|
||||
"ThemeStorageError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "write"]),
|
||||
storageKey: Schema.String,
|
||||
theme: Schema.optional(ThemePreference),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to ${this.operation} theme preference for ${this.storageKey}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const isThemeStorageError = Schema.is(ThemeStorageError);
|
||||
|
||||
export class DesktopThemeSyncError extends Schema.TaggedErrorClass<DesktopThemeSyncError>()(
|
||||
"DesktopThemeSyncError",
|
||||
{
|
||||
theme: ThemePreference,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to sync the ${this.theme} theme to the desktop shell.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const isDesktopThemeSyncError = Schema.is(DesktopThemeSyncError);
|
||||
|
||||
let listeners: Array<() => void> = [];
|
||||
let lastSnapshot: ThemeSnapshot | null = null;
|
||||
let lastDesktopTheme: Theme | null = null;
|
||||
let lastAppliedTheme: ThemeSnapshot | null = null;
|
||||
let themeStorageReadFailure: ThemeStorageError | null = null;
|
||||
|
||||
function emitChange() {
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
function hasThemeStorage() {
|
||||
return typeof window !== "undefined" && typeof localStorage !== "undefined";
|
||||
}
|
||||
|
||||
function getSystemDark() {
|
||||
return (
|
||||
typeof window !== "undefined" &&
|
||||
@@ -69,61 +36,13 @@ function getSystemDark() {
|
||||
);
|
||||
}
|
||||
|
||||
export function readThemePreference(): Theme {
|
||||
if (typeof window === "undefined") return DEFAULT_THEME_SNAPSHOT.theme;
|
||||
let raw: string | null;
|
||||
try {
|
||||
raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
} catch (cause) {
|
||||
throw new ThemeStorageError({
|
||||
operation: "read",
|
||||
storageKey: STORAGE_KEY,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
function getStored(): Theme {
|
||||
if (!hasThemeStorage()) return DEFAULT_THEME_SNAPSHOT.theme;
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (raw === "light" || raw === "dark" || raw === "system") return raw;
|
||||
return DEFAULT_THEME_SNAPSHOT.theme;
|
||||
}
|
||||
|
||||
export function writeThemePreference(theme: Theme): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, theme);
|
||||
themeStorageReadFailure = null;
|
||||
} catch (cause) {
|
||||
throw new ThemeStorageError({
|
||||
operation: "write",
|
||||
storageKey: STORAGE_KEY,
|
||||
theme,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function getStored(): Theme {
|
||||
if (themeStorageReadFailure !== null) {
|
||||
return DEFAULT_THEME_SNAPSHOT.theme;
|
||||
}
|
||||
try {
|
||||
return readThemePreference();
|
||||
} catch (cause) {
|
||||
const error = isThemeStorageError(cause)
|
||||
? cause
|
||||
: new ThemeStorageError({
|
||||
operation: "read",
|
||||
storageKey: STORAGE_KEY,
|
||||
cause,
|
||||
});
|
||||
themeStorageReadFailure = error;
|
||||
console.error(error.message, {
|
||||
operation: error.operation,
|
||||
storageKey: error.storageKey,
|
||||
...safeErrorLogAttributes(error),
|
||||
});
|
||||
return DEFAULT_THEME_SNAPSHOT.theme;
|
||||
}
|
||||
}
|
||||
|
||||
function ensureThemeColorMetaTag(): HTMLMetaElement {
|
||||
let element = document.querySelector<HTMLMetaElement>(DYNAMIC_THEME_COLOR_SELECTOR);
|
||||
if (element) {
|
||||
@@ -199,18 +118,7 @@ function applyTheme(theme: Theme, suppressTransitions = false) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function syncDesktopThemePreference(
|
||||
bridge: DesktopThemeBridge,
|
||||
theme: Theme,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await bridge.setTheme(theme);
|
||||
} catch (cause) {
|
||||
throw new DesktopThemeSyncError({ theme, cause });
|
||||
}
|
||||
}
|
||||
|
||||
export function syncDesktopTheme(theme: Theme) {
|
||||
function syncDesktopTheme(theme: Theme) {
|
||||
if (typeof window === "undefined") return;
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge || typeof bridge.setTheme !== "function" || lastDesktopTheme === theme) {
|
||||
@@ -218,14 +126,7 @@ export function syncDesktopTheme(theme: Theme) {
|
||||
}
|
||||
|
||||
lastDesktopTheme = theme;
|
||||
void syncDesktopThemePreference(bridge, theme).catch((cause: unknown) => {
|
||||
const error = isDesktopThemeSyncError(cause)
|
||||
? cause
|
||||
: new DesktopThemeSyncError({ theme, cause });
|
||||
console.error(error.message, {
|
||||
theme: error.theme,
|
||||
...safeErrorLogAttributes(error),
|
||||
});
|
||||
void bridge.setTheme(theme).catch(() => {
|
||||
if (lastDesktopTheme === theme) {
|
||||
lastDesktopTheme = null;
|
||||
}
|
||||
@@ -233,12 +134,12 @@ export function syncDesktopTheme(theme: Theme) {
|
||||
}
|
||||
|
||||
// Apply immediately on module load to prevent flash
|
||||
if (typeof document !== "undefined" && typeof window !== "undefined") {
|
||||
if (typeof document !== "undefined" && hasThemeStorage()) {
|
||||
applyTheme(getStored());
|
||||
}
|
||||
|
||||
function getSnapshot(): ThemeSnapshot {
|
||||
if (typeof window === "undefined") return DEFAULT_THEME_SNAPSHOT;
|
||||
if (!hasThemeStorage()) return DEFAULT_THEME_SNAPSHOT;
|
||||
const theme = getStored();
|
||||
const systemDark = theme === "system" ? getSystemDark() : false;
|
||||
|
||||
@@ -269,7 +170,6 @@ function subscribe(listener: () => void): () => void {
|
||||
// Listen for storage changes from other tabs
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === STORAGE_KEY) {
|
||||
themeStorageReadFailure = null;
|
||||
applyTheme(getStored(), true);
|
||||
emitChange();
|
||||
}
|
||||
@@ -291,26 +191,8 @@ export function useTheme() {
|
||||
theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
|
||||
|
||||
const setTheme = useCallback((next: Theme) => {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
writeThemePreference(next);
|
||||
} catch (cause) {
|
||||
const error = isThemeStorageError(cause)
|
||||
? cause
|
||||
: new ThemeStorageError({
|
||||
operation: "write",
|
||||
storageKey: STORAGE_KEY,
|
||||
theme: next,
|
||||
cause,
|
||||
});
|
||||
console.error(error.message, {
|
||||
operation: error.operation,
|
||||
storageKey: error.storageKey,
|
||||
theme: next,
|
||||
...safeErrorLogAttributes(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!hasThemeStorage()) return;
|
||||
localStorage.setItem(STORAGE_KEY, next);
|
||||
applyTheme(next, true);
|
||||
emitChange();
|
||||
}, []);
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ThreadArchiveBlockedError } from "./useThreadActions";
|
||||
|
||||
describe("ThreadArchiveBlockedError", () => {
|
||||
it("keeps the blocked thread context with the fixed message", () => {
|
||||
const error = new ThreadArchiveBlockedError({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
});
|
||||
|
||||
expect(error).toMatchObject({
|
||||
environmentId: "environment-1",
|
||||
threadId: "thread-1",
|
||||
});
|
||||
expect(error.message).toBe("Cannot archive a running thread.");
|
||||
});
|
||||
});
|
||||
@@ -4,9 +4,9 @@ import {
|
||||
scopeThreadRef,
|
||||
} from "@t3tools/client-runtime/environment";
|
||||
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
|
||||
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
|
||||
import { type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Data from "effect/Data";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useRouter } from "@tanstack/react-router";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
@@ -27,17 +27,9 @@ import { stackedThreadToast, toastManager } from "../components/ui/toast";
|
||||
import { useClientSettings } from "./useSettings";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
|
||||
export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArchiveBlockedError>()(
|
||||
"ThreadArchiveBlockedError",
|
||||
{
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Cannot archive a running thread.";
|
||||
}
|
||||
}
|
||||
export class ThreadArchiveBlockedError extends Data.TaggedError("ThreadArchiveBlockedError")<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
|
||||
export function useThreadActions() {
|
||||
const closeTerminal = useAtomCommand(terminalEnvironment.close);
|
||||
@@ -97,8 +89,7 @@ export function useThreadActions() {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadArchiveBlockedError({
|
||||
environmentId: threadRef.environmentId,
|
||||
threadId: threadRef.threadId,
|
||||
message: "Cannot archive a running thread.",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -7,24 +7,13 @@
|
||||
:root {
|
||||
--workspace-topbar-height: 52px;
|
||||
--workspace-controls-top: 0px;
|
||||
--workspace-controls-left: calc(env(safe-area-inset-left) + 0.75rem);
|
||||
--workspace-controls-right: calc(env(safe-area-inset-right) + 0.75rem);
|
||||
--workspace-native-controls-inset: 0px;
|
||||
--workspace-titlebar-control-size: 1.75rem;
|
||||
--workspace-titlebar-control-gap: 0.75rem;
|
||||
}
|
||||
|
||||
[data-slot="sidebar-wrapper"] {
|
||||
--workspace-titlebar-content-left: calc(
|
||||
var(--workspace-controls-left) + var(--workspace-titlebar-control-size) +
|
||||
var(--workspace-titlebar-control-gap)
|
||||
);
|
||||
}
|
||||
|
||||
.wco {
|
||||
--workspace-topbar-height: env(titlebar-area-height, 52px);
|
||||
--workspace-controls-top: env(titlebar-area-y, 0px);
|
||||
--workspace-controls-left: calc(env(titlebar-area-x, 0px) + 0.75rem);
|
||||
--workspace-controls-right: calc(
|
||||
100vw - env(titlebar-area-width, 100vw) - env(titlebar-area-x, 0px) + 0.75rem
|
||||
);
|
||||
@@ -101,28 +90,6 @@
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.sidebar-brand {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.sidebar-brand-stage {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (min-width: 48rem) {
|
||||
@container sidebar-header (min-width: 13.5rem) {
|
||||
.sidebar-brand {
|
||||
display: flex;
|
||||
}
|
||||
}
|
||||
|
||||
@container sidebar-header (min-width: 15.75rem) {
|
||||
.sidebar-brand-stage {
|
||||
display: inline-flex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.workspace-topbar {
|
||||
display: flex;
|
||||
height: var(--workspace-topbar-height);
|
||||
|
||||
@@ -85,7 +85,6 @@ function compile(bindings: TestBinding[]): ResolvedKeybindingsConfig {
|
||||
}
|
||||
|
||||
const DEFAULT_BINDINGS = compile([
|
||||
{ shortcut: modShortcut("b"), command: "sidebar.toggle" },
|
||||
{ shortcut: modShortcut("j"), command: "terminal.toggle" },
|
||||
{ shortcut: modShortcut("b", { altKey: true }), command: "rightPanel.toggle" },
|
||||
{
|
||||
@@ -313,10 +312,6 @@ describe("shortcutLabelForCommand", () => {
|
||||
});
|
||||
|
||||
it("returns effective labels for non-terminal commands", () => {
|
||||
assert.strictEqual(
|
||||
shortcutLabelForCommand(DEFAULT_BINDINGS, "sidebar.toggle", "MacIntel"),
|
||||
"⌘B",
|
||||
);
|
||||
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
|
||||
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "diff.toggle", "Linux"), "Ctrl+D");
|
||||
assert.strictEqual(
|
||||
|
||||
@@ -303,6 +303,7 @@ export function resolveAppModelSelectionState(
|
||||
provider,
|
||||
model,
|
||||
models: entry.models,
|
||||
prompt: "",
|
||||
modelOptions: selectedEntry ? selection.options : undefined,
|
||||
});
|
||||
|
||||
@@ -320,6 +321,7 @@ export function resolveAppModelSelectionState(
|
||||
provider,
|
||||
model,
|
||||
models: getProviderModels(providers, provider),
|
||||
prompt: "",
|
||||
modelOptions: keptSelectedProvider ? selection.options : undefined,
|
||||
});
|
||||
|
||||
|
||||
@@ -4,12 +4,10 @@ import { LinkIcon, PlusIcon } from "lucide-react";
|
||||
import { NoActiveThreadState } from "../components/NoActiveThreadState";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";
|
||||
import { SidebarInset } from "../components/ui/sidebar";
|
||||
import { SidebarInset, SidebarTrigger } from "../components/ui/sidebar";
|
||||
import { useEnvironments } from "../state/environments";
|
||||
import { APP_DISPLAY_NAME } from "~/branding";
|
||||
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
|
||||
function ChatIndexRouteView() {
|
||||
const { authGateState } = Route.useRouteContext();
|
||||
@@ -32,13 +30,9 @@ function HostedStaticOnboardingState() {
|
||||
return (
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
|
||||
<header
|
||||
className={cn(
|
||||
"border-b border-border px-3 py-2 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5 sm:py-3",
|
||||
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
|
||||
)}
|
||||
>
|
||||
<header className="border-b border-border px-3 py-2 sm:px-5 sm:py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
<span className="text-sm font-medium text-foreground md:text-muted-foreground/60">
|
||||
{APP_DISPLAY_NAME}
|
||||
</span>
|
||||
|
||||
@@ -11,10 +11,8 @@ import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { useSettingsRestore } from "../components/settings/SettingsPanels";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { SidebarInset } from "../components/ui/sidebar";
|
||||
import { SidebarInset, SidebarTrigger } from "../components/ui/sidebar";
|
||||
import { isElectron } from "../env";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
|
||||
|
||||
function RestoreDefaultsButton({ onRestored }: { onRestored: () => void }) {
|
||||
const { changedSettingLabels, restoreDefaults } = useSettingsRestore(onRestored);
|
||||
@@ -66,13 +64,9 @@ function SettingsContentLayout() {
|
||||
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
|
||||
{!isElectron && (
|
||||
<header
|
||||
className={cn(
|
||||
"border-b border-border px-3 py-2 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
|
||||
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
|
||||
)}
|
||||
>
|
||||
<header className="border-b border-border px-3 py-2 sm:px-5">
|
||||
<div className="flex min-h-7 items-center gap-2 sm:min-h-6">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
<span className="text-sm font-medium text-foreground">Settings</span>
|
||||
{showRestoreDefaults ? (
|
||||
<div className="ms-auto flex items-center gap-2">
|
||||
@@ -84,12 +78,7 @@ function SettingsContentLayout() {
|
||||
)}
|
||||
|
||||
{isElectron && (
|
||||
<div
|
||||
className={cn(
|
||||
"drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
|
||||
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
|
||||
)}
|
||||
>
|
||||
<div className="drag-region flex h-[52px] shrink-0 items-center border-b border-border px-5 wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]">
|
||||
<span className="text-xs font-medium tracking-wide text-muted-foreground/70">
|
||||
Settings
|
||||
</span>
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
|
||||
import { AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { createDesktopUpdateStateAtom, DesktopUpdateStateReadError } from "./desktopUpdate";
|
||||
import { createDesktopUpdateStateAtom } from "./desktopUpdate";
|
||||
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
@@ -117,13 +117,8 @@ describe("desktopUpdateStateAtom", () => {
|
||||
errorTag: "DesktopUpdateStateReadError",
|
||||
attemptCount: 3,
|
||||
});
|
||||
const loggedError = (errorContext as { readonly error: unknown }).error;
|
||||
expect(loggedError).toBeInstanceOf(DesktopUpdateStateReadError);
|
||||
expect(loggedError).toMatchObject({
|
||||
_tag: "DesktopUpdateStateReadError",
|
||||
attemptCount: 3,
|
||||
});
|
||||
expect((loggedError as DesktopUpdateStateReadError).cause).toBe(cause);
|
||||
expect(errorContext).not.toHaveProperty("error");
|
||||
expect(errorContext).not.toHaveProperty("cause");
|
||||
|
||||
listener?.(baseState);
|
||||
await vi.waitFor(() => {
|
||||
|
||||
@@ -59,9 +59,9 @@ export function createDesktopUpdateStateAtom(getBridge: () => DesktopUpdateBridg
|
||||
Effect.catchTags({
|
||||
DesktopUpdateStateReadError: (error) =>
|
||||
Effect.logError(error.message, {
|
||||
error,
|
||||
errorTag: error._tag,
|
||||
attemptCount: error.attemptCount,
|
||||
stack: error.stack,
|
||||
}).pipe(Effect.as(null)),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
export const COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS =
|
||||
"[[data-sidebar-state=collapsed]_&]:pl-[var(--workspace-titlebar-content-left)]";
|
||||
@@ -7,9 +7,7 @@ import { describe, expect, it } from "@effect/vitest";
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as References from "effect/References";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
HttpClient,
|
||||
@@ -631,17 +629,6 @@ describe("ApnsDeliveries", () => {
|
||||
|
||||
it.effect("processes signed jobs through APNs and records attempts", () => {
|
||||
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
|
||||
const transportErrors: Array<ApnsDeliveries.ApnsDeliveryTransportError> = [];
|
||||
const logger = Logger.make(({ fiber }) => {
|
||||
const annotation = fiber.getRef(References.CurrentLogAnnotations).error;
|
||||
if (!Redacted.isRedacted(annotation)) {
|
||||
return;
|
||||
}
|
||||
const error = Redacted.value(annotation);
|
||||
if (ApnsDeliveries.isApnsDeliveryTransportError(error)) {
|
||||
transportErrors.push(error);
|
||||
}
|
||||
});
|
||||
const payload = makeApnsDeliveryJobPayload({
|
||||
kind: "live_activity_update",
|
||||
userId: target.user_id,
|
||||
@@ -670,29 +657,7 @@ describe("ApnsDeliveries", () => {
|
||||
token: "activity-token",
|
||||
},
|
||||
]);
|
||||
expect(transportErrors).toHaveLength(1);
|
||||
const error = transportErrors[0]!;
|
||||
expect(error).toMatchObject({
|
||||
deviceId: target.device_id,
|
||||
kind: "live_activity_update",
|
||||
sourceJobId: "job-1",
|
||||
apnsErrorTag: "ApnsJwtSigningError",
|
||||
requestStage: null,
|
||||
});
|
||||
expect(error.cause).toBeInstanceOf(ApnsClient.ApnsJwtSigningError);
|
||||
expect(error.cause).toMatchObject({
|
||||
teamId: "team-id",
|
||||
keyId: "key-id",
|
||||
});
|
||||
expect((error.cause as ApnsClient.ApnsJwtSigningError).cause).toBeDefined();
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
makeLayer({ attempts }),
|
||||
Logger.layer([logger], { mergeWithExisting: false }),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.provide(makeLayer({ attempts })));
|
||||
});
|
||||
|
||||
it.effect("processes signed push notification jobs through APNs and records attempts", () => {
|
||||
|
||||
@@ -7,14 +7,12 @@ import type {
|
||||
import {
|
||||
RelayAgentActivityAggregateState as RelayAgentActivityAggregateStateSchema,
|
||||
RelayAgentAwarenessPreferences as RelayAgentAwarenessPreferencesSchema,
|
||||
RelayDeliveryKind as RelayDeliveryKindSchema,
|
||||
} from "@t3tools/contracts/relay";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Redacted from "effect/Redacted";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
@@ -89,28 +87,6 @@ export class ApnsDeliveryJobClaimInFlight extends Schema.TaggedErrorClass<ApnsDe
|
||||
}
|
||||
}
|
||||
|
||||
export class ApnsDeliveryTransportError extends Schema.TaggedErrorClass<ApnsDeliveryTransportError>()(
|
||||
"ApnsDeliveryTransportError",
|
||||
{
|
||||
deviceId: Schema.String,
|
||||
kind: RelayDeliveryKindSchema,
|
||||
sourceJobId: Schema.NullOr(Schema.String),
|
||||
apnsErrorTag: Schema.Literals([
|
||||
"ApnsJwtEncodingError",
|
||||
"ApnsJwtSigningError",
|
||||
"ApnsHttpRequestError",
|
||||
]),
|
||||
requestStage: Schema.NullOr(Schema.Literals(["send", "read-response"])),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `APNs ${this.kind} delivery failed for device ${this.deviceId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export const isApnsDeliveryTransportError = Schema.is(ApnsDeliveryTransportError);
|
||||
|
||||
const decodeRelayAgentActivityAggregateStateJson = Schema.decodeUnknownOption(
|
||||
Schema.fromJsonString(RelayAgentActivityAggregateStateSchema),
|
||||
);
|
||||
@@ -326,42 +302,6 @@ function deliveryAttemptOutcome(result: Apns.ApnsDeliveryResult) {
|
||||
};
|
||||
}
|
||||
|
||||
const recoverApnsDeliveryTransportError = (
|
||||
input: {
|
||||
readonly deviceId: string;
|
||||
readonly kind: RelayDeliveryKind;
|
||||
readonly sourceJobId: string | null;
|
||||
},
|
||||
cause: Apns.ApnsError,
|
||||
): Effect.Effect<Apns.ApnsDeliveryResult> => {
|
||||
const error = new ApnsDeliveryTransportError({
|
||||
deviceId: input.deviceId,
|
||||
kind: input.kind,
|
||||
sourceJobId: input.sourceJobId,
|
||||
apnsErrorTag: cause._tag,
|
||||
requestStage: cause._tag === "ApnsHttpRequestError" ? cause.stage : null,
|
||||
cause,
|
||||
});
|
||||
return Effect.logError(error.message).pipe(
|
||||
Effect.annotateLogs({
|
||||
error: Redacted.make(error, { label: error._tag }),
|
||||
"error.type": error._tag,
|
||||
"error.apns_error_tag": error.apnsErrorTag,
|
||||
...(error.requestStage === null ? {} : { "error.request_stage": error.requestStage }),
|
||||
...(error.stack === undefined ? {} : { "error.stack": error.stack }),
|
||||
"relay.mobile.device_id": error.deviceId,
|
||||
"relay.delivery.kind": error.kind,
|
||||
...(error.sourceJobId === null ? {} : { "relay.delivery.job_id": error.sourceJobId }),
|
||||
}),
|
||||
Effect.as({
|
||||
ok: false,
|
||||
status: 0,
|
||||
reason: cause.message,
|
||||
apnsId: null,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
interface LiveActivityDeliveryTarget {
|
||||
readonly user_id: string;
|
||||
readonly device_id: string;
|
||||
@@ -500,15 +440,6 @@ export const make = Effect.gen(function* () {
|
||||
{ ...input, aggregate } as SendLiveActivityDeliveryInput,
|
||||
now,
|
||||
);
|
||||
const recoverTransportError = (cause: Apns.ApnsError) =>
|
||||
recoverApnsDeliveryTransportError(
|
||||
{
|
||||
deviceId: input.target.device_id,
|
||||
kind: input.kind,
|
||||
sourceJobId: input.sourceJobId ?? null,
|
||||
},
|
||||
cause,
|
||||
);
|
||||
if (input.sourceJobId) {
|
||||
const claim = yield* attempts.claimSourceJob({
|
||||
userId: input.target.user_id,
|
||||
@@ -545,11 +476,14 @@ export const make = Effect.gen(function* () {
|
||||
issuedAtUnixSeconds: epochSeconds,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchTags({
|
||||
ApnsJwtEncodingError: recoverTransportError,
|
||||
ApnsJwtSigningError: recoverTransportError,
|
||||
ApnsHttpRequestError: recoverTransportError,
|
||||
}),
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed({
|
||||
ok: false,
|
||||
status: 0,
|
||||
reason: error.message,
|
||||
apnsId: null,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (result.ok) {
|
||||
yield* liveActivities.markDelivery({
|
||||
@@ -617,15 +551,6 @@ export const make = Effect.gen(function* () {
|
||||
token: input.token,
|
||||
notification,
|
||||
});
|
||||
const recoverTransportError = (cause: Apns.ApnsError) =>
|
||||
recoverApnsDeliveryTransportError(
|
||||
{
|
||||
deviceId: input.target.device_id,
|
||||
kind: "push_notification",
|
||||
sourceJobId: input.sourceJobId ?? null,
|
||||
},
|
||||
cause,
|
||||
);
|
||||
if (input.sourceJobId) {
|
||||
const claim = yield* attempts.claimSourceJob({
|
||||
userId: input.target.user_id,
|
||||
@@ -668,11 +593,14 @@ export const make = Effect.gen(function* () {
|
||||
issuedAtUnixSeconds: epochSeconds,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchTags({
|
||||
ApnsJwtEncodingError: recoverTransportError,
|
||||
ApnsJwtSigningError: recoverTransportError,
|
||||
ApnsHttpRequestError: recoverTransportError,
|
||||
}),
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed({
|
||||
ok: false,
|
||||
status: 0,
|
||||
reason: error.message,
|
||||
apnsId: null,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (isPermanentApnsTokenFailure(result)) {
|
||||
yield* liveActivities.invalidateDeliveryToken({
|
||||
|
||||
@@ -81,6 +81,7 @@ export class ConnectionTransientError extends Schema.TaggedErrorClass<Connection
|
||||
reason: ConnectionTransientReason,
|
||||
detail: Schema.String,
|
||||
traceId: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.optionalKey(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
|
||||
@@ -689,12 +689,13 @@ describe("EnvironmentRegistry", () => {
|
||||
|
||||
it.effect("keeps the runtime registered when durable removal fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const persistenceCause = new Error("Storage is unavailable.");
|
||||
const harness = yield* makeHarness([RELAY_TARGET], [], [], {
|
||||
beforeRegistrationRemove: () =>
|
||||
Effect.fail(
|
||||
new Persistence.ConnectionPersistenceError({
|
||||
operation: "remove-connection",
|
||||
message: "Storage is unavailable.",
|
||||
cause: persistenceCause,
|
||||
}),
|
||||
),
|
||||
});
|
||||
@@ -711,6 +712,8 @@ describe("EnvironmentRegistry", () => {
|
||||
const error = yield* Effect.flip(registry.removeRelayEnvironments());
|
||||
|
||||
expect(error._tag).toBe("ConnectionPersistenceError");
|
||||
expect(error.message).toBe("Could not remove connection.");
|
||||
expect(error.cause).toBe(persistenceCause);
|
||||
expect(yield* Ref.get(harness.releasedSessions)).toBe(0);
|
||||
expect((yield* SubscriptionRef.get(registry.entries)).has(RELAY_TARGET.environmentId)).toBe(
|
||||
true,
|
||||
|
||||
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user