Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 40624c1a71 Use typed file system override in browse test
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 16:12:45 +00:00
Cursor AgentandJulius Marminge 5a994cd866 Format workspace entries browse filter
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 16:11:10 +00:00
Cursor AgentandJulius Marminge 4c853e3714 Fix workspace browse file system mock
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 16:10:33 +00:00
Cursor AgentandJulius Marminge 7e7a18de0c Use Effect file system in workspace services
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 16:08:14 +00:00
Wout StiensandCodex 4abf8b46c5 [codex] fix: ignore stale shell reducer events (#3517)
Co-authored-by: Codex <[email protected]>
2026-06-22 22:33:23 -07:00
Wout StiensandCodex 3083d712ee [codex] fix: clarify Cursor CLI setup error (#3519)
Co-authored-by: Codex <[email protected]>
2026-06-22 22:33:01 -07:00
Julius Marminge 6672a1d210 Bump Clerk packages and refresh lockfile (#3511) 2026-06-22 16:59:56 -07:00
92e54fb96c [codex] fix: guard DPoP fallback URL construction (#3503)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 16:21:06 -07:00
Julius MarmingeandJulius Marminge 8cc9a6fa6b [codex] Restore T3 Connect account controls (#3492)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 15:58:54 -07:00
b2d17b7108 Add main sidebar toggle (#3497)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-22 14:00:30 -07:00
Abdul AzeezandJulius Marminge fb1034546f feat: add persistent word-wrap setting for chat code blocks and tables (#3480)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 13:14:24 -07:00
f5f98cf0ae Stabilize composer provider state while typing (#3507)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 12:52:13 -07:00
Julius Marmingeandcodex 37ac970e28 Persist mobile composer selectors across drafts (#3496)
Co-authored-by: codex <[email protected]>
2026-06-22 12:37:31 -07:00
Wout StiensandCodex 8919ae7c53 [codex] Reject unsupported remote pairing protocols (#3498)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:15:43 -07:00
Wout StiensandCodex c1e2408e1f [codex] fix: preserve localhost preview hosts (#3499)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:14:16 -07:00
Wout StiensandCodex 8b993bc9ff [codex] fix: restore pending input keyboard activation (#3501)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:10:47 -07:00
Wout StiensandCodex ea52bb1dbd [codex] fix: guard trace ID clipboard copy (#3505)
Co-authored-by: Codex <[email protected]>
2026-06-22 09:46:15 -07:00
69 changed files with 2060 additions and 892 deletions

No files matched your search

@@ -18,7 +18,6 @@ const clientSettings: ClientSettings = {
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path",
@@ -29,6 +28,7 @@ const clientSettings: ClientSettings = {
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
timestampFormat: "24-hour",
wordWrap: true,
};
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
+7 -10
View File
@@ -104,16 +104,13 @@ const capabilitiesLayer = Layer.succeedContext(
}),
),
);
return yield* Option.match(token, {
onNone: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
}),
),
onSome: Effect.succeed,
});
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
});
}
return token;
}),
}),
).pipe(
@@ -1,17 +1,12 @@
import { ClerkProvider, useAuth } from "@clerk/expo";
import { tokenCache } from "@clerk/expo/token-cache";
import {
ManagedRelay,
ManagedRelaySessionTokenReadError,
setManagedRelaySession,
} from "@t3tools/client-runtime/relay";
import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import {
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
} from "@t3tools/client-runtime/state/runtime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { type ReactNode, useEffect, useRef } from "react";
import { environmentCatalog } from "../../connection/catalog";
@@ -44,11 +39,7 @@ export function activateCloudRelayAccount(
setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);
setManagedRelaySession(appAtomRegistry, {
accountId,
readClerkToken: () =>
Effect.tryPromise({
try: tokenProvider,
catch: (cause) => new ManagedRelaySessionTokenReadError({ cause }),
}).pipe(Effect.map(Option.fromNullOr)),
readClerkToken: tokenProvider,
});
}
@@ -30,7 +30,9 @@ 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";
@@ -63,6 +65,7 @@ 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)";
@@ -78,6 +81,12 @@ export function NewTaskDraftScreen(props: {
) ?? null;
if (directProject) {
if (
selectedProject?.environmentId === directProject.environmentId &&
selectedProject.id === directProject.id
) {
return;
}
setProject(directProject);
return;
}
@@ -105,10 +114,16 @@ 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, selectedProject]);
}, [flow.loadBranches, selectedProject]);
useEffect(() => {
if (!selectedProject) {
@@ -292,11 +307,7 @@ export function NewTaskDraftScreen(props: {
if (!event.startsWith("model:")) {
return;
}
// 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);
flow.setSelectedModelKey(event.slice("model:".length));
}
function handleEnvironmentMenuAction(event: string) {
@@ -366,27 +377,42 @@ 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 (
!flow.selectedProject ||
!flow.selectedModel ||
flow.prompt.trim().length === 0 ||
!modelSelection ||
initialMessageText.length === 0 ||
flow.submitting ||
(flow.workspaceMode === "worktree" && !flow.selectedBranchName)
(workspaceMode === "worktree" && !selectedBranchName)
) {
return;
}
flow.setSubmitting(true);
const result = await createProjectThread({
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,
project: selectedProject,
modelSelection,
envMode: workspaceMode,
branch: selectedBranchName,
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
runtimeMode,
interactionMode,
initialMessageText,
initialAttachments: draft.attachments,
});
flow.setSubmitting(false);
@@ -1,13 +1,7 @@
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useState } from "react";
import * as Option from "effect/Option";
import {
EnvironmentId,
type ModelSelection,
type ProjectScript,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { EnvironmentId, type ProjectScript } 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";
@@ -79,18 +73,6 @@ 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<{
@@ -105,6 +87,18 @@ 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"));
@@ -157,51 +151,6 @@ 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 ||
@@ -435,7 +384,7 @@ export function ThreadRouteScreen() {
<View className="flex-1 bg-screen">
<ThreadDetailScreen
selectedThread={selectedThread}
selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
contentPresentation={contentPresentation}
screenTone={connectionTone(routeConnectionState)}
connectionError={routeConnectionError}
@@ -466,9 +415,9 @@ export function ThreadRouteScreen() {
onStopThread={handleStopThread}
onSendMessage={composer.onSendMessage}
onReconnectEnvironment={handleReconnectEnvironment}
onUpdateThreadModelSelection={handleUpdateThreadModelSelection}
onUpdateThreadRuntimeMode={handleUpdateThreadRuntimeMode}
onUpdateThreadInteractionMode={handleUpdateThreadInteractionMode}
onUpdateThreadModelSelection={composer.onUpdateModelSelection}
onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
onRespondToApproval={requests.onRespondToApproval}
onSelectUserInputOption={requests.onSelectUserInputOption}
onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
@@ -1,4 +1,4 @@
import React, { useCallback, useMemo, useRef, useState } from "react";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import type {
EnvironmentId,
@@ -23,6 +23,7 @@ import {
removeComposerDraftAttachment,
replaceComposerDraftAttachments,
setComposerDraftText,
updateComposerDraftSettings,
useComposerDraft,
} from "../../state/use-composer-drafts";
import { useBranches } from "../../state/queries";
@@ -158,34 +159,15 @@ 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);
}, []);
@@ -247,33 +229,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,
selectedProject?.defaultModelSelection ?? null,
selectedProjectDraft.modelSelection ?? selectedProject?.defaultModelSelection ?? null,
),
[selectedEnvironmentServerConfig, selectedProject?.defaultModelSelection],
[
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection,
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) ??
const selectedModel =
selectedProjectDraft.modelSelection ??
selectedProject?.defaultModelSelection ??
modelOptions[0]?.selection ??
null;
const selectedModelIdentity = baseSelectedModel
? `${baseSelectedModel.instanceId}:${baseSelectedModel.model}`
const selectedModelKey = selectedModel
? `${selectedModel.instanceId}:${selectedModel.model}`
: null;
const selectedModel =
(selectedModelIdentity ? modelSelectionOverrides[selectedModelIdentity] : null) ??
baseSelectedModel;
const selectedModelOption =
modelOptions.find(
@@ -282,13 +264,31 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
option.selection.instanceId === selectedModel.instanceId &&
option.selection.model === selectedModel.model,
) ?? null;
const selectedProviderSkills =
selectedEnvironmentServerConfig?.providers.find(
(provider) => provider.instanceId === selectedModel?.instanceId,
)?.skills ?? [];
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 setSelectedModelOptions = useCallback(
(options: ReadonlyArray<ProviderOptionSelection> | undefined) => {
if (!selectedModel || !selectedModelIdentity) {
if (!selectedModel || !selectedProjectDraftKey) {
return;
}
const nextSelection: ModelSelection = options
@@ -297,12 +297,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
instanceId: selectedModel.instanceId,
model: selectedModel.model,
};
setModelSelectionOverrides((current) => ({
...current,
[selectedModelIdentity]: nextSelection,
}));
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: nextSelection,
});
},
[selectedModel, selectedModelIdentity],
[selectedModel, selectedProjectDraftKey],
);
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
@@ -381,62 +380,85 @@ 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) => {
setSelectedBranchName(branch.name);
setSelectedWorktreePath(
selectedProject ? normalizeSelectedWorktreePath(selectedProject, branch) : null,
);
if (!selectedProject || !selectedProjectDraftKey) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
workspaceSelection: {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
},
});
},
[selectedProject],
[selectedProject, selectedProjectDraftKey, workspaceMode],
);
const refreshBranches = branchState.refresh;
const loadBranches = useCallback(async () => {
if (!selectedProject) {
return;
}
setPendingConnectionError(null);
refreshBranches();
}, [refreshBranches, selectedProject]);
const loadVersion = ++branchLoadVersionRef.current;
const projectKey = scopedProjectKey(selectedProject.environmentId, selectedProject.id);
branchState.refresh();
if (loadVersion !== branchLoadVersionRef.current || selectedProjectKey !== projectKey) {
useEffect(() => {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
return;
}
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);
}
const preferredBranch =
availableBranches.find((branch) => branch.current) ??
availableBranches.find((branch) => branch.isDefault) ??
null;
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [
availableBranches,
branchState,
selectedBranchName,
selectedProject,
selectedProjectKey,
workspaceMode,
]);
}, [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],
);
const value = useMemo<NewTaskFlowContextValue>(
() => ({
@@ -513,6 +535,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
setProject,
selectBranch,
selectEnvironment,
setInteractionMode,
setPrompt,
setRuntimeMode,
setSelectedModelKey,
setWorkspaceMode,
submitting,
workspaceMode,
appendAttachments,
@@ -0,0 +1,11 @@
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,
});
+65 -13
View File
@@ -1,32 +1,38 @@
import { isTransportConnectionErrorMessage } from "@t3tools/client-runtime/errors";
import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
import { CommandId, EnvironmentId, IsoDateTime, MessageId, ThreadId } from "@t3tools/contracts";
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 * 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 = 1;
const THREAD_OUTBOX_SCHEMA_VERSION = 2;
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.Literal(THREAD_OUTBOX_SCHEMA_VERSION),
schemaVersion: Schema.Literals([1, 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,
});
@@ -40,9 +46,37 @@ 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,
@@ -119,3 +153,21 @@ 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";
}
+78 -1
View File
@@ -1,11 +1,21 @@
import { describe, expect, it } from "@effect/vitest";
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
import {
CommandId,
EnvironmentId,
MessageId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { AtomRegistry } from "effect/unstable/reactivity";
import {
decodeQueuedThreadMessage,
encodeQueuedThreadMessage,
groupQueuedThreadMessages,
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
shouldRetryThreadOutboxDelivery,
threadOutboxRetryDelayMs,
type QueuedThreadMessage,
@@ -66,6 +76,54 @@ 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,
@@ -271,4 +329,23 @@ 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,14 +1,136 @@
import { describe, expect, it } from "@effect/vitest";
import { EnvironmentId } from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "@effect/vitest";
import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
import { type ComposerDraft, removeComposerDraftsForEnvironment } from "./use-composer-drafts";
import { appAtomRegistry } from "./atom-registry";
import {
clearComposerDraftContentState,
composerDraftsAtom,
decodePersistedComposerDrafts,
type ComposerDraft,
getComposerDraftSnapshot,
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");
@@ -17,12 +139,15 @@ 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,
});
});
});
+124 -22
View File
@@ -1,9 +1,18 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import {
ModelSelection as ModelSelectionSchema,
ProviderInteractionMode as ProviderInteractionModeSchema,
RuntimeMode as RuntimeModeSchema,
type EnvironmentId,
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
} 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";
@@ -29,13 +38,47 @@ 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;
}
interface PersistedComposerDrafts {
readonly schemaVersion: typeof COMPOSER_DRAFTS_SCHEMA_VERSION;
readonly drafts: Record<string, ComposerDraft>;
export interface ComposerDraftWorkspaceSelection {
readonly mode: "local" | "worktree";
readonly branch: string | null;
readonly worktreePath: string | null;
}
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: [],
@@ -54,13 +97,32 @@ 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;
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)),
);
}
async function getComposerDraftsFile() {
@@ -80,20 +142,7 @@ async function loadPersistedComposerDrafts(): Promise<Record<string, ComposerDra
operation = "read";
const raw = await file.text();
operation = "decode";
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)
);
}),
);
return decodePersistedComposerDrafts(JSON.parse(raw) as unknown);
} catch (cause) {
console.warn(
"[composer-drafts] ignored persisted draft failure",
@@ -116,10 +165,10 @@ async function writePersistedComposerDrafts(drafts: Record<string, ComposerDraft
const nonEmptyDrafts = Object.fromEntries(
Object.entries(drafts).filter(([, draft]) => !isEmptyDraft(draft)),
);
const document: PersistedComposerDrafts = {
const document = {
schemaVersion: COMPOSER_DRAFTS_SCHEMA_VERSION,
drafts: nonEmptyDrafts,
};
} as const;
const encoded = JSON.stringify(document);
operation = "write";
if (!file.exists) {
@@ -282,6 +331,55 @@ 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]) {
@@ -298,8 +396,12 @@ 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)),
Object.entries(drafts).filter(
([draftKey]) =>
!draftKey.startsWith(environmentPrefix) && !draftKey.startsWith(newTaskPrefix),
),
);
}
@@ -1,7 +1,15 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useEffect, useMemo } from "react";
import { CommandId, MessageId, type EnvironmentId, type ThreadId } from "@t3tools/contracts";
import {
CommandId,
MessageId,
type EnvironmentId,
type ModelSelection,
type ProviderInteractionMode,
type RuntimeMode,
type ThreadId,
} from "@t3tools/contracts";
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
import { deriveActiveWorkStartedAt } from "@t3tools/shared/orchestrationTiming";
@@ -18,11 +26,13 @@ import { appAtomRegistry } from "../state/atom-registry";
import {
appendComposerDraftAttachments,
appendComposerDraftText,
clearComposerDraft,
clearComposerDraftContent,
composerDraftsAtom,
ensureComposerDraftsLoaded,
getComposerDraftSnapshot,
removeComposerDraftAttachment,
setComposerDraftText,
updateComposerDraftSettings,
useComposerDraft,
} from "./use-composer-drafts";
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
@@ -98,6 +108,10 @@ 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;
@@ -130,7 +144,6 @@ export function useThreadComposerState() {
selectedThreadShell,
]);
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
const activeThreadBusy =
!!selectedThread &&
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
@@ -141,9 +154,10 @@ export function useThreadComposerState() {
}
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const draft = composerDrafts[threadKey];
const text = (draft?.text ?? "").trim();
const attachments = draft?.attachments ?? [];
const draft = getComposerDraftSnapshot(threadKey);
const thread = selectedThreadDetail ?? selectedThreadShell;
const text = draft.text.trim();
const attachments = draft.attachments;
if (text.length === 0 && attachments.length === 0) {
return;
}
@@ -157,15 +171,18 @@ 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,
});
clearComposerDraft(threadKey);
clearComposerDraftContent(threadKey);
} catch (error) {
setPendingConnectionError(
error instanceof Error ? error.message : "Failed to save the queued message.",
);
}
}, [composerDrafts, selectedThreadShell]);
}, [selectedThreadDetail, selectedThreadShell]);
const onChangeDraftMessage = useCallback(
(value: string) => {
@@ -255,12 +272,45 @@ 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,
@@ -268,5 +318,8 @@ export function useThreadComposerState() {
onNativePasteImages,
onRemoveDraftImage,
onSendMessage,
onUpdateModelSelection,
onUpdateRuntimeMode,
onUpdateInteractionMode,
};
}
+116 -33
View File
@@ -1,6 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { type MessageId } from "@t3tools/contracts";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import { CommandId, 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";
@@ -10,10 +11,13 @@ import { appAtomRegistry } from "./atom-registry";
import { useThreadShells } from "./entities";
import { ensureThreadOutboxLoaded, removeThreadOutboxMessage } from "./thread-outbox";
import {
modelSelectionsEqual,
resolveThreadOutboxDeliveryAction,
shouldRetryThreadOutboxDelivery,
resolveThreadOutboxFailureAction,
resolveQueuedThreadSettings,
threadOutboxRetryDelayMs,
type QueuedThreadMessage,
type ThreadOutboxCommandStage,
} from "./thread-outbox-model";
import { threadEnvironment } from "./threads";
import { useAtomCommand } from "./use-atom-command";
@@ -44,8 +48,21 @@ 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();
@@ -68,6 +85,98 @@ 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: {
@@ -79,41 +188,15 @@ export function useThreadOutboxDrain(): void {
text: queuedMessage.text,
attachments: queuedMessage.attachments,
},
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
modelSelection: settings.modelSelection,
runtimeMode: settings.runtimeMode,
interactionMode: settings.interactionMode,
createdAt: queuedMessage.createdAt,
},
});
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;
}
return completeDelivery(deliveryResult);
},
[startTurn],
[setThreadInteractionMode, setThreadRuntimeMode, startTurn, updateThreadMetadata],
);
useEffect(() => {
+9 -18
View File
@@ -3,7 +3,8 @@ 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 type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as Option from "effect/Option";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import {
ServerAuthDpopReplayKeyCalculationError,
@@ -13,22 +14,6 @@ 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 =>
@@ -48,11 +33,17 @@ 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: requestAbsoluteUrl(input.request),
url: url.value.href,
nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),
...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),
...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),
+1
View File
@@ -198,6 +198,7 @@ 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");
@@ -4,6 +4,7 @@ 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";
@@ -24,7 +25,11 @@ import {
} from "./CursorProvider.ts";
const runNode = <A, E>(
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
effect: Effect.Effect<
A,
E,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
>,
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
@@ -293,6 +298,18 @@ 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", () => {
@@ -338,12 +355,11 @@ describe("buildCursorProviderSnapshot", () => {
auth: { status: "unauthenticated" },
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
},
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
discoveryWarning: cursorAcpDiscoveryFailedMessage,
}),
).toMatchObject({
status: "error",
message:
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
models: [
{
slug: "claude-sonnet-4-6",
@@ -411,10 +427,28 @@ 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 Effect.runPromise(
const provider = await runNode(
checkCursorProviderStatus(
{
enabled: true,
@@ -426,7 +460,7 @@ describe("checkCursorProviderStatus", () => {
...process.env,
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
},
).pipe(Effect.provide(NodeServices.layer)),
),
);
expect(provider.models.map((model) => model.slug)).toEqual([
@@ -443,13 +477,13 @@ describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await runNode(makeMockAgentWrapper());
const models = await Effect.runPromise(
const models = await runNode(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
}).pipe(Effect.scoped),
);
expect(models.map((model) => model.slug)).toEqual([
@@ -465,13 +499,13 @@ describe("discoverCursorModelsViaAcp", () => {
makeExitLogFixture("cursor-provider-exit-log-"),
);
await Effect.runPromise(
await runNode(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer)),
}),
);
const exitLog = await runNode(waitForFileContent(exitLogPath));
@@ -62,6 +62,13 @@ 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,
@@ -608,6 +615,14 @@ 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;
@@ -1020,7 +1035,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Cursor Agent CLI (`agent`) is not installed or not on PATH."
? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)
: "Failed to execute Cursor Agent CLI health check.",
},
});
@@ -1079,7 +1094,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. Check server logs for details.";
discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;
} 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) {
@@ -1,8 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFSP from "node:fs/promises";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { FileFinder } from "@ff-labs/fff-node";
import { it, afterEach, describe, expect } from "@effect/vitest";
import { assert, it, afterEach, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -16,11 +14,6 @@ import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as WorkspaceEntries from "./WorkspaceEntries.ts";
import * as WorkspacePaths from "./WorkspacePaths.ts";
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return { ...actual, readdir: vi.fn(actual.readdir) };
});
const TestLayer = Layer.empty.pipe(
Layer.provideMerge(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer))),
Layer.provideMerge(WorkspacePaths.layer),
@@ -378,16 +371,36 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceEntries", (it) => {
it.effect("returns an empty listing when the OS denies directory access", () =>
Effect.gen(function* () {
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const fileSystem = yield* FileSystem.FileSystem;
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-eacces-" });
const denied = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" });
vi.mocked(NodeFSP.readdir).mockRejectedValueOnce(denied);
const denied = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readDirectory",
pathOrDescriptor: cwd,
description: "Test PermissionDenied readDirectory failure.",
});
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries.pipe(
Effect.provide(
WorkspaceEntries.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(
Layer.succeed(
FileSystem.FileSystem,
FileSystem.FileSystem.of({
...fileSystem,
readDirectory: () => Effect.fail(denied),
}),
),
),
),
),
);
const result = yield* workspaceEntries.browse({
partialPath: yield* appendSeparator(cwd),
});
expect(result).toEqual({ parentPath: cwd, entries: [] });
assert.deepEqual(result, { parentPath: cwd, entries: [] });
}),
);
});
+24 -25
View File
@@ -1,10 +1,11 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as Context from "effect/Context";
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 Path from "effect/Path";
import * as RcMap from "effect/RcMap";
import * as Schema from "effect/Schema";
@@ -133,6 +134,7 @@ const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(fu
});
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;
@@ -185,37 +187,34 @@ export const make = Effect.gen(function* () {
const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
const dirents = yield* Effect.tryPromise({
try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),
catch: (cause) =>
new WorkspaceEntriesReadDirectoryError({
cwd: input.cwd,
partialPath: input.partialPath,
parentPath,
cause,
}),
}).pipe(
Effect.catchIf(
(error) => {
const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
return code === "EACCES" || code === "EPERM";
},
() => Effect.succeed([]),
const entryNames = yield* fileSystem.readDirectory(parentPath).pipe(
Effect.catchTag("PlatformError", (cause) =>
cause.reason._tag === "PermissionDenied"
? Effect.succeed([])
: Effect.fail(
new WorkspaceEntriesReadDirectoryError({
cwd: input.cwd,
partialPath: input.partialPath,
parentPath,
cause,
}),
),
),
);
const showHidden = endsWithSeparator || prefix.startsWith(".");
const lowerPrefix = prefix.toLowerCase();
const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
for (const dirent of dirents) {
if (
dirent.isDirectory() &&
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
(showHidden || !dirent.name.startsWith("."))
) {
for (const name of entryNames) {
if (name.toLowerCase().startsWith(lowerPrefix) && (showHidden || !name.startsWith("."))) {
const fullPath = path.join(parentPath, name);
const info = yield* fileSystem.stat(fullPath).pipe(Effect.option);
if (Option.isNone(info) || info.value.type !== "Directory") {
continue;
}
entries.push({
name: dirent.name,
fullPath: path.join(parentPath, dirent.name),
name,
fullPath,
});
}
}
@@ -1,9 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import { assert, it, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as ServerConfig from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
@@ -185,8 +186,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
operationPath: resolvedPath,
operation: "realpath-target",
});
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "NotFound");
}),
);
});
@@ -1,4 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -7,8 +6,6 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
ProjectReadFileResult,
@@ -19,6 +16,7 @@ import * as Context from "effect/Context";
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 Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -140,30 +138,28 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
const toOperationError =
(
operation: WorkspaceFileSystemOperationError["operation"],
operationPath: string,
resolvedPath = target.absolutePath,
) =>
(cause: unknown) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
resolvedPath,
operationPath,
operation,
cause,
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
});
const realWorkspaceRoot = yield* fileSystem
.realPath(input.cwd)
.pipe(Effect.mapError(toOperationError("realpath-workspace-root", input.cwd)));
const realTargetPath = yield* fileSystem
.realPath(target.absolutePath)
.pipe(Effect.mapError(toOperationError("realpath-target", target.absolutePath)));
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
@@ -178,84 +174,45 @@ export const make = Effect.gen(function* () {
});
}
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
return yield* Effect.scoped(
Effect.gen(function* () {
const handle = yield* fileSystem
.open(realTargetPath, { flag: "r" })
.pipe(Effect.mapError(toOperationError("open", realTargetPath, realTargetPath)));
const stat = yield* handle.stat.pipe(
Effect.mapError(toOperationError("stat", realTargetPath, realTargetPath)),
);
if (stat.type !== "File") {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
});
}
const byteLength = Number(stat.size);
const bytesToRead = Math.min(byteLength, PROJECT_READ_FILE_MAX_BYTES);
const fileBytes = Option.getOrElse(
yield* handle
.readAlloc(bytesToRead)
.pipe(Effect.mapError(toOperationError("read", realTargetPath, realTargetPath))),
() => new Uint8Array(0),
);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength,
truncated: byteLength > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.gen(function* () {
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "stat",
cause,
}),
});
if (!stat.isFile()) {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = yield* Effect.tryPromise({
try: () => handle.read(buffer, 0, bytesToRead, 0),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
});
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "close",
cause,
}),
}),
);
});
@@ -47,6 +47,14 @@ 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,6 +24,11 @@ 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,
@@ -68,6 +73,12 @@ 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,4 +69,25 @@ 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,6 +33,7 @@ import {
readPrimaryCloudLinkState,
type CloudLinkTarget,
unlinkPrimaryEnvironmentFromCloud,
updatePrimaryCloudPreferences,
} from "./linkEnvironment";
const TARGET: CloudLinkTarget = {
@@ -252,6 +253,38 @@ 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,6 +8,7 @@ import {
linkPrimaryEnvironmentToCloud,
type CloudLinkTarget,
unlinkPrimaryEnvironmentFromCloud,
updatePrimaryCloudPreferences,
} from "./linkEnvironment";
const cloudLinkScheduler = createAtomCommandScheduler();
@@ -31,3 +32,11 @@ 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 -3
View File
@@ -1,6 +1,4 @@
import { managedRelaySessionAtom, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -47,7 +45,7 @@ describe("managed relay authentication", () => {
it("replaces an existing account session atomically", () => {
setManagedRelaySession(appAtomRegistry, {
accountId: "account-1",
readClerkToken: () => Effect.succeed(Option.some("account-1-token")),
readClerkToken: async () => "account-1-token",
});
activateManagedRelayAuthentication("account-2", async () => "account-2-token");
+2 -11
View File
@@ -1,16 +1,11 @@
import { useAuth } from "@clerk/react";
import {
ManagedRelay,
ManagedRelaySessionTokenReadError,
setManagedRelaySession,
} from "@t3tools/client-runtime/relay";
import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";
import {
reportAtomCommandResult,
settleAsyncResult,
settlePromise,
} from "@t3tools/client-runtime/state/runtime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { useEffect, useRef, type ReactNode } from "react";
import { environmentCatalog } from "../connection/catalog";
@@ -37,11 +32,7 @@ export function activateManagedRelayAuthentication(
relayTokenProvider = readClerkToken;
setManagedRelaySession(appAtomRegistry, {
accountId,
readClerkToken: () =>
Effect.tryPromise({
try: readClerkToken,
catch: (cause) => new ManagedRelaySessionTokenReadError({ cause }),
}).pipe(Effect.map(Option.fromNullOr)),
readClerkToken,
});
}
+54 -3
View File
@@ -1,14 +1,64 @@
import { useEffect, type ReactNode } from "react";
import { useAtomValue } from "@effect/atom-react";
import { useEffect, type CSSProperties, 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 } from "./ui/sidebar";
import { Sidebar, SidebarProvider, SidebarRail, SidebarTrigger, useSidebar } from "./ui/sidebar";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
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;
@@ -28,7 +78,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
}, [navigate]);
return (
<SidebarProvider className="h-dvh! min-h-0!" defaultOpen>
<SidebarProvider className="h-dvh! min-h-0!" defaultOpen style={macosWindowControlsStyle}>
<Sidebar
side="left"
collapsible="offcanvas"
@@ -44,6 +94,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
<SidebarRail />
</Sidebar>
{children}
<SidebarControl />
</SidebarProvider>
);
}
+4 -2
View File
@@ -54,6 +54,7 @@ import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
import { fnv1a32 } from "../lib/diffRendering";
import { LRUCache } from "../lib/lruCache";
import { useTheme } from "../hooks/useTheme";
import { useClientSettings } from "../hooks/useSettings";
import {
chatMarkdownClipboardPayload,
serializeTableElementToCsv,
@@ -295,7 +296,7 @@ function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {
const containerRef = useRef<HTMLDivElement | null>(null);
const tableRef = useRef<HTMLTableElement | null>(null);
const [expanded, setExpanded] = useState(false);
const [expanded, setExpanded] = useState(useClientSettings((settings) => settings.wordWrap));
const [copied, setCopied] = useState(false);
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const expandLabel = expanded ? "Collapse table cells" : "Expand table cells";
@@ -525,10 +526,11 @@ function MarkdownCodeBlock({
children: ReactNode;
}) {
const [copied, setCopied] = useState(false);
const [wrapped, setWrapped] = useState(false);
const [wrapped, setWrapped] = useState(useClientSettings((settings) => settings.wordWrap));
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;
+3 -1
View File
@@ -128,6 +128,7 @@ 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";
@@ -4677,7 +4678,7 @@ function ChatViewContent(props: ChatViewProps) {
<header
data-chat-header
className={cn(
"border-b border-border",
"border-b border-border transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none",
isElectron
? cn(
"workspace-topbar drag-region relative px-3 sm:px-5",
@@ -4686,6 +4687,7 @@ 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}
+8 -9
View File
@@ -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 [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
const [wordWrap, setWordWrap] = useState(settings.wordWrap);
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
const [baseRefQuery, setBaseRefQuery] = useState("");
const [collapsedDiffFiles, setCollapsedDiffFiles] = useState<CollapsedDiffFilesState>(() => ({
@@ -194,6 +194,7 @@ 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),
@@ -695,14 +696,12 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
<TooltipTrigger
render={
<Toggle
aria-label={
diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"
}
aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
variant="outline"
size="xs"
pressed={diffWordWrap}
pressed={wordWrap}
onPressedChange={(pressed) => {
setDiffWordWrap(Boolean(pressed));
setWordWrap(Boolean(pressed));
}}
/>
}
@@ -710,7 +709,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
<TextWrapIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup side="top">
{diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
{wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
</TooltipPopup>
</Tooltip>
<Tooltip>
@@ -844,7 +843,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
options={{
diffStyle: diffRenderMode === "split" ? "split" : "unified",
lineDiffType: "none",
overflow: diffWordWrap ? "wrap" : "scroll",
overflow: wordWrap ? "wrap" : "scroll",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme as DiffThemeType,
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
@@ -860,7 +859,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",
diffWordWrap
wordWrap
? "overflow-auto whitespace-pre-wrap wrap-break-word"
: "overflow-auto",
)}
@@ -1,7 +1,8 @@
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "./ui/empty";
import { SidebarInset, SidebarTrigger } from "./ui/sidebar";
import { SidebarInset } from "./ui/sidebar";
import { isElectron } from "../env";
import { cn } from "~/lib/utils";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
export function NoActiveThreadState() {
return (
@@ -9,8 +10,9 @@ 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 sm:px-5",
"border-b border-border px-3 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
isElectron ? "workspace-topbar drag-region" : "workspace-topbar",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
{isElectron ? (
@@ -19,7 +21,6 @@ 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>
+53 -53
View File
@@ -70,7 +70,7 @@ import {
type SidebarThreadSortOrder,
} from "@t3tools/contracts/settings";
import { isElectron } from "../env";
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
import { APP_STAGE_LABEL } 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,22 +2452,6 @@ 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"
@@ -2664,48 +2648,64 @@ 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;
const stageBadgeLabel = resolveSidebarStageBadgeLabel({
return resolveSidebarStageBadgeLabel({
primaryServerVersion,
fallbackStageLabel: APP_STAGE_LABEL,
});
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>
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 SidebarChromeFooter = memo(function SidebarChromeFooter() {
const navigate = useNavigate();
@@ -78,6 +78,7 @@ import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
import {
getComposerPromptInjectionState,
getComposerProviderState,
renderProviderTraitsMenuContent,
renderProviderTraitsPicker,
@@ -791,18 +792,22 @@ 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,
prompt,
promptInjectionState: composerPromptInjectionState,
modelOptions: composerModelOptions?.[selectedInstanceId],
}),
[
composerModelOptions,
prompt,
composerPromptInjectionState,
selectedInstanceId,
selectedModel,
selectedProvider,
@@ -14,7 +14,6 @@ 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";
@@ -80,7 +79,6 @@ 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,19 +208,17 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
</>
);
return (
<div
<button
key={`${activeQuestion.id}:${option.label}`}
role="button"
tabIndex={isResponding ? -1 : 0}
aria-disabled={isResponding}
type="button"
disabled={isResponding}
onClick={() => {
if (isResponding) return;
handleOptionSelection(activeQuestion.id, option.label);
}}
className={className}
>
{content}
</div>
</button>
);
})}
</div>
@@ -6,6 +6,7 @@ import {
type ServerProviderModel,
} from "@t3tools/contracts";
import {
getComposerPromptInjectionState,
getComposerProviderState,
renderProviderTraitsMenuContent,
renderProviderTraitsPicker,
@@ -61,6 +62,13 @@ 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,
@@ -71,7 +79,6 @@ describe("getComposerProviderState", () => {
{ id: "high", label: "High", isDefault: true },
]),
]),
prompt: "",
modelOptions: undefined,
});
@@ -93,7 +100,6 @@ describe("getComposerProviderState", () => {
]),
booleanDescriptor("fastMode"),
]),
prompt: "",
modelOptions: selections(["effort", "low"], ["fastMode", true]),
});
@@ -112,7 +118,6 @@ describe("getComposerProviderState", () => {
selectDescriptor("effort", [{ id: "high", label: "High", isDefault: true }]),
booleanDescriptor("fastMode"),
]),
prompt: "",
modelOptions: selections(["effort", "high"], ["fastMode", false]),
});
@@ -126,7 +131,6 @@ describe("getComposerProviderState", () => {
provider: PROVIDER,
model: MODEL,
models: modelWith([booleanDescriptor("thinking")]),
prompt: "",
modelOptions: selections(["effort", "max"], ["thinking", false]),
});
@@ -152,7 +156,6 @@ describe("getComposerProviderState", () => {
{ id: "plan", label: "Plan" },
]),
]),
prompt: "",
modelOptions: selections(["agent", "plan"]),
});
@@ -167,7 +170,6 @@ describe("getComposerProviderState", () => {
provider: PROVIDER,
model: MODEL,
models: modelWith([]),
prompt: "",
modelOptions: selections(["anything", "value"]),
});
@@ -193,7 +195,9 @@ describe("getComposerProviderState", () => {
["ultrathink"],
),
]),
prompt: "Ultrathink:\nInvestigate this failure",
promptInjectionState: getComposerPromptInjectionState(
"Ultrathink:\nInvestigate this failure",
),
modelOptions: selections(["effort", "medium"]),
});
@@ -212,7 +216,9 @@ describe("getComposerProviderState", () => {
models: modelWith([
selectDescriptor("effort", [{ id: "high", label: "High", isDefault: true }]),
]),
prompt: "Ultrathink:\nInvestigate this failure",
promptInjectionState: getComposerPromptInjectionState(
"Ultrathink:\nInvestigate this failure",
),
modelOptions: undefined,
});
@@ -21,10 +21,12 @@ export type ComposerProviderStateInput = {
provider: ProviderDriverKind;
model: string;
models: ReadonlyArray<ServerProviderModel>;
prompt: string;
promptInjectionState?: ComposerPromptInjectionState;
modelOptions: ReadonlyArray<ProviderOptionSelection> | null | undefined;
};
export type ComposerPromptInjectionState = "none" | "ultrathink";
export type ComposerProviderState = {
provider: ProviderDriverKind;
promptEffort: string | null;
@@ -46,8 +48,12 @@ 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, prompt, modelOptions } = input;
const { provider, model, models, modelOptions, promptInjectionState = "none" } = input;
const caps = getProviderModelCapabilities(models, model, provider);
const descriptors = getProviderOptionDescriptors({ caps, selections: modelOptions });
const primarySelectDescriptor = descriptors.find(
@@ -58,7 +64,7 @@ export function getComposerProviderState(input: ComposerProviderStateInput): Com
const promptEffort = typeof primaryValue === "string" ? primaryValue : null;
const ultrathinkActive =
(primarySelectDescriptor?.promptInjectedValues?.length ?? 0) > 0 &&
isClaudeUltrathinkPrompt(prompt);
promptInjectionState === "ultrathink";
return {
provider,
@@ -0,0 +1,65 @@
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");
});
});
@@ -0,0 +1,39 @@
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)}`;
}
@@ -0,0 +1,166 @@
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,8 +1,9 @@
import { UserButton, useAuth } from "@clerk/react";
import { LogInIcon } from "lucide-react";
import { LogInIcon, SmartphoneIcon } 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() {
@@ -30,7 +31,15 @@ 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>
);
}
@@ -18,6 +18,7 @@ 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";
@@ -248,6 +249,7 @@ interface EditableFileSurfaceProps {
contents: string;
resolvedTheme: "light" | "dark";
revealRequestId: number;
wordWrap: boolean;
onPostRender: FilePostRender;
onPendingChange: (relativePath: string, pending: boolean) => void;
}
@@ -296,6 +298,7 @@ function EditableFileSurface({
contents,
resolvedTheme,
revealRequestId,
wordWrap,
onPostRender,
onPendingChange,
}: EditableFileSurfaceProps) {
@@ -516,7 +519,7 @@ function EditableFileSurface({
onGutterUtilityClick: setSelectedRange,
onLineSelectionChange: setSelectedRange,
onLineSelectionEnd: handleLineSelectionEnd,
overflow: "scroll",
overflow: wordWrap ? "wrap" : "scroll",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme,
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
@@ -557,7 +560,12 @@ function RenderedMarkdownSurface({
onPendingChange,
}: Omit<
EditableFileSurfaceProps,
"resolvedTheme" | "composerDraftTarget" | "revealLine" | "revealRequestId" | "onPostRender"
| "resolvedTheme"
| "composerDraftTarget"
| "revealLine"
| "revealRequestId"
| "wordWrap"
| "onPostRender"
> & {
threadRef: ScopedThreadRef;
}) {
@@ -613,6 +621,7 @@ 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, {
@@ -844,7 +853,7 @@ export default function FilePreviewPanel({
}}
options={{
disableFileHeader: true,
overflow: "scroll",
overflow: wordWrap ? "wrap" : "scroll",
theme: resolveDiffThemeName(resolvedTheme),
themeType: resolvedTheme,
unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS,
@@ -863,6 +872,7 @@ export default function FilePreviewPanel({
contents={file.data.contents}
resolvedTheme={resolvedTheme}
revealRequestId={revealRequestId}
wordWrap={wordWrap}
onPostRender={onFilePostRender}
onPendingChange={onPendingChange}
/>
@@ -118,6 +118,7 @@ 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";
@@ -1423,6 +1424,31 @@ 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" &&
@@ -1432,7 +1458,7 @@ function SavedBackendListRow({
: null;
const metadataBits = [
sshTarget ? `SSH ${formatDesktopSshTarget(sshTarget)}` : null,
environment.relayManaged ? "T3 Cloud" : null,
environment.relayManaged ? "T3 Connect" : null,
].filter((value): value is string => value !== null);
return (
@@ -1468,7 +1494,7 @@ function SavedBackendListRow({
<button
type="button"
className="shrink-0 underline underline-offset-2"
onClick={() => void navigator.clipboard.writeText(errorTraceId)}
onClick={() => copyTraceId(errorTraceId)}
>
Copy trace ID
</button>
@@ -1550,7 +1576,7 @@ function CloudLinkSwitch({
}) {
const control = (
<Switch
aria-label="Enable T3 Cloud"
aria-label="Enable T3 Connect"
checked={checked}
disabled={disabled}
{...(onCheckedChange ? { onCheckedChange } : {})}
@@ -1577,18 +1603,23 @@ 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 Cloud access.";
const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";
const traceId = findErrorTraceId(cause);
console.error("[t3-cloud] Could not update T3 Cloud", { message, traceId, cause });
console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });
setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);
toastManager.add({
type: "error",
title: "Could not update T3 Cloud",
title: "Could not update T3 Connect",
description: message,
data: traceId
? {
@@ -1618,9 +1649,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
return;
}
if (enabled && !tokenResult.value) {
reportUpdateFailure(
new Error("Sign in from T3 Cloud settings before linking this environment."),
);
reportUpdateFailure(new Error("Sign in to T3 Connect before linking this environment."));
setIsUpdating(false);
return;
}
@@ -1655,38 +1684,95 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
toastManager.add({
type: "success",
title: enabled ? "T3 Cloud linked" : "T3 Cloud unlinked",
title: enabled ? "T3 Connect linked" : "T3 Connect unlinked",
description: enabled
? "This environment is available through T3 Cloud."
: "This environment is no longer available through T3 Cloud.",
? "This environment is available through T3 Connect."
: "This environment is no longer available through T3 Connect.",
});
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 from T3 Cloud settings to manage this environment."
? "Sign in to T3 Connect to manage this environment."
: !canManageRelay
? "Your session does not have permission to manage T3 Cloud access."
? "Your session does not have permission to manage T3 Connect access."
: null;
const linked = primaryCloudLinkState.data?.linked ?? false;
return (
<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)}
<>
<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)}
/>
}
/>
}
/>
) : null}
</>
);
}
@@ -1704,7 +1790,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 Cloud."
? "Click “Add environment” to pair another environment, or connect one from T3 Connect."
: "Click “Add environment” to pair another environment."}
</EmptyDescription>
</EmptyHeader>
@@ -1769,7 +1855,7 @@ function ConfiguredCloudRemoteEnvironmentRows({
toastManager.add({
type: "success",
title: "Environment connected",
description: `${environment.label} is available through T3 Cloud.`,
description: `${environment.label} is available through T3 Connect.`,
});
return;
}
@@ -1778,9 +1864,9 @@ function ConfiguredCloudRemoteEnvironmentRows({
}
const cause = squashAtomCommandFailure(result);
const message =
cause instanceof Error ? cause.message : "Could not connect the T3 Cloud environment.";
cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.";
const traceId = findErrorTraceId(cause);
console.error("[t3-cloud] Could not connect environment", { message, traceId, cause });
console.error("[t3-connect] Could not connect environment", { message, traceId, cause });
toastManager.add({
type: "error",
title: "Could not connect environment",
@@ -391,9 +391,7 @@ export function useSettingsRestore(onRestored?: () => void) {
...(settings.sidebarThreadPreviewCount !== DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount
? ["Visible threads"]
: []),
...(settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap
? ["Diff line wrapping"]
: []),
...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []),
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
? ["Diff whitespace changes"]
: []),
@@ -434,11 +432,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,
],
);
@@ -456,7 +454,7 @@ export function useSettingsRestore(onRestored?: () => void) {
setTheme("system");
updateSettings({
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
diffWordWrap: DEFAULT_UNIFIED_SETTINGS.diffWordWrap,
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
autoOpenPlanSidebar: DEFAULT_UNIFIED_SETTINGS.autoOpenPlanSidebar,
@@ -594,15 +592,15 @@ export function GeneralSettingsPanel() {
/>
<SettingsRow
title="Diff line wrapping"
description="Set the default wrap state when the diff panel opens."
title="Word wrap"
description="Wrap long lines in code blocks, tables, diffs, and file previews by default."
resetAction={
settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap ? (
settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? (
<SettingResetButton
label="diff line wrapping"
label="word wrapping"
onClick={() =>
updateSettings({
diffWordWrap: DEFAULT_UNIFIED_SETTINGS.diffWordWrap,
wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,
})
}
/>
@@ -610,9 +608,9 @@ export function GeneralSettingsPanel() {
}
control={
<Switch
checked={settings.diffWordWrap}
onCheckedChange={(checked) => updateSettings({ diffWordWrap: Boolean(checked) })}
aria-label="Wrap diff lines by default"
checked={settings.wordWrap}
onCheckedChange={(checked) => updateSettings({ wordWrap: Boolean(checked) })}
aria-label="Wrap code, tables, diffs, and file previews by default"
/>
}
/>
@@ -6,7 +6,9 @@ import {
SidebarMenuButton,
SidebarMenuSubButton,
SidebarProvider,
SidebarTrigger,
} from "./sidebar";
import { resolveSidebarState } from "./sidebarState";
function renderSidebarButton(className?: string) {
return renderToStaticMarkup(
@@ -17,6 +19,37 @@ 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();
+18 -5
View File
@@ -19,6 +19,7 @@ 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";
@@ -29,7 +30,7 @@ const SIDEBAR_WIDTH_ICON = "3rem";
const SIDEBAR_RESIZE_DEFAULT_MIN_WIDTH = 16 * 16;
type SidebarContextProps = {
state: "expanded" | "collapsed";
state: ResponsiveSidebarState;
open: boolean;
setOpen: (open: boolean) => void;
openMobile: boolean;
@@ -85,6 +86,11 @@ function useSidebar() {
return context;
}
function useSidebarVisibility() {
const { isMobile, open, openMobile } = useSidebar();
return isMobile ? openMobile : open;
}
function SidebarProvider({
defaultOpen = true,
open: openProp,
@@ -132,7 +138,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 = open ? "expanded" : "collapsed";
const state = resolveSidebarState({ isMobile, open, openMobile });
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
@@ -154,6 +160,7 @@ 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={
{
@@ -310,13 +317,18 @@ function Sidebar({
}
function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
const { toggleSidebar, openMobile } = useSidebar();
const { toggleSidebar } = useSidebar();
const isOpen = useSidebarVisibility();
return (
<Button
className={cn("size-7", className)}
className={cn(
"size-[var(--workspace-titlebar-control-size)]! [-webkit-app-region:no-drag]",
className,
)}
data-sidebar="trigger"
data-slot="sidebar-trigger"
aria-pressed={isOpen}
onClick={(event) => {
onClick?.(event);
toggleSidebar();
@@ -325,7 +337,7 @@ function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<t
variant="ghost"
{...props}
>
{openMobile ? <PanelLeftCloseIcon /> : <PanelLeftIcon />}
{isOpen ? <PanelLeftCloseIcon /> : <PanelLeftIcon />}
<span className="sr-only">Toggle Sidebar</span>
</Button>
);
@@ -1004,4 +1016,5 @@ export {
SidebarSeparator,
SidebarTrigger,
useSidebar,
useSidebarVisibility,
};
@@ -0,0 +1,9 @@
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";
}
+7 -10
View File
@@ -176,16 +176,13 @@ const capabilitiesLayer = Layer.effectContext(
}),
),
);
return yield* Option.match(token, {
onNone: () =>
Effect.fail(
new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
}),
),
onSome: Effect.succeed,
});
if (token === null) {
return yield* new ConnectionBlockedError({
reason: "authentication",
detail: "The T3 Cloud session is unavailable.",
});
}
return token;
}),
});
const identity = RelayDeviceIdentity.of({
+33
View File
@@ -7,13 +7,24 @@
: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
);
@@ -90,6 +101,28 @@
}
@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);
+5
View File
@@ -85,6 +85,7 @@ 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" },
{
@@ -312,6 +313,10 @@ 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(
-2
View File
@@ -303,7 +303,6 @@ export function resolveAppModelSelectionState(
provider,
model,
models: entry.models,
prompt: "",
modelOptions: selectedEntry ? selection.options : undefined,
});
@@ -321,7 +320,6 @@ export function resolveAppModelSelectionState(
provider,
model,
models: getProviderModels(providers, provider),
prompt: "",
modelOptions: keptSelectedProvider ? selection.options : undefined,
});
+9 -3
View File
@@ -4,10 +4,12 @@ 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, SidebarTrigger } from "../components/ui/sidebar";
import { SidebarInset } 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();
@@ -30,9 +32,13 @@ 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="border-b border-border px-3 py-2 sm:px-5 sm:py-3">
<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,
)}
>
<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>
+15 -4
View File
@@ -11,8 +11,10 @@ import { useCallback, useEffect, useState } from "react";
import { useSettingsRestore } from "../components/settings/SettingsPanels";
import { Button } from "../components/ui/button";
import { SidebarInset, SidebarTrigger } from "../components/ui/sidebar";
import { SidebarInset } 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);
@@ -64,9 +66,13 @@ 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="border-b border-border px-3 py-2 sm:px-5">
<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,
)}
>
<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">
@@ -78,7 +84,12 @@ function SettingsContentLayout() {
)}
{isElectron && (
<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)]">
<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,
)}
>
<span className="text-xs font-medium tracking-wide text-muted-foreground/70">
Settings
</span>
+2
View File
@@ -0,0 +1,2 @@
export const COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS =
"[[data-sidebar-state=collapsed]_&]:pl-[var(--workspace-titlebar-content-left)]";
@@ -4,15 +4,11 @@ import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { Atom, AtomRegistry } from "effect/unstable/reactivity";
import { afterEach, vi } from "vite-plus/test";
@@ -100,7 +96,7 @@ function createManager(
function setSession() {
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: () => Effect.succeed(Option.some("clerk-token")),
readClerkToken: () => Promise.resolve("clerk-token"),
});
}
@@ -119,17 +115,20 @@ describe("createManagedRelayQueryManager", () => {
setSession();
assert.equal(yield* Fiber.join(tokenFiber), "clerk-token");
assert.equal(registry.getNodes().get(managedRelaySessionAtom)?.listeners.size, 0);
expect(yield* Fiber.join(tokenFiber)).toBe("clerk-token");
expect(registry.getNodes().get(managedRelaySessionAtom)?.listeners.size).toBe(0);
}),
);
it.effect("deduplicates concurrent Clerk token reads and reuses the token until JWT expiry", () =>
Effect.gen(function* () {
const token = clerkToken(4_102_444_800);
const tokenDeferred = yield* Deferred.make<string>();
const readClerkToken = vi.fn(() =>
Deferred.await(tokenDeferred).pipe(Effect.map(Option.some)),
let resolveToken!: (value: string) => void;
const readClerkToken = vi.fn(
() =>
new Promise<string>((resolve) => {
resolveToken = resolve;
}),
);
const session = createManagedRelaySession({
accountId: "account-1",
@@ -140,69 +139,48 @@ describe("createManagedRelayQueryManager", () => {
concurrency: "unbounded",
}).pipe(Effect.forkChild);
yield* Effect.yieldNow;
assert.equal(readClerkToken.mock.calls.length, 1);
expect(readClerkToken).toHaveBeenCalledTimes(1);
yield* Deferred.succeed(tokenDeferred, token);
assert.deepEqual(yield* Fiber.join(readsFiber), [Option.some(token), Option.some(token)]);
assert.equal(Option.getOrThrow(yield* session.readClerkToken()), token);
assert.equal(readClerkToken.mock.calls.length, 1);
resolveToken(token);
expect(yield* Fiber.join(readsFiber)).toEqual([token, token]);
expect(yield* session.readClerkToken()).toBe(token);
expect(readClerkToken).toHaveBeenCalledTimes(1);
}),
);
it.effect("refreshes the cached Clerk token after JWT expiry using TestClock", () =>
Effect.gen(function* () {
const firstToken = clerkToken(10);
const secondToken = clerkToken(30);
const tokens = [firstToken, secondToken];
const readClerkToken = vi.fn(() =>
Effect.sync(() => Option.some(tokens.shift() ?? "unexpected-token")),
);
const session = createManagedRelaySession({
accountId: "account-1",
readClerkToken,
});
assert.equal(Option.getOrThrow(yield* session.readClerkToken()), firstToken);
assert.equal(Option.getOrThrow(yield* session.readClerkToken()), firstToken);
assert.equal(readClerkToken.mock.calls.length, 1);
yield* TestClock.adjust(Duration.seconds(6));
assert.equal(Option.getOrThrow(yield* session.readClerkToken()), secondToken);
assert.equal(readClerkToken.mock.calls.length, 2);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("updates the token provider without replacing a same-account session", () =>
Effect.gen(function* () {
const firstRead = vi.fn(() => Effect.succeed(Option.none<string>()));
const firstRead = vi.fn(() => Promise.resolve<string | null>(null));
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: firstRead,
});
const firstSession = registry.get(managedRelaySessionAtom);
expect(firstSession).not.toBeNull();
assert.isTrue(Option.isNone(yield* firstSession!.readClerkToken()));
expect(yield* firstSession!.readClerkToken()).toBeNull();
const secondRead = vi.fn(() => Effect.succeed(Option.some("refreshed-token")));
const secondRead = vi.fn(() => Promise.resolve<string | null>("refreshed-token"));
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: secondRead,
});
expect(registry.get(managedRelaySessionAtom)).toBe(firstSession);
assert.equal(Option.getOrThrow(yield* firstSession!.readClerkToken()), "refreshed-token");
assert.equal(firstRead.mock.calls.length, 1);
assert.equal(secondRead.mock.calls.length, 1);
expect(yield* firstSession!.readClerkToken()).toBe("refreshed-token");
expect(firstRead).toHaveBeenCalledTimes(1);
expect(secondRead).toHaveBeenCalledTimes(1);
}),
);
it.effect("does not pin a refreshed session to an older pending token read", () =>
Effect.gen(function* () {
const firstTokenDeferred = yield* Deferred.make<string>();
let resolveFirst!: (token: string) => void;
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: () => Deferred.await(firstTokenDeferred).pipe(Effect.map(Option.some)),
readClerkToken: () =>
new Promise<string>((resolve) => {
resolveFirst = resolve;
}),
});
const session = registry.get(managedRelaySessionAtom);
const firstRead = yield* session!.readClerkToken().pipe(Effect.forkChild);
@@ -210,19 +188,19 @@ describe("createManagedRelayQueryManager", () => {
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: () => Effect.succeed(Option.some("refreshed-token")),
readClerkToken: () => Promise.resolve("refreshed-token"),
});
assert.equal(Option.getOrThrow(yield* session!.readClerkToken()), "refreshed-token");
yield* Deferred.succeed(firstTokenDeferred, "older-token");
assert.equal(Option.getOrThrow(yield* Fiber.join(firstRead)), "older-token");
expect(yield* session!.readClerkToken()).toBe("refreshed-token");
resolveFirst("older-token");
expect(yield* Fiber.join(firstRead)).toBe("older-token");
}),
);
it("emits credential changes only when the managed relay account changes", async () => {
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: () => Effect.succeed(Option.some("first-token")),
readClerkToken: () => Promise.resolve("first-token"),
});
const changes = Effect.runPromise(
managedRelayAccountChanges(registry).pipe(Stream.take(2), Stream.runCollect),
@@ -233,11 +211,11 @@ describe("createManagedRelayQueryManager", () => {
setManagedRelaySession(registry, {
accountId: "account-1",
readClerkToken: () => Effect.succeed(Option.some("refreshed-token")),
readClerkToken: () => Promise.resolve("refreshed-token"),
});
setManagedRelaySession(registry, {
accountId: "account-2",
readClerkToken: () => Effect.succeed(Option.some("second-token")),
readClerkToken: () => Promise.resolve("second-token"),
});
setManagedRelaySession(registry, null);
@@ -256,7 +234,7 @@ describe("createManagedRelayQueryManager", () => {
},
} satisfies RelayClientEnvironmentRecord;
const token = clerkToken(4_102_444_800);
const readClerkToken = vi.fn(() => Effect.succeed(Option.some(token)));
const readClerkToken = vi.fn(() => Promise.resolve(token));
const manager = createManager({
listEnvironments: () => Effect.succeed([environment, secondEnvironment]),
getEnvironmentStatus: ({ environmentId }) => {
@@ -9,30 +9,27 @@ import {
import { decodeRelayJwt } from "@t3tools/shared/relayJwt";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
import { findErrorTraceId } from "../errors/errorTrace.ts";
import * as ManagedRelay from "./managedRelay.ts";
const DEFAULT_STALE_TIME = Duration.seconds(15);
const DEFAULT_IDLE_TTL = Duration.minutes(5);
const CLERK_TOKEN_EXPIRY_SKEW = Duration.seconds(5);
const DEFAULT_STALE_TIME_MS = 15_000;
const DEFAULT_IDLE_TTL_MS = 5 * 60_000;
const CLERK_TOKEN_EXPIRY_SKEW_MS = 5_000;
export interface ManagedRelaySession {
readonly accountId: string;
readonly readClerkToken: () => Effect.Effect<Option.Option<string>, ManagedRelaySessionError>;
readonly readClerkToken: () => Effect.Effect<string | null, ManagedRelaySessionError>;
}
export interface ManagedRelaySessionInput {
readonly accountId: string;
readonly readClerkToken: () => Effect.Effect<Option.Option<string>, ManagedRelaySessionError>;
readonly readClerkToken: () => Promise<string | null>;
}
interface ManagedRelaySessionControl {
@@ -58,36 +55,14 @@ export interface ManagedRelayQueryEvent {
readonly traceId?: string | null;
}
export class ManagedRelaySessionTokenReadError extends Schema.TaggedErrorClass<ManagedRelaySessionTokenReadError>()(
"ManagedRelaySessionTokenReadError",
{ cause: Schema.Defect() },
) {
override get message(): string {
return "Could not obtain the T3 Cloud session token.";
}
}
export class ManagedRelaySessionError extends Data.TaggedError("ManagedRelaySessionError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class ManagedRelaySessionTokenUnavailableError extends Schema.TaggedErrorClass<ManagedRelaySessionTokenUnavailableError>()(
"ManagedRelaySessionTokenUnavailableError",
{ reason: Schema.Literals(["missing-session", "missing-token"]) },
) {
override get message(): string {
return this.reason === "missing-session"
? "Sign in to T3 Cloud before loading relay data."
: "The T3 Cloud session token is unavailable.";
}
}
export const ManagedRelaySessionError = Schema.Union([
ManagedRelaySessionTokenReadError,
ManagedRelaySessionTokenUnavailableError,
]);
export type ManagedRelaySessionError = typeof ManagedRelaySessionError.Type;
export class ManagedRelaySnapshotError extends Schema.TaggedErrorClass<ManagedRelaySnapshotError>()(
"ManagedRelaySnapshotError",
{ message: Schema.String },
) {}
export class ManagedRelaySnapshotError extends Data.TaggedError("ManagedRelaySnapshotError")<{
readonly message: string;
}> {}
export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(null).pipe(
Atom.keepAlive,
@@ -96,102 +71,69 @@ export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(nul
const managedRelaySessionControls = new WeakMap<ManagedRelaySession, ManagedRelaySessionControl>();
interface CachedClerkToken {
readonly token: string;
readonly expiresAtMillis: number;
}
interface PendingClerkTokenRead {
readonly deferred: Deferred.Deferred<Option.Option<string>, ManagedRelaySessionError>;
}
interface ManagedRelaySessionCacheState {
readonly readClerkToken: ManagedRelaySessionInput["readClerkToken"];
readonly generation: number;
readonly cachedToken: Option.Option<CachedClerkToken>;
readonly pendingToken: Option.Option<PendingClerkTokenRead>;
}
function isFreshCachedToken(cachedToken: CachedClerkToken, nowMillis: number): boolean {
return cachedToken.expiresAtMillis > nowMillis + Duration.toMillis(CLERK_TOKEN_EXPIRY_SKEW);
}
function decodeCachedToken(token: string): Option.Option<CachedClerkToken> {
try {
const expiresAtSeconds = decodeRelayJwt(token).exp;
return typeof expiresAtSeconds === "number"
? Option.some({ token, expiresAtMillis: expiresAtSeconds * 1_000 })
: Option.none();
} catch {
return Option.none();
}
}
export function createManagedRelaySession(input: ManagedRelaySessionInput): ManagedRelaySession {
let state: ManagedRelaySessionCacheState = {
readClerkToken: input.readClerkToken,
generation: 0,
cachedToken: Option.none(),
pendingToken: Option.none(),
let cachedToken: { readonly token: string; readonly expiresAtMillis: number } | null = null;
let pendingToken: Promise<string | null> | null = null;
let readClerkToken = input.readClerkToken;
let tokenProviderGeneration = 0;
const readCachedClerkToken = async (nowMillis: number): Promise<string | null> => {
if (cachedToken && cachedToken.expiresAtMillis > nowMillis + CLERK_TOKEN_EXPIRY_SKEW_MS) {
return cachedToken.token;
}
if (pendingToken) {
return await pendingToken;
}
const operationGeneration = tokenProviderGeneration;
const operation = readClerkToken().then((token) => {
if (operationGeneration !== tokenProviderGeneration) {
return token;
}
if (!token) {
cachedToken = null;
return null;
}
try {
const expiresAtSeconds = decodeRelayJwt(token).exp;
cachedToken =
typeof expiresAtSeconds === "number"
? { token, expiresAtMillis: expiresAtSeconds * 1_000 }
: null;
} catch {
cachedToken = null;
}
return token;
});
pendingToken = operation;
try {
return await operation;
} finally {
if (pendingToken === operation) {
pendingToken = null;
}
}
};
const session: ManagedRelaySession = {
accountId: input.accountId,
readClerkToken: Effect.fn("clientRuntime.managedRelaySession.readClerkToken")(function* () {
const nowMillis = yield* Clock.currentTimeMillis;
const current = state;
if (
Option.isSome(current.cachedToken) &&
isFreshCachedToken(current.cachedToken.value, nowMillis)
) {
return Option.some(current.cachedToken.value.token);
}
if (Option.isSome(current.pendingToken)) {
return yield* Deferred.await(current.pendingToken.value.deferred);
}
const deferred = yield* Deferred.make<Option.Option<string>, ManagedRelaySessionError>();
state = {
...state,
pendingToken: Option.some({ deferred }),
};
const readExit = yield* Effect.exit(current.readClerkToken());
if (Exit.isSuccess(readExit)) {
if (state.generation === current.generation) {
state = {
...state,
cachedToken: Option.isSome(readExit.value)
? decodeCachedToken(readExit.value.value)
: Option.none(),
};
}
yield* Deferred.succeed(deferred, readExit.value).pipe(Effect.orDie);
} else {
yield* Deferred.failCause(deferred, readExit.cause).pipe(Effect.orDie);
}
if (Option.isSome(state.pendingToken) && state.pendingToken.value.deferred === deferred) {
state = {
...state,
pendingToken: Option.none(),
};
}
if (Exit.isSuccess(readExit)) {
return readExit.value;
}
return yield* Effect.failCause(readExit.cause);
return yield* Effect.tryPromise({
try: () => readCachedClerkToken(nowMillis),
catch: (cause) =>
new ManagedRelaySessionError({
message: "Could not obtain the T3 Cloud session token.",
cause,
}),
});
}),
};
managedRelaySessionControls.set(session, {
updateReadClerkToken: (nextReadClerkToken) => {
state = {
readClerkToken: nextReadClerkToken,
generation: state.generation + 1,
cachedToken: Option.none(),
pendingToken: Option.none(),
};
readClerkToken = nextReadClerkToken;
tokenProviderGeneration += 1;
pendingToken = null;
},
});
return session;
@@ -234,12 +176,14 @@ function readSessionClerkToken(
session: ManagedRelaySession,
): Effect.Effect<string, ManagedRelaySessionError> {
return session.readClerkToken().pipe(
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(new ManagedRelaySessionTokenUnavailableError({ reason: "missing-token" })),
onSome: Effect.succeed,
}),
Effect.flatMap((token) =>
token
? Effect.succeed(token)
: Effect.fail(
new ManagedRelaySessionError({
message: "The T3 Cloud session token is unavailable.",
}),
),
),
);
}
@@ -280,7 +224,11 @@ function requireClerkToken(
): Effect.Effect<string, ManagedRelaySessionError> {
const session = get(managedRelaySessionAtom);
if (!session || session.accountId !== accountId) {
return Effect.fail(new ManagedRelaySessionTokenUnavailableError({ reason: "missing-session" }));
return Effect.fail(
new ManagedRelaySessionError({
message: "Sign in to T3 Cloud before loading relay data.",
}),
);
}
return readSessionClerkToken(session);
}
@@ -367,8 +315,8 @@ export function createManagedRelayQueryManager(
readonly onQueryEvent?: (event: ManagedRelayQueryEvent) => void;
},
) {
const staleTime = options?.staleTimeMs ?? Duration.toMillis(DEFAULT_STALE_TIME);
const idleTtl = options?.idleTtlMs ?? Duration.toMillis(DEFAULT_IDLE_TTL);
const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS;
const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
const observe = <A, E, R>(
input: Omit<ManagedRelayQueryEvent, "phase" | "message" | "traceId">,
effect: Effect.Effect<A, E, R>,
@@ -44,6 +44,26 @@ const stubThread = {
} as const;
describe("applyShellStreamEvent", () => {
it("ignores stale project upserts without mutating the snapshot", () => {
const snapshotWithProject: OrchestrationShellSnapshot = {
...baseSnapshot,
snapshotSequence: 4,
projects: [stubProject],
};
for (const sequence of [3, 4]) {
const next = applyShellStreamEvent(snapshotWithProject, {
kind: "project-upserted",
sequence,
project: { ...stubProject, title: "Stale Title" },
});
expect(next).toBe(snapshotWithProject);
expect(next.snapshotSequence).toBe(4);
expect(next.projects[0]?.title).toBe("Test Project");
}
});
describe("project-upserted", () => {
it("adds a new project", () => {
const event: OrchestrationShellStreamEvent = {
@@ -13,6 +13,8 @@ export function applyShellStreamEvent(
snapshot: OrchestrationShellSnapshot,
event: OrchestrationShellStreamEvent,
): OrchestrationShellSnapshot {
if (event.sequence <= snapshot.snapshotSequence) return snapshot;
switch (event.kind) {
case "project-upserted": {
const projects = snapshot.projects.some((p) => p.id === event.project.id)
@@ -29,6 +29,12 @@ it.effect("parses keybinding rules", () =>
});
assert.strictEqual(parsed.command, "terminal.toggle");
const parsedSidebarToggle = yield* decode(KeybindingRule, {
key: "mod+b",
command: "sidebar.toggle",
});
assert.strictEqual(parsedSidebarToggle.command, "sidebar.toggle");
const parsedRightPanelToggle = yield* decode(KeybindingRule, {
key: "mod+alt+b",
command: "rightPanel.toggle",
+1
View File
@@ -48,6 +48,7 @@ export const MODEL_PICKER_KEYBINDING_COMMANDS = [
export type ModelPickerKeybindingCommand = (typeof MODEL_PICKER_KEYBINDING_COMMANDS)[number];
const STATIC_KEYBINDING_COMMANDS = [
"sidebar.toggle",
"terminal.toggle",
"terminal.split",
"terminal.splitVertical",
+24 -1
View File
@@ -2,12 +2,35 @@ import { describe, expect, it } from "vite-plus/test";
import * as Schema from "effect/Schema";
import { ProviderInstanceId } from "./providerInstance.ts";
import { DEFAULT_SERVER_SETTINGS, ServerSettings, ServerSettingsPatch } from "./settings.ts";
import {
ClientSettingsSchema,
DEFAULT_SERVER_SETTINGS,
ServerSettings,
ServerSettingsPatch,
} from "./settings.ts";
const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema);
const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);
const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
describe("ClientSettings word wrap", () => {
it("defaults word wrap on", () => {
expect(decodeClientSettings({}).wordWrap).toBe(true);
});
it("ignores obsolete wrapping preferences", () => {
const decoded = decodeClientSettings({
chatWordWrap: false,
diffWordWrap: false,
});
expect(decoded.wordWrap).toBe(true);
expect(decoded).not.toHaveProperty("chatWordWrap");
expect(decoded).not.toHaveProperty("diffWordWrap");
});
});
describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
it("defaults to an empty record so legacy configs without the key still decode", () => {
expect(DEFAULT_SERVER_SETTINGS.providerInstances).toEqual({});
+2 -2
View File
@@ -47,7 +47,6 @@ export const ClientSettingsSchema = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed([])),
),
diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
// Model favorites. Historically keyed by provider kind, now
// widened to `ProviderInstanceId` so users can favorite a specific model
// on a custom provider instance (e.g. "Codex Personal · gpt-5") without
@@ -92,6 +91,7 @@ export const ClientSettingsSchema = Schema.Struct({
timestampFormat: TimestampFormat.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)),
),
wordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
});
export type ClientSettings = typeof ClientSettingsSchema.Type;
@@ -538,7 +538,6 @@ export const ClientSettingsPatch = Schema.Struct({
confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
diffWordWrap: Schema.optionalKey(Schema.Boolean),
favorites: Schema.optionalKey(
Schema.Array(
Schema.Struct({
@@ -568,5 +567,6 @@ export const ClientSettingsPatch = Schema.Struct({
sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder),
sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount),
timestampFormat: Schema.optionalKey(TimestampFormat),
wordWrap: Schema.optionalKey(Schema.Boolean),
});
export type ClientSettingsPatch = typeof ClientSettingsPatch.Type;
+1
View File
@@ -19,6 +19,7 @@ type WhenToken =
| { type: "rparen" };
export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+b", command: "sidebar.toggle" },
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+alt+b", command: "rightPanel.toggle" },
{ key: "mod+d", command: "terminal.split", when: "terminalFocus" },
+47
View File
@@ -72,6 +72,53 @@ describe("remote", () => {
});
});
it("rejects unsupported direct pairing URL protocols", () => {
let pairingUrlError: unknown;
try {
resolveRemotePairingTarget({
pairingUrl: "ftp://remote.example.com/pair#token=pairing-token",
});
} catch (cause) {
pairingUrlError = cause;
}
expect(pairingUrlError).toBeInstanceOf(RemotePairingUrlInvalidError);
expect(pairingUrlError).toMatchObject({ protocol: "ftp:" });
expect((pairingUrlError as RemotePairingUrlInvalidError).cause).toBeUndefined();
});
it("rejects unsupported hosted pairing backend protocols", () => {
let hostError: unknown;
try {
resolveRemotePairingTarget({
pairingUrl:
"https://app.t3.codes/pair?host=ftp%3A%2F%2Fremote.example.com#token=pairing-token",
});
} catch (cause) {
hostError = cause;
}
expect(hostError).toBeInstanceOf(RemoteBackendUrlInvalidError);
expect(hostError).toMatchObject({ source: "hosted-pairing-host", protocol: "ftp:" });
expect((hostError as RemoteBackendUrlInvalidError).cause).toBeUndefined();
});
it("rejects unsupported direct host protocols", () => {
let hostError: unknown;
try {
resolveRemotePairingTarget({
host: "ftp://remote.example.com",
pairingCode: "pairing-token",
});
} catch (cause) {
hostError = cause;
}
expect(hostError).toBeInstanceOf(RemoteBackendUrlInvalidError);
expect(hostError).toMatchObject({ source: "direct-host", protocol: "ftp:" });
expect((hostError as RemoteBackendUrlInvalidError).cause).toBeUndefined();
});
it("uses distinct structural errors for missing pairing inputs", () => {
expect(() => resolveRemotePairingTarget({})).toThrowError(RemoteBackendUrlMissingError);
expect(() =>
+21 -2
View File
@@ -3,6 +3,7 @@ import * as Schema from "effect/Schema";
const PAIRING_TOKEN_PARAM = "token";
const HOSTED_PAIRING_HOST_PARAM = "host";
const HOSTED_PAIRING_LABEL_PARAM = "label";
const SUPPORTED_REMOTE_BACKEND_PROTOCOLS = new Set(["http:", "https:", "ws:", "wss:"]);
const readHashParams = (url: URL): URLSearchParams =>
new URLSearchParams(url.hash.startsWith("#") ? url.hash.slice(1) : url.hash);
@@ -18,7 +19,10 @@ export class RemoteBackendUrlMissingError extends Schema.TaggedErrorClass<Remote
export class RemotePairingUrlInvalidError extends Schema.TaggedErrorClass<RemotePairingUrlInvalidError>()(
"RemotePairingUrlInvalidError",
{ cause: Schema.Defect() },
{
cause: Schema.optional(Schema.Defect()),
protocol: Schema.optional(Schema.String),
},
) {
override get message(): string {
return "Pairing URL is invalid.";
@@ -29,7 +33,8 @@ export class RemoteBackendUrlInvalidError extends Schema.TaggedErrorClass<Remote
"RemoteBackendUrlInvalidError",
{
source: Schema.Literals(["direct-host", "hosted-pairing-host"]),
cause: Schema.Defect(),
cause: Schema.optional(Schema.Defect()),
protocol: Schema.optional(Schema.String),
},
) {
override get message(): string {
@@ -64,6 +69,9 @@ export const RemotePairingTargetError = Schema.Union([
]);
export type RemotePairingTargetError = typeof RemotePairingTargetError.Type;
const hasSupportedRemoteBackendProtocol = (url: URL): boolean =>
SUPPORTED_REMOTE_BACKEND_PROTOCOLS.has(url.protocol);
const normalizeRemoteBaseUrl = (
rawValue: string,
source: RemoteBackendUrlInvalidError["source"],
@@ -83,6 +91,12 @@ const normalizeRemoteBaseUrl = (
} catch (cause) {
throw new RemoteBackendUrlInvalidError({ source, cause });
}
if (!hasSupportedRemoteBackendProtocol(url)) {
throw new RemoteBackendUrlInvalidError({
source,
protocol: url.protocol,
});
}
url.pathname = "/";
url.search = "";
url.hash = "";
@@ -184,6 +198,11 @@ export const resolveRemotePairingTarget = (input: {
} catch (cause) {
throw new RemotePairingUrlInvalidError({ cause });
}
if (!hasSupportedRemoteBackendProtocol(url)) {
throw new RemotePairingUrlInvalidError({
protocol: url.protocol,
});
}
const hostedPairingRequest = readHostedPairingRequest(url);
if (hostedPairingRequest) {
const hostedBackendUrl = normalizeRemoteBaseUrl(
+74 -74
View File
@@ -35,13 +35,13 @@ catalogs:
version: 0.1.24
overrides:
'@clerk/backend': 3.8.2-snapshot.v20260619001138
'@clerk/clerk-js': 6.18.2-snapshot.v20260619001138
'@clerk/electron': 0.0.1-snapshot.v20260619001138
'@clerk/electron-passkeys': 0.0.1-snapshot.v20260619001138
'@clerk/expo': 3.4.8-snapshot.v20260619001138
'@clerk/react': 6.10.4-snapshot.v20260619001138
'@clerk/shared': 4.19.2-snapshot.v20260619001138
'@clerk/backend': 3.8.3-snapshot.v20260622234151
'@clerk/clerk-js': 6.21.0-snapshot.v20260622234151
'@clerk/electron': 0.0.2-snapshot.v20260622234151
'@clerk/electron-passkeys': 0.0.2-snapshot.v20260622234151
'@clerk/expo': 3.5.3-snapshot.v20260622234151
'@clerk/react': 6.11.0-snapshot.v20260622234151
'@clerk/shared': 4.21.0-snapshot.v20260622234151
'@clerk/clerk-js>@base-org/account': '-'
'@clerk/clerk-js>@coinbase/wallet-sdk': '-'
'@clerk/clerk-js>@solana/wallet-adapter-base': '-'
@@ -113,11 +113,11 @@ importers:
apps/desktop:
dependencies:
'@clerk/electron':
specifier: 0.0.1-snapshot.v20260619001138
version: 0.0.1-snapshot.v20260619001138(@clerk/[email protected].1-snapshot.v20260619001138)([email protected])([email protected])([email protected]([email protected]))([email protected])
specifier: 0.0.2-snapshot.v20260622234151
version: 0.0.2-snapshot.v20260622234151(@clerk/[email protected].2-snapshot.v20260622234151)([email protected])([email protected])([email protected]([email protected]))([email protected])
'@clerk/electron-passkeys':
specifier: 0.0.1-snapshot.v20260619001138
version: 0.0.1-snapshot.v20260619001138
specifier: 0.0.2-snapshot.v20260622234151
version: 0.0.2-snapshot.v20260622234151
'@effect/platform-node':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78([email protected])([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))([email protected])([email protected])
@@ -196,8 +196,8 @@ importers:
specifier: ^0.7.1
version: 0.7.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
'@clerk/expo':
specifier: 3.4.8-snapshot.v20260619001138
version: 3.4.8-snapshot.v20260619001138([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
specifier: 3.5.3-snapshot.v20260622234151
version: 3.5.3-snapshot.v20260622234151([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])
'@effect/atom-react':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))([email protected])([email protected])
@@ -483,11 +483,11 @@ importers:
specifier: ^1.4.1
version: 1.5.0(@types/[email protected])([email protected]([email protected]))([email protected])
'@clerk/electron':
specifier: 0.0.1-snapshot.v20260619001138
version: 0.0.1-snapshot.v20260619001138(@clerk/[email protected].1-snapshot.v20260619001138)([email protected])([email protected])([email protected]([email protected]))([email protected])
specifier: 0.0.2-snapshot.v20260622234151
version: 0.0.2-snapshot.v20260622234151(@clerk/[email protected].2-snapshot.v20260622234151)([email protected])([email protected])([email protected]([email protected]))([email protected])
'@clerk/react':
specifier: 6.10.4-snapshot.v20260619001138
version: 6.10.4-snapshot.v20260619001138([email protected]([email protected]))([email protected])
specifier: 6.11.0-snapshot.v20260622234151
version: 6.11.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])
'@dnd-kit/core':
specifier: ^6.3.1
version: 6.3.1([email protected]([email protected]))([email protected])
@@ -637,8 +637,8 @@ importers:
infra/relay:
dependencies:
'@clerk/backend':
specifier: 3.8.2-snapshot.v20260619001138
version: 3.8.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
specifier: 3.8.3-snapshot.v20260622234151
version: 3.8.3-snapshot.v20260622234151([email protected]([email protected]))([email protected])
'@effect/sql-pg':
specifier: 4.0.0-beta.78
version: 4.0.0-beta.78([email protected](patch_hash=c502bc684210b707dfceb87d8fe6ad6843395af6e19cfc02cd65854898bde2c5))
@@ -1532,43 +1532,43 @@ packages:
resolution: {integrity: sha512-wKh+wTjmrUoUdkZg8KpJO5X+p9PWV+KE9mePseq9UYWkukgTKsGS47RRL2HstwVcvDQH+PenrPJWII8+MfiiyA==}
engines: {node: '>= 20.12.0'}
'@clerk/[email protected].2-snapshot.v20260619001138':
resolution: {integrity: sha512-nT6M7rKTuvoDnSZwO3Th2NMjcWZy/0ZfXYyqd/o/lFpUFcQO0J4fM2e2wF9kNCl99EPvDQQUAR8APNNy/j40rg==}
'@clerk/[email protected].3-snapshot.v20260622234151':
resolution: {integrity: sha512-B5goX0n/5pibc4dMQOfMmn4mPq7eqtrbNV20tOqO9qMPzFA+TKAj9SnB0oJvFsZAXKO6+/n16uYPbqeM2PN6CA==}
engines: {node: '>=20.9.0'}
'@clerk/clerk-js@6.18.2-snapshot.v20260619001138':
resolution: {integrity: sha512-BpRSi2QXdfR5nnzC7/YCCqK40m1M4A/rN5unau7QKHj6V7xChl2fOvxYjekpH+DEyw6NAe/2jdqQv35iv3T5oA==}
'@clerk/clerk-js@6.21.0-snapshot.v20260622234151':
resolution: {integrity: sha512-mRNn6H8GbeEkcCIzZ03WZ9c1Uy8znf70okYmmeJKzK72gsdwnrxEfbu3DYE/5yRbX6lvL7ugWaNTT3DvPEbBzg==}
engines: {node: '>=20.9.0'}
'@clerk/[email protected].1-snapshot.v20260619001138':
resolution: {integrity: sha512-dbQ/0ZtfDQgYKCSzu3AMxTnGSrdZxulurZMT4Jpvin48Etc27PdcT7VvwOGIa7R+Ab8yMeaoLJbfwHTZv35F+Q==}
'@clerk/[email protected].2-snapshot.v20260622234151':
resolution: {integrity: sha512-NZjIVGitAf0yyQvs1WXIAYOle9RjGsExpfwje2U20POTnNueFy56M0g39UTFQXJ42saTZ0zauLD8sd0cHqpOjA==}
cpu: [arm64]
os: [darwin]
'@clerk/[email protected].1-snapshot.v20260619001138':
resolution: {integrity: sha512-g9tbni7yKIJ/Xpollm25Gf7YLyFP24VyqRHcGDnEsHC1tIffG41spjLr10NgsBoRvFLMlaQJMSrfpjVOpBhAjw==}
'@clerk/[email protected].2-snapshot.v20260622234151':
resolution: {integrity: sha512-gGAwinVoIxa9lefCJjhf5D6oA8uq1sXQ/JwqffkBPJrvczYyAv9FYuQ1/ihji3jTplC0/bpTuIrwBkBCzwj5ug==}
cpu: [x64]
os: [darwin]
'@clerk/[email protected].1-snapshot.v20260619001138':
resolution: {integrity: sha512-mFDQ1vQ9dLIUrnjNGhIGxqyK0iiym919gYDPO3orYEcICdEiE8xZyEbCtKSVaeX6RWGJAcqFzCxbLVG6V+1k4Q==}
'@clerk/[email protected].2-snapshot.v20260622234151':
resolution: {integrity: sha512-anBFktMTAF7of37nLQsqQuW489w563J75l4QolWtblKbrBjlwFsEif95uj3vlQj0qWVVRWpAcxD21oD6wdJcwQ==}
cpu: [arm64]
os: [win32]
'@clerk/[email protected].1-snapshot.v20260619001138':
resolution: {integrity: sha512-IwkLw+d73bd7YJPRR8LAkqP42VIIpbJXCCbs5eVKbmam9M0vSUyeLWEtSiWUEypmLK13xv+7316K4GIA2tmDGQ==}
'@clerk/[email protected].2-snapshot.v20260622234151':
resolution: {integrity: sha512-Pq4FOklTJNpyMTJpxY+/gq6CukvWHFJfGYjuz985cPHup1OSsVmuO/GYil36vh7Qbe8vDivT91wNe73DbEOcVw==}
cpu: [x64]
os: [win32]
'@clerk/[email protected].1-snapshot.v20260619001138':
resolution: {integrity: sha512-diU5Q9Nx+30mesrLFOmr0OCnmxE0ogUHXktZBTQx2nQvZb/n2UGOpGNLbY1p9edKMcSc5LfJEsQ8NogfLBBvPg==}
'@clerk/[email protected].2-snapshot.v20260622234151':
resolution: {integrity: sha512-UvBweTg9+FCbygxARV7RvJ4/lcQgLN+gJC6Lj++cLmbxpgRwRAgR9xXRlKV6dVg1p5k81a4DcFNMu/oR6zBdlQ==}
engines: {node: '>=20.9.0'}
'@clerk/[email protected].1-snapshot.v20260619001138':
resolution: {integrity: sha512-wrBEdMMRqhMF4a7aQpZaBXKJfONIpaYLcgBl0m1b2r+Xg4yuZ47YUoDxhI2Ksvbx2KQPd4i9HP0enL6gEcoqfA==}
'@clerk/[email protected].2-snapshot.v20260622234151':
resolution: {integrity: sha512-T0LUJeAPaAZxpk13Q14b9LSVKKio/X/zFo67hgdr35MaOChsn4T6lQ/rEL7laScQBduskcs1yyjr3e9ndy5ojg==}
engines: {node: '>=20.9.0'}
peerDependencies:
'@clerk/electron-passkeys': 0.0.1-snapshot.v20260619001138
'@clerk/electron-passkeys': 0.0.2-snapshot.v20260622234151
electron: '>=28'
electron-store: ^8.2.0
react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0
@@ -1581,11 +1581,11 @@ packages:
react-dom:
optional: true
'@clerk/expo@3.4.8-snapshot.v20260619001138':
resolution: {integrity: sha512-E6q4p5ded45aO3y/+f7APfy5pFj2Y/BEpe/1gzdr6UGxj9kJxkiZQV29hcpjYEFMEJK60f7XbOHZTQEZRB5OwQ==}
'@clerk/expo@3.5.3-snapshot.v20260622234151':
resolution: {integrity: sha512-qeKTJYA7cTe5oCmRVCT4A2QEPRp2af0ox0VdXzIhWRqRVFNF5bnsZRNKE2e4QnsC16NYLsGHLR5uQGC15qBiug==}
engines: {node: '>=20.9.0'}
peerDependencies:
'@clerk/expo-passkeys': 1.1.8-snapshot.v20260619001138
'@clerk/expo-passkeys': 1.1.9-snapshot.v20260622234151
expo: '>=53 <57'
expo-apple-authentication: '>=7.0.0'
expo-auth-session: '>=5'
@@ -1596,7 +1596,7 @@ packages:
expo-web-browser: '>=12.5.0'
react: ^18.0.0 || ^19.0.0
react-dom: ^18.0.0 || ^19.0.0
react-native: '>=0.73'
react-native: '>=0.75'
peerDependenciesMeta:
'@clerk/expo-passkeys':
optional: true
@@ -1617,15 +1617,15 @@ packages:
react-dom:
optional: true
'@clerk/[email protected]0.4-snapshot.v20260619001138':
resolution: {integrity: sha512-Z7Otjly14SoxadMmk8d9ZdbaXU0me9B1zGdCtnNIcQ7X2GCbeyKm/lOM27IzWYXZKO6o+sXlqsq9A9tcxet5nA==}
'@clerk/[email protected]1.0-snapshot.v20260622234151':
resolution: {integrity: sha512-yF4jQFJqEHAqZCpOtjQ/Kg9yqZlEG6vW2vmVR5kVwgESkpOR1KPJIEMU8o3b6W86RKQai4lt3CWtY+o7CJsDyw==}
engines: {node: '>=20.9.0'}
peerDependencies:
react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0
react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0
'@clerk/shared@4.19.2-snapshot.v20260619001138':
resolution: {integrity: sha512-NAIz0L6+CaRrYn0DoXclUP1R0g6C2ljOzHogQ3rx9/SWUVpfaYX2lxPhURU89xvPoOGBZQb2xwk6xFh/7cjJfQ==}
'@clerk/shared@4.21.0-snapshot.v20260622234151':
resolution: {integrity: sha512-OYu+hO0GHiHwYTwSFe/GCHmuQlyTHyNa7fJ8vrmtUyML09mf+dayRFeUnxgkwOYhGriyq40t1zxdVx53Td73xg==}
engines: {node: '>=20.9.0'}
peerDependencies:
react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0
@@ -10871,18 +10871,18 @@ snapshots:
fast-wrap-ansi: 0.2.2
sisteransi: 1.0.5
'@clerk/[email protected].2-snapshot.v20260619001138([email protected]([email protected]))([email protected])':
'@clerk/[email protected].3-snapshot.v20260622234151([email protected]([email protected]))([email protected])':
dependencies:
'@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@clerk/shared': 4.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])
standardwebhooks: 1.0.0
tslib: 2.8.1
transitivePeerDependencies:
- react
- react-dom
'@clerk/clerk-js@6.18.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])':
'@clerk/clerk-js@6.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])':
dependencies:
'@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@clerk/shared': 4.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])
'@stripe/stripe-js': 5.6.0
'@swc/helpers': 0.5.21
'@tanstack/query-core': 5.100.14
@@ -10897,9 +10897,9 @@ snapshots:
- react
- react-dom
'@clerk/clerk-js@6.18.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])':
'@clerk/clerk-js@6.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])':
dependencies:
'@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@clerk/shared': 4.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])
'@stripe/stripe-js': 5.6.0
'@swc/helpers': 0.5.21
'@tanstack/query-core': 5.100.14
@@ -10914,43 +10914,43 @@ snapshots:
- react
- react-dom
'@clerk/[email protected].1-snapshot.v20260619001138':
'@clerk/[email protected].2-snapshot.v20260622234151':
optional: true
'@clerk/[email protected].1-snapshot.v20260619001138':
'@clerk/[email protected].2-snapshot.v20260622234151':
optional: true
'@clerk/[email protected].1-snapshot.v20260619001138':
'@clerk/[email protected].2-snapshot.v20260622234151':
optional: true
'@clerk/[email protected].1-snapshot.v20260619001138':
'@clerk/[email protected].2-snapshot.v20260622234151':
optional: true
'@clerk/[email protected].1-snapshot.v20260619001138':
'@clerk/[email protected].2-snapshot.v20260622234151':
optionalDependencies:
'@clerk/electron-passkeys-darwin-arm64': 0.0.1-snapshot.v20260619001138
'@clerk/electron-passkeys-darwin-x64': 0.0.1-snapshot.v20260619001138
'@clerk/electron-passkeys-win32-arm64-msvc': 0.0.1-snapshot.v20260619001138
'@clerk/electron-passkeys-win32-x64-msvc': 0.0.1-snapshot.v20260619001138
'@clerk/electron-passkeys-darwin-arm64': 0.0.2-snapshot.v20260622234151
'@clerk/electron-passkeys-darwin-x64': 0.0.2-snapshot.v20260622234151
'@clerk/electron-passkeys-win32-arm64-msvc': 0.0.2-snapshot.v20260622234151
'@clerk/electron-passkeys-win32-x64-msvc': 0.0.2-snapshot.v20260622234151
'@clerk/[email protected].1-snapshot.v20260619001138(@clerk/[email protected].1-snapshot.v20260619001138)([email protected])([email protected])([email protected]([email protected]))([email protected])':
'@clerk/[email protected].2-snapshot.v20260622234151(@clerk/[email protected].2-snapshot.v20260622234151)([email protected])([email protected])([email protected]([email protected]))([email protected])':
dependencies:
'@clerk/clerk-js': 6.18.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@clerk/react': 6.10.4-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@clerk/clerk-js': 6.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])
'@clerk/react': 6.11.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])
'@clerk/shared': 4.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])
electron: 41.5.0
react: 19.2.6
tslib: 2.8.1
optionalDependencies:
'@clerk/electron-passkeys': 0.0.1-snapshot.v20260619001138
'@clerk/electron-passkeys': 0.0.2-snapshot.v20260622234151
electron-store: 8.2.0
react-dom: 19.2.6([email protected])
'@clerk/expo@3.4.8-snapshot.v20260619001138([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])':
'@clerk/expo@3.5.3-snapshot.v20260622234151([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])':
dependencies:
'@clerk/clerk-js': 6.18.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@clerk/react': 6.10.4-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@clerk/clerk-js': 6.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])
'@clerk/react': 6.11.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])
'@clerk/shared': 4.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])
base-64: 1.0.0
expo: 56.0.8(@babel/[email protected])(@expo/[email protected])(@expo/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])([email protected])
react: 19.2.3
@@ -10965,21 +10965,21 @@ snapshots:
expo-web-browser: 56.0.5([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))
react-dom: 19.2.3([email protected])
'@clerk/[email protected]0.4-snapshot.v20260619001138([email protected]([email protected]))([email protected])':
'@clerk/[email protected]1.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])':
dependencies:
'@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@clerk/shared': 4.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])
react: 19.2.3
react-dom: 19.2.3([email protected])
tslib: 2.8.1
'@clerk/[email protected]0.4-snapshot.v20260619001138([email protected]([email protected]))([email protected])':
'@clerk/[email protected]1.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])':
dependencies:
'@clerk/shared': 4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])
'@clerk/shared': 4.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])
react: 19.2.6
react-dom: 19.2.6([email protected])
tslib: 2.8.1
'@clerk/shared@4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])':
'@clerk/shared@4.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])':
dependencies:
'@tanstack/query-core': 5.100.14
dequal: 2.0.3
@@ -10989,7 +10989,7 @@ snapshots:
react: 19.2.3
react-dom: 19.2.3([email protected])
'@clerk/shared@4.19.2-snapshot.v20260619001138([email protected]([email protected]))([email protected])':
'@clerk/shared@4.21.0-snapshot.v20260622234151([email protected]([email protected]))([email protected])':
dependencies:
'@tanstack/query-core': 5.100.14
dequal: 2.0.3
+7 -7
View File
@@ -6,13 +6,13 @@ packages:
- scripts
catalog:
"@clerk/backend": 3.8.2-snapshot.v20260619001138
"@clerk/clerk-js": 6.18.2-snapshot.v20260619001138
"@clerk/electron": 0.0.1-snapshot.v20260619001138
"@clerk/electron-passkeys": 0.0.1-snapshot.v20260619001138
"@clerk/expo": 3.4.8-snapshot.v20260619001138
"@clerk/react": 6.10.4-snapshot.v20260619001138
"@clerk/shared": 4.19.2-snapshot.v20260619001138
"@clerk/backend": 3.8.3-snapshot.v20260622234151
"@clerk/clerk-js": 6.21.0-snapshot.v20260622234151
"@clerk/electron": 0.0.2-snapshot.v20260622234151
"@clerk/electron-passkeys": 0.0.2-snapshot.v20260622234151
"@clerk/expo": 3.5.3-snapshot.v20260622234151
"@clerk/react": 6.11.0-snapshot.v20260622234151
"@clerk/shared": 4.21.0-snapshot.v20260622234151
"@effect/atom-react": 4.0.0-beta.78
"@effect/openapi-generator": 4.0.0-beta.78
"@effect/platform-bun": 4.0.0-beta.78