Compare commits

..
Author SHA1 Message Date
Cursor Agent d88b052264 Fix revoke race returning orphan pending status in ConnectClientStore
When markSeen returns none because the client was revoked between the
upsert and the markSeen call, return 'rejected' status instead of
'pending'. The synthetic 'pending' client was never persisted or
emitted, leaving the connecting client waiting for an approval that
could never come. Returning 'rejected' correctly signals that the
client's access was revoked.
2026-06-27 14:49:16 +00:00
Julius Marminge f09ee2dd7c Fix Connect approval race handling 2026-06-27 07:36:59 -07:00
Julius Marminge 4f4335b7f7 Add Connect client approval mode 2026-06-27 07:27:55 -07:00
Julius Marminge 24abab789e Stabilize chat scroll anchoring after send (#3564) 2026-06-26 14:26:36 -07:00
66 changed files with 3619 additions and 2679 deletions

No files matched your search

@@ -835,7 +835,7 @@ describe("mobile cloud link environment client", () => {
// @effect-diagnostics-next-line preferSchemaOverJson:off
expect(JSON.parse(connectRequestBody)).toMatchObject({
deviceId: "device-1",
clientKeyThumbprint: "client-proof-key-thumbprint",
clientProofKeyThumbprint: "client-proof-key-thumbprint",
});
expect(createProofMock).toHaveBeenCalledWith({
method: "POST",
@@ -484,6 +484,7 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
scopes: [RelayEnvironmentConnectScope],
environmentId: input.environmentId,
deviceId,
client: authClientMetadata(),
})
.pipe(
Effect.mapError(
@@ -497,21 +498,30 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
message: "Relay returned credentials for a different environment.",
});
}
if (!("credential" in connect)) {
return yield* new CloudEnvironmentLinkError({
message:
connect.approvalStatus === "rejected"
? "This device was rejected by the environment. Approve it in the environment settings to connect."
: "Waiting for this device to be approved in the environment settings.",
});
}
const authorizedConnect = connect;
if (input.expectedEnvironment) {
yield* ensureConnectEndpointMatchesEnvironment({
environment: input.expectedEnvironment,
connect,
connect: authorizedConnect,
});
}
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
httpBaseUrl: connect.endpoint.httpBaseUrl,
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
}).pipe(
Effect.mapError(
cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
),
);
if (descriptor.environmentId !== connect.environmentId) {
if (descriptor.environmentId !== authorizedConnect.environmentId) {
return yield* new CloudEnvironmentLinkError({
message: "Connected endpoint descriptor does not match the selected environment.",
});
@@ -520,12 +530,12 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
const bootstrapDpop = yield* signer
.createProof({
method: "POST",
url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
url: new URL("/oauth/token", authorizedConnect.endpoint.httpBaseUrl).toString(),
})
.pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
const bootstrap = yield* exchangeRemoteDpopAccessToken({
httpBaseUrl: connect.endpoint.httpBaseUrl,
credential: connect.credential,
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
credential: authorizedConnect.credential,
dpopProof: bootstrapDpop,
clientMetadata: authClientMetadata(),
}).pipe(
@@ -533,16 +543,16 @@ const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManag
cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
),
);
const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
const pairingUrl = new URL(authorizedConnect.endpoint.httpBaseUrl);
pairingUrl.hash = new URLSearchParams([["token", authorizedConnect.credential]]).toString();
return {
environmentId: descriptor.environmentId,
environmentLabel: descriptor.label,
pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
displayUrl: connect.endpoint.httpBaseUrl,
httpBaseUrl: connect.endpoint.httpBaseUrl,
wsBaseUrl: connect.endpoint.wsBaseUrl,
displayUrl: authorizedConnect.endpoint.httpBaseUrl,
httpBaseUrl: authorizedConnect.endpoint.httpBaseUrl,
wsBaseUrl: authorizedConnect.endpoint.wsBaseUrl,
bearerToken: null,
authenticationMethod: "dpop",
dpopAccessToken: bootstrap.access_token,
+107 -55
View File
@@ -74,7 +74,7 @@ import {
type ThreadFeedLatestTurn,
} from "../../lib/threadActivity";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import { ThreadWorkLog } from "./thread-work-log";
import { ThreadWorkGroupToggle, ThreadWorkLog } from "./thread-work-log";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
@@ -655,7 +655,6 @@ function renderFeedEntry(
info: { item: ThreadFeedEntry; index: number },
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
readonly expandedWorkRows: Record<string, boolean>;
readonly terminalAssistantMessageIds: ReadonlySet<string>;
readonly unsettledTurnId: TurnId | null;
@@ -698,6 +697,18 @@ function renderFeedEntry(
);
}
if (entry.type === "work-toggle") {
return (
<ThreadWorkGroupToggle
expanded={entry.expanded}
hiddenCount={entry.hiddenCount}
iconSubtleColor={iconSubtleColor}
onlyToolActivities={entry.onlyToolActivities}
onToggle={() => props.onToggleWorkGroup(entry.groupId)}
/>
);
}
if (entry.type === "message") {
const { message } = entry;
const isUser = message.role === "user";
@@ -825,11 +836,9 @@ function renderFeedEntry(
<ThreadWorkLog
activities={entry.activities}
copiedRowId={props.copiedRowId}
expanded={props.expandedWorkGroups[entry.id] ?? false}
expandedRows={props.expandedWorkRows}
iconSubtleColor={iconSubtleColor}
onCopyRow={props.onCopyWorkRow}
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
onToggleRow={props.onToggleWorkRow}
/>
);
@@ -1110,9 +1119,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const foldSettleFrameRef = useRef<number | null>(null);
const foldSettleSecondFrameRef = useRef<number | null>(null);
const disclosureAnchorKeyRef = useRef<string | null>(null);
const previousLatestTurnRef = useRef(props.latestTurn);
const { width: viewportWidth } = useWindowDimensions();
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
const [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
@@ -1173,7 +1183,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const listAppearanceData = useMemo(
() => ({
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
@@ -1182,7 +1191,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}),
[
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
@@ -1190,9 +1198,24 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
userBubbleColor,
],
);
const expandedWorkGroupIds = useMemo(() => {
const ids = new Set<string>();
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
if (expanded) {
ids.add(groupId);
}
}
return ids;
}, [expandedWorkGroups]);
const presentedFeed = useMemo(
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
[expandedTurnIds, props.feed, props.latestTurn],
() =>
deriveThreadFeedPresentation(
props.feed,
props.latestTurn,
expandedTurnIds,
expandedWorkGroupIds,
),
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
);
const anchoredEndSpace = useMemo(
() =>
@@ -1259,6 +1282,39 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
};
}, []);
const suspendEndScrollMaintenanceForDisclosure = useCallback((anchorKey: string | null) => {
disclosureAnchorKeyRef.current = anchorKey;
setDisclosureToggleSettling(true);
if (foldSettleFrameRef.current !== null) {
cancelAnimationFrame(foldSettleFrameRef.current);
}
if (foldSettleSecondFrameRef.current !== null) {
cancelAnimationFrame(foldSettleSecondFrameRef.current);
}
foldSettleFrameRef.current = requestAnimationFrame(() => {
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
disclosureAnchorKeyRef.current = null;
setDisclosureToggleSettling(false);
foldSettleFrameRef.current = null;
foldSettleSecondFrameRef.current = null;
});
});
}, []);
const shouldRestoreVisibleContentPosition = useCallback((entry: ThreadFeedEntry) => {
const disclosureAnchorKey = disclosureAnchorKeyRef.current;
return disclosureAnchorKey === null || entry.id === disclosureAnchorKey;
}, []);
const maintainVisibleContentPosition = useMemo(
() => ({
data: true,
size: true,
shouldRestorePosition: shouldRestoreVisibleContentPosition,
}),
[shouldRestoreVisibleContentPosition],
);
const onCopyWorkRow = useCallback((rowId: string, value: string) => {
copyTextWithHaptic(value, {
target: "thread-work-row",
@@ -1276,51 +1332,49 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}, 1200);
}, []);
const onToggleWorkGroup = useCallback((groupId: string) => {
setInteractionState((current) => ({
...current,
expandedWorkGroups: {
...current.expandedWorkGroups,
[groupId]: !(current.expandedWorkGroups[groupId] ?? false),
},
}));
}, []);
const onToggleWorkGroup = useCallback(
(groupId: string) => {
suspendEndScrollMaintenanceForDisclosure(`work-toggle:${groupId}`);
setInteractionState((current) => ({
...current,
expandedWorkGroups: {
...current.expandedWorkGroups,
[groupId]: !(current.expandedWorkGroups[groupId] ?? false),
},
}));
},
[suspendEndScrollMaintenanceForDisclosure],
);
const onToggleWorkRow = useCallback((rowId: string) => {
setInteractionState((current) => ({
...current,
expandedWorkRows: {
...current.expandedWorkRows,
[rowId]: !(current.expandedWorkRows[rowId] ?? false),
},
}));
}, []);
const onToggleWorkRow = useCallback(
(rowId: string) => {
suspendEndScrollMaintenanceForDisclosure(rowId);
setInteractionState((current) => ({
...current,
expandedWorkRows: {
...current.expandedWorkRows,
[rowId]: !(current.expandedWorkRows[rowId] ?? false),
},
}));
},
[suspendEndScrollMaintenanceForDisclosure],
);
const onToggleTurnFold = useCallback((turnId: TurnId) => {
setFoldToggleSettling(true);
if (foldSettleFrameRef.current !== null) {
cancelAnimationFrame(foldSettleFrameRef.current);
}
if (foldSettleSecondFrameRef.current !== null) {
cancelAnimationFrame(foldSettleSecondFrameRef.current);
}
setInteractionState((current) => {
const next = new Set(current.expandedTurnIds);
if (next.has(turnId)) {
next.delete(turnId);
} else {
next.add(turnId);
}
return { ...current, expandedTurnIds: next };
});
foldSettleFrameRef.current = requestAnimationFrame(() => {
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
setFoldToggleSettling(false);
foldSettleFrameRef.current = null;
foldSettleSecondFrameRef.current = null;
const onToggleTurnFold = useCallback(
(turnId: TurnId) => {
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
setInteractionState((current) => {
const next = new Set(current.expandedTurnIds);
if (next.has(turnId)) {
next.delete(turnId);
} else {
next.add(turnId);
}
return { ...current, expandedTurnIds: next };
});
});
}, []);
},
[suspendEndScrollMaintenanceForDisclosure],
);
const onPressImage = useCallback((uri: string, headers?: Record<string, string>) => {
setExpandedImage({ uri, headers });
@@ -1331,7 +1385,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
renderFeedEntry(info, {
environmentId: props.environmentId,
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
terminalAssistantMessageIds,
unsettledTurnId,
@@ -1351,7 +1404,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}),
[
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
terminalAssistantMessageIds,
unsettledTurnId,
@@ -1410,7 +1462,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
freeze={props.freeze}
maintainScrollAtEnd={
foldToggleSettling
disclosureToggleSettling
? false
: {
animated: false,
@@ -1421,7 +1473,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
},
}
}
maintainVisibleContentPosition
maintainVisibleContentPosition={maintainVisibleContentPosition}
data={presentedFeed}
extraData={listAppearanceData}
renderItem={renderItem}
@@ -6,7 +6,6 @@ import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
const WORK_LOG_LAYOUT_ANIMATION = {
duration: 180,
create: {
@@ -72,11 +71,9 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
export function ThreadWorkLog(props: {
readonly activities: ReadonlyArray<ThreadFeedActivity>;
readonly copiedRowId: string | null;
readonly expanded: boolean;
readonly expandedRows: Readonly<Record<string, boolean>>;
readonly iconSubtleColor: import("react-native").ColorValue;
readonly onCopyRow: (rowId: string, value: string) => void;
readonly onToggleGroup: () => void;
readonly onToggleRow: (rowId: string) => void;
}) {
const colorScheme = useColorScheme();
@@ -89,14 +86,10 @@ export function ThreadWorkLog(props: {
return null;
}
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleRows =
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
const hiddenCount = rows.length - visibleRows.length;
const onlyToolRows = rows.every((row) => row.toolLike);
return (
<View className="-mx-1 mb-3 px-1 py-0.5">
<View className="-mx-1 mb-1 px-1 py-0">
{!onlyToolRows ? (
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
work log
@@ -104,7 +97,7 @@ export function ThreadWorkLog(props: {
) : null}
<View className="gap-px">
{visibleRows.map((row) => {
{rows.map((row) => {
const expanded = props.expandedRows[row.id] ?? false;
const canExpand = row.fullDetail !== null;
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
@@ -132,13 +125,13 @@ export function ThreadWorkLog(props: {
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="rounded-md px-0.5 py-0.5"
className="rounded-md px-0.5 py-0"
>
<View className="min-h-9 flex-row items-center gap-1.5">
<View className="h-5 w-5 shrink-0 items-center justify-center">
<View className="min-h-8 flex-row items-center gap-1.5">
<View className="h-[18px] w-5 shrink-0 items-center justify-center">
<SymbolView
name={workRowSymbolName(row.icon)}
size={14}
size={13}
weight="medium"
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
type="monochrome"
@@ -146,7 +139,7 @@ export function ThreadWorkLog(props: {
</View>
<Text
className="min-w-0 flex-1 text-xs leading-5 text-foreground"
className="min-w-0 flex-1 text-xs leading-4 text-foreground"
numberOfLines={1}
>
<Text
@@ -199,7 +192,7 @@ export function ThreadWorkLog(props: {
</Pressable>
{expanded && row.fullDetail ? (
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
<View className="ml-7 border-l border-neutral-300/60 pb-1 pl-3 pt-0.5 dark:border-white/[0.12]">
<ScrollView
nestedScrollEnabled
directionalLockEnabled
@@ -221,41 +214,59 @@ export function ThreadWorkLog(props: {
);
})}
</View>
{hasOverflow ? (
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
accessibilityLabel={
props.expanded
? "Show fewer tool calls"
: `Show ${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`
}
hitSlop={4}
onPress={() => {
triggerDisclosureFeedback();
props.onToggleGroup();
}}
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
>
<View className="h-5 w-5 items-center justify-center">
<SymbolView
name={props.expanded ? "chevron.up" : "chevron.down"}
size={13}
tintColor={props.iconSubtleColor}
type="monochrome"
/>
</View>
<Text className="font-t3-medium text-xs text-foreground opacity-80">
{props.expanded
? "Show fewer tool calls"
: `+${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`}
</Text>
</Pressable>
) : null}
</View>
);
}
export function ThreadWorkGroupToggle(props: {
readonly expanded: boolean;
readonly hiddenCount: number;
readonly iconSubtleColor: import("react-native").ColorValue;
readonly onlyToolActivities: boolean;
readonly onToggle: () => void;
}) {
const colorScheme = useColorScheme();
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
const noun = props.onlyToolActivities
? props.hiddenCount === 1
? "tool call"
: "tool calls"
: props.hiddenCount === 1
? "log entry"
: "log entries";
const collapsedLabel = `Show ${props.hiddenCount} previous ${noun}`;
const expandedLabel = props.onlyToolActivities
? "Show fewer tool calls"
: "Show fewer log entries";
return (
<View className="-mx-1 mb-1 px-1 py-0">
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
hitSlop={4}
onPress={() => {
void Haptics.selectionAsync();
props.onToggle();
}}
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0"
>
<View className="h-[18px] w-5 items-center justify-center">
<SymbolView
name={props.expanded ? "chevron.up" : "chevron.down"}
size={12}
tintColor={props.iconSubtleColor}
type="monochrome"
/>
</View>
<Text className="font-t3-medium text-xs text-foreground opacity-80">
{props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`}
</Text>
</Pressable>
</View>
);
}
+60 -1
View File
@@ -11,7 +11,12 @@ import {
type OrchestrationThreadActivity,
} from "@t3tools/contracts";
import { buildThreadFeed, deriveThreadFeedPresentation } from "./threadActivity";
import {
buildThreadFeed,
deriveThreadFeedPresentation,
type ThreadFeedActivity,
type ThreadFeedEntry,
} from "./threadActivity";
function makeActivity(
input: Partial<OrchestrationThreadActivity> &
@@ -406,4 +411,58 @@ describe("buildThreadFeed", () => {
activities: [{ status: "failure" }],
});
});
it("models work-log overflow as list rows", () => {
const activity = (
id: string,
createdAt: string,
status: ThreadFeedActivity["status"] = "success",
): ThreadFeedActivity => ({
id,
createdAt,
turnId: null,
summary: `Tool ${id}`,
detail: null,
fullDetail: null,
copyText: id,
icon: "command",
toolLike: true,
status,
});
const feed: ThreadFeedEntry[] = [
{
type: "activity-group",
id: "work-group-1",
createdAt: "2026-04-01T00:00:01.000Z",
turnId: null,
activities: [
activity("activity-1", "2026-04-01T00:00:01.000Z"),
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
activity("activity-2", "2026-04-01T00:00:03.000Z"),
activity("activity-3", "2026-04-01T00:00:04.000Z"),
],
},
];
const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
expect(collapsed.map((entry) => entry.id)).toEqual(["activity-3", "work-toggle:work-group-1"]);
expect(collapsed[1]).toMatchObject({
type: "work-toggle",
groupId: "work-group-1",
hiddenCount: 2,
expanded: false,
});
const expanded = deriveThreadFeedPresentation(feed, null, new Set(), new Set(["work-group-1"]));
expect(expanded.map((entry) => entry.id)).toEqual([
"activity-1",
"activity-2",
"activity-3",
"work-toggle:work-group-1",
]);
expect(expanded.at(-1)).toMatchObject({
type: "work-toggle",
expanded: true,
});
});
});
+67 -2
View File
@@ -55,6 +55,8 @@ export interface ThreadFeedActivity {
readonly status: "success" | "failure" | "neutral" | null;
}
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
type WorkLogToolLifecycleStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped";
interface WorkLogEntry {
@@ -103,6 +105,16 @@ export type ThreadFeedEntry =
readonly turnId: TurnId | null;
readonly activities: ReadonlyArray<ThreadFeedActivity>;
}
| {
readonly type: "work-toggle";
readonly id: string;
readonly createdAt: string;
readonly turnId: TurnId | null;
readonly groupId: string;
readonly hiddenCount: number;
readonly expanded: boolean;
readonly onlyToolActivities: boolean;
}
| {
readonly type: "turn-fold";
readonly id: string;
@@ -1092,8 +1104,11 @@ export function deriveThreadFeedPresentation(
feed: ReadonlyArray<ThreadFeedEntry>,
latestTurn: ThreadFeedLatestTurn | null,
expandedTurnIds: ReadonlySet<TurnId>,
expandedWorkGroupIds: ReadonlySet<string> = new Set(),
): ThreadFeedEntry[] {
const sourceFeed = feed.filter((entry) => entry.type !== "turn-fold");
const sourceFeed = feed.filter(
(entry) => entry.type !== "turn-fold" && entry.type !== "work-toggle",
);
const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn);
const collapsedEntryIds = new Set<string>();
for (const fold of foldsByAnchorId.values()) {
@@ -1118,12 +1133,62 @@ export function deriveThreadFeedPresentation(
});
}
if (!collapsedEntryIds.has(entry.id)) {
result.push(entry);
appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
}
}
return result;
}
function appendPresentedFeedEntry(
result: ThreadFeedEntry[],
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" }>,
expandedWorkGroupIds: ReadonlySet<string>,
): void {
if (entry.type !== "activity-group") {
result.push(entry);
return;
}
const activities = entry.activities.filter(
(activity) => !(activity.toolLike && activity.status === "neutral"),
);
if (activities.length === 0) {
return;
}
if (activities.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
result.push({
...entry,
activities,
});
return;
}
const groupId = entry.id;
const expanded = expandedWorkGroupIds.has(groupId);
const hiddenCount = activities.length - MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleActivities = expanded ? activities : activities.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
for (const activity of visibleActivities) {
result.push({
type: "activity-group",
id: activity.id,
createdAt: activity.createdAt,
turnId: activity.turnId,
activities: [activity],
});
}
result.push({
type: "work-toggle",
id: `work-toggle:${groupId}`,
createdAt: entry.createdAt,
turnId: entry.turnId,
groupId,
hiddenCount,
expanded,
onlyToolActivities: activities.every((activity) => activity.toolLike),
});
}
export function derivePendingApprovals(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): PendingApproval[] {
@@ -0,0 +1,117 @@
import { expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as AuthConnectClients from "../persistence/AuthConnectClients.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import * as ConnectClientStore from "./ConnectClientStore.ts";
const textEncoder = new TextEncoder();
const requestedAt = DateTime.makeUnsafe("2026-06-27T12:00:00.000Z");
const approvedAt = DateTime.makeUnsafe("2026-06-27T12:05:00.000Z");
const rejectedAt = DateTime.makeUnsafe("2026-06-27T12:06:00.000Z");
const approvedRecord: AuthConnectClients.AuthConnectClientRecord = {
clientProofKeyThumbprint: "client-thumbprint",
cloudUserId: "cloud-user",
deviceId: "device-1",
status: "approved",
client: {
label: "Client",
ipAddress: null,
userAgent: null,
deviceType: "desktop",
os: "macOS",
browser: null,
},
requestedAt,
updatedAt: approvedAt,
approvedAt,
rejectedAt: null,
revokedAt: null,
lastSeenAt: null,
};
const secretStoreLayer = Layer.succeed(
ServerSecretStore.ServerSecretStore,
ServerSecretStore.ServerSecretStore.of({
get: () => Effect.succeed(Option.some(textEncoder.encode("client-approval"))),
set: () => Effect.void,
create: () => Effect.void,
getOrCreateRandom: () => Effect.succeed(new Uint8Array()),
remove: () => Effect.void,
}),
);
const makeStoreLayer = (
overrides: Partial<AuthConnectClients.AuthConnectClientRepository["Service"]>,
) =>
Layer.effect(ConnectClientStore.ConnectClientStore, ConnectClientStore.make).pipe(
Layer.provide(secretStoreLayer),
Layer.provide(
Layer.succeed(
AuthConnectClients.AuthConnectClientRepository,
AuthConnectClients.AuthConnectClientRepository.of({
upsertRequest: () => Effect.succeed(approvedRecord),
updateStatus: () => Effect.succeed(Option.none()),
revoke: () => Effect.succeed(false),
markSeen: () => Effect.succeed(Option.some(approvedRecord)),
listActive: () => Effect.succeed([]),
...overrides,
}),
),
),
);
it.effect("returns rejected when an approved client is rejected before last-seen update", () =>
Effect.gen(function* () {
const store = yield* ConnectClientStore.ConnectClientStore;
const authorization = yield* store.requestClient({
cloudUserId: "cloud-user",
clientProofKeyThumbprint: "client-thumbprint",
});
expect(authorization.mode).toBe("client-approval");
expect(authorization.status).toBe("rejected");
}).pipe(
Effect.provide(
makeStoreLayer({
markSeen: () =>
Effect.succeed(
Option.some({
...approvedRecord,
status: "rejected",
updatedAt: rejectedAt,
rejectedAt,
}),
),
}),
),
),
);
it.effect("returns rejected when an approved client is revoked before last-seen update", () =>
Effect.gen(function* () {
const store = yield* ConnectClientStore.ConnectClientStore;
const authorization = yield* store.requestClient({
cloudUserId: "cloud-user",
clientProofKeyThumbprint: "client-thumbprint",
});
expect(authorization.mode).toBe("client-approval");
expect(authorization.status).toBe("rejected");
if (authorization.mode === "client-approval") {
expect(authorization.client.status).toBe("rejected");
expect(authorization.client.approvedAt).toBeNull();
expect(authorization.client.lastSeenAt).toBeNull();
}
}).pipe(
Effect.provide(
makeStoreLayer({
markSeen: () => Effect.succeed(Option.none()),
}),
),
),
);
+424
View File
@@ -0,0 +1,424 @@
import {
AuthConnectSecurityMode,
type AuthClientMetadata,
type AuthClientPresentationMetadata,
type AuthConnectClient,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as AuthConnectClients from "../persistence/AuthConnectClients.ts";
import type { AuthConnectClientRepositoryError } from "../persistence/Errors.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
const CONNECT_SECURITY_MODE_SECRET = "connect-security-mode";
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
const connectClientInternalErrorContext = {
cause: Schema.Defect(),
};
export class ConnectSecurityModeLoadError extends Schema.TaggedErrorClass<ConnectSecurityModeLoadError>()(
"ConnectSecurityModeLoadError",
{
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return "Failed to load Connect security mode.";
}
}
export class ConnectSecurityModeUpdateError extends Schema.TaggedErrorClass<ConnectSecurityModeUpdateError>()(
"ConnectSecurityModeUpdateError",
{
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return "Failed to update Connect security mode.";
}
}
export class ConnectClientsLoadError extends Schema.TaggedErrorClass<ConnectClientsLoadError>()(
"ConnectClientsLoadError",
{
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return "Failed to load Connect clients.";
}
}
export class ConnectClientRequestError extends Schema.TaggedErrorClass<ConnectClientRequestError>()(
"ConnectClientRequestError",
{
clientProofKeyThumbprint: Schema.String,
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return `Failed to record Connect client '${this.clientProofKeyThumbprint}'.`;
}
}
export class ConnectClientApprovalError extends Schema.TaggedErrorClass<ConnectClientApprovalError>()(
"ConnectClientApprovalError",
{
clientProofKeyThumbprint: Schema.String,
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return `Failed to approve Connect client '${this.clientProofKeyThumbprint}'.`;
}
}
export class ConnectClientRejectionError extends Schema.TaggedErrorClass<ConnectClientRejectionError>()(
"ConnectClientRejectionError",
{
clientProofKeyThumbprint: Schema.String,
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return `Failed to reject Connect client '${this.clientProofKeyThumbprint}'.`;
}
}
export class ConnectClientRevocationError extends Schema.TaggedErrorClass<ConnectClientRevocationError>()(
"ConnectClientRevocationError",
{
clientProofKeyThumbprint: Schema.String,
...connectClientInternalErrorContext,
},
) {
override get message(): string {
return `Failed to revoke Connect client '${this.clientProofKeyThumbprint}'.`;
}
}
export const ConnectClientStoreError = Schema.Union([
ConnectSecurityModeLoadError,
ConnectSecurityModeUpdateError,
ConnectClientsLoadError,
ConnectClientRequestError,
ConnectClientApprovalError,
ConnectClientRejectionError,
ConnectClientRevocationError,
]);
export type ConnectClientStoreError = typeof ConnectClientStoreError.Type;
export const isConnectClientStoreError = Schema.is(ConnectClientStoreError);
export type ConnectClientChange =
| {
readonly type: "connectSecurityModeUpdated";
readonly mode: AuthConnectSecurityMode;
}
| {
readonly type: "connectClientUpserted";
readonly client: AuthConnectClient;
}
| {
readonly type: "connectClientRemoved";
readonly clientProofKeyThumbprint: string;
};
export type ConnectClientAuthorization =
| {
readonly mode: "account";
readonly status: "approved";
}
| {
readonly mode: "client-approval";
readonly status: "pending" | "approved" | "rejected";
readonly client: AuthConnectClient;
};
export class ConnectClientStore extends Context.Service<
ConnectClientStore,
{
readonly getSecurityMode: () => Effect.Effect<
AuthConnectSecurityMode,
ConnectSecurityModeLoadError
>;
readonly setSecurityMode: (
mode: AuthConnectSecurityMode,
) => Effect.Effect<AuthConnectSecurityMode, ConnectSecurityModeUpdateError>;
readonly listClients: () => Effect.Effect<
ReadonlyArray<AuthConnectClient>,
ConnectClientsLoadError
>;
readonly requestClient: (input: {
readonly cloudUserId: string;
readonly clientProofKeyThumbprint: string;
readonly deviceId?: string;
readonly client?: AuthClientPresentationMetadata;
}) => Effect.Effect<
ConnectClientAuthorization,
ConnectClientRequestError | ConnectSecurityModeLoadError
>;
readonly approve: (
clientProofKeyThumbprint: string,
) => Effect.Effect<Option.Option<AuthConnectClient>, ConnectClientApprovalError>;
readonly reject: (
clientProofKeyThumbprint: string,
) => Effect.Effect<Option.Option<AuthConnectClient>, ConnectClientRejectionError>;
readonly revoke: (
clientProofKeyThumbprint: string,
) => Effect.Effect<boolean, ConnectClientRevocationError>;
readonly streamChanges: Stream.Stream<ConnectClientChange>;
}
>()("t3/auth/ConnectClientStore") {}
function toAuthClientMetadata(
record: AuthConnectClients.AuthConnectClientMetadataRecord,
): AuthClientMetadata {
return {
...(record.label ? { label: record.label } : {}),
...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),
...(record.userAgent ? { userAgent: record.userAgent } : {}),
deviceType: record.deviceType,
...(record.os ? { os: record.os } : {}),
...(record.browser ? { browser: record.browser } : {}),
};
}
function toAuthConnectClient(
record: AuthConnectClients.AuthConnectClientRecord,
): AuthConnectClient {
return {
clientProofKeyThumbprint: record.clientProofKeyThumbprint,
cloudUserId: record.cloudUserId,
...(record.deviceId ? { deviceId: record.deviceId } : {}),
status: record.status,
client: toAuthClientMetadata(record.client),
requestedAt: DateTime.toUtc(record.requestedAt),
updatedAt: DateTime.toUtc(record.updatedAt),
approvedAt: record.approvedAt === null ? null : DateTime.toUtc(record.approvedAt),
rejectedAt: record.rejectedAt === null ? null : DateTime.toUtc(record.rejectedAt),
lastSeenAt: record.lastSeenAt === null ? null : DateTime.toUtc(record.lastSeenAt),
};
}
function fromPresentationMetadata(
client: AuthClientPresentationMetadata | undefined,
): AuthConnectClients.AuthConnectClientMetadataRecord {
return {
label: client?.label ?? null,
ipAddress: null,
userAgent: null,
deviceType: client?.deviceType ?? "unknown",
os: client?.os ?? null,
browser: null,
};
}
function decodeSecurityMode(bytes: Uint8Array): AuthConnectSecurityMode {
const value = textDecoder.decode(bytes).trim();
return value === "client-approval" ? "client-approval" : "account";
}
function encodeSecurityMode(mode: AuthConnectSecurityMode): Uint8Array {
return textEncoder.encode(mode);
}
export const make = Effect.gen(function* () {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const repository = yield* AuthConnectClients.AuthConnectClientRepository;
const changesPubSub = yield* PubSub.unbounded<ConnectClientChange>();
const emitMode = (mode: AuthConnectSecurityMode) =>
PubSub.publish(changesPubSub, {
type: "connectSecurityModeUpdated",
mode,
}).pipe(Effect.asVoid);
const emitUpsert = (client: AuthConnectClient) =>
PubSub.publish(changesPubSub, {
type: "connectClientUpserted",
client,
}).pipe(Effect.asVoid);
const emitRemoved = (clientProofKeyThumbprint: string) =>
PubSub.publish(changesPubSub, {
type: "connectClientRemoved",
clientProofKeyThumbprint,
}).pipe(Effect.asVoid);
const getSecurityMode: ConnectClientStore["Service"]["getSecurityMode"] = () =>
secrets.get(CONNECT_SECURITY_MODE_SECRET).pipe(
Effect.map((mode) =>
Option.isSome(mode) ? decodeSecurityMode(mode.value) : ("account" as const),
),
Effect.mapError((cause) => new ConnectSecurityModeLoadError({ cause })),
Effect.withSpan("ConnectClientStore.getSecurityMode"),
);
const setSecurityMode: ConnectClientStore["Service"]["setSecurityMode"] = (mode) =>
secrets.set(CONNECT_SECURITY_MODE_SECRET, encodeSecurityMode(mode)).pipe(
Effect.as(mode),
Effect.tap(emitMode),
Effect.mapError((cause) => new ConnectSecurityModeUpdateError({ cause })),
Effect.withSpan("ConnectClientStore.setSecurityMode"),
);
const listClients: ConnectClientStore["Service"]["listClients"] = () =>
repository.listActive().pipe(
Effect.map((clients) => clients.map(toAuthConnectClient)),
Effect.mapError((cause) => new ConnectClientsLoadError({ cause })),
Effect.withSpan("ConnectClientStore.listClients"),
);
const requestClient: ConnectClientStore["Service"]["requestClient"] = Effect.fn(
"ConnectClientStore.requestClient",
)(function* (input) {
const mode = yield* getSecurityMode();
if (mode === "account") {
return { mode, status: "approved" as const };
}
const requestedAt = yield* DateTime.now;
const record = yield* repository
.upsertRequest({
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
cloudUserId: input.cloudUserId,
deviceId: input.deviceId ?? null,
client: fromPresentationMetadata(input.client),
requestedAt,
})
.pipe(
Effect.mapError(
(cause) =>
new ConnectClientRequestError({
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
cause,
}),
),
);
const visibleClient = toAuthConnectClient(record);
yield* emitUpsert(visibleClient);
if (record.status !== "approved") {
return { mode, status: record.status, client: visibleClient };
}
const seenAt = yield* DateTime.now;
const seen = yield* repository
.markSeen({
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
seenAt,
})
.pipe(
Effect.mapError(
(cause) =>
new ConnectClientRequestError({
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
cause,
}),
),
);
if (Option.isSome(seen)) {
const seenClient = toAuthConnectClient(seen.value);
yield* emitUpsert(seenClient);
return { mode, status: seen.value.status, client: seenClient };
}
return {
mode,
status: "rejected" as const,
client: {
...visibleClient,
status: "rejected" as const,
updatedAt: DateTime.toUtc(seenAt),
approvedAt: null,
lastSeenAt: null,
},
};
});
const updateDecision = <E extends ConnectClientApprovalError | ConnectClientRejectionError>(
clientProofKeyThumbprint: string,
status: "approved" | "rejected",
toError: (cause: AuthConnectClientRepositoryError) => E,
): Effect.Effect<Option.Option<AuthConnectClient>, E> =>
DateTime.now.pipe(
Effect.flatMap((decidedAt) =>
repository.updateStatus({
clientProofKeyThumbprint,
status,
decidedAt,
}),
),
Effect.mapError(toError),
Effect.map((updated) => Option.map(updated, toAuthConnectClient)),
Effect.tap((updated) => (Option.isSome(updated) ? emitUpsert(updated.value) : Effect.void)),
);
const approve: ConnectClientStore["Service"]["approve"] = (clientProofKeyThumbprint) =>
updateDecision(
clientProofKeyThumbprint,
"approved",
(cause) =>
new ConnectClientApprovalError({
clientProofKeyThumbprint,
cause,
}),
).pipe(Effect.withSpan("ConnectClientStore.approve"));
const reject: ConnectClientStore["Service"]["reject"] = (clientProofKeyThumbprint) =>
updateDecision(
clientProofKeyThumbprint,
"rejected",
(cause) =>
new ConnectClientRejectionError({
clientProofKeyThumbprint,
cause,
}),
).pipe(Effect.withSpan("ConnectClientStore.reject"));
const revoke: ConnectClientStore["Service"]["revoke"] = (clientProofKeyThumbprint) =>
DateTime.now.pipe(
Effect.flatMap((revokedAt) =>
repository.revoke({
clientProofKeyThumbprint,
revokedAt,
}),
),
Effect.tap((revoked) => (revoked ? emitRemoved(clientProofKeyThumbprint) : Effect.void)),
Effect.mapError(
(cause) =>
new ConnectClientRevocationError({
clientProofKeyThumbprint,
cause,
}),
),
Effect.withSpan("ConnectClientStore.revoke"),
);
return ConnectClientStore.of({
getSecurityMode,
setSecurityMode,
listClients,
requestClient,
approve,
reject,
revoke,
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
});
});
export const layer = Layer.effect(ConnectClientStore, make).pipe(
Layer.provideMerge(AuthConnectClients.layer),
);
+179
View File
@@ -3,6 +3,9 @@ import {
AuthAccessWriteScope,
AuthAdministrativeScopes,
AuthStandardClientScopes,
type AuthClientPresentationMetadata,
type AuthConnectClient,
type AuthConnectSecurityMode,
type AuthAccessTokenResult,
type AuthBrowserSessionResult,
type AuthClientMetadata,
@@ -26,9 +29,11 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";
import * as ConnectClientStore from "./ConnectClientStore.ts";
import * as PairingGrantStore from "./PairingGrantStore.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import * as SessionStore from "./SessionStore.ts";
@@ -307,6 +312,83 @@ export class ServerAuthCloudMintJwtSigningError extends Schema.TaggedErrorClass<
}
}
export class ServerAuthConnectSecurityModeReadError extends Schema.TaggedErrorClass<ServerAuthConnectSecurityModeReadError>()(
"ServerAuthConnectSecurityModeReadError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to read Connect security mode.";
}
}
export class ServerAuthConnectSecurityModeUpdateError extends Schema.TaggedErrorClass<ServerAuthConnectSecurityModeUpdateError>()(
"ServerAuthConnectSecurityModeUpdateError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to update Connect security mode.";
}
}
export class ServerAuthConnectClientsListError extends Schema.TaggedErrorClass<ServerAuthConnectClientsListError>()(
"ServerAuthConnectClientsListError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to list Connect clients.";
}
}
export class ServerAuthConnectClientRequestError extends Schema.TaggedErrorClass<ServerAuthConnectClientRequestError>()(
"ServerAuthConnectClientRequestError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to authorize Connect client request.";
}
}
export class ServerAuthConnectClientApprovalError extends Schema.TaggedErrorClass<ServerAuthConnectClientApprovalError>()(
"ServerAuthConnectClientApprovalError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to approve Connect client.";
}
}
export class ServerAuthConnectClientRejectionError extends Schema.TaggedErrorClass<ServerAuthConnectClientRejectionError>()(
"ServerAuthConnectClientRejectionError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to reject Connect client.";
}
}
export class ServerAuthConnectClientRevocationError extends Schema.TaggedErrorClass<ServerAuthConnectClientRevocationError>()(
"ServerAuthConnectClientRevocationError",
{
...serverAuthInternalErrorContext,
},
) {
override get message(): string {
return "Failed to revoke Connect client.";
}
}
export const ServerAuthInternalError = Schema.Union([
ServerAuthBootstrapCredentialValidationError,
ServerAuthSessionCredentialValidationError,
@@ -330,6 +412,13 @@ export const ServerAuthInternalError = Schema.Union([
ServerAuthCloudRelayIssuerMissingError,
ServerAuthCloudHealthJwtSigningError,
ServerAuthCloudMintJwtSigningError,
ServerAuthConnectSecurityModeReadError,
ServerAuthConnectSecurityModeUpdateError,
ServerAuthConnectClientsListError,
ServerAuthConnectClientRequestError,
ServerAuthConnectClientApprovalError,
ServerAuthConnectClientRejectionError,
ServerAuthConnectClientRevocationError,
]);
export type ServerAuthInternalError = typeof ServerAuthInternalError.Type;
export const isServerAuthInternalError = Schema.is(ServerAuthInternalError);
@@ -476,6 +565,33 @@ export class EnvironmentAuth extends Context.Service<
readonly revokeOtherClientSessions: (
currentSessionId: AuthSessionId,
) => Effect.Effect<number, ServerAuthInternalError>;
readonly getConnectSecurityMode: () => Effect.Effect<
AuthConnectSecurityMode,
ServerAuthInternalError
>;
readonly setConnectSecurityMode: (
mode: AuthConnectSecurityMode,
) => Effect.Effect<AuthConnectSecurityMode, ServerAuthInternalError>;
readonly listConnectClients: () => Effect.Effect<
ReadonlyArray<AuthConnectClient>,
ServerAuthInternalError
>;
readonly authorizeConnectClientRequest: (input: {
readonly cloudUserId: string;
readonly clientProofKeyThumbprint: string;
readonly deviceId?: string;
readonly client?: AuthClientPresentationMetadata;
}) => Effect.Effect<ConnectClientStore.ConnectClientAuthorization, ServerAuthInternalError>;
readonly approveConnectClient: (
clientProofKeyThumbprint: string,
) => Effect.Effect<Option.Option<AuthConnectClient>, ServerAuthInternalError>;
readonly rejectConnectClient: (
clientProofKeyThumbprint: string,
) => Effect.Effect<Option.Option<AuthConnectClient>, ServerAuthInternalError>;
readonly revokeConnectClient: (
clientProofKeyThumbprint: string,
) => Effect.Effect<boolean, ServerAuthInternalError>;
readonly streamConnectClientChanges: Stream.Stream<ConnectClientStore.ConnectClientChange>;
readonly authenticateHttpRequest: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
@@ -557,6 +673,7 @@ export const make = Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
const sessions = yield* SessionStore.SessionStore;
const connectClients = yield* ConnectClientStore.ConnectClientStore;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const crypto = yield* Crypto.Crypto;
const descriptor = yield* policy.getDescriptor();
@@ -903,6 +1020,59 @@ export const make = Effect.gen(function* () {
Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
);
const getConnectSecurityMode: EnvironmentAuth["Service"]["getConnectSecurityMode"] = () =>
connectClients.getSecurityMode().pipe(
Effect.mapError((cause) => new ServerAuthConnectSecurityModeReadError({ cause })),
Effect.withSpan("EnvironmentAuth.getConnectSecurityMode"),
);
const setConnectSecurityMode: EnvironmentAuth["Service"]["setConnectSecurityMode"] = (mode) =>
connectClients.setSecurityMode(mode).pipe(
Effect.mapError((cause) => new ServerAuthConnectSecurityModeUpdateError({ cause })),
Effect.withSpan("EnvironmentAuth.setConnectSecurityMode"),
);
const listConnectClients: EnvironmentAuth["Service"]["listConnectClients"] = () =>
connectClients.listClients().pipe(
Effect.mapError((cause) => new ServerAuthConnectClientsListError({ cause })),
Effect.withSpan("EnvironmentAuth.listConnectClients"),
);
const authorizeConnectClientRequest: EnvironmentAuth["Service"]["authorizeConnectClientRequest"] =
(input) =>
connectClients.requestClient(input).pipe(
Effect.mapError((cause) =>
cause._tag === "ConnectSecurityModeLoadError"
? new ServerAuthConnectSecurityModeReadError({ cause })
: new ServerAuthConnectClientRequestError({ cause }),
),
Effect.withSpan("EnvironmentAuth.authorizeConnectClientRequest"),
);
const approveConnectClient: EnvironmentAuth["Service"]["approveConnectClient"] = (
clientProofKeyThumbprint,
) =>
connectClients.approve(clientProofKeyThumbprint).pipe(
Effect.mapError((cause) => new ServerAuthConnectClientApprovalError({ cause })),
Effect.withSpan("EnvironmentAuth.approveConnectClient"),
);
const rejectConnectClient: EnvironmentAuth["Service"]["rejectConnectClient"] = (
clientProofKeyThumbprint,
) =>
connectClients.reject(clientProofKeyThumbprint).pipe(
Effect.mapError((cause) => new ServerAuthConnectClientRejectionError({ cause })),
Effect.withSpan("EnvironmentAuth.rejectConnectClient"),
);
const revokeConnectClient: EnvironmentAuth["Service"]["revokeConnectClient"] = (
clientProofKeyThumbprint,
) =>
connectClients.revoke(clientProofKeyThumbprint).pipe(
Effect.mapError((cause) => new ServerAuthConnectClientRevocationError({ cause })),
Effect.withSpan("EnvironmentAuth.revokeConnectClient"),
);
const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
issueStartupPairingCredential().pipe(
Effect.map((issued) => {
@@ -973,6 +1143,14 @@ export const make = Effect.gen(function* () {
listClientSessions,
revokeClientSession,
revokeOtherClientSessions,
getConnectSecurityMode,
setConnectSecurityMode,
listConnectClients,
authorizeConnectClientRequest,
approveConnectClient,
rejectConnectClient,
revokeConnectClient,
streamConnectClientChanges: connectClients.streamChanges,
authenticateHttpRequest,
authenticateWebSocketUpgrade,
issueWebSocketTicket,
@@ -983,6 +1161,7 @@ export const make = Effect.gen(function* () {
export const layer = Layer.effect(EnvironmentAuth, make).pipe(
Layer.provideMerge(PairingGrantStore.layer),
Layer.provideMerge(SessionStore.layer),
Layer.provideMerge(ConnectClientStore.layer),
Layer.provideMerge(EnvironmentAuthPolicy.layer),
);
+76
View File
@@ -27,6 +27,7 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Cookies from "effect/unstable/http/Cookies";
import * as HttpEffect from "effect/unstable/http/HttpEffect";
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
@@ -419,6 +420,81 @@ export const authHttpApiLayer = HttpApiBuilder.group(
failEnvironmentInternal("client_session_revoke_failed", error),
),
),
)
.handle(
"connectSecurityMode",
Effect.fn("environment.auth.connectSecurityMode")(
function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthAccessWriteScope);
const mode = yield* serverAuth.setConnectSecurityMode(args.payload.mode);
return { mode };
},
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("connect_security_mode_update_failed", error),
),
),
)
.handle(
"connectClients",
Effect.fn("environment.auth.connectClients")(
function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthAccessReadScope);
return yield* serverAuth.listConnectClients();
},
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("connect_clients_load_failed", error),
),
),
)
.handle(
"approveConnectClient",
Effect.fn("environment.auth.approveConnectClient")(
function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthAccessWriteScope);
const client = yield* serverAuth.approveConnectClient(
args.payload.clientProofKeyThumbprint,
);
return { client: Option.getOrNull(client) };
},
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("connect_client_approval_failed", error),
),
),
)
.handle(
"rejectConnectClient",
Effect.fn("environment.auth.rejectConnectClient")(
function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthAccessWriteScope);
const client = yield* serverAuth.rejectConnectClient(
args.payload.clientProofKeyThumbprint,
);
return { client: Option.getOrNull(client) };
},
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("connect_client_rejection_failed", error),
),
),
)
.handle(
"revokeConnectClient",
Effect.fn("environment.auth.revokeConnectClient")(
function* (args) {
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthAccessWriteScope);
const revoked = yield* serverAuth.revokeConnectClient(
args.payload.clientProofKeyThumbprint,
);
return { revoked };
},
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("connect_client_revoke_failed", error),
),
),
);
}),
);
+1 -9
View File
@@ -10,16 +10,11 @@ import packageJson from "../package.json" with { type: "json" };
import { authCommand } from "./cli/auth.ts";
import { connectCommand } from "./cli/connect.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import * as BoundedChildProcessSpawner from "./cli/boundedChildProcessSpawner.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
import { installNodeShutdownSignalEscalation } from "./cli/shutdownSignalEscalation.ts";
const CliRuntimeLayer = Layer.mergeAll(
BoundedChildProcessSpawner.layer().pipe(Layer.provideMerge(NodeServices.layer)),
NetService.layer,
);
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
const connectPublicConfigMissingMessage =
"T3 Connect commands are unavailable: this build is missing T3 Connect public configuration.";
@@ -59,12 +54,9 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
export const cli = makeCli();
if (import.meta.main) {
const removeShutdownSignalEscalation = installNodeShutdownSignalEscalation();
Command.run(cli, { version: packageJson.version }).pipe(
Effect.scoped,
Effect.provide(CliRuntimeLayer),
Effect.ensuring(Effect.sync(removeShutdownSignalEscalation)),
NodeRuntime.runMain,
);
}
@@ -1,291 +0,0 @@
import { NodeServices } from "@effect/platform-node";
import { expect, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Scope from "effect/Scope";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { layer, make, type ChildProcessShutdownSignal } from "./boundedChildProcessSpawner.ts";
const makeHandle = (input: {
readonly pid: number;
readonly exitCode: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly isRunning: Effect.Effect<boolean>;
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
readonly unref?: ChildProcessSpawner.ChildProcessHandle["unref"];
}) =>
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(input.pid),
exitCode: input.exitCode,
isRunning: input.isRunning,
kill: input.kill ?? (() => Effect.void),
unref: input.unref ?? Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
const errnoCode = (cause: unknown) =>
cause instanceof Error ? Reflect.get(cause, "code") : undefined;
const isProcessAlive = (pid: number) => {
try {
process.kill(pid, 0);
return true;
} catch (cause) {
return errnoCode(cause) !== "ESRCH";
}
};
const killProcessGroup = (pid: number) => {
try {
process.kill(-pid, "SIGKILL");
} catch {
try {
process.kill(pid, "SIGKILL");
} catch {
// The process group has already exited.
}
}
};
const readFixturePids = (line: string) => {
const value: unknown = JSON.parse(line);
if (typeof value !== "object" || value === null) {
throw new Error("Expected the child fixture to print an object");
}
const pid = Reflect.get(value, "pid");
const descendantPid = Reflect.get(value, "descendantPid");
if (typeof pid !== "number" || typeof descendantPid !== "number") {
throw new Error("Expected numeric child fixture pids");
}
return { pid, descendantPid };
};
const waitForProcessesToStop = Effect.fn("waitForProcessesToStop")(function* (
pids: ReadonlyArray<number>,
timeoutMs: number,
) {
let remainingMs = timeoutMs;
while (pids.some(isProcessAlive)) {
if (remainingMs <= 0) return false;
const delayMs = Math.min(10, remainingMs);
yield* Effect.sleep(delayMs);
remainingMs -= delayMs;
}
return true;
});
it.effect("closes the delegate scope after a natural child exit", () =>
Effect.gen(function* () {
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
const delegateClosed = yield* Deferred.make<void>();
const handle = makeHandle({
pid: 1,
exitCode: Deferred.await(exited),
isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)),
});
const delegate = ChildProcessSpawner.make(() =>
Effect.gen(function* () {
yield* Effect.addFinalizer(() => Deferred.succeed(delegateClosed, undefined));
return handle;
}),
);
const spawner = make(delegate);
const callerScope = yield* Scope.make();
const spawned = yield* spawner
.spawn(ChildProcess.make("unused"))
.pipe(Effect.provideService(Scope.Scope, callerScope));
expect(spawned.pid).toBe(handle.pid);
yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0));
yield* Deferred.await(delegateClosed).pipe(Effect.timeout("1 second"));
yield* Scope.close(callerScope, Exit.void);
}),
);
it.effect("preserves unref as an opt-out from scope-owned termination", () =>
Effect.gen(function* () {
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
const signals: Array<ChildProcessShutdownSignal> = [];
let running = true;
const handle = makeHandle({
pid: 43,
exitCode: Deferred.await(exited),
isRunning: Effect.sync(() => running),
kill: ({ killSignal } = {}) =>
Effect.sync(() => {
if (killSignal === "SIGTERM" || killSignal === "SIGKILL") signals.push(killSignal);
}),
});
const spawner = make(
ChildProcessSpawner.make(() => Effect.succeed(handle)),
{
termGraceMs: 0,
killGraceMs: 0,
},
);
const callerScope = yield* Scope.make();
const spawned = yield* spawner
.spawn(ChildProcess.make("unused"))
.pipe(Effect.provideService(Scope.Scope, callerScope));
const reref = yield* spawned.unref;
yield* Scope.close(callerScope, Exit.void);
expect(signals).toEqual([]);
yield* reref;
running = false;
yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0));
}),
);
it.effect("bounds explicit handle kill calls and escalates to SIGKILL", () =>
Effect.gen(function* () {
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
const signals: Array<ChildProcessShutdownSignal> = [];
let running = true;
const handle = makeHandle({
pid: 44,
exitCode: Deferred.await(exited),
isRunning: Effect.sync(() => running),
kill: ({ killSignal } = {}) =>
Effect.sync(() => {
if (killSignal !== "SIGTERM" && killSignal !== "SIGKILL") return;
signals.push(killSignal);
if (killSignal === "SIGKILL") running = false;
}).pipe(Effect.andThen(Deferred.await(exited)), Effect.asVoid),
});
const spawner = make(
ChildProcessSpawner.make(() => Effect.succeed(handle)),
{
termGraceMs: 0,
killGraceMs: 0,
},
);
const callerScope = yield* Scope.make();
const spawned = yield* spawner
.spawn(ChildProcess.make("unused"))
.pipe(Effect.provideService(Scope.Scope, callerScope));
yield* spawned.kill({ forceKillAfter: 0 });
expect(signals).toEqual(["SIGTERM", "SIGKILL"]);
yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137));
yield* Scope.close(callerScope, Exit.void);
}),
);
it.effect("does not wait for the delegate's unbounded finalizer", () =>
Effect.gen(function* () {
const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
const delegateCloseStarted = yield* Deferred.make<void>();
const allowDelegateClose = yield* Deferred.make<void>();
const signals: Array<ChildProcessShutdownSignal> = [];
let running = true;
const handle = makeHandle({
pid: 42,
exitCode: Deferred.await(exited),
isRunning: Effect.sync(() => running),
kill: ({ killSignal } = {}) =>
Effect.sync(() => {
if (killSignal !== "SIGTERM" && killSignal !== "SIGKILL") return;
signals.push(killSignal);
if (killSignal === "SIGKILL") running = false;
}),
});
const delegate = ChildProcessSpawner.make(() =>
Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Deferred.succeed(delegateCloseStarted, undefined).pipe(
Effect.andThen(Deferred.await(allowDelegateClose)),
),
);
return handle;
}),
);
const spawner = make(delegate, {
termGraceMs: 0,
killGraceMs: 0,
});
const callerScope = yield* Scope.make();
yield* spawner
.spawn(ChildProcess.make("unused"))
.pipe(Effect.provideService(Scope.Scope, callerScope));
yield* Scope.close(callerScope, Exit.void);
expect(signals).toEqual(["SIGTERM", "SIGKILL"]);
yield* Deferred.await(delegateCloseStarted).pipe(Effect.timeout("1 second"));
yield* Deferred.succeed(allowDelegateClose, undefined);
yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137));
}),
);
it.effect(
"kills a TERM-ignoring Node child and its descendant without blocking scope close",
() => {
const descendantScript = `
process.on("SIGTERM", () => {});
process.stdout.write("ready\\n");
setInterval(() => {}, 1_000);
`;
const childScript = `
const { spawn } = require("node:child_process");
process.on("SIGTERM", () => {});
const descendant = spawn(process.execPath, ["-e", ${JSON.stringify(descendantScript)}], {
stdio: ["ignore", "pipe", "inherit"],
});
descendant.stdout.once("data", () => {
console.log(JSON.stringify({ pid: process.pid, descendantPid: descendant.pid }));
});
setInterval(() => {}, 1_000);
`;
const boundedLayer = layer({
termGraceMs: 100,
killGraceMs: 1_000,
pollIntervalMs: 10,
}).pipe(Layer.provideMerge(NodeServices.layer));
return Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
if (platform === "win32") return;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const callerScope = yield* Scope.make();
const handle = yield* spawner
.spawn(ChildProcess.make(process.execPath, ["-e", childScript]))
.pipe(Effect.provideService(Scope.Scope, callerScope));
const line = yield* handle.stdout.pipe(
Stream.decodeText(),
Stream.splitLines,
Stream.runHead,
Effect.timeout("2 seconds"),
Effect.map(Option.getOrThrow),
);
const pids = readFixturePids(line);
yield* Effect.addFinalizer(() => Effect.sync(() => killProcessGroup(pids.pid)));
const closeFiber = yield* Scope.close(callerScope, Exit.void).pipe(
Effect.forkDetach({ startImmediately: true }),
);
yield* Fiber.join(closeFiber).pipe(Effect.timeout("2 seconds"));
expect(yield* waitForProcessesToStop([pids.pid, pids.descendantPid], 2_000)).toBe(true);
expect(isProcessAlive(pids.pid)).toBe(false);
expect(isProcessAlive(pids.descendantPid)).toBe(false);
}).pipe(Effect.scoped, Effect.provide(boundedLayer), TestClock.withLive);
},
);
@@ -1,185 +0,0 @@
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
export type ChildProcessShutdownSignal = "SIGTERM" | "SIGKILL";
export interface BoundedChildProcessSpawnerOptions {
readonly termGraceMs?: number;
readonly killGraceMs?: number;
readonly pollIntervalMs?: number;
}
const DEFAULT_TERM_GRACE_MS = 2_000;
const DEFAULT_KILL_GRACE_MS = 1_000;
const DEFAULT_POLL_INTERVAL_MS = 25;
const normalizedDelay = (value: number | undefined, fallback: number) =>
value === undefined || !Number.isFinite(value) ? fallback : Math.max(0, value);
const isStillRunning = (handle: ChildProcessSpawner.ChildProcessHandle) =>
handle.isRunning.pipe(Effect.orElseSucceed(() => true));
const waitUntilStopped = Effect.fn("BoundedChildProcessSpawner.waitUntilStopped")(function* (
handle: ChildProcessSpawner.ChildProcessHandle,
timeoutMs: number,
pollIntervalMs: number,
) {
let remainingMs = timeoutMs;
while (yield* isStillRunning(handle)) {
if (remainingMs <= 0) return false;
const delayMs = Math.min(pollIntervalMs, remainingMs);
yield* Effect.sleep(delayMs);
remainingMs -= delayMs;
}
return true;
});
const closeScopeDetached = Effect.fn("BoundedChildProcessSpawner.closeScopeDetached")(function* (
scope: Scope.Closeable,
) {
yield* Scope.close(scope, Exit.void).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkDetach({ startImmediately: true }),
);
});
export const make = (
delegate: ChildProcessSpawner.ChildProcessSpawner["Service"],
options: BoundedChildProcessSpawnerOptions = {},
) => {
const termGraceMs = normalizedDelay(options.termGraceMs, DEFAULT_TERM_GRACE_MS);
const killGraceMs = normalizedDelay(options.killGraceMs, DEFAULT_KILL_GRACE_MS);
const pollIntervalMs = Math.max(
1,
normalizedDelay(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS),
);
const sendSignal = Effect.fn("BoundedChildProcessSpawner.sendSignal")(function* (
handle: ChildProcessSpawner.ChildProcessHandle,
signal: ChildProcess.Signal,
) {
yield* handle
.kill({ killSignal: signal })
.pipe(Effect.ignore, Effect.forkDetach({ startImmediately: true }));
});
const kill = Effect.fn("BoundedChildProcessSpawner.kill")(function* (
handle: ChildProcessSpawner.ChildProcessHandle,
killOptions?: ChildProcess.KillOptions,
) {
if (!(yield* isStillRunning(handle))) return;
const initialSignal = killOptions?.killSignal ?? "SIGTERM";
const initialGraceMs =
initialSignal === "SIGKILL"
? killGraceMs
: Math.min(
termGraceMs,
normalizedDelay(
killOptions?.forceKillAfter === undefined
? undefined
: Duration.toMillis(killOptions.forceKillAfter),
termGraceMs,
),
);
yield* sendSignal(handle, initialSignal);
const stoppedAfterInitialSignal = yield* waitUntilStopped(
handle,
initialGraceMs,
pollIntervalMs,
);
if (stoppedAfterInitialSignal) return;
if (initialSignal !== "SIGKILL") {
yield* sendSignal(handle, "SIGKILL");
if (yield* waitUntilStopped(handle, killGraceMs, pollIntervalMs)) return;
}
yield* Effect.logWarning("Child process did not stop after SIGKILL grace period", {
pid: Number(handle.pid),
killGraceMs,
});
});
const shutdown = Effect.fn("BoundedChildProcessSpawner.shutdown")(function* (
handle: ChildProcessSpawner.ChildProcessHandle,
childScope: Scope.Closeable,
isReferenced: () => boolean,
) {
if (isReferenced()) {
yield* kill(handle);
}
// The platform spawner's own finalizer can wait forever for an exit event.
// Run it detached so it can finish normally without blocking the caller's
// scope when the operating system does not report an exit in time.
yield* closeScopeDetached(childScope);
});
const spawn = Effect.fn("BoundedChildProcessSpawner.spawn")(function* (
command: ChildProcess.Command,
) {
const childScope = yield* Scope.make("sequential");
const spawned = yield* delegate
.spawn(command)
.pipe(Effect.provideService(Scope.Scope, childScope), Effect.exit);
if (Exit.isFailure(spawned)) {
yield* closeScopeDetached(childScope);
return yield* Effect.failCause(spawned.cause);
}
const delegateHandle = spawned.value;
let referenced = true;
const handle = ChildProcessSpawner.makeHandle({
pid: delegateHandle.pid,
exitCode: delegateHandle.exitCode,
isRunning: delegateHandle.isRunning,
kill: (killOptions) => kill(delegateHandle, killOptions),
stdin: delegateHandle.stdin,
stdout: delegateHandle.stdout,
stderr: delegateHandle.stderr,
all: delegateHandle.all,
getInputFd: delegateHandle.getInputFd,
getOutputFd: delegateHandle.getOutputFd,
unref: delegateHandle.unref.pipe(
Effect.tap(() =>
Effect.sync(() => {
referenced = false;
}),
),
Effect.map((reref) =>
reref.pipe(
Effect.tap(() =>
Effect.sync(() => {
referenced = true;
}),
),
),
),
),
});
yield* Effect.addFinalizer(() => shutdown(delegateHandle, childScope, () => referenced));
yield* handle.exitCode.pipe(
Effect.exit,
Effect.andThen(Scope.close(childScope, Exit.void)),
Effect.ignoreCause({ log: true }),
Effect.forkDetach({ startImmediately: true }),
);
return handle;
}, Effect.uninterruptible);
return ChildProcessSpawner.make(spawn);
};
export const layer = (options?: BoundedChildProcessSpawnerOptions) =>
Layer.effect(
ChildProcessSpawner.ChildProcessSpawner,
Effect.map(ChildProcessSpawner.ChildProcessSpawner, (delegate) => make(delegate, options)),
);
+253 -11
View File
@@ -1,14 +1,19 @@
import {
AuthConnectClient,
AuthConnectSecurityMode,
AuthRelayWriteScope,
EnvironmentHttpApi,
type AuthConnectClient as AuthConnectClientType,
type RelayClientInstallProgressEvent,
type RelayClientInstallProgressStage,
} from "@t3tools/contracts";
import { RelayOkResponse } from "@t3tools/contracts/relay";
import * as RelayClient from "@t3tools/shared/relayClient";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
import * as Cause from "effect/Cause";
import * as Console from "effect/Console";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -16,7 +21,8 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
import * as Schema from "effect/Schema";
import { Argument, Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";
import {
FetchHttpClient,
HttpClient,
@@ -52,9 +58,69 @@ interface CloudCliStatus {
readonly linked: boolean;
readonly cloudUserId: string | null;
readonly relayUrl: string | null;
readonly connectSecurityMode: AuthConnectSecurityMode;
readonly relayClient: RelayClient.RelayClientStatus;
}
const ConnectSecurityModeOutput = Schema.Struct({
mode: AuthConnectSecurityMode,
});
const encodeConnectSecurityModeOutputJson = Schema.encodeUnknownEffect(
fromJsonStringPretty(ConnectSecurityModeOutput),
);
const ConnectSecurityClientsOutput = Schema.Struct({
clients: Schema.Array(AuthConnectClient),
});
const ConnectSecurityClientDecisionOutput = Schema.Struct({
client: Schema.NullOr(AuthConnectClient),
});
const ConnectSecurityClientRevokeOutput = Schema.Struct({
revoked: Schema.Boolean,
});
const encodeConnectSecurityClientsOutputJson = Schema.encodeUnknownEffect(
fromJsonStringPretty(ConnectSecurityClientsOutput),
);
const encodeConnectSecurityClientDecisionOutputJson = Schema.encodeUnknownEffect(
fromJsonStringPretty(ConnectSecurityClientDecisionOutput),
);
const encodeConnectSecurityClientRevokeOutputJson = Schema.encodeUnknownEffect(
fromJsonStringPretty(ConnectSecurityClientRevokeOutput),
);
function formatConnectClientLabel(client: AuthConnectClientType): string {
return (
client.client.label ??
client.client.os ??
`client ${client.clientProofKeyThumbprint.slice(0, 12)}`
);
}
function formatConnectClientDetails(client: AuthConnectClientType): string {
const details = [
client.client.deviceType !== "unknown" ? client.client.deviceType : null,
client.client.os ?? null,
client.deviceId ? `device ${client.deviceId}` : null,
client.lastSeenAt ? `last seen ${DateTime.formatIso(client.lastSeenAt)}` : null,
`requested ${DateTime.formatIso(client.requestedAt)}`,
].filter((value): value is string => value !== null);
return details.join(", ");
}
function formatConnectClientList(clients: ReadonlyArray<AuthConnectClientType>): string {
if (clients.length === 0) {
return "No T3 Connect clients are registered.";
}
return [
"T3 Connect clients",
...clients.map(
(client) =>
` ${client.clientProofKeyThumbprint} ${client.status} ${formatConnectClientLabel(
client,
)} (${formatConnectClientDetails(client)})`,
),
].join("\n");
}
function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {
switch (executable.status) {
case "available": {
@@ -103,6 +169,9 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
` Exposure: ${status.desired ? "enabled" : "disabled"}`,
` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
` Environment link: ${provisioned}`,
` Client approval: ${
status.connectSecurityMode === "client-approval" ? "required" : "account-wide"
}`,
` Relay: ${status.relayUrl ?? "not provisioned"}`,
...formatRelayClientStatus(status.relayClient),
...(nextStep ? ["", `Next: ${nextStep}`] : []),
@@ -411,22 +480,26 @@ const connectStatusCommand = Command.make("status", {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const relayClient = yield* RelayClient.RelayClient;
const tokens = yield* CliTokenManager.CloudCliTokenManager;
const [desired, authenticated, cloudUserId, relayUrl, executable] = yield* Effect.all(
[
CliState.readCliDesiredCloudLink,
tokens.hasCredential,
secrets.get(CLOUD_LINKED_USER_ID),
secrets.get(RELAY_URL_SECRET),
relayClient.resolve,
],
{ concurrency: "unbounded" },
);
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const [desired, authenticated, cloudUserId, relayUrl, connectSecurityMode, executable] =
yield* Effect.all(
[
CliState.readCliDesiredCloudLink,
tokens.hasCredential,
secrets.get(CLOUD_LINKED_USER_ID),
secrets.get(RELAY_URL_SECRET),
environmentAuth.getConnectSecurityMode(),
relayClient.resolve,
],
{ concurrency: "unbounded" },
);
const status: CloudCliStatus = {
desired,
authenticated,
linked: Option.isSome(cloudUserId),
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,
connectSecurityMode,
relayClient: executable,
};
yield* Console.log(formatCloudStatus(status, { json: flags.json }));
@@ -438,6 +511,174 @@ const connectStatusCommand = Command.make("status", {
),
);
const connectSecurityModeFlag = Flag.choice("mode", ["account", "client-approval"] as const).pipe(
Flag.withDescription("Connect security mode."),
Flag.optional,
);
const connectClientThumbprintArgument = Argument.string("client-proof-key-thumbprint").pipe(
Argument.withDescription("T3 Connect client proof key thumbprint."),
);
const connectSecurityClientsCommand = Command.make("clients", {
...projectLocationFlags,
json: jsonFlag,
}).pipe(
Command.withDescription("List T3 Connect clients registered for approval."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const clients = yield* environmentAuth.listConnectClients();
if (flags.json) {
const output = yield* encodeConnectSecurityClientsOutputJson({ clients });
yield* Console.log(output);
return;
}
yield* Console.log(formatConnectClientList(clients));
}),
{
quietLogs: flags.json,
},
),
),
);
const connectSecurityApproveCommand = Command.make("approve", {
...projectLocationFlags,
clientProofKeyThumbprint: connectClientThumbprintArgument,
json: jsonFlag,
}).pipe(
Command.withDescription("Approve a T3 Connect client."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const client = yield* environmentAuth.approveConnectClient(flags.clientProofKeyThumbprint);
const clientOrNull = Option.getOrNull(client);
if (flags.json) {
const output = yield* encodeConnectSecurityClientDecisionOutputJson({
client: clientOrNull,
});
yield* Console.log(output);
return;
}
yield* Console.log(
clientOrNull
? `Approved T3 Connect client ${flags.clientProofKeyThumbprint}.`
: `No active T3 Connect client found for ${flags.clientProofKeyThumbprint}.`,
);
}),
{
quietLogs: flags.json,
},
),
),
);
const connectSecurityRejectCommand = Command.make("reject", {
...projectLocationFlags,
clientProofKeyThumbprint: connectClientThumbprintArgument,
json: jsonFlag,
}).pipe(
Command.withDescription("Reject a T3 Connect client."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const client = yield* environmentAuth.rejectConnectClient(flags.clientProofKeyThumbprint);
const clientOrNull = Option.getOrNull(client);
if (flags.json) {
const output = yield* encodeConnectSecurityClientDecisionOutputJson({
client: clientOrNull,
});
yield* Console.log(output);
return;
}
yield* Console.log(
clientOrNull
? `Rejected T3 Connect client ${flags.clientProofKeyThumbprint}.`
: `No active T3 Connect client found for ${flags.clientProofKeyThumbprint}.`,
);
}),
{
quietLogs: flags.json,
},
),
),
);
const connectSecurityRevokeCommand = Command.make("revoke", {
...projectLocationFlags,
clientProofKeyThumbprint: connectClientThumbprintArgument,
json: jsonFlag,
}).pipe(
Command.withDescription("Revoke a T3 Connect client approval record."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const revoked = yield* environmentAuth.revokeConnectClient(flags.clientProofKeyThumbprint);
if (flags.json) {
const output = yield* encodeConnectSecurityClientRevokeOutputJson({ revoked });
yield* Console.log(output);
return;
}
yield* Console.log(
revoked
? `Revoked T3 Connect client ${flags.clientProofKeyThumbprint}.`
: `No active T3 Connect client found for ${flags.clientProofKeyThumbprint}.`,
);
}),
{
quietLogs: flags.json,
},
),
),
);
const connectSecurityCommand = Command.make("security", {
...projectLocationFlags,
mode: connectSecurityModeFlag,
json: jsonFlag,
}).pipe(
Command.withDescription("Read or update T3 Connect client-approval mode."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const mode = Option.isSome(flags.mode)
? yield* environmentAuth.setConnectSecurityMode(flags.mode.value)
: yield* environmentAuth.getConnectSecurityMode();
if (flags.json) {
const output = yield* encodeConnectSecurityModeOutputJson({ mode });
yield* Console.log(output);
return;
}
yield* Console.log(
mode === "client-approval"
? "T3 Connect client approval is required."
: "T3 Connect uses account-wide access.",
);
}),
{
quietLogs: flags.json,
},
),
),
Command.withSubcommands([
connectSecurityClientsCommand,
connectSecurityApproveCommand,
connectSecurityRejectCommand,
connectSecurityRevokeCommand,
]),
);
const connectUnlinkCommand = Command.make("unlink", {
...projectLocationFlags,
}).pipe(
@@ -462,6 +703,7 @@ export const connectCommand = Command.make("connect").pipe(
connectLoginCommand,
connectLinkCommand,
connectStatusCommand,
connectSecurityCommand,
connectUnlinkCommand,
connectLogoutCommand,
]),
@@ -1,111 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import {
installShutdownSignalEscalation,
type ShutdownSignal,
type ShutdownSignalEscalationOptions,
} from "./shutdownSignalEscalation.ts";
const makeHarness = () => {
const listeners: Record<ShutdownSignal, Set<() => void>> = {
SIGINT: new Set(),
SIGTERM: new Set(),
};
const exitCodes: Array<number> = [];
const timers = new Map<number, { readonly callback: () => void; readonly delayMs: number }>();
const clearedTimers: Array<number> = [];
let nextTimerHandle = 1;
const options = {
process: {
addSignalListener: (signal, listener) => {
listeners[signal].add(listener);
},
removeSignalListener: (signal, listener) => {
listeners[signal].delete(listener);
},
exit: (code) => {
exitCodes.push(code);
},
},
timers: {
setTimeout: (callback, delayMs) => {
const handle = nextTimerHandle;
nextTimerHandle += 1;
timers.set(handle, { callback, delayMs });
return handle;
},
clearTimeout: (handle) => {
clearedTimers.push(handle);
timers.delete(handle);
},
},
} satisfies ShutdownSignalEscalationOptions<number>;
const emit = (signal: ShutdownSignal) => {
for (const listener of listeners[signal]) listener();
};
const runNextTimer = () => {
const next = timers.entries().next();
if (next.done) throw new Error("Expected a pending timer");
const [handle, timer] = next.value;
timers.delete(handle);
timer.callback();
};
return { clearedTimers, emit, exitCodes, listeners, options, runNextTimer, timers };
};
describe("installShutdownSignalEscalation", () => {
it.each([
["SIGINT", 130],
["SIGTERM", 143],
] as const)("gives the first %s a bounded graceful-shutdown window", (signal, exitCode) => {
const harness = makeHarness();
const dispose = installShutdownSignalEscalation({
...harness.options,
forceExitAfterMs: 2_500,
});
harness.emit(signal);
expect(harness.exitCodes).toEqual([]);
expect([...harness.timers.values()].map((timer) => timer.delayMs)).toEqual([2_500]);
harness.runNextTimer();
expect(harness.exitCodes).toEqual([exitCode]);
dispose();
});
it("uses the second signal's conventional exit code immediately", () => {
const harness = makeHarness();
const dispose = installShutdownSignalEscalation(harness.options);
harness.emit("SIGTERM");
harness.emit("SIGINT");
expect(harness.exitCodes).toEqual([130]);
expect(harness.clearedTimers).toEqual([1]);
expect(harness.timers.size).toBe(0);
dispose();
});
it("removes both listeners and cancels the deadline when disposed", () => {
const harness = makeHarness();
const dispose = installShutdownSignalEscalation(harness.options);
harness.emit("SIGINT");
dispose();
dispose();
expect(harness.listeners.SIGINT.size).toBe(0);
expect(harness.listeners.SIGTERM.size).toBe(0);
expect(harness.clearedTimers).toEqual([1]);
expect(harness.timers.size).toBe(0);
harness.emit("SIGINT");
expect(harness.exitCodes).toEqual([]);
});
});
@@ -1,94 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off - This module is the CLI process and signal boundary.
import * as NodeProcess from "node:process";
import * as NodeTimers from "node:timers";
export type ShutdownSignal = "SIGINT" | "SIGTERM";
export interface ShutdownSignalProcessHooks {
readonly addSignalListener: (signal: ShutdownSignal, listener: () => void) => void;
readonly removeSignalListener: (signal: ShutdownSignal, listener: () => void) => void;
readonly exit: (code: number) => void;
}
export interface ShutdownSignalTimerHooks<TimerHandle> {
readonly setTimeout: (callback: () => void, delayMs: number) => TimerHandle;
readonly clearTimeout: (handle: TimerHandle) => void;
}
export interface ShutdownSignalEscalationOptions<TimerHandle> {
readonly process: ShutdownSignalProcessHooks;
readonly timers: ShutdownSignalTimerHooks<TimerHandle>;
readonly forceExitAfterMs?: number;
}
const defaultForceExitAfterMs = 10_000;
const conventionalExitCode = (signal: ShutdownSignal) => (signal === "SIGINT" ? 130 : 143);
export const installShutdownSignalEscalation = <TimerHandle>({
process: processHooks,
timers,
forceExitAfterMs = defaultForceExitAfterMs,
}: ShutdownSignalEscalationOptions<TimerHandle>) => {
let firstSignal: ShutdownSignal | undefined;
let forceExitTimer: { readonly handle: TimerHandle } | undefined;
let disposed = false;
const clearForceExitTimer = () => {
if (forceExitTimer === undefined) return;
timers.clearTimeout(forceExitTimer.handle);
forceExitTimer = undefined;
};
const forceExit = (signal: ShutdownSignal) => {
clearForceExitTimer();
processHooks.exit(conventionalExitCode(signal));
};
const handleSignal = (signal: ShutdownSignal) => {
if (firstSignal !== undefined) {
forceExit(signal);
return;
}
firstSignal = signal;
forceExitTimer = {
handle: timers.setTimeout(() => {
forceExitTimer = undefined;
processHooks.exit(conventionalExitCode(signal));
}, forceExitAfterMs),
};
};
const handleSigint = () => handleSignal("SIGINT");
const handleSigterm = () => handleSignal("SIGTERM");
processHooks.addSignalListener("SIGINT", handleSigint);
processHooks.addSignalListener("SIGTERM", handleSigterm);
return () => {
if (disposed) return;
disposed = true;
processHooks.removeSignalListener("SIGINT", handleSigint);
processHooks.removeSignalListener("SIGTERM", handleSigterm);
clearForceExitTimer();
};
};
export const installNodeShutdownSignalEscalation = () =>
installShutdownSignalEscalation({
process: {
addSignalListener: (signal, listener) => {
NodeProcess.on(signal, listener);
},
removeSignalListener: (signal, listener) => {
NodeProcess.removeListener(signal, listener);
},
exit: (code) => NodeProcess.exit(code),
},
timers: {
// @effect-diagnostics-next-line globalTimers:off - The forced exit deadline must outlive a stuck Effect shutdown.
setTimeout: (callback, delayMs) => NodeTimers.setTimeout(callback, delayMs),
clearTimeout: (handle) => NodeTimers.clearTimeout(handle),
},
});
+66 -9
View File
@@ -608,15 +608,17 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function* (
dependencies: CloudHttpDependencies,
) {
const [cloudUserId, relayUrl, relayIssuer, publishAgentActivity] = yield* Effect.all(
[
dependencies.secrets.get(CLOUD_LINKED_USER_ID),
dependencies.secrets.get(RELAY_URL_SECRET),
dependencies.secrets.get(RELAY_ISSUER_SECRET),
dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
],
{ concurrency: 4 },
);
const [cloudUserId, relayUrl, relayIssuer, publishAgentActivity, connectSecurityMode] =
yield* Effect.all(
[
dependencies.secrets.get(CLOUD_LINKED_USER_ID),
dependencies.secrets.get(RELAY_URL_SECRET),
dependencies.secrets.get(RELAY_ISSUER_SECRET),
dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),
dependencies.environmentAuth.getConnectSecurityMode(),
],
{ concurrency: 5 },
);
return {
linked: Option.isSome(cloudUserId),
cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,
@@ -625,6 +627,7 @@ const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function
publishAgentActivity: Option.isSome(publishAgentActivity)
? bytesToString(publishAgentActivity.value) === "true"
: false,
connectSecurityMode,
} satisfies EnvironmentCloudLinkStateResult;
});
@@ -637,6 +640,9 @@ const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not read environment relay configuration."),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
);
const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(
@@ -680,6 +686,9 @@ const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(
ServerSecretStore.isSecretStoreError,
failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),
),
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentCloudInternalError(error.message)(error),
),
);
const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(
@@ -868,6 +877,54 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
}
const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);
const connectAuthorization = yield* dependencies.environmentAuth.authorizeConnectClientRequest({
cloudUserId: linkedCloudUserId,
clientProofKeyThumbprint: proof.clientProofKeyThumbprint,
...(proof.deviceId ? { deviceId: proof.deviceId } : {}),
...(proof.client ? { client: proof.client } : {}),
});
if (
connectAuthorization.mode === "client-approval" &&
connectAuthorization.status !== "approved"
) {
const responseExpiresAt = DateTime.add(now, { minutes: 5 });
const responsePayload = {
iss: `t3-env:${environmentId}`,
aud: normalizeRelayIssuer(relayIssuer),
sub: environmentId,
jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),
iat: nowSeconds,
exp: Math.floor(responseExpiresAt.epochMilliseconds / 1_000),
environmentId,
clientProofKeyThumbprint: proof.clientProofKeyThumbprint,
requestNonce: proof.nonce,
status: "pending_approval",
approvalStatus: connectAuthorization.status,
} satisfies RelayEnvironmentMintResponseProofPayload;
const responseProof = yield* signRelayJwt({
privateKey: keyPair.privateKey,
typ: RELAY_MINT_RESPONSE_TYP,
payload: responsePayload,
}).pipe(
Effect.mapError(
(cause) =>
new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({
cause,
}),
),
);
const response = {
status: "pending_approval",
clientProofKeyThumbprint: proof.clientProofKeyThumbprint,
approvalStatus: connectAuthorization.status,
requestedAt: DateTime.formatIso(connectAuthorization.client.requestedAt),
proof: responseProof,
} satisfies RelayEnvironmentMintResponseShape;
yield* appendCloudCredentialResponseHeaders;
return response;
}
const issued = yield* dependencies.environmentAuth.createPairingLink({
scopes: AuthStandardClientScopes,
subject: "cloud-connect",
@@ -45,7 +45,6 @@ export class GitWorkflowService extends Context.Service<
input: VcsStatusInput,
options?: GitVcsDriver.GitRemoteStatusOptions,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly refreshStatusUpstream: (cwd: string) => Effect.Effect<void, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -271,12 +270,6 @@ export const make = Effect.gen(function* () {
isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
),
),
refreshStatusUpstream: (cwd) =>
detectGitRepositoryForStatus("GitWorkflowService.refreshStatusUpstream", cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository ? git.refreshStatusUpstream(cwd) : Effect.void,
),
),
invalidateLocalStatus: gitManager.invalidateLocalStatus,
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
invalidateStatus: gitManager.invalidateStatus,
@@ -0,0 +1,59 @@
import { expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as AuthConnectClients from "./AuthConnectClients.ts";
import { SqlitePersistenceMemory } from "./Layers/Sqlite.ts";
const layer = AuthConnectClients.layer.pipe(Layer.provideMerge(SqlitePersistenceMemory));
const client = {
label: "Client",
ipAddress: null,
userAgent: null,
deviceType: "desktop",
os: "macOS",
browser: null,
} satisfies AuthConnectClients.AuthConnectClientMetadataRecord;
it.effect("clears stale last-seen timestamps when a revoked client re-registers", () =>
Effect.gen(function* () {
const clients = yield* AuthConnectClients.AuthConnectClientRepository;
const clientProofKeyThumbprint = "client-thumbprint";
yield* clients.upsertRequest({
clientProofKeyThumbprint,
cloudUserId: "cloud-user",
deviceId: "device-1",
client,
requestedAt: DateTime.makeUnsafe("2026-06-27T12:00:00.000Z"),
});
yield* clients.updateStatus({
clientProofKeyThumbprint,
status: "approved",
decidedAt: DateTime.makeUnsafe("2026-06-27T12:01:00.000Z"),
});
const seen = yield* clients.markSeen({
clientProofKeyThumbprint,
seenAt: DateTime.makeUnsafe("2026-06-27T12:02:00.000Z"),
});
expect(Option.isSome(seen) ? seen.value.lastSeenAt : null).not.toBeNull();
yield* clients.revoke({
clientProofKeyThumbprint,
revokedAt: DateTime.makeUnsafe("2026-06-27T12:03:00.000Z"),
});
const reregistered = yield* clients.upsertRequest({
clientProofKeyThumbprint,
cloudUserId: "cloud-user",
deviceId: "device-1",
client,
requestedAt: DateTime.makeUnsafe("2026-06-27T12:04:00.000Z"),
});
expect(reregistered.status).toBe("pending");
expect(reregistered.lastSeenAt).toBeNull();
}).pipe(Effect.provide(layer)),
);
@@ -0,0 +1,442 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { AuthClientMetadataDeviceType, AuthConnectClientStatus } from "@t3tools/contracts";
import {
type AuthConnectClientRepositoryError,
PersistenceDecodeError,
type PersistenceErrorCorrelation,
PersistenceSqlError,
} from "./Errors.ts";
export const AuthConnectClientMetadataRecord = Schema.Struct({
label: Schema.NullOr(Schema.String),
ipAddress: Schema.NullOr(Schema.String),
userAgent: Schema.NullOr(Schema.String),
deviceType: AuthClientMetadataDeviceType,
os: Schema.NullOr(Schema.String),
browser: Schema.NullOr(Schema.String),
});
export type AuthConnectClientMetadataRecord = typeof AuthConnectClientMetadataRecord.Type;
export const AuthConnectClientRecord = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
cloudUserId: Schema.String,
deviceId: Schema.NullOr(Schema.String),
status: AuthConnectClientStatus,
client: AuthConnectClientMetadataRecord,
requestedAt: Schema.DateTimeUtcFromString,
updatedAt: Schema.DateTimeUtcFromString,
approvedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
rejectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
lastSeenAt: Schema.NullOr(Schema.DateTimeUtcFromString),
});
export type AuthConnectClientRecord = typeof AuthConnectClientRecord.Type;
export const UpsertAuthConnectClientRequestInput = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
cloudUserId: Schema.String,
deviceId: Schema.NullOr(Schema.String),
client: AuthConnectClientMetadataRecord,
requestedAt: Schema.DateTimeUtcFromString,
});
export type UpsertAuthConnectClientRequestInput = typeof UpsertAuthConnectClientRequestInput.Type;
export const UpdateAuthConnectClientStatusInput = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
status: Schema.Literals(["approved", "rejected"]),
decidedAt: Schema.DateTimeUtcFromString,
});
export type UpdateAuthConnectClientStatusInput = typeof UpdateAuthConnectClientStatusInput.Type;
export const RevokeAuthConnectClientInput = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
revokedAt: Schema.DateTimeUtcFromString,
});
export type RevokeAuthConnectClientInput = typeof RevokeAuthConnectClientInput.Type;
export const MarkAuthConnectClientSeenInput = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
seenAt: Schema.DateTimeUtcFromString,
});
export type MarkAuthConnectClientSeenInput = typeof MarkAuthConnectClientSeenInput.Type;
export class AuthConnectClientRepository extends Context.Service<
AuthConnectClientRepository,
{
readonly upsertRequest: (
input: UpsertAuthConnectClientRequestInput,
) => Effect.Effect<AuthConnectClientRecord, AuthConnectClientRepositoryError>;
readonly updateStatus: (
input: UpdateAuthConnectClientStatusInput,
) => Effect.Effect<Option.Option<AuthConnectClientRecord>, AuthConnectClientRepositoryError>;
readonly revoke: (
input: RevokeAuthConnectClientInput,
) => Effect.Effect<boolean, AuthConnectClientRepositoryError>;
readonly markSeen: (
input: MarkAuthConnectClientSeenInput,
) => Effect.Effect<Option.Option<AuthConnectClientRecord>, AuthConnectClientRepositoryError>;
readonly listActive: () => Effect.Effect<
ReadonlyArray<AuthConnectClientRecord>,
AuthConnectClientRepositoryError
>;
}
>()("t3/persistence/AuthConnectClients/AuthConnectClientRepository") {}
const AuthConnectClientDbRow = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
cloudUserId: Schema.String,
deviceId: Schema.NullOr(Schema.String),
status: AuthConnectClientStatus,
clientLabel: Schema.NullOr(Schema.String),
clientIpAddress: Schema.NullOr(Schema.String),
clientUserAgent: Schema.NullOr(Schema.String),
clientDeviceType: Schema.Literals(["desktop", "mobile", "tablet", "bot", "unknown"]),
clientOs: Schema.NullOr(Schema.String),
clientBrowser: Schema.NullOr(Schema.String),
requestedAt: Schema.DateTimeUtcFromString,
updatedAt: Schema.DateTimeUtcFromString,
approvedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
rejectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
lastSeenAt: Schema.NullOr(Schema.DateTimeUtcFromString),
});
const AuthConnectClientRawDbRow = Schema.Struct({
clientProofKeyThumbprint: Schema.String,
cloudUserId: Schema.Unknown,
deviceId: Schema.Unknown,
status: Schema.Unknown,
clientLabel: Schema.Unknown,
clientIpAddress: Schema.Unknown,
clientUserAgent: Schema.Unknown,
clientDeviceType: Schema.Unknown,
clientOs: Schema.Unknown,
clientBrowser: Schema.Unknown,
requestedAt: Schema.Unknown,
updatedAt: Schema.Unknown,
approvedAt: Schema.Unknown,
rejectedAt: Schema.Unknown,
revokedAt: Schema.Unknown,
lastSeenAt: Schema.Unknown,
});
const decodeAuthConnectClientDbRow = Schema.decodeUnknownEffect(AuthConnectClientDbRow);
function toAuthConnectClientRecord(
row: typeof AuthConnectClientDbRow.Type,
): AuthConnectClientRecord {
return {
clientProofKeyThumbprint: row.clientProofKeyThumbprint,
cloudUserId: row.cloudUserId,
deviceId: row.deviceId,
status: row.status,
client: {
label: row.clientLabel,
ipAddress: row.clientIpAddress,
userAgent: row.clientUserAgent,
deviceType: row.clientDeviceType,
os: row.clientOs,
browser: row.clientBrowser,
},
requestedAt: row.requestedAt,
updatedAt: row.updatedAt,
approvedAt: row.approvedAt,
rejectedAt: row.rejectedAt,
revokedAt: row.revokedAt,
lastSeenAt: row.lastSeenAt,
};
}
function toPersistenceSqlOrDecodeError(
sqlOperation: string,
decodeOperation: string,
correlation?: PersistenceErrorCorrelation,
) {
return (cause: unknown): AuthConnectClientRepositoryError =>
Schema.isSchemaError(cause)
? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)
: new PersistenceSqlError({
operation: sqlOperation,
...(correlation === undefined ? {} : { correlation }),
cause,
});
}
const rowSelection = `
client_proof_key_thumbprint AS "clientProofKeyThumbprint",
cloud_user_id AS "cloudUserId",
device_id AS "deviceId",
status AS "status",
client_label AS "clientLabel",
client_ip_address AS "clientIpAddress",
client_user_agent AS "clientUserAgent",
client_device_type AS "clientDeviceType",
client_os AS "clientOs",
client_browser AS "clientBrowser",
requested_at AS "requestedAt",
updated_at AS "updatedAt",
approved_at AS "approvedAt",
rejected_at AS "rejectedAt",
revoked_at AS "revokedAt",
last_seen_at AS "lastSeenAt"
`;
export const make = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const upsertRequestRow = SqlSchema.findOne({
Request: UpsertAuthConnectClientRequestInput,
Result: AuthConnectClientRawDbRow,
execute: (input) =>
sql`
INSERT INTO auth_connect_clients (
client_proof_key_thumbprint,
cloud_user_id,
device_id,
status,
client_label,
client_ip_address,
client_user_agent,
client_device_type,
client_os,
client_browser,
requested_at,
updated_at,
approved_at,
rejected_at,
revoked_at,
last_seen_at
)
VALUES (
${input.clientProofKeyThumbprint},
${input.cloudUserId},
${input.deviceId},
'pending',
${input.client.label},
${input.client.ipAddress},
${input.client.userAgent},
${input.client.deviceType},
${input.client.os},
${input.client.browser},
${input.requestedAt},
${input.requestedAt},
NULL,
NULL,
NULL,
NULL
)
ON CONFLICT(client_proof_key_thumbprint) DO UPDATE SET
cloud_user_id = excluded.cloud_user_id,
device_id = excluded.device_id,
status = CASE
WHEN auth_connect_clients.revoked_at IS NULL THEN auth_connect_clients.status
ELSE 'pending'
END,
client_label = excluded.client_label,
client_ip_address = excluded.client_ip_address,
client_user_agent = excluded.client_user_agent,
client_device_type = excluded.client_device_type,
client_os = excluded.client_os,
client_browser = excluded.client_browser,
requested_at = excluded.requested_at,
updated_at = excluded.updated_at,
approved_at = CASE
WHEN auth_connect_clients.revoked_at IS NULL THEN auth_connect_clients.approved_at
ELSE NULL
END,
rejected_at = CASE
WHEN auth_connect_clients.revoked_at IS NULL THEN auth_connect_clients.rejected_at
ELSE NULL
END,
last_seen_at = CASE
WHEN auth_connect_clients.revoked_at IS NULL THEN auth_connect_clients.last_seen_at
ELSE NULL
END,
revoked_at = NULL
RETURNING ${sql.unsafe(rowSelection)}
`,
});
const updateStatusRow = SqlSchema.findOneOption({
Request: UpdateAuthConnectClientStatusInput,
Result: AuthConnectClientRawDbRow,
execute: ({ clientProofKeyThumbprint, status, decidedAt }) =>
sql`
UPDATE auth_connect_clients
SET
status = ${status},
updated_at = ${decidedAt},
approved_at = CASE WHEN ${status} = 'approved' THEN ${decidedAt} ELSE approved_at END,
rejected_at = CASE WHEN ${status} = 'rejected' THEN ${decidedAt} ELSE rejected_at END,
last_seen_at = CASE
WHEN ${status} = 'approved' AND status = 'approved' THEN last_seen_at
ELSE NULL
END,
revoked_at = NULL
WHERE client_proof_key_thumbprint = ${clientProofKeyThumbprint}
AND revoked_at IS NULL
RETURNING ${sql.unsafe(rowSelection)}
`,
});
const revokeRow = SqlSchema.findAll({
Request: RevokeAuthConnectClientInput,
Result: Schema.Struct({ clientProofKeyThumbprint: Schema.String }),
execute: ({ clientProofKeyThumbprint, revokedAt }) =>
sql`
UPDATE auth_connect_clients
SET
revoked_at = ${revokedAt},
updated_at = ${revokedAt}
WHERE client_proof_key_thumbprint = ${clientProofKeyThumbprint}
AND revoked_at IS NULL
RETURNING client_proof_key_thumbprint AS "clientProofKeyThumbprint"
`,
});
const markSeenRow = SqlSchema.findOneOption({
Request: MarkAuthConnectClientSeenInput,
Result: AuthConnectClientRawDbRow,
execute: ({ clientProofKeyThumbprint, seenAt }) =>
sql`
UPDATE auth_connect_clients
SET
last_seen_at = CASE WHEN status = 'approved' THEN ${seenAt} ELSE last_seen_at END,
updated_at = CASE WHEN status = 'approved' THEN ${seenAt} ELSE updated_at END
WHERE client_proof_key_thumbprint = ${clientProofKeyThumbprint}
AND revoked_at IS NULL
RETURNING ${sql.unsafe(rowSelection)}
`,
});
const listRows = SqlSchema.findAll({
Request: Schema.Void,
Result: AuthConnectClientRawDbRow,
execute: () =>
sql`
SELECT ${sql.unsafe(rowSelection)}
FROM auth_connect_clients
WHERE revoked_at IS NULL
ORDER BY
CASE status
WHEN 'pending' THEN 0
WHEN 'approved' THEN 1
ELSE 2
END,
updated_at DESC,
client_proof_key_thumbprint DESC
`,
});
const decodeRow = (
row: typeof AuthConnectClientRawDbRow.Type,
operation: string,
): Effect.Effect<AuthConnectClientRecord, PersistenceDecodeError> =>
decodeAuthConnectClientDbRow(row).pipe(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(operation, cause, {
clientProofKeyThumbprint: row.clientProofKeyThumbprint,
}),
),
Effect.map(toAuthConnectClientRecord),
);
const upsertRequest: AuthConnectClientRepository["Service"]["upsertRequest"] = (input) =>
upsertRequestRow(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthConnectClientRepository.upsertRequest:query",
"AuthConnectClientRepository.upsertRequest:decodeRow",
{ clientProofKeyThumbprint: input.clientProofKeyThumbprint },
),
),
Effect.flatMap((row) =>
decodeRow(row, "AuthConnectClientRepository.upsertRequest:decodeRow"),
),
);
const updateStatus: AuthConnectClientRepository["Service"]["updateStatus"] = (input) =>
updateStatusRow(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthConnectClientRepository.updateStatus:query",
"AuthConnectClientRepository.updateStatus:decodeRow",
{ clientProofKeyThumbprint: input.clientProofKeyThumbprint },
),
),
Effect.flatMap((rowOption) =>
Option.match(rowOption, {
onNone: () => Effect.succeed(Option.none()),
onSome: (row) =>
decodeRow(row, "AuthConnectClientRepository.updateStatus:decodeRow").pipe(
Effect.map(Option.some),
),
}),
),
);
const revoke: AuthConnectClientRepository["Service"]["revoke"] = (input) =>
revokeRow(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthConnectClientRepository.revoke:query",
"AuthConnectClientRepository.revoke:decodeRows",
{ clientProofKeyThumbprint: input.clientProofKeyThumbprint },
),
),
Effect.map((rows) => rows.length > 0),
);
const markSeen: AuthConnectClientRepository["Service"]["markSeen"] = (input) =>
markSeenRow(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthConnectClientRepository.markSeen:query",
"AuthConnectClientRepository.markSeen:decodeRow",
{ clientProofKeyThumbprint: input.clientProofKeyThumbprint },
),
),
Effect.flatMap((rowOption) =>
Option.match(rowOption, {
onNone: () => Effect.succeed(Option.none()),
onSome: (row) =>
decodeRow(row, "AuthConnectClientRepository.markSeen:decodeRow").pipe(
Effect.map(Option.some),
),
}),
),
);
const listActive: AuthConnectClientRepository["Service"]["listActive"] = () =>
listRows().pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"AuthConnectClientRepository.listActive:query",
"AuthConnectClientRepository.listActive:decodeRows",
),
),
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) =>
decodeRow(row, "AuthConnectClientRepository.listActive:decodeRows"),
),
),
);
return {
upsertRequest,
updateStatus,
revoke,
markSeen,
listActive,
} satisfies AuthConnectClientRepository["Service"];
});
export const layer = Layer.effect(AuthConnectClientRepository, make);
+2
View File
@@ -23,6 +23,7 @@ export const PersistenceErrorCorrelation = Schema.Union([
Schema.Struct({ sessionId: Schema.String }),
Schema.Struct({ currentSessionId: Schema.String }),
Schema.Struct({ pairingLinkId: Schema.String }),
Schema.Struct({ clientProofKeyThumbprint: Schema.String }),
Schema.Struct({ threadId: Schema.String }),
]);
export type PersistenceErrorCorrelation = typeof PersistenceErrorCorrelation.Type;
@@ -134,5 +135,6 @@ export type OrchestrationCommandReceiptRepositoryError =
export type ProviderSessionRuntimeRepositoryError = PersistenceSqlError | PersistenceDecodeError;
export type AuthPairingLinkRepositoryError = PersistenceSqlError | PersistenceDecodeError;
export type AuthSessionRepositoryError = PersistenceSqlError | PersistenceDecodeError;
export type AuthConnectClientRepositoryError = PersistenceSqlError | PersistenceDecodeError;
export type ProjectionRepositoryError = PersistenceSqlError | PersistenceDecodeError;
@@ -45,6 +45,7 @@ import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexe
import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_AuthConnectClientApprovals.ts";
/**
* Migration loader with all migrations defined inline.
@@ -89,6 +90,7 @@ export const migrationEntries = [
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
[31, "AuthAuthorizationScopes", Migration0031],
[32, "AuthPairingProofKeyThumbprint", Migration0032],
[33, "AuthConnectClientApprovals", Migration0033],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,37 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE TABLE IF NOT EXISTS auth_connect_clients (
client_proof_key_thumbprint TEXT PRIMARY KEY,
cloud_user_id TEXT NOT NULL,
device_id TEXT,
status TEXT NOT NULL,
client_label TEXT,
client_ip_address TEXT,
client_user_agent TEXT,
client_device_type TEXT NOT NULL DEFAULT 'unknown',
client_os TEXT,
client_browser TEXT,
requested_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
approved_at TEXT,
rejected_at TEXT,
revoked_at TEXT,
last_seen_at TEXT
)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_auth_connect_clients_active
ON auth_connect_clients(revoked_at, status, updated_at)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_auth_connect_clients_cloud_user
ON auth_connect_clients(cloud_user_id, revoked_at)
`;
});
@@ -3703,6 +3703,7 @@ describe("ClaudeAdapterLive", () => {
nativeThreadIds.push(threadId ?? null);
return Effect.void;
},
close: () => Effect.void,
},
});
return Effect.gen(function* () {
@@ -1347,13 +1347,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, options?.environment).pipe(
Effect.provideService(Path.Path, path),
);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined;
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
: undefined);
const createQuery =
options?.createQuery ??
@@ -1387,7 +1387,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
const logNativeSdkMessage = Effect.fnUntraced(function* (
const logNativeSdkMessage = Effect.fn("logNativeSdkMessage")(function* (
context: ClaudeSessionContext,
message: SDKMessage,
) {
@@ -3843,7 +3843,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
Effect.logError("Failed to emit Claude session shutdown event.", { cause }),
),
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
),
);
@@ -1227,7 +1227,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
yield* Scope.close(scope, Exit.void);
scopeClosed = true;
const threadLogPath = NodePath.join(tempDir, "provider-native-thread-logger.log");
const threadLogPath = NodePath.join(tempDir, "thread-logger.log");
NodeAssert.equal(NodeFS.existsSync(threadLogPath), true);
const contents = NodeFS.readFileSync(threadLogPath, "utf8");
NodeAssert.match(contents, /NTIVE: .*"message":"native flush test"/);
@@ -1354,13 +1354,15 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const crypto = yield* Crypto.Crypto;
const serverConfig = yield* Effect.service(ServerConfig);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined;
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const sessions = new Map<ThreadId, CodexAdapterSessionContext>();
@@ -1635,7 +1637,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
),
);
const writeNativeEvent = Effect.fnUntraced(function* (event: ProviderEvent) {
const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
if (!nativeEventLogger) {
return;
}
@@ -124,7 +124,7 @@ function waitForJsonLogMatch(
if (requests.some(predicate)) {
return requests;
}
yield* Effect.sleep("10 millis").pipe(TestClock.withLive);
yield* Effect.yieldNow;
}
return yield* Effect.promise(() => readJsonLines(filePath));
});
@@ -321,13 +321,15 @@ export function makeCursorAdapter(
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const crypto = yield* Crypto.Crypto;
const managedNativeEventLogger =
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined;
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
const sessions = new Map<ThreadId, CursorSessionContext>();
@@ -5,25 +5,13 @@ import * as NodePath from "node:path";
import { ThreadId } from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Logger from "effect/Logger";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import { makeEventNdjsonLogger, makeEventNdjsonLogStore } from "./EventNdjsonLogger.ts";
import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
const decodeOmittedRecord = Schema.decodeUnknownSync(
Schema.fromJsonString(
Schema.Struct({
_tag: Schema.String,
reason: Schema.String,
originalBytes: Schema.Number,
eventType: Schema.NullOr(Schema.String),
}),
),
);
function parseLogLine(line: string) {
const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
@@ -44,13 +32,6 @@ function parseLogLine(line: string) {
};
}
function threadLogPath(basePath: string, threadSegment: string) {
return NodePath.join(
NodePath.dirname(basePath),
`${NodePath.parse(basePath).name}-${threadSegment}.log`,
);
}
describe("EventNdjsonLogger", () => {
it.effect("logs bounded diagnostics when an event cannot be serialized", () => {
const messages: Array<unknown> = [];
@@ -74,7 +55,6 @@ describe("EventNdjsonLogger", () => {
assert.exists(logger);
if (!logger) return;
yield* logger.write(circular, ThreadId.make("thread-1"));
yield* logger.close();
const serialized = encodeUnknownJson(messages);
assert.notInclude(serialized, secret);
@@ -107,8 +87,8 @@ describe("EventNdjsonLogger", () => {
);
yield* logger.close();
const threadOnePath = threadLogPath(basePath, "thread-1");
const threadTwoPath = threadLogPath(basePath, "thread-2");
const threadOnePath = NodePath.join(tempDir, "thread-1.log");
const threadTwoPath = NodePath.join(tempDir, "thread-2.log");
assert.equal(NodeFS.existsSync(threadOnePath), true);
assert.equal(NodeFS.existsSync(threadTwoPath), true);
@@ -149,7 +129,7 @@ describe("EventNdjsonLogger", () => {
yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
yield* logger.close();
const globalPath = threadLogPath(basePath, "_global");
const globalPath = NodePath.join(tempDir, "_global.log");
assert.equal(NodeFS.existsSync(globalPath), true);
const lines = NodeFS.readFileSync(globalPath, "utf8")
.trim()
@@ -192,7 +172,7 @@ describe("EventNdjsonLogger", () => {
);
yield* logger.close();
const globalPath = threadLogPath(basePath, "_global");
const globalPath = NodePath.join(tempDir, "_global.log");
assert.equal(NodeFS.existsSync(globalPath), true);
const lines = NodeFS.readFileSync(globalPath, "utf8")
.trim()
@@ -210,102 +190,25 @@ describe("EventNdjsonLogger", () => {
}),
);
it.effect("shares one thread writer across native and canonical streams", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "events.log");
try {
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
const native = store.logger("native");
const canonical = store.logger("canonical");
const threadId = ThreadId.make("thread-shared");
assert.notProperty(native, "close");
assert.notProperty(canonical, "close");
yield* native.write({ id: "native-event" }, threadId);
yield* canonical.write({ type: "item.completed", id: "canonical-event" }, threadId);
yield* store.close();
const lines = NodeFS.readFileSync(threadLogPath(basePath, "thread-shared"), "utf8")
.trim()
.split("\n")
.map(parseLogLine);
assert.deepEqual(
lines.map(({ stream, payload }) => ({ stream, payload })),
[
{ stream: "NTIVE", payload: '{"id":"native-event"}' },
{
stream: "CANON",
payload: '{"type":"item.completed","id":"canonical-event"}',
},
],
);
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("drops transient canonical events before serialization", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "events.log");
try {
const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 });
const canonical = store.logger("canonical");
const native = store.logger("native");
const threadId = ThreadId.make("thread-filtered");
const circularDelta: Record<string, unknown> = { type: "content.delta" };
circularDelta["self"] = circularDelta;
yield* canonical.write(circularDelta, threadId);
yield* canonical.write({ type: "item.completed", id: "final" }, threadId);
yield* native.write({ type: "content.delta", id: "native-delta" }, threadId);
yield* store.close();
const lines = NodeFS.readFileSync(threadLogPath(basePath, "thread-filtered"), "utf8")
.trim()
.split("\n")
.map(parseLogLine);
assert.deepEqual(
lines.map(({ stream, payload }) => ({ stream, payload })),
[
{ stream: "CANON", payload: '{"type":"item.completed","id":"final"}' },
{ stream: "NTIVE", payload: '{"type":"content.delta","id":"native-delta"}' },
],
);
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("rotates per-thread files when max size is exceeded", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "provider-native.ndjson");
try {
const store = yield* makeEventNdjsonLogStore(basePath, {
maxBytes: 512,
const logger = yield* makeEventNdjsonLogger(basePath, {
stream: "native",
maxBytes: 120,
maxFiles: 2,
batchWindowMs: 0,
maxBufferedBytes: 256,
maxRecordBytes: 256,
});
const native = store.logger("native");
const canonical = store.logger("canonical");
assert.notEqual(logger, undefined);
if (!logger) {
return;
}
for (let index = 0; index < 10; index += 1) {
const logger = index % 2 === 0 ? native : canonical;
yield* logger.write(
{
type: "session.started",
threadId: "provider-thread-rotate",
id: `evt-${index}`,
payload: "x".repeat(40),
@@ -313,9 +216,9 @@ describe("EventNdjsonLogger", () => {
ThreadId.make("thread-rotate"),
);
}
yield* store.close();
yield* logger.close();
const fileStem = NodePath.basename(threadLogPath(basePath, "thread-rotate"));
const fileStem = "thread-rotate.log";
const matchingFiles = NodeFS.readdirSync(tempDir)
.filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
.toSorted();
@@ -332,132 +235,6 @@ describe("EventNdjsonLogger", () => {
matchingFiles.some((entry) => entry === `${fileStem}.3`),
false,
);
for (const entry of matchingFiles) {
assert.isAtMost(NodeFS.statSync(NodePath.join(tempDir, entry)).size, 512);
}
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("replaces oversized records with a bounded omission marker", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "events.log");
try {
const store = yield* makeEventNdjsonLogStore(basePath, {
maxBytes: 512,
maxRecordBytes: 256,
maxBufferedBytes: 256,
batchWindowMs: 0,
});
yield* store
.logger("canonical")
.write(
{ type: "item.completed", payload: "x".repeat(2_000) },
ThreadId.make("thread-oversized"),
);
yield* store
.logger("canonical")
.write(
{ type: "x".repeat(1_000), payload: "x".repeat(2_000) },
ThreadId.make("thread-oversized-type"),
);
yield* store.close();
const filePath = threadLogPath(basePath, "thread-oversized");
assert.isAtMost(NodeFS.statSync(filePath).size, 256);
const line = parseLogLine(NodeFS.readFileSync(filePath, "utf8").trim());
const payload = decodeOmittedRecord(line.payload);
assert.equal(payload._tag, "ProviderEventLogRecordOmitted");
assert.equal(payload.eventType, "item.completed");
assert.isAbove(payload.originalBytes, 2_000);
const longTypeFilePath = threadLogPath(basePath, "thread-oversized-type");
assert.isAtMost(NodeFS.statSync(longTypeFilePath).size, 256);
const longTypeLine = parseLogLine(NodeFS.readFileSync(longTypeFilePath, "utf8").trim());
const longTypePayload = decodeOmittedRecord(longTypeLine.payload);
assert.equal(longTypePayload.eventType, null);
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("enforces aggregate age and byte retention on startup", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "events.log");
const expiredPath = threadLogPath(basePath, "expired");
const oldPath = threadLogPath(basePath, "old");
const newPath = threadLogPath(basePath, "new");
const unrelatedLogPath = NodePath.join(tempDir, "unrelated.log");
const ignoredPath = NodePath.join(tempDir, "ignored.txt");
try {
yield* TestClock.setTime(1_800_000_000_000);
const now = yield* Clock.currentTimeMillis;
for (const filePath of [expiredPath, oldPath, newPath, unrelatedLogPath, ignoredPath]) {
NodeFS.writeFileSync(filePath, "x".repeat(400));
}
NodeFS.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
NodeFS.utimesSync(oldPath, (now - 5_000) / 1_000, (now - 5_000) / 1_000);
NodeFS.utimesSync(newPath, now / 1_000, now / 1_000);
NodeFS.utimesSync(unrelatedLogPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000);
const store = yield* makeEventNdjsonLogStore(basePath, {
maxAgeMs: 10_000,
maxTotalBytes: 600,
});
yield* store.close();
assert.equal(NodeFS.existsSync(expiredPath), false);
assert.equal(NodeFS.existsSync(oldPath), false);
assert.equal(NodeFS.existsSync(newPath), true);
assert.equal(NodeFS.existsSync(unrelatedLogPath), true);
assert.equal(NodeFS.existsSync(ignoredPath), true);
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("keeps aggregate provider logs within the byte budget while writing", () =>
Effect.gen(function* () {
const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
const basePath = NodePath.join(tempDir, "events.log");
try {
const store = yield* makeEventNdjsonLogStore(basePath, {
maxBytes: 512,
maxFiles: 2,
maxTotalBytes: 1_200,
maxBufferedBytes: 256,
maxRecordBytes: 256,
batchWindowMs: 0,
});
for (let index = 0; index < 30; index += 1) {
yield* store.logger(index % 2 === 0 ? "native" : "canonical").write(
{
type: "item.completed",
id: `evt-${index}`,
payload: "x".repeat(80),
},
ThreadId.make(`thread-${index % 4}`),
);
}
yield* store.close();
const totalBytes = NodeFS.readdirSync(tempDir, { withFileTypes: true })
.filter((entry) => entry.isFile() && /^events-.+\.log(?:\.\d+)?$/u.test(entry.name))
.reduce(
(total, entry) => total + NodeFS.statSync(NodePath.join(tempDir, entry.name)).size,
0,
);
assert.isAtMost(totalBytes, 1_200);
} finally {
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
@@ -1,9 +1,10 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* Best-effort provider event logging with one shared writer store.
* Provider event logger helper.
*
* Native and canonical views share batching, rotation, and retention state so
* they cannot race while appending to the same thread-scoped file.
* Best-effort writer for observability logs. Each record is formatted as a
* single effect-style text line in a thread-scoped file. Failures are
* downgraded to warnings so provider runtime behavior is unaffected.
*/
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
@@ -11,435 +12,84 @@ import * as NodePath from "node:path";
import type { ThreadId } from "@t3tools/contracts";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { errorTag } from "@t3tools/shared/observability";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Logger from "effect/Logger";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as SynchronizedRef from "effect/SynchronizedRef";
import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
const MEBIBYTE = 1024 * 1024;
const DAY_MS = 24 * 60 * 60 * 1_000;
const MIN_RECORD_BYTES = 256;
const DEFAULT_MAX_BYTES = 10 * MEBIBYTE;
const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
const DEFAULT_MAX_FILES = 10;
const DEFAULT_BATCH_WINDOW_MS = 1_000;
const DEFAULT_MAX_TOTAL_BYTES = 512 * MEBIBYTE;
const DEFAULT_MAX_AGE_MS = 14 * DAY_MS;
const DEFAULT_RETENTION_CHECK_INTERVAL_MS = 5 * 60 * 1_000;
const DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE;
const DEFAULT_MAX_BUFFERED_RECORDS = 512;
const DEFAULT_MAX_RECORD_BYTES = MEBIBYTE;
const DEFAULT_MAX_CACHED_SINKS = 64;
const DEFAULT_BATCH_WINDOW_MS = 200;
const GLOBAL_THREAD_SEGMENT = "_global";
const LOG_SCOPE = "provider-observability";
const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const transientCanonicalEventTypes = new Set([
"content.delta",
"hook.progress",
"item.updated",
"task.progress",
"thread.realtime.audio.delta",
"tool.progress",
"turn.proposed.delta",
]);
export type EventNdjsonStream = "native" | "canonical" | "orchestration";
export interface EventNdjsonLogger {
readonly filePath: string;
readonly write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void, never, never>;
close: () => Effect.Effect<void, never, never>;
}
export interface ManagedEventNdjsonLogger extends EventNdjsonLogger {
readonly close: () => Effect.Effect<void>;
}
export interface EventNdjsonLogStore {
readonly filePath: string;
readonly logger: (stream: EventNdjsonStream) => EventNdjsonLogger;
readonly close: () => Effect.Effect<void>;
}
export interface EventNdjsonLogStoreOptions {
export interface EventNdjsonLoggerOptions {
readonly stream: EventNdjsonStream;
readonly maxBytes?: number;
readonly maxFiles?: number;
readonly batchWindowMs?: number;
readonly maxTotalBytes?: number;
readonly maxAgeMs?: number;
readonly retentionCheckIntervalMs?: number;
readonly maxBufferedBytes?: number;
readonly maxBufferedRecords?: number;
readonly maxRecordBytes?: number;
readonly maxCachedSinks?: number;
}
export interface EventNdjsonLoggerOptions extends EventNdjsonLogStoreOptions {
readonly stream: EventNdjsonStream;
interface ThreadWriter {
writeMessage: (message: string) => Effect.Effect<void>;
close: () => Effect.Effect<void>;
}
export class EventNdjsonLogConfigurationError extends Schema.TaggedErrorClass<EventNdjsonLogConfigurationError>()(
"EventNdjsonLogConfigurationError",
{
filePath: Schema.String,
option: Schema.String,
value: Schema.Number,
minimum: Schema.Number,
},
) {
override get message(): string {
return `Provider event log option '${this.option}' must be an integer >= ${this.minimum}; received ${this.value} for '${this.filePath}'`;
}
interface LoggerState {
readonly threadWriters: Map<string, ThreadWriter>;
readonly failedSegments: Set<string>;
}
export class EventNdjsonLogDirectoryError extends Schema.TaggedErrorClass<EventNdjsonLogDirectoryError>()(
"EventNdjsonLogDirectoryError",
{
directory: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to create provider event log directory '${this.directory}'`;
}
}
export type EventNdjsonLogStoreError =
| EventNdjsonLogConfigurationError
| EventNdjsonLogDirectoryError;
interface ResolvedOptions {
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly maxTotalBytes: number;
readonly maxAgeMs: number;
readonly retentionCheckIntervalMs: number;
readonly maxBufferedBytes: number;
readonly maxBufferedRecords: number;
readonly maxRecordBytes: number;
readonly maxCachedSinks: number;
}
interface PendingRecord {
readonly threadSegment: string;
readonly line: string;
readonly bytes: number;
}
interface StoreState {
readonly pending: ReadonlyArray<PendingRecord>;
readonly pendingBytes: number;
readonly sinks: ReadonlyMap<string, RotatingFileSink>;
readonly closed: boolean;
readonly lastRetentionAt: number;
readonly retainedBytesEstimate: number;
}
interface FileOperationFailure {
readonly filePath: string;
readonly cause: unknown;
}
interface RetentionResult {
readonly failures: ReadonlyArray<FileOperationFailure>;
readonly removedCount: number;
readonly totalBytes: number;
}
interface DrainResult {
readonly failures: ReadonlyArray<FileOperationFailure>;
}
function logWarning(message: string, context: Record<string, unknown>) {
function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
}
function resolveThreadSegment(raw: string | null | undefined) {
function resolveThreadSegment(raw: string | null | undefined): string {
const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null;
return normalized ?? GLOBAL_THREAD_SEGMENT;
}
function resolveStreamLabel(stream: EventNdjsonStream) {
return stream === "native" ? "NTIVE" : "CANON";
function formatLoggerMessage(message: unknown): string {
if (Array.isArray(message)) {
return message.map((part) => (typeof part === "string" ? part : String(part))).join(" ");
}
return typeof message === "string" ? message : String(message);
}
function shouldPersist(stream: EventNdjsonStream, event: unknown) {
if (stream !== "canonical" || typeof event !== "object" || event === null) {
return true;
}
const type = Reflect.get(event, "type");
return typeof type !== "string" || !transientCanonicalEventTypes.has(type);
function makeLineLogger(streamLabel: string): Logger.Logger<unknown, string> {
return Logger.make(
({ date, message }) =>
`[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`,
);
}
function eventType(event: unknown) {
if (typeof event !== "object" || event === null) return null;
const type = Reflect.get(event, "type");
return typeof type === "string" ? type.slice(0, 128) : null;
function resolveStreamLabel(stream: EventNdjsonStream): string {
switch (stream) {
case "native":
return "NTIVE";
case "canonical":
case "orchestration":
default:
return "CANON";
}
}
function formatRecordLine(input: {
readonly stream: EventNdjsonStream;
readonly event: unknown;
readonly observedAt: string;
readonly payload: string;
readonly maxRecordBytes: number;
}) {
const prefix = `[${input.observedAt}] ${resolveStreamLabel(input.stream)}: `;
const line = `${prefix}${input.payload}\n`;
const bytes = Buffer.byteLength(line);
if (bytes <= input.maxRecordBytes) {
return { line, bytes };
}
const omittedPayload = (type: string | null) =>
JSON.stringify({
_tag: "ProviderEventLogRecordOmitted",
reason: "record_too_large",
originalBytes: bytes,
eventType: type,
});
let omittedLine = `${prefix}${omittedPayload(eventType(input.event))}\n`;
if (Buffer.byteLength(omittedLine) > input.maxRecordBytes) {
omittedLine = `${prefix}${omittedPayload(null)}\n`;
}
return {
line: omittedLine,
bytes: Buffer.byteLength(omittedLine),
};
}
function writeBatchedRecords(
sink: RotatingFileSink,
records: ReadonlyArray<PendingRecord>,
maxChunkBytes: number,
) {
let pendingLines: Array<string> = [];
let pendingBytes = 0;
const flush = () => {
if (pendingLines.length === 0) return;
sink.write(pendingLines.join(""));
pendingLines = [];
pendingBytes = 0;
};
for (const record of records) {
if (pendingBytes > 0 && pendingBytes + record.bytes > maxChunkBytes) {
flush();
}
pendingLines.push(record.line);
pendingBytes += record.bytes;
if (pendingBytes >= maxChunkBytes) {
flush();
}
}
flush();
}
function enforceRetention(input: {
readonly directory: string;
readonly filePattern: RegExp;
readonly maxTotalBytes: number;
readonly maxAgeMs: number;
readonly now: number;
}): RetentionResult {
const failures: Array<FileOperationFailure> = [];
const files: Array<{ filePath: string; mtimeMs: number; size: number }> = [];
let entries: ReadonlyArray<NodeFS.Dirent>;
try {
entries = NodeFS.readdirSync(input.directory, { withFileTypes: true });
} catch (cause) {
return {
failures: [{ filePath: input.directory, cause }],
removedCount: 0,
totalBytes: input.maxTotalBytes + 1,
};
}
for (const entry of entries) {
if (!entry.isFile() || !input.filePattern.test(entry.name)) continue;
const filePath = NodePath.join(input.directory, entry.name);
try {
const stat = NodeFS.statSync(filePath);
files.push({ filePath, mtimeMs: stat.mtimeMs, size: stat.size });
} catch (cause) {
failures.push({ filePath, cause });
}
}
let totalBytes = files.reduce((total, file) => total + file.size, 0);
let removedCount = 0;
const remove = (file: (typeof files)[number]) => {
try {
NodeFS.rmSync(file.filePath, { force: true });
totalBytes -= file.size;
removedCount += 1;
return true;
} catch (cause) {
failures.push({ filePath: file.filePath, cause });
return false;
}
};
const retained = files.filter((file) => {
if (input.now - file.mtimeMs <= input.maxAgeMs) return true;
return !remove(file);
});
for (const file of retained.toSorted(
(left, right) => left.mtimeMs - right.mtimeMs || left.filePath.localeCompare(right.filePath),
)) {
if (totalBytes <= input.maxTotalBytes) break;
if (!remove(file)) break;
}
return { failures, removedCount, totalBytes };
}
function validateOption(input: {
readonly filePath: string;
readonly option: string;
readonly value: number;
readonly minimum: number;
}) {
if (Number.isInteger(input.value) && input.value >= input.minimum) return undefined;
return new EventNdjsonLogConfigurationError(input);
}
function resolveOptions(filePath: string, options: EventNdjsonLogStoreOptions) {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
const maxBufferedBytes = options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES;
const requestedMaxRecordBytes = options.maxRecordBytes ?? DEFAULT_MAX_RECORD_BYTES;
const resolved = {
maxBytes,
maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES,
batchWindowMs: options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS,
maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
retentionCheckIntervalMs:
options.retentionCheckIntervalMs ?? DEFAULT_RETENTION_CHECK_INTERVAL_MS,
maxBufferedBytes,
maxBufferedRecords: options.maxBufferedRecords ?? DEFAULT_MAX_BUFFERED_RECORDS,
maxRecordBytes: Math.min(requestedMaxRecordBytes, maxBytes, maxBufferedBytes),
maxCachedSinks: options.maxCachedSinks ?? DEFAULT_MAX_CACHED_SINKS,
} satisfies ResolvedOptions;
const validations = [
["maxBytes", maxBytes, MIN_RECORD_BYTES],
["maxFiles", resolved.maxFiles, 1],
["batchWindowMs", resolved.batchWindowMs, 0],
["maxTotalBytes", resolved.maxTotalBytes, 1],
["maxAgeMs", resolved.maxAgeMs, 1],
["retentionCheckIntervalMs", resolved.retentionCheckIntervalMs, 1],
["maxBufferedBytes", maxBufferedBytes, MIN_RECORD_BYTES],
["maxBufferedRecords", resolved.maxBufferedRecords, 1],
["maxRecordBytes", requestedMaxRecordBytes, MIN_RECORD_BYTES],
["maxCachedSinks", resolved.maxCachedSinks, 1],
] as const;
for (const [option, value, minimum] of validations) {
const error = validateOption({ filePath, option, value, minimum });
if (error) return Effect.fail(error);
}
return Effect.succeed(resolved);
}
function drainPending(input: {
readonly directory: string;
readonly filePrefix: string;
readonly filePattern: RegExp;
readonly options: ResolvedOptions;
readonly state: StoreState;
readonly now: number;
readonly close: boolean;
}): readonly [DrainResult, StoreState] {
if (input.state.closed) {
return [{ failures: [] }, input.state];
}
let sinks = new Map(input.state.sinks);
const failures: Array<FileOperationFailure> = [];
const recordsBySegment = new Map<string, Array<PendingRecord>>();
for (const record of input.state.pending) {
const records = recordsBySegment.get(record.threadSegment) ?? [];
records.push(record);
recordsBySegment.set(record.threadSegment, records);
}
let writtenBytes = 0;
for (const [threadSegment, records] of recordsBySegment) {
const filePath = NodePath.join(input.directory, `${input.filePrefix}-${threadSegment}.log`);
let sink = sinks.get(threadSegment);
try {
if (!sink) {
sink = new RotatingFileSink({
filePath,
maxBytes: input.options.maxBytes,
maxFiles: input.options.maxFiles,
throwOnError: true,
});
}
sinks.delete(threadSegment);
sinks.set(threadSegment, sink);
while (sinks.size > input.options.maxCachedSinks) {
const oldest = sinks.keys().next().value;
if (oldest === undefined) break;
sinks.delete(oldest);
}
writeBatchedRecords(
sink,
records,
Math.min(input.options.maxBytes, input.options.maxBufferedBytes),
);
writtenBytes += records.reduce((total, record) => total + record.bytes, 0);
} catch (cause) {
sinks.delete(threadSegment);
failures.push({ filePath, cause });
}
}
const retainedBytesEstimate = input.state.retainedBytesEstimate + writtenBytes;
const retentionDue =
input.close ||
failures.length > 0 ||
retainedBytesEstimate > input.options.maxTotalBytes ||
input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs;
const retention = retentionDue
? enforceRetention({
directory: input.directory,
filePattern: input.filePattern,
maxTotalBytes: input.options.maxTotalBytes,
maxAgeMs: input.options.maxAgeMs,
now: input.now,
})
: null;
if (retention && retention.removedCount > 0) {
sinks = new Map();
}
return [
{
failures: [...failures, ...(retention?.failures ?? [])],
},
{
pending: [],
pendingBytes: 0,
sinks,
closed: input.close,
lastRetentionAt: retention ? input.now : input.state.lastRetentionAt,
retainedBytesEstimate: retention?.totalBytes ?? retainedBytesEstimate,
},
];
}
const serializeEvent = Effect.fnUntraced(function* (event: unknown) {
const toLogMessage = Effect.fn("toLogMessage")(function* (
event: unknown,
): Effect.fn.Return<string | undefined> {
return yield* encodeUnknownJsonString(event).pipe(
Effect.catch((error) =>
logWarning("failed to serialize provider event log record", {
@@ -449,169 +99,188 @@ const serializeEvent = Effect.fnUntraced(function* (event: unknown) {
);
});
export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
filePath: string,
options: EventNdjsonLogStoreOptions = {},
): Effect.fn.Return<EventNdjsonLogStore, EventNdjsonLogStoreError> {
const resolved = yield* resolveOptions(filePath, options);
const directory = NodePath.dirname(filePath);
const filePrefix =
toSafeThreadAttachmentSegment(NodePath.parse(filePath).name) ?? "provider-events";
const filePattern = new RegExp(`^${filePrefix}-.+\\.log(?:\\.\\d+)?$`, "u");
yield* Effect.try({
try: () => NodeFS.mkdirSync(directory, { recursive: true }),
catch: (cause) => new EventNdjsonLogDirectoryError({ directory, cause }),
});
const initializedAt = yield* Clock.currentTimeMillis;
const initialRetention = yield* Effect.sync(() =>
enforceRetention({
directory,
filePattern,
maxTotalBytes: resolved.maxTotalBytes,
maxAgeMs: resolved.maxAgeMs,
now: initializedAt,
}),
);
for (const failure of initialRetention.failures) {
yield* logWarning("provider event log retention failed", {
filePath: failure.filePath,
errorTag: errorTag(failure.cause),
});
}
const stateRef = yield* SynchronizedRef.make<StoreState>({
pending: [],
pendingBytes: 0,
sinks: new Map(),
closed: false,
lastRetentionAt: initializedAt,
retainedBytesEstimate: initialRetention.totalBytes,
});
const timerScope = yield* Scope.make();
const reportDrainResult = Effect.fnUntraced(function* (result: DrainResult) {
for (const failure of result.failures) {
yield* logWarning("provider event log write or retention failed", {
filePath: failure.filePath,
errorTag: errorTag(failure.cause),
});
const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly streamLabel: string;
}): Effect.fn.Return<ThreadWriter | undefined> {
const sinkResult = yield* Effect.sync(() => {
try {
return {
ok: true as const,
sink: new RotatingFileSink({
filePath: input.filePath,
maxBytes: input.maxBytes,
maxFiles: input.maxFiles,
throwOnError: true,
}),
};
} catch (error) {
return { ok: false as const, error };
}
});
const flush = Effect.fnUntraced(function* (close: boolean) {
const now = yield* Clock.currentTimeMillis;
const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
Effect.sync(() =>
drainPending({
directory,
filePrefix,
filePattern,
options: resolved,
state,
now,
close,
}),
),
);
yield* reportDrainResult(result);
});
if (resolved.batchWindowMs > 0) {
yield* Effect.forkIn(
Effect.forever(Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(false)))),
timerScope,
{ startImmediately: true },
);
if (!sinkResult.ok) {
yield* logWarning("failed to initialize provider thread log file", {
filePath: input.filePath,
errorTag: errorTag(sinkResult.error),
});
return undefined;
}
const close = Effect.fnUntraced(function* () {
yield* flush(true);
yield* Scope.close(timerScope, Exit.void);
});
const loggerViews = new Map<EventNdjsonStream, EventNdjsonLogger>();
const logger = (stream: EventNdjsonStream): EventNdjsonLogger => {
const existing = loggerViews.get(stream);
if (existing) return existing;
const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) {
if (!shouldPersist(stream, event)) return;
const payload = yield* serializeEvent(event);
if (payload === undefined) return;
const observedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));
const record = formatRecordLine({
stream,
event,
observedAt,
payload,
maxRecordBytes: resolved.maxRecordBytes,
const sink = sinkResult.sink;
const scope = yield* Scope.make();
const lineLogger = makeLineLogger(input.streamLabel);
const batchedLogger = yield* Logger.batched(lineLogger, {
window: input.batchWindowMs,
flush: Effect.fn("makeThreadWriter.flush")(function* (messages) {
const flushResult = yield* Effect.sync(() => {
try {
for (const message of messages) {
sink.write(message);
}
return { ok: true as const };
} catch (error) {
return { ok: false as const, error };
}
});
const now = yield* Clock.currentTimeMillis;
const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
if (state.closed) {
return Effect.succeed([null, state] as const);
}
const pending = [
...state.pending,
{
threadSegment: resolveThreadSegment(threadId),
line: record.line,
bytes: record.bytes,
},
];
const pendingBytes = state.pendingBytes + record.bytes;
const shouldFlush =
resolved.batchWindowMs === 0 ||
pending.length >= resolved.maxBufferedRecords ||
pendingBytes >= resolved.maxBufferedBytes;
const nextState = {
...state,
pending,
pendingBytes,
};
if (!shouldFlush) {
return Effect.succeed([null, nextState] as const);
}
return Effect.sync(() => {
const [drainResult, drainedState] = drainPending({
directory,
filePrefix,
filePattern,
options: resolved,
state: nextState,
now,
close: false,
});
return [drainResult, drainedState] as const;
if (!flushResult.ok) {
yield* logWarning("provider event log batch flush failed", {
filePath: input.filePath,
errorTag: errorTag(flushResult.error),
});
});
if (result) {
yield* reportDrainResult(result);
}
});
}),
}).pipe(Effect.provideService(Scope.Scope, scope));
const view = { filePath, write } satisfies EventNdjsonLogger;
loggerViews.set(stream, view);
return view;
};
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
return { filePath, logger, close } satisfies EventNdjsonLogStore;
return {
writeMessage(message: string) {
return Effect.log(message).pipe(Effect.provide(loggerLayer));
},
close() {
return Scope.close(scope, Exit.void);
},
} satisfies ThreadWriter;
});
export const makeEventNdjsonLogger = Effect.fnUntraced(function* (
export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* (
filePath: string,
options: EventNdjsonLoggerOptions,
): Effect.fn.Return<ManagedEventNdjsonLogger | undefined> {
const store = yield* makeEventNdjsonLogStore(filePath, options).pipe(
Effect.catch((error) =>
logWarning(error.message, { error }).pipe(
Effect.as<EventNdjsonLogStore | undefined>(undefined),
),
),
);
if (!store) return undefined;
return { ...store.logger(options.stream), close: store.close };
): Effect.fn.Return<EventNdjsonLogger | undefined> {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
const streamLabel = resolveStreamLabel(options.stream);
const directoryReady = yield* Effect.sync(() => {
try {
NodeFS.mkdirSync(NodePath.dirname(filePath), { recursive: true });
return true;
} catch (error) {
return { ok: false as const, error };
}
});
if (directoryReady !== true) {
yield* logWarning("failed to create provider event log directory", {
filePath,
errorTag: errorTag(directoryReady.error),
});
return undefined;
}
const stateRef = yield* SynchronizedRef.make<LoggerState>({
threadWriters: new Map(),
failedSegments: new Set(),
});
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
threadSegment: string,
): Effect.fn.Return<ThreadWriter | undefined> {
return yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
if (state.failedSegments.has(threadSegment)) {
return Effect.succeed([undefined, state] as const);
}
const existing = state.threadWriters.get(threadSegment);
if (existing) {
return Effect.succeed([existing, state] as const);
}
return makeThreadWriter({
filePath: NodePath.join(NodePath.dirname(filePath), `${threadSegment}.log`),
maxBytes,
maxFiles,
batchWindowMs,
streamLabel,
}).pipe(
Effect.map((writer) => {
if (!writer) {
const nextFailedSegments = new Set(state.failedSegments);
nextFailedSegments.add(threadSegment);
return [
undefined,
{
...state,
failedSegments: nextFailedSegments,
},
] as const;
}
const nextThreadWriters = new Map(state.threadWriters);
nextThreadWriters.set(threadSegment, writer);
return [
writer,
{
...state,
threadWriters: nextThreadWriters,
},
] as const;
}),
);
});
});
const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
const threadSegment = resolveThreadSegment(threadId);
const message = yield* toLogMessage(event);
if (!message) {
return;
}
const writer = yield* resolveThreadWriter(threadSegment);
if (!writer) {
return;
}
yield* writer.writeMessage(message);
});
const close = Effect.fn("close")(function* () {
yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
Effect.gen(function* () {
for (const writer of state.threadWriters.values()) {
yield* writer.close();
}
return [
undefined,
{
threadWriters: new Map<string, ThreadWriter>(),
failedSegments: new Set<string>(),
},
] as const;
}),
);
});
return {
filePath,
write,
close,
} satisfies EventNdjsonLogger;
});
@@ -693,6 +693,7 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
JSON.stringify(record).includes("late after cancel")
? Deferred.succeed(lateNativeUpdate, undefined).pipe(Effect.asVoid)
: Effect.void,
close: () => Effect.void,
},
});
@@ -1175,6 +1176,7 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
record.event.kind === "notification"
? Effect.die(new Error("native log write failed"))
: Effect.void,
close: () => Effect.void,
},
});
const contentDelta = yield* Deferred.make<void>();
@@ -232,11 +232,13 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const crypto = yield* Crypto.Crypto;
const managedNativeEventLogger =
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: "native" })
: undefined;
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
const sessions = new Map<ThreadId, GrokSessionContext>();
@@ -433,15 +433,17 @@ export function makeOpenCodeAdapter(
const serverConfig = yield* ServerConfig;
const openCodeRuntime = yield* OpenCodeRuntime;
const crypto = yield* Crypto.Crypto;
// Only close loggers we created. If the caller passed one in via
// `options.nativeEventLogger`, they own its lifecycle.
const managedNativeEventLogger =
options?.nativeEventLogger === undefined && options?.nativeEventLogPath !== undefined
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
stream: "native",
})
: undefined;
const nativeEventLogger = options?.nativeEventLogger ?? managedNativeEventLogger;
: undefined);
// Only close loggers we created. If the caller passed one in via
// `options.nativeEventLogger`, they own its lifecycle.
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
const sessions = new Map<ThreadId, OpenCodeSessionContext>();
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
@@ -1,6 +1,6 @@
/**
* ProviderEventLoggers — single observability service that owns the shared
* provider event log store and exposes its two runtime views:
* ProviderEventLoggers — single observability service that owns the two
* shared NDJSON streams the provider runtime writes:
*
* - `native` — provider-protocol events as the SDK emits them, written
* from inside each `<X>Adapter` factory.
@@ -13,14 +13,17 @@
* not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`
* call site where we can hand an `EventNdjsonLogger` in by hand.
* - Multiple driver instances per kind (`codex_personal`, `codex_work`)
* should share one underlying log store — opening N writers against the
* same rotating file would race the rotation logic. Owning the loggers on
* a single tag keeps that invariant intact.
* should share one underlying log writer per stream — opening N writers
* against the same rotating file would race the rotation logic. Owning
* the loggers on a single tag keeps that invariant intact.
* - Tests can swap one (or both) loggers with in-memory recorders by
* `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of
* juggling per-Layer option threading.
*
* Both fields are optional because observability must not prevent startup.
* Both fields are optional. `makeEventNdjsonLogger` returns `undefined` when
* the target directory cannot be created; we forward that as `undefined`
* rather than failing the boot Layer, matching the previous best-effort
* behavior of `server.ts`.
*
* @module provider/Layers/ProviderEventLoggers
*/
@@ -29,11 +32,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { ServerConfig } from "../../config.ts";
import {
type EventNdjsonLogger,
type EventNdjsonLogStore,
makeEventNdjsonLogStore,
} from "./EventNdjsonLogger.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
export interface ProviderEventLoggersShape {
readonly native: EventNdjsonLogger | undefined;
@@ -64,30 +63,23 @@ export const NoOpProviderEventLoggers: ProviderEventLoggersShape = {
};
/**
* Live layer that builds both stream views over one shared store. Setup
* failures are logged and downgraded to the no-op service so diagnostics never
* block startup. The layer scope flushes and closes the store during shutdown.
* Live Layer that builds both loggers from `ServerConfig.providerEventLogPath`.
* If the directory create fails for either stream, the corresponding field
* is `undefined` and writes from that stream become no-ops downstream.
*/
export const ProviderEventLoggersLive = Layer.effect(
ProviderEventLoggers,
Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
const store = yield* makeEventNdjsonLogStore(providerEventLogPath).pipe(
Effect.catch((error) =>
Effect.logWarning(error.message, { error }).pipe(
Effect.annotateLogs({ scope: "provider-observability" }),
Effect.as<EventNdjsonLogStore | undefined>(undefined),
),
),
);
if (!store) {
return NoOpProviderEventLoggers;
}
yield* Effect.addFinalizer(() => store.close());
const native = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
});
const canonical = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "canonical",
});
return {
native: store.logger("native"),
canonical: store.logger("canonical"),
native,
canonical,
} satisfies ProviderEventLoggersShape;
}),
);
@@ -605,6 +605,7 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se
canonicalThreadIds.push(threadId ?? null);
return Effect.void;
},
close: () => Effect.void,
},
}).pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
@@ -21,6 +21,7 @@ nodeServicesIt("ACP native logging", (it) => {
const nativeEventLogger: EventNdjsonLogger = {
filePath: "/tmp/provider-native.ndjson",
write: (event) => Effect.sync(() => void records.push(event)),
close: () => Effect.void,
};
const makeLogger = yield* makeAcpNativeLoggerFactory();
const logger = makeLogger({
@@ -83,6 +84,7 @@ nodeServicesIt("ACP native logging", (it) => {
nativeEventLogger: {
filePath: "/tmp/provider-native.ndjson",
write: () => Effect.die(new Error(secret)),
close: () => Effect.void,
},
provider: ProviderDriverKind.make("cursor"),
threadId: ThreadId.make("thread-1"),
@@ -111,6 +113,7 @@ nodeServicesIt("ACP native logging", (it) => {
nativeEventLogger: {
filePath: "/tmp/provider-native.ndjson",
write: () => Effect.interrupt,
close: () => Effect.void,
},
provider: ProviderDriverKind.make("cursor"),
threadId: ThreadId.make("thread-1"),
-1
View File
@@ -199,7 +199,6 @@ export class GitVcsDriver extends Context.Service<
cwd: string,
options?: GitRemoteStatusOptions,
) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
readonly refreshStatusUpstream: (cwd: string) => Effect.Effect<void, GitCommandError>;
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
+1 -321
View File
@@ -2,15 +2,12 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, describe } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import * as TestClock from "effect/testing/TestClock";
import { GitCommandError } from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { ServerConfig } from "../config.ts";
import { splitNullSeparatedGitStdoutPaths } from "./GitVcsDriverCore.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
@@ -61,20 +58,6 @@ const git = (
return result.stdout.trim();
});
const findGitExecutable = Effect.fn("GitVcsDriver.test.findGitExecutable")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const pathDelimiter = (yield* HostProcessPlatform) === "win32" ? ";" : ":";
for (const entry of (process.env.PATH ?? "").split(pathDelimiter)) {
if (entry.length === 0) continue;
const candidate = pathService.join(entry, "git");
if (yield* fileSystem.exists(candidate)) {
return yield* fileSystem.realPath(candidate);
}
}
return yield* Effect.die(new Error("Could not find the Git executable in PATH."));
});
const initRepoWithCommit = (
cwd: string,
): Effect.Effect<
@@ -165,7 +148,6 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
const cwd = pathService.join(parent, "missing");
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* driver.refreshStatusUpstream(cwd);
const [localStatus, remoteStatus, refs] = yield* Effect.all([
driver.statusDetails(cwd),
driver.statusDetailsRemote(cwd, { refreshUpstream: false }),
@@ -453,16 +435,8 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
process.env.SSH_ASKPASS_REQUIRE = "force";
process.env.T3_TEST_SSH_ASKPASS_LOG = sshLogPath;
const refreshError = yield* (yield* GitVcsDriver.GitVcsDriver)
.refreshStatusUpstream(cwd)
.pipe(Effect.flip);
yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
assert.deepInclude(refreshError, {
_tag: "GitCommandError",
operation: "GitVcsDriver.fetchRemoteForStatus",
cwd,
detail: "Background Git fetch failed.",
});
assert.deepEqual((yield* fileSystem.readFileString(sshLogPath)).trim().split(/\r?\n/), [
"GCM_INTERACTIVE=never",
"GIT_ASKPASS=",
@@ -487,300 +461,6 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("fetches status remotes from the worktree with hardened background flags", () =>
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
if (platform === "win32") return;
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const wrapperDir = yield* makeTmpDir("git-vcs-driver-wrapper-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const realGit = yield* findGitExecutable();
const wrapperPath = pathService.join(wrapperDir, "git");
const invocationLogPath = pathService.join(wrapperDir, "fetch-invocation.txt");
const fetchHeadPath = pathService.join(cwd, ".git", "FETCH_HEAD");
const previousPath = process.env.PATH;
const previousRealGit = process.env.T3_TEST_REAL_GIT;
const previousInvocationLog = process.env.T3_TEST_FETCH_INVOCATION_LOG;
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* fileSystem.writeFileString(fetchHeadPath, "sentinel-fetch-head\n");
yield* fileSystem.writeFileString(
wrapperPath,
[
"#!/bin/sh",
"is_fetch=0",
'for arg in "$@"; do',
' if [ "$arg" = "fetch" ]; then is_fetch=1; fi',
"done",
'if [ "$is_fetch" = "1" ]; then',
' printf "cwd=%s\\n" "$PWD" > "$T3_TEST_FETCH_INVOCATION_LOG"',
' for arg in "$@"; do',
' printf "arg=%s\\n" "$arg" >> "$T3_TEST_FETCH_INVOCATION_LOG"',
" done",
"fi",
'exec "$T3_TEST_REAL_GIT" "$@"',
"",
].join("\n"),
);
yield* fileSystem.chmod(wrapperPath, 0o755);
yield* Effect.gen(function* () {
process.env.PATH = `${wrapperDir}:${previousPath ?? ""}`;
process.env.T3_TEST_REAL_GIT = realGit;
process.env.T3_TEST_FETCH_INVOCATION_LOG = invocationLogPath;
yield* (yield* GitVcsDriver.GitVcsDriver).refreshStatusUpstream(cwd);
assert.deepStrictEqual(
(yield* fileSystem.readFileString(invocationLogPath)).trim().split(/\r?\n/),
[
`cwd=${cwd}`,
"arg=fetch",
"arg=--quiet",
"arg=--no-tags",
"arg=--no-write-fetch-head",
"arg=--no-auto-maintenance",
"arg=--no-recurse-submodules",
"arg=--",
"arg=origin",
],
);
assert.equal(yield* fileSystem.readFileString(fetchHeadPath), "sentinel-fetch-head\n");
}).pipe(
Effect.ensuring(
Effect.sync(() => {
if (previousPath === undefined) delete process.env.PATH;
else process.env.PATH = previousPath;
if (previousRealGit === undefined) delete process.env.T3_TEST_REAL_GIT;
else process.env.T3_TEST_REAL_GIT = previousRealGit;
if (previousInvocationLog === undefined) {
delete process.env.T3_TEST_FETCH_INVOCATION_LOG;
} else {
process.env.T3_TEST_FETCH_INVOCATION_LOG = previousInvocationLog;
}
}),
),
);
}),
);
it.effect("coalesces matching refreshes and serializes different remotes sharing objects", () =>
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
if (platform === "win32") return;
const cwd = yield* makeTmpDir();
const origin = yield* makeTmpDir("git-vcs-driver-origin-");
const backup = yield* makeTmpDir("git-vcs-driver-backup-");
const worktreeParent = yield* makeTmpDir("git-vcs-driver-worktrees-");
const wrapperDir = yield* makeTmpDir("git-vcs-driver-wrapper-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const worktreeCwd = pathService.join(worktreeParent, "feature");
const realGit = yield* findGitExecutable();
const wrapperPath = pathService.join(wrapperDir, "git");
const invocationLogPath = pathService.join(wrapperDir, "fetches.txt");
const activeLockPath = pathService.join(wrapperDir, "active-fetch");
const overlapLogPath = pathService.join(wrapperDir, "overlap.txt");
const previousPath = process.env.PATH;
const previousRealGit = process.env.T3_TEST_REAL_GIT;
const previousInvocationLog = process.env.T3_TEST_FETCH_INVOCATION_LOG;
const previousActiveLock = process.env.T3_TEST_FETCH_ACTIVE_LOCK;
const previousOverlapLog = process.env.T3_TEST_FETCH_OVERLAP_LOG;
yield* git(origin, ["init", "--bare"]);
yield* git(backup, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", origin]);
yield* git(cwd, ["remote", "add", "backup", backup]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["worktree", "add", "-b", "feature/serialized", worktreeCwd]);
yield* git(worktreeCwd, ["push", "-u", "backup", "feature/serialized"]);
yield* fileSystem.writeFileString(
wrapperPath,
[
"#!/bin/sh",
"is_fetch=0",
'for arg in "$@"; do',
' if [ "$arg" = "fetch" ]; then is_fetch=1; fi',
"done",
'if [ "$is_fetch" = "1" ]; then',
' printf "start\\n" >> "$T3_TEST_FETCH_INVOCATION_LOG"',
' if ! mkdir "$T3_TEST_FETCH_ACTIVE_LOCK" 2>/dev/null; then',
' printf "overlap\\n" >> "$T3_TEST_FETCH_OVERLAP_LOG"',
" fi",
" sleep 0.2",
' "$T3_TEST_REAL_GIT" "$@"',
" status=$?",
' rmdir "$T3_TEST_FETCH_ACTIVE_LOCK" 2>/dev/null || true',
' printf "end\\n" >> "$T3_TEST_FETCH_INVOCATION_LOG"',
" exit $status",
"fi",
'exec "$T3_TEST_REAL_GIT" "$@"',
"",
].join("\n"),
);
yield* fileSystem.chmod(wrapperPath, 0o755);
yield* Effect.gen(function* () {
process.env.PATH = `${wrapperDir}:${previousPath ?? ""}`;
process.env.T3_TEST_REAL_GIT = realGit;
process.env.T3_TEST_FETCH_INVOCATION_LOG = invocationLogPath;
process.env.T3_TEST_FETCH_ACTIVE_LOCK = activeLockPath;
process.env.T3_TEST_FETCH_OVERLAP_LOG = overlapLogPath;
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* Effect.all(
[
driver.refreshStatusUpstream(cwd),
driver.refreshStatusUpstream(cwd),
driver.refreshStatusUpstream(worktreeCwd),
],
{ concurrency: "unbounded", discard: true },
);
const invocationLines = (yield* fileSystem.readFileString(invocationLogPath))
.trim()
.split(/\r?\n/);
assert.deepStrictEqual(invocationLines, ["start", "end", "start", "end"]);
assert.equal(yield* fileSystem.exists(overlapLogPath), false);
}).pipe(
Effect.ensuring(
Effect.sync(() => {
if (previousPath === undefined) delete process.env.PATH;
else process.env.PATH = previousPath;
if (previousRealGit === undefined) delete process.env.T3_TEST_REAL_GIT;
else process.env.T3_TEST_REAL_GIT = previousRealGit;
if (previousInvocationLog === undefined) {
delete process.env.T3_TEST_FETCH_INVOCATION_LOG;
} else {
process.env.T3_TEST_FETCH_INVOCATION_LOG = previousInvocationLog;
}
if (previousActiveLock === undefined) delete process.env.T3_TEST_FETCH_ACTIVE_LOCK;
else process.env.T3_TEST_FETCH_ACTIVE_LOCK = previousActiveLock;
if (previousOverlapLog === undefined) delete process.env.T3_TEST_FETCH_OVERLAP_LOG;
else process.env.T3_TEST_FETCH_OVERLAP_LOG = previousOverlapLog;
}),
),
);
}),
);
it.effect("keeps a waiting worktree refresh alive when the cache owner disconnects", () =>
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
if (platform === "win32") return;
const cwd = yield* makeTmpDir();
const origin = yield* makeTmpDir("git-vcs-driver-origin-");
const worktreeParent = yield* makeTmpDir("git-vcs-driver-worktrees-");
const wrapperDir = yield* makeTmpDir("git-vcs-driver-wrapper-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const worktreeCwd = pathService.join(worktreeParent, "feature");
const realGit = yield* findGitExecutable();
const wrapperPath = pathService.join(wrapperDir, "git");
const invocationLogPath = pathService.join(wrapperDir, "fetches.txt");
const ownerLockPath = pathService.join(wrapperDir, "owner-fetch");
const ownerStartedPath = pathService.join(wrapperDir, "owner-started");
const waiterReadyPath = pathService.join(wrapperDir, "waiter-ready");
const envKeys = [
"PATH",
"T3_TEST_REAL_GIT",
"T3_TEST_FETCH_INVOCATION_LOG",
"T3_TEST_FETCH_OWNER_LOCK",
"T3_TEST_FETCH_OWNER_STARTED",
"T3_TEST_FETCH_WAITER_CWD",
"T3_TEST_FETCH_WAITER_READY",
] as const;
const previousEnv = new Map(envKeys.map((key) => [key, process.env[key]]));
yield* git(origin, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", origin]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["worktree", "add", "-b", "feature/interrupted", worktreeCwd]);
yield* git(worktreeCwd, ["push", "-u", "origin", "feature/interrupted"]);
yield* fileSystem.writeFileString(
wrapperPath,
[
"#!/bin/sh",
"is_fetch=0",
"is_common_dir=0",
'for arg in "$@"; do',
' if [ "$arg" = "fetch" ]; then is_fetch=1; fi',
' if [ "$arg" = "--git-common-dir" ]; then is_common_dir=1; fi',
"done",
'if [ "$is_fetch" = "1" ]; then',
' printf "start:%s\\n" "$PWD" >> "$T3_TEST_FETCH_INVOCATION_LOG"',
' if mkdir "$T3_TEST_FETCH_OWNER_LOCK" 2>/dev/null; then',
' : > "$T3_TEST_FETCH_OWNER_STARTED"',
" trap 'exit 130' INT TERM HUP",
" while :; do sleep 1; done",
" fi",
' exec "$T3_TEST_REAL_GIT" "$@"',
"fi",
'"$T3_TEST_REAL_GIT" "$@"',
"status=$?",
'if [ "$PWD" = "$T3_TEST_FETCH_WAITER_CWD" ] && [ "$is_common_dir" = "1" ]; then',
' : > "$T3_TEST_FETCH_WAITER_READY"',
"fi",
"exit $status",
"",
].join("\n"),
);
yield* fileSystem.chmod(wrapperPath, 0o755);
yield* Effect.gen(function* () {
process.env.PATH = `${wrapperDir}:${previousEnv.get("PATH") ?? ""}`;
process.env.T3_TEST_REAL_GIT = realGit;
process.env.T3_TEST_FETCH_INVOCATION_LOG = invocationLogPath;
process.env.T3_TEST_FETCH_OWNER_LOCK = ownerLockPath;
process.env.T3_TEST_FETCH_OWNER_STARTED = ownerStartedPath;
process.env.T3_TEST_FETCH_WAITER_CWD = worktreeCwd;
process.env.T3_TEST_FETCH_WAITER_READY = waiterReadyPath;
const waitForFile = (filePath: string) =>
Effect.gen(function* () {
while (!(yield* fileSystem.exists(filePath))) {
yield* Effect.sleep("10 millis");
}
}).pipe(Effect.timeout("2 seconds"));
const driver = yield* GitVcsDriver.GitVcsDriver;
const owner = yield* driver.refreshStatusUpstream(cwd).pipe(Effect.forkChild);
yield* waitForFile(ownerStartedPath);
const waiter = yield* driver.refreshStatusUpstream(worktreeCwd).pipe(Effect.forkChild);
yield* waitForFile(waiterReadyPath);
yield* Effect.sleep("50 millis");
yield* Fiber.interrupt(owner);
yield* Fiber.join(waiter).pipe(Effect.timeout("5 seconds"));
assert.deepStrictEqual(
(yield* fileSystem.readFileString(invocationLogPath)).trim().split(/\r?\n/),
[`start:${cwd}`, `start:${worktreeCwd}`],
);
}).pipe(
Effect.ensuring(
Effect.sync(() => {
for (const key of envKeys) {
const previous = previousEnv.get(key);
if (previous === undefined) delete process.env[key];
else process.env[key] = previous;
}
}),
),
TestClock.withLive,
);
}),
);
it.effect("reuses the no-upstream fallback ahead count for default-branch delta", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+43 -133
View File
@@ -1,15 +1,13 @@
import * as Arr from "effect/Array";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as Encoding from "effect/Encoding";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Hash from "effect/Hash";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
@@ -52,7 +50,7 @@ const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 120_000;
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(30);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({
GCM_INTERACTIVE: "never",
@@ -76,11 +74,6 @@ const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitStatusDetail
behindCount: 0,
aheadOfDefaultCount: 0,
});
export const statusUpstreamRefreshCacheTimeToLive = <A, E>(exit: Exit.Exit<A, E>) => {
if (Exit.isSuccess(exit)) return STATUS_UPSTREAM_REFRESH_INTERVAL;
return Cause.hasInterrupts(exit.cause) ? Duration.zero : STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN;
};
const NON_REPOSITORY_REMOTE_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitRemoteStatusDetails>({
isRepo: false,
isDefaultBranch: false,
@@ -97,35 +90,10 @@ type TraceTailState = {
remainder: string;
};
class StatusRemoteRefreshCacheKey {
readonly objectDir: string;
readonly remoteName: string;
readonly cwd: string;
constructor(objectDir: string, remoteName: string, cwd: string) {
this.objectDir = objectDir;
this.remoteName = remoteName;
this.cwd = cwd;
}
[Equal.symbol](that: unknown) {
return (
that instanceof StatusRemoteRefreshCacheKey &&
this.objectDir === that.objectDir &&
this.remoteName === that.remoteName &&
this.cwd === that.cwd
);
}
[Hash.symbol]() {
return Hash.string(`${this.objectDir}\0${this.remoteName}\0${this.cwd}`);
}
}
interface StatusRefreshLock {
readonly semaphore: Semaphore.Semaphore;
readonly users: number;
}
class StatusRemoteRefreshCacheKey extends Data.Class<{
gitCommonDir: string;
remoteName: string;
}> {}
interface ExecuteGitOptions {
stdin?: string | undefined;
@@ -952,26 +920,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
);
});
const fetchRemoteForStatus = (cwd: string, remoteName: string) =>
executeGit(
const fetchRemoteForStatus = (
gitCommonDir: string,
remoteName: string,
): Effect.Effect<void, GitCommandError> => {
const fetchCwd =
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
return executeGit(
"GitVcsDriver.fetchRemoteForStatus",
cwd,
[
"fetch",
"--quiet",
"--no-tags",
"--no-write-fetch-head",
"--no-auto-maintenance",
"--no-recurse-submodules",
"--",
remoteName,
],
fetchCwd,
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
{
allowNonZeroExit: true,
env: STATUS_UPSTREAM_REFRESH_ENV,
fallbackErrorDetail: "Background Git fetch failed.",
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
},
).pipe(Effect.asVoid);
};
const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) {
const gitCommonDir = yield* runGitStdout("GitVcsDriver.resolveGitCommonDir", cwd, [
@@ -981,76 +946,20 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
});
const resolveCanonicalGitObjectDir = Effect.fn("resolveCanonicalGitObjectDir")(function* (
cwd: string,
) {
const gitCommonDir = yield* resolveGitCommonDir(cwd);
const objectDir = path.join(gitCommonDir, "objects");
return yield* fileSystem.realPath(objectDir).pipe(Effect.orElseSucceed(() => objectDir));
});
const statusRefreshLocks = yield* Ref.make<ReadonlyMap<string, StatusRefreshLock>>(new Map());
const statusRefreshLocksGuard = yield* Semaphore.make(1);
const withStatusRefreshLock = <A, E, R>(objectDir: string, effect: Effect.Effect<A, E, R>) =>
Effect.acquireUseRelease(
statusRefreshLocksGuard.withPermits(1)(
Effect.gen(function* () {
const current = yield* Ref.get(statusRefreshLocks);
const existing = current.get(objectDir);
if (existing) {
yield* Ref.set(
statusRefreshLocks,
new Map(current).set(objectDir, {
semaphore: existing.semaphore,
users: existing.users + 1,
}),
);
return existing.semaphore;
}
const semaphore = yield* Semaphore.make(1);
yield* Ref.set(
statusRefreshLocks,
new Map(current).set(objectDir, { semaphore, users: 1 }),
);
return semaphore;
}),
),
(semaphore) => semaphore.withPermits(1)(effect),
(semaphore) =>
statusRefreshLocksGuard.withPermits(1)(
Ref.update(statusRefreshLocks, (current) => {
const existing = current.get(objectDir);
if (!existing || existing.semaphore !== semaphore) {
return current;
}
const next = new Map(current);
if (existing.users === 1) {
next.delete(objectDir);
} else {
next.set(objectDir, {
semaphore,
users: existing.users - 1,
});
}
return next;
}),
),
);
const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
cacheKey: StatusRemoteRefreshCacheKey,
) {
yield* fetchRemoteForStatus(cacheKey.cwd, cacheKey.remoteName);
yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
return true as const;
});
const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
timeToLive: statusUpstreamRefreshCacheTimeToLive,
timeToLive: (exit) =>
Exit.isSuccess(exit)
? STATUS_UPSTREAM_REFRESH_INTERVAL
: STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN,
});
const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* (
@@ -1058,26 +967,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
) {
const upstream = yield* resolveCurrentUpstream(cwd);
if (!upstream) return;
const objectDir = yield* resolveCanonicalGitObjectDir(cwd);
yield* withStatusRefreshLock(
objectDir,
Cache.get(
statusRemoteRefreshCache,
new StatusRemoteRefreshCacheKey(objectDir, upstream.remoteName, cwd),
),
const gitCommonDir = yield* resolveGitCommonDir(cwd);
yield* Cache.get(
statusRemoteRefreshCache,
new StatusRemoteRefreshCacheKey({
gitCommonDir,
remoteName: upstream.remoteName,
}),
);
});
const refreshStatusUpstream: GitVcsDriver.GitVcsDriver["Service"]["refreshStatusUpstream"] =
Effect.fn("refreshStatusUpstream")(function* (cwd) {
yield* refreshStatusUpstreamIfStale(cwd).pipe(
Effect.catchTags({
GitCommandError: (error) =>
isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),
}),
);
});
const resolveDefaultBranchName = (
cwd: string,
remoteName: string,
@@ -1575,14 +1474,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn(
"statusDetails",
)(function* (cwd) {
yield* refreshStatusUpstream(cwd).pipe(Effect.ignore);
yield* refreshStatusUpstreamIfStale(cwd).pipe(
Effect.catchTags({
GitCommandError: (error) =>
isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),
}),
Effect.ignoreCause({ log: true }),
);
return yield* readStatusDetailsLocal(cwd);
});
const statusDetailsRemote: GitVcsDriver.GitVcsDriver["Service"]["statusDetailsRemote"] =
Effect.fn("statusDetailsRemote")(function* (cwd, options) {
if (options?.refreshUpstream !== false) {
yield* refreshStatusUpstream(cwd).pipe(Effect.ignore);
yield* refreshStatusUpstreamIfStale(cwd).pipe(
Effect.catchTags({
GitCommandError: (error) =>
isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),
}),
Effect.ignoreCause({ log: true }),
);
}
return yield* readStatusDetailsRemote(cwd);
});
@@ -2624,7 +2535,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
statusDetails,
statusDetailsLocal,
statusDetailsRemote,
refreshStatusUpstream,
prepareCommitContext,
commit,
pushCurrentBranch,
@@ -1,6 +1,5 @@
import { assert, it, describe } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
@@ -22,7 +21,6 @@ import type {
} from "@t3tools/contracts";
import { GitManagerError } from "@t3tools/contracts";
import { statusUpstreamRefreshCacheTimeToLive } from "./GitVcsDriverCore.ts";
import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
@@ -71,7 +69,6 @@ function makeTestLayer(state: {
remoteStatusCalls: number;
localInvalidationCalls: number;
remoteInvalidationCalls: number;
remoteRefreshCalls?: number;
remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;
}) {
return VcsStatusBroadcaster.layer.pipe(
@@ -89,10 +86,6 @@ function makeTestLayer(state: {
state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
return state.currentRemoteStatus;
}),
refreshStatusUpstream: () =>
Effect.sync(() => {
state.remoteRefreshCalls = (state.remoteRefreshCalls ?? 0) + 1;
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
@@ -132,40 +125,6 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("evicts the least recently used status after reaching cache capacity", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
for (let index = 0; index < VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY; index += 1) {
yield* broadcaster.getStatus({ cwd: `/repo-${index}` });
}
assert.equal(state.localStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY);
assert.equal(state.remoteStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY);
yield* broadcaster.getStatus({ cwd: "/repo-0" });
yield* broadcaster.getStatus({ cwd: "/repo-overflow" });
yield* broadcaster.getStatus({ cwd: "/repo-0" });
assert.equal(state.localStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY + 1);
assert.equal(state.remoteStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY + 1);
yield* broadcaster.getStatus({ cwd: "/repo-1" });
assert.equal(state.localStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY + 2);
assert.equal(state.remoteStatusCalls, VcsStatusBroadcaster.VCS_STATUS_CACHE_CAPACITY + 2);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("refreshes the cached snapshot after explicit invalidation", () => {
const state = {
currentLocalStatus: baseLocalStatus,
@@ -586,96 +545,6 @@ describe("VcsStatusBroadcaster", () => {
);
});
it.effect("publishes stale remote status and backs off when upstream refresh fails", () => {
const state = {
refreshCalls: 0,
remoteStatusCalls: 0,
remoteInvalidationCalls: 0,
remoteStatusRefreshUpstreamValues: [] as Array<boolean | undefined>,
};
let firstRefreshDeferred: Deferred.Deferred<void> | null = null;
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () => Effect.succeed(baseLocalStatus),
refreshStatusUpstream: () =>
Effect.suspend(() => {
state.refreshCalls += 1;
if (state.refreshCalls !== 1) {
return Effect.void;
}
return Effect.fail(
new GitManagerError({
operation: "GitWorkflowService.refreshStatusUpstream",
cwd: "/repo",
detail: "background fetch failed",
}),
).pipe(
Effect.ensuring(
firstRefreshDeferred
? Deferred.succeed(firstRefreshDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
);
}),
remoteStatus: (_input, options) =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
state.remoteStatusRefreshUpstreamValues.push(options?.refreshUpstream);
return baseRemoteStatus;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
),
);
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const scope = yield* Scope.make();
firstRefreshDeferred = yield* Deferred.make<void>();
const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
yield* Stream.runForEach(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) },
),
(event) =>
event._tag === "remoteUpdated"
? Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(scope));
yield* Deferred.await(firstRefreshDeferred);
const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred);
yield* Effect.yieldNow;
assert.deepStrictEqual(remoteUpdated, {
_tag: "remoteUpdated",
remote: baseRemoteStatus,
} satisfies VcsStatusStreamEvent);
assert.equal(state.refreshCalls, 1);
assert.equal(state.remoteStatusCalls, 1);
assert.equal(state.remoteInvalidationCalls, 1);
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]);
yield* TestClock.adjust(Duration.seconds(29));
assert.equal(state.refreshCalls, 1);
yield* TestClock.adjust(Duration.seconds(1));
yield* Effect.yieldNow;
assert.equal(state.refreshCalls, 2);
assert.equal(state.remoteStatusCalls, 2);
assert.equal(state.remoteInvalidationCalls, 2);
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false, false]);
yield* Scope.close(scope, Exit.void);
}).pipe(Effect.provide(Layer.merge(testLayer, TestClock.layer())));
});
it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
const state = {
currentLocalStatus: baseLocalStatus,
@@ -762,168 +631,6 @@ describe("VcsStatusBroadcaster", () => {
});
});
it.effect("evicts the cached status after the last stream subscriber disconnects", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
return Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const remoteUpdated = yield* Deferred.make<VcsStatusStreamEvent>();
const scope = yield* Scope.make();
yield* Stream.runForEach(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) },
),
(event) =>
event._tag === "remoteUpdated"
? Deferred.succeed(remoteUpdated, event).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(scope));
yield* Deferred.await(remoteUpdated);
assert.equal(state.localStatusCalls, 1);
assert.equal(state.remoteStatusCalls, 1);
yield* Scope.close(scope, Exit.void);
yield* broadcaster.getStatus({ cwd: "/repo" });
assert.equal(state.localStatusCalls, 2);
assert.equal(state.remoteStatusCalls, 2);
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("restarts an interrupted refresh after a subscriber reconnects", () =>
Effect.gen(function* () {
const firstRefreshStarted = yield* Deferred.make<void>();
const secondRefreshStarted = yield* Deferred.make<void>();
const secondRemoteUpdated = yield* Deferred.make<void>();
let refreshLookups = 0;
const refreshCache = yield* Cache.makeWith(
() =>
Effect.gen(function* () {
refreshLookups += 1;
if (refreshLookups === 1) {
yield* Deferred.succeed(firstRefreshStarted, undefined);
return yield* Effect.never;
}
yield* Deferred.succeed(secondRefreshStarted, undefined);
}),
{
capacity: 1,
timeToLive: statusUpstreamRefreshCacheTimeToLive,
},
);
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () => Effect.succeed(baseLocalStatus),
refreshStatusUpstream: () => Cache.get(refreshCache, "repo"),
remoteStatus: () => Effect.succeed(baseRemoteStatus),
invalidateRemoteStatus: () => Effect.void,
} satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
),
);
yield* Effect.gen(function* () {
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const firstScope = yield* Scope.make();
yield* broadcaster
.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.hours(1)) },
)
.pipe(Stream.runDrain, Effect.forkIn(firstScope));
yield* Deferred.await(firstRefreshStarted).pipe(Effect.timeout("1 second"));
yield* Scope.close(firstScope, Exit.void);
const secondScope = yield* Scope.make();
yield* Stream.runForEach(
broadcaster.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.hours(1)) },
),
(event) =>
event._tag === "remoteUpdated"
? Deferred.succeed(secondRemoteUpdated, undefined).pipe(Effect.ignore)
: Effect.void,
).pipe(Effect.forkIn(secondScope));
yield* Deferred.await(secondRefreshStarted).pipe(Effect.timeout("1 second"));
yield* Deferred.await(secondRemoteUpdated).pipe(Effect.timeout("1 second"));
assert.equal(refreshLookups, 2);
yield* Scope.close(secondScope, Exit.void);
}).pipe(Effect.provide(testLayer), TestClock.withLive);
}),
);
it.effect("does not continue remote status work after an upstream refresh is interrupted", () => {
const state = {
remoteStatusCalls: 0,
remoteInvalidationCalls: 0,
};
let refreshStartedDeferred: Deferred.Deferred<void> | null = null;
let refreshInterruptedDeferred: Deferred.Deferred<void> | null = null;
const testLayer = VcsStatusBroadcaster.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(
Layer.mock(GitWorkflowService.GitWorkflowService)({
localStatus: () => Effect.succeed(baseLocalStatus),
refreshStatusUpstream: () =>
Effect.gen(function* () {
if (refreshStartedDeferred) {
yield* Deferred.succeed(refreshStartedDeferred, undefined);
}
return yield* Effect.never;
}).pipe(
Effect.onInterrupt(() =>
refreshInterruptedDeferred
? Deferred.succeed(refreshInterruptedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
return baseRemoteStatus;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
),
);
return Effect.gen(function* () {
refreshStartedDeferred = yield* Deferred.make<void>();
refreshInterruptedDeferred = yield* Deferred.make<void>();
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
const scope = yield* Scope.make();
yield* broadcaster
.streamStatus(
{ cwd: "/repo" },
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.hours(1)) },
)
.pipe(Stream.runDrain, Effect.forkIn(scope));
yield* Deferred.await(refreshStartedDeferred);
yield* Scope.close(scope, Exit.void);
yield* Deferred.await(refreshInterruptedDeferred);
assert.equal(state.remoteInvalidationCalls, 0);
assert.equal(state.remoteStatusCalls, 0);
}).pipe(Effect.provide(testLayer));
});
it.effect("stops the remote poller after the last stream subscriber disconnects", () => {
const state = {
currentLocalStatus: baseLocalStatus,
@@ -960,7 +667,6 @@ describe("VcsStatusBroadcaster", () => {
: Effect.void,
),
),
refreshStatusUpstream: () => Effect.void,
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
+30 -77
View File
@@ -29,7 +29,6 @@ const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15);
const MAX_FAILURE_DIAGNOSTIC_VALUES = 8;
const MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH = 128;
export const VCS_STATUS_CACHE_CAPACITY = 128;
function boundedDiagnosticValue(value: string): string {
return value.slice(0, MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH);
@@ -189,39 +188,13 @@ export const make = Effect.gen(function* () {
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
Scope.close(scope, Exit.void),
);
const statusCache = new Map<string, CachedVcsStatus>();
const activeRemotePollerCwds = new Set<string>();
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
const setCachedStatus = (cwd: string, status: CachedVcsStatus) => {
statusCache.delete(cwd);
statusCache.set(cwd, status);
while (statusCache.size > VCS_STATUS_CACHE_CAPACITY) {
let oldestCwd: string | undefined;
for (const cachedCwd of statusCache.keys()) {
if (!activeRemotePollerCwds.has(cachedCwd)) {
oldestCwd = cachedCwd;
break;
}
}
if (oldestCwd === undefined) {
break;
}
statusCache.delete(oldestCwd);
}
};
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
cwd: string,
) {
return yield* Effect.sync(() => {
const cached = statusCache.get(cwd) ?? null;
if (cached) {
setCachedStatus(cwd, cached);
}
return cached;
});
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
});
const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
@@ -230,13 +203,14 @@ export const make = Effect.gen(function* () {
fingerprint: fingerprintStatusPart(local),
value: local,
} satisfies CachedValue<VcsStatusLocalResult>;
const shouldPublish = yield* Effect.sync(() => {
const previous = statusCache.get(cwd) ?? { local: null, remote: null };
setCachedStatus(cwd, {
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
local: nextLocal,
});
return previous.local?.fingerprint !== nextLocal.fingerprint;
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
@@ -259,13 +233,14 @@ export const make = Effect.gen(function* () {
fingerprint: fingerprintStatusPart(remote),
value: remote,
} satisfies CachedValue<VcsStatusRemoteResult | null>;
const shouldPublish = yield* Effect.sync(() => {
const previous = statusCache.get(cwd) ?? { local: null, remote: null };
setCachedStatus(cwd, {
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
remote: nextRemote,
});
return previous.remote?.fingerprint !== nextRemote.fingerprint;
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
@@ -296,16 +271,18 @@ export const make = Effect.gen(function* () {
fingerprint: fingerprintStatusPart(remote),
value: remote,
} satisfies CachedValue<VcsStatusRemoteResult | null>;
const shouldPublish = yield* Effect.sync(() => {
const previous = statusCache.get(cwd) ?? { local: null, remote: null };
setCachedStatus(cwd, {
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
local: nextLocal,
remote: nextRemote,
});
return (
return [
previous.local?.fingerprint !== nextLocal.fingerprint ||
previous.remote?.fingerprint !== nextRemote.fingerprint
);
previous.remote?.fingerprint !== nextRemote.fingerprint,
nextCache,
] as const;
});
if (options?.publish && shouldPublish) {
@@ -378,22 +355,11 @@ export const make = Effect.gen(function* () {
cwd: string,
options?: { readonly refreshUpstream?: boolean },
) {
const refreshExit =
options?.refreshUpstream === false
? Exit.void
: yield* workflow.refreshStatusUpstream(cwd).pipe(Effect.exit);
if (Exit.isFailure(refreshExit) && Cause.hasInterrupts(refreshExit.cause)) {
return yield* Effect.failCause(refreshExit.cause);
}
if (options?.refreshUpstream !== false) {
yield* workflow.invalidateRemoteStatus(cwd);
}
const remote = yield* workflow.remoteStatus({ cwd }, { refreshUpstream: false });
const updated = yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
if (Exit.isFailure(refreshExit)) {
return yield* Effect.failCause(refreshExit.cause);
}
return updated;
const remote = yield* workflow.remoteStatus({ cwd }, options);
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
});
const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
@@ -496,7 +462,6 @@ export const make = Effect.gen(function* () {
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval, refreshImmediately).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
activeRemotePollerCwds.add(cwd);
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
fiber,
@@ -533,17 +498,6 @@ export const make = Effect.gen(function* () {
if (pollerToInterrupt) {
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
if (activePollers.has(cwd)) {
return Effect.succeed([undefined, activePollers] as const);
}
return Effect.sync(() => {
activeRemotePollerCwds.delete(cwd);
statusCache.delete(cwd);
return [undefined, activePollers] as const;
});
});
}
});
@@ -555,16 +509,15 @@ export const make = Effect.gen(function* () {
const initialLocal = yield* getOrLoadLocalStatus(cwd);
const cachedStatus = yield* getCachedStatus(cwd);
const initialRemote = cachedStatus?.remote?.value ?? null;
yield* Effect.acquireRelease(
retainRemotePoller(
cwd,
options?.automaticRemoteRefreshInterval ??
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
cachedStatus?.remote === null || cachedStatus?.remote === undefined,
),
() => releaseRemotePoller(cwd),
yield* retainRemotePoller(
cwd,
options?.automaticRemoteRefreshInterval ??
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
cachedStatus?.remote === null || cachedStatus?.remote === undefined,
);
const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
return Stream.concat(
Stream.make({
_tag: "snapshot" as const,
@@ -575,7 +528,7 @@ export const make = Effect.gen(function* () {
Stream.filter((event) => event.cwd === cwd),
Stream.map((event) => event.event),
),
);
).pipe(Stream.ensuring(release));
}),
);
+35 -3
View File
@@ -110,6 +110,7 @@ import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
import * as VcsProcess from "./vcs/VcsProcess.ts";
import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
import * as SessionStore from "./auth/SessionStore.ts";
import * as ConnectClientStore from "./auth/ConnectClientStore.ts";
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
import * as RelayClient from "@t3tools/shared/relayClient";
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
@@ -346,7 +347,10 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
]);
function toAuthAccessStreamEvent(
change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,
change:
| PairingGrantStore.BootstrapCredentialChange
| SessionStore.SessionCredentialChange
| ConnectClientStore.ConnectClientChange,
revision: number,
currentSessionId: AuthSessionId,
): AuthAccessStreamEvent {
@@ -382,6 +386,27 @@ function toAuthAccessStreamEvent(
type: "clientRemoved",
payload: { sessionId: change.sessionId },
};
case "connectSecurityModeUpdated":
return {
version: 1,
revision,
type: "connectSecurityModeUpdated",
payload: { mode: change.mode },
};
case "connectClientUpserted":
return {
version: 1,
revision,
type: "connectClientUpserted",
payload: change.client,
};
case "connectClientRemoved":
return {
version: 1,
revision,
type: "connectClientRemoved",
payload: { clientProofKeyThumbprint: change.clientProofKeyThumbprint },
};
}
}
@@ -512,6 +537,8 @@ const makeWsRpcLayer = (
const loadAuthAccessSnapshot = () =>
Effect.all({
connectSecurityMode: serverAuth.getConnectSecurityMode(),
connectClients: serverAuth.listConnectClients(),
pairingLinks: serverAuth.listPairingLinks(),
clientSessions: serverAuth.listClientSessions(currentSessionId),
}).pipe(
@@ -1761,8 +1788,13 @@ const makeWsRpcLayer = (
const initialSnapshot = yield* loadAuthAccessSnapshot();
const revisionRef = yield* Ref.make(1);
const accessChanges: Stream.Stream<
PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange
> = Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges);
| PairingGrantStore.BootstrapCredentialChange
| SessionStore.SessionCredentialChange
| ConnectClientStore.ConnectClientChange
> = Stream.merge(
Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges),
serverAuth.streamConnectClientChanges,
);
const liveEvents: Stream.Stream<AuthAccessStreamEvent> = accessChanges.pipe(
Stream.mapEffect((change) =>
@@ -205,6 +205,7 @@ describe("web cloud link environment client", () => {
relayUrl: "https://relay.example.test",
relayIssuer: "https://relay.example.test",
publishAgentActivity: false,
connectSecurityMode: "account",
}),
);
vi.stubGlobal("fetch", fetchMock);
@@ -218,6 +219,7 @@ describe("web cloud link environment client", () => {
relayUrl: "https://relay.example.test",
relayIssuer: "https://relay.example.test",
publishAgentActivity: false,
connectSecurityMode: "account",
}),
);
expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
@@ -235,6 +237,7 @@ describe("web cloud link environment client", () => {
relayUrl: "https://relay.example.test",
relayIssuer: "https://relay.example.test",
publishAgentActivity: false,
connectSecurityMode: "account",
}),
);
vi.stubGlobal("fetch", fetchMock);
@@ -262,6 +265,7 @@ describe("web cloud link environment client", () => {
relayUrl: "https://relay.example.test",
relayIssuer: "https://relay.example.test",
publishAgentActivity: true,
connectSecurityMode: "account",
}),
);
vi.stubGlobal("fetch", fetchMock);
+82 -5
View File
@@ -36,6 +36,7 @@ import {
createModelSelection,
resolvePromptInjectedEffort,
} from "@t3tools/shared/model";
import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { truncate } from "@t3tools/shared/String";
import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
@@ -3147,10 +3148,83 @@ function ChatViewContent(props: ChatViewProps) {
],
);
// Scroll helpers — LegendList handles auto-scroll via maintainScrollAtEnd.
// Scrolling is explicit so streamed timeline updates never take control away
// from the user after the newly sent row has been positioned once.
const scrollToEnd = useCallback((animated = false) => {
void legendListRef.current?.scrollToEnd?.({ animated });
}, []);
const positionedTimelineAnchorRef = useRef<MessageId | null>(null);
const settledTimelineAnchorRef = useRef<MessageId | null>(null);
const pendingAnchorScrollRestoreRef = useRef<{
readonly messageId: MessageId;
readonly offset: number;
} | null>(null);
const anchorScrollRestoreFrameRef = useRef<number | null>(null);
const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => {
if (positionedTimelineAnchorRef.current === messageId) {
return;
}
positionedTimelineAnchorRef.current = messageId;
settledTimelineAnchorRef.current = null;
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (positionedTimelineAnchorRef.current !== messageId) {
return;
}
const list = legendListRef.current;
if (!list) {
return;
}
const scrollNode = list.getScrollableNode();
let finished = false;
const finishAnimatedPositioning = () => {
if (finished) {
return;
}
finished = true;
window.clearTimeout(fallbackTimer);
scrollNode.removeEventListener("scrollend", finishAnimatedPositioning);
if (positionedTimelineAnchorRef.current !== messageId) {
return;
}
const scrollOffset = list.getState().scroll;
void list.scrollToOffset({ offset: scrollOffset, animated: false });
settledTimelineAnchorRef.current = messageId;
};
const fallbackTimer = window.setTimeout(finishAnimatedPositioning, 750);
scrollNode.addEventListener("scrollend", finishAnimatedPositioning, { once: true });
void list.scrollToIndex({
index: anchorIndex,
animated: true,
viewPosition: 0,
viewOffset: CHAT_LIST_ANCHOR_OFFSET,
});
});
});
}, []);
const onTimelineAnchorSizeChanged = useCallback((messageId: MessageId) => {
if (settledTimelineAnchorRef.current !== messageId) {
return;
}
const scrollOffset = legendListRef.current?.getState().scroll;
if (scrollOffset === undefined) {
return;
}
if (pendingAnchorScrollRestoreRef.current === null) {
pendingAnchorScrollRestoreRef.current = { messageId, offset: scrollOffset };
}
if (anchorScrollRestoreFrameRef.current !== null) {
return;
}
anchorScrollRestoreFrameRef.current = requestAnimationFrame(() => {
anchorScrollRestoreFrameRef.current = null;
const pending = pendingAnchorScrollRestoreRef.current;
pendingAnchorScrollRestoreRef.current = null;
if (pending && settledTimelineAnchorRef.current === pending.messageId) {
void legendListRef.current?.scrollToOffset({ offset: pending.offset, animated: false });
}
});
}, []);
// Debounce *showing* the scroll-to-bottom pill so it doesn't flash during
// thread switches. LegendList fires scroll events with isAtEnd=false while
@@ -3751,8 +3825,6 @@ function ChatViewContent(props: ChatViewProps) {
streaming: false,
},
]);
void legendListRef.current?.scrollToEnd?.({ animated: false });
setThreadError(threadIdForSend, null);
if (expiredTerminalContextCount > 0) {
const toastCopy = buildExpiredTerminalContextToastCopy(
@@ -4165,11 +4237,14 @@ function ChatViewContent(props: ChatViewProps) {
beginLocalDispatch({ preparingWorktree: false });
setThreadError(threadIdForSend, null);
// Scroll to the current end *before* adding the optimistic message.
// Position this sent row once LegendList has measured the anchored tail.
isAtEndRef.current = true;
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
await legendListRef.current?.scrollToEnd?.({ animated: false });
setTimelineAnchor({
threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
messageId: messageIdForSend,
});
setOptimisticUserMessages((existing) => [
...existing,
@@ -4789,6 +4864,8 @@ function ChatViewContent(props: ChatViewProps) {
workspaceRoot={activeWorkspaceRoot}
skills={activeProviderStatus?.skills ?? EMPTY_PROVIDER_SKILLS}
anchorMessageId={timelineAnchorMessageId}
onAnchorReady={onTimelineAnchorReady}
onAnchorSizeChanged={onTimelineAnchorSizeChanged}
contentInsetEndAdjustment={composerOverlayHeight}
onIsAtEndChange={onIsAtEndChange}
/>
@@ -940,6 +940,77 @@ describe("deriveMessagesTimelineRows", () => {
expect(assistantRow?.showAssistantMeta).toBe(false);
expect(assistantRow?.showAssistantCopyButton).toBe(false);
});
it("models work log overflow expansion as inserted list rows", () => {
const timelineEntries = [
{
id: "work-entry-1",
kind: "work" as const,
createdAt: "2026-01-01T00:00:01Z",
entry: {
id: "work-1",
createdAt: "2026-01-01T00:00:01Z",
label: "read",
detail: "Reading package.json",
tone: "tool" as const,
},
},
{
id: "work-entry-2",
kind: "work" as const,
createdAt: "2026-01-01T00:00:02Z",
entry: {
id: "work-2",
createdAt: "2026-01-01T00:00:02Z",
label: "edit",
detail: "Editing MessagesTimeline.tsx",
tone: "tool" as const,
},
},
{
id: "work-entry-3",
kind: "work" as const,
createdAt: "2026-01-01T00:00:03Z",
entry: {
id: "work-3",
createdAt: "2026-01-01T00:00:03Z",
label: "test",
detail: "Running tests",
tone: "tool" as const,
},
},
];
const baseInput = {
timelineEntries,
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
};
const collapsedRows = deriveMessagesTimelineRows(baseInput);
const expandedRows = deriveMessagesTimelineRows({
...baseInput,
expandedWorkGroupIds: new Set(["work-group:work-entry-1"]),
});
expect(collapsedRows.map((row) => row.id)).toEqual(["work-3", "work-toggle:work-entry-1"]);
expect(collapsedRows.find((row) => row.kind === "work-toggle")).toMatchObject({
groupId: "work-group:work-entry-1",
hiddenCount: 2,
expanded: false,
onlyToolEntries: true,
});
expect(expandedRows.map((row) => row.id)).toEqual([
"work-1",
"work-2",
"work-3",
"work-toggle:work-entry-1",
]);
expect(expandedRows.find((row) => row.kind === "work-toggle")).toMatchObject({
expanded: true,
});
});
});
describe("computeStableMessagesTimelineRows", () => {
@@ -1,5 +1,11 @@
import * as Equal from "effect/Equal";
import { formatDuration, type TimelineEntry, type WorkLogEntry } from "../../session-logic";
import {
formatDuration,
workEntryIndicatesToolNeutralStatus,
workLogEntryIsToolLike,
type TimelineEntry,
type WorkLogEntry,
} from "../../session-logic";
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
@@ -42,6 +48,15 @@ export type MessagesTimelineRow =
createdAt: string;
groupedEntries: WorkLogEntry[];
}
| {
kind: "work-toggle";
id: string;
createdAt: string;
groupId: string;
hiddenCount: number;
expanded: boolean;
onlyToolEntries: boolean;
}
| {
kind: "turn-fold";
id: string;
@@ -300,6 +315,7 @@ export function deriveMessagesTimelineRows(input: {
latestTurn?: TimelineLatestTurn | null;
runningTurnId?: TurnId | null;
expandedTurnIds?: ReadonlySet<TurnId>;
expandedWorkGroupIds?: ReadonlySet<string>;
isWorking: boolean;
activeTurnStartedAt: string | null;
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
@@ -367,12 +383,44 @@ export function deriveMessagesTimelineRows(input: {
groupedEntries.push(nextEntry.entry);
cursor += 1;
}
nextRows.push({
kind: "work",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
groupedEntries,
});
const visibleGroupedEntries = groupedEntries.filter(
(entry) => !workEntryIndicatesToolNeutralStatus(entry),
);
if (visibleGroupedEntries.length > 0) {
if (visibleGroupedEntries.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
nextRows.push({
kind: "work",
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
groupedEntries: visibleGroupedEntries,
});
} else {
const groupId = `work-group:${timelineEntry.id}`;
const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
const hiddenEntries = visibleGroupedEntries.slice(0, -MAX_VISIBLE_WORK_LOG_ENTRIES);
const visibleEntries = visibleGroupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
const renderedEntries = expanded ? [...hiddenEntries, ...visibleEntries] : visibleEntries;
for (const workEntry of renderedEntries) {
nextRows.push({
kind: "work",
id: workEntry.id,
createdAt: workEntry.createdAt,
groupedEntries: [workEntry],
});
}
nextRows.push({
kind: "work-toggle",
id: `work-toggle:${timelineEntry.id}`,
createdAt: timelineEntry.createdAt,
groupId,
hiddenCount: hiddenEntries.length,
expanded,
onlyToolEntries: visibleGroupedEntries.every((entry) => workLogEntryIsToolLike(entry)),
});
}
}
index = cursor - 1;
continue;
}
@@ -473,6 +521,17 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
case "work":
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
case "work-toggle": {
const bw = b as typeof a;
return (
a.createdAt === bw.createdAt &&
a.groupId === bw.groupId &&
a.hiddenCount === bw.hiddenCount &&
a.expanded === bw.expanded &&
a.onlyToolEntries === bw.onlyToolEntries
);
}
case "message": {
const bm = b as typeof a;
return (
@@ -17,24 +17,59 @@ vi.mock("@legendapp/list/react", async () => {
anchorIndex: number;
anchorMaxSize?: number;
anchorOffset?: number;
onReady?: (info: { anchorIndex: number }) => void;
onSizeChanged?: (size: number) => void;
};
contentInsetEndAdjustment?: number;
className?: string;
maintainScrollAtEnd?: boolean;
maintainVisibleContentPosition?:
| boolean
| {
data?: boolean;
size?: boolean;
shouldRestorePosition?: (item: { id: string }) => boolean;
};
ref?: Ref<LegendListRef>;
}) => (
<div
data-testid={legendListTestId}
data-anchor-index={props.anchoredEndSpace?.anchorIndex}
data-anchor-max-size={props.anchoredEndSpace?.anchorMaxSize}
data-anchor-offset={props.anchoredEndSpace?.anchorOffset}
data-content-inset-end={props.contentInsetEndAdjustment}
>
{props.ListHeaderComponent}
{props.data.map((item) => (
<div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
))}
{props.ListFooterComponent}
</div>
);
}) => {
if (props.anchoredEndSpace) {
props.anchoredEndSpace.onSizeChanged?.(240);
props.anchoredEndSpace.onReady?.({ anchorIndex: props.anchoredEndSpace.anchorIndex });
}
return (
<div
data-testid={legendListTestId}
data-anchor-index={props.anchoredEndSpace?.anchorIndex}
data-anchor-max-size={props.anchoredEndSpace?.anchorMaxSize}
data-anchor-offset={props.anchoredEndSpace?.anchorOffset}
data-anchor-on-ready={Boolean(props.anchoredEndSpace?.onReady)}
data-content-inset-end={props.contentInsetEndAdjustment}
data-class-name={props.className}
data-maintain-scroll-at-end={props.maintainScrollAtEnd}
data-maintain-visible-content-position={
typeof props.maintainVisibleContentPosition === "object"
? "object"
: props.maintainVisibleContentPosition
}
data-maintain-visible-content-position-data={
typeof props.maintainVisibleContentPosition === "object"
? props.maintainVisibleContentPosition.data
: undefined
}
data-maintain-visible-content-position-size={
typeof props.maintainVisibleContentPosition === "object"
? props.maintainVisibleContentPosition.size
: undefined
}
>
{props.ListHeaderComponent}
{props.data.map((item) => (
<div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
))}
{props.ListFooterComponent}
</div>
);
};
return { LegendList };
});
@@ -123,6 +158,8 @@ function buildProps() {
timestampFormat: "locale" as const,
workspaceRoot: undefined,
anchorMessageId: null,
onAnchorReady: () => {},
onAnchorSizeChanged: () => {},
contentInsetEndAdjustment: 0,
onIsAtEndChange: () => {},
};
@@ -154,6 +191,8 @@ function buildUserTimelineEntry(text: string) {
describe("MessagesTimeline", () => {
it("anchors a sent attachment message using its measured height", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const onAnchorReady = vi.fn();
const onAnchorSizeChanged = vi.fn();
const firstEntry = buildUserTimelineEntry("First prompt.");
const secondEntry = {
...buildUserTimelineEntry("Newest prompt."),
@@ -177,6 +216,8 @@ describe("MessagesTimeline", () => {
<MessagesTimeline
{...buildProps()}
anchorMessageId={secondEntry.message.id}
onAnchorReady={onAnchorReady}
onAnchorSizeChanged={onAnchorSizeChanged}
contentInsetEndAdjustment={144}
timelineEntries={[firstEntry, secondEntry]}
/>,
@@ -184,8 +225,17 @@ describe("MessagesTimeline", () => {
expect(markup).toContain('data-anchor-index="1"');
expect(markup).toContain('data-anchor-offset="16"');
expect(markup).toContain('data-anchor-on-ready="true"');
expect(markup).not.toContain("data-anchor-max-size=");
expect(markup).toContain('data-content-inset-end="144"');
expect(markup).toContain("[overflow-anchor:none]");
expect(markup).not.toContain("data-maintain-scroll-at-end=");
expect(markup).toContain('data-maintain-visible-content-position="object"');
expect(markup).toContain('data-maintain-visible-content-position-data="true"');
expect(markup).toContain('data-maintain-visible-content-position-size="false"');
expect(onAnchorReady).toHaveBeenCalledOnce();
expect(onAnchorReady).toHaveBeenCalledWith(secondEntry.message.id, 1);
expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);
});
it("renders collapse controls for long user messages", async () => {
+115 -116
View File
@@ -14,13 +14,13 @@ import {
use,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type KeyboardEvent,
type ReactNode,
} from "react";
import { flushSync } from "react-dom";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { FileDiff } from "@pierre/diffs/react";
import {
@@ -43,7 +43,6 @@ import {
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
ChevronUpIcon,
CircleAlertIcon,
EyeIcon,
GlobeIcon,
@@ -67,7 +66,6 @@ import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
import { MessageCopyButton } from "./MessageCopyButton";
import {
computeStableMessagesTimelineRows,
MAX_VISIBLE_WORK_LOG_ENTRIES,
deriveMessagesTimelineRows,
normalizeCompactToolLabel,
resolveAssistantMessageCopyState,
@@ -128,6 +126,7 @@ interface TimelineRowSharedState {
onImageExpand: (preview: ExpandedImagePreview) => void;
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
onToggleTurnFold: (turnId: TurnId) => void;
onToggleWorkGroup: (groupId: string, anchorElement?: HTMLElement) => void;
}
interface TimelineRowActivityState {
@@ -168,6 +167,8 @@ interface MessagesTimelineProps {
workspaceRoot: string | undefined;
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
anchorMessageId: MessageId | null;
onAnchorReady: (messageId: MessageId, anchorIndex: number) => void;
onAnchorSizeChanged: (messageId: MessageId, size: number) => void;
contentInsetEndAdjustment: number;
onIsAtEndChange: (isAtEnd: boolean) => void;
}
@@ -198,20 +199,15 @@ export const MessagesTimeline = memo(function MessagesTimeline({
workspaceRoot,
skills = EMPTY_TIMELINE_SKILLS,
anchorMessageId,
onAnchorReady,
onAnchorSizeChanged,
contentInsetEndAdjustment,
onIsAtEndChange,
}: MessagesTimelineProps) {
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
// Toggling a fold inserts/removes rows between the fold row and the final
// message — everything above the trigger is unchanged, so the trigger stays
// put as long as the list doesn't re-anchor. maintainScrollAtEnd would do
// exactly that (pin the bottom content when row data changes while scrolled
// to the end), yanking the trigger out of view. Suppress it for the frames
// in which the toggle's data change and item measurements settle.
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
const onToggleTurnFold = useCallback((turnId: TurnId) => {
setFoldToggleSettling(true);
setExpandedTurnIds((existing) => {
const next = new Set(existing);
if (next.has(turnId)) {
@@ -222,23 +218,39 @@ export const MessagesTimeline = memo(function MessagesTimeline({
return next;
});
}, []);
useEffect(() => {
if (!foldToggleSettling) {
return;
}
let secondFrameId: number | null = null;
const firstFrameId = window.requestAnimationFrame(() => {
secondFrameId = window.requestAnimationFrame(() => {
setFoldToggleSettling(false);
const onToggleWorkGroup = useCallback(
(groupId: string, anchorElement?: HTMLElement) => {
const anchorBottomBeforeToggle = anchorElement?.getBoundingClientRect().bottom ?? null;
flushSync(() => {
setExpandedWorkGroupIds((existing) => {
const next = new Set(existing);
if (next.has(groupId)) {
next.delete(groupId);
} else {
next.add(groupId);
}
return next;
});
});
});
return () => {
window.cancelAnimationFrame(firstFrameId);
if (secondFrameId !== null) {
window.cancelAnimationFrame(secondFrameId);
if (anchorBottomBeforeToggle === null || !anchorElement) {
return;
}
};
}, [foldToggleSettling]);
const delta = anchorElement.getBoundingClientRect().bottom - anchorBottomBeforeToggle;
if (Math.abs(delta) < 0.5) {
return;
}
const list = listRef.current;
const currentScroll = list?.getState?.().scroll;
if (list && typeof currentScroll === "number") {
list.scrollToOffset({ offset: currentScroll + delta, animated: false });
}
},
[listRef],
);
// An in-session interrupt leaves its turn expanded so the user keeps their
// place; the next turn (or a reload, since this is local state) folds it.
@@ -276,6 +288,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
latestTurn,
runningTurnId,
expandedTurnIds,
expandedWorkGroupIds,
isWorking,
activeTurnStartedAt,
turnDiffSummaryByAssistantMessageId,
@@ -286,6 +299,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
latestTurn,
runningTurnId,
expandedTurnIds,
expandedWorkGroupIds,
isWorking,
activeTurnStartedAt,
turnDiffSummaryByAssistantMessageId,
@@ -293,13 +307,30 @@ export const MessagesTimeline = memo(function MessagesTimeline({
],
);
const rows = useStableRows(rawRows);
const anchoredEndSpace = useMemo(
() =>
resolveChatListAnchoredEndSpace(rows, anchorMessageId, (row) =>
row.kind === "message" ? row.message.id : null,
),
[anchorMessageId, rows],
const handleAnchorReady = useCallback(
(info: { anchorIndex: number | undefined }) => {
if (anchorMessageId !== null && info.anchorIndex !== undefined) {
onAnchorReady(anchorMessageId, info.anchorIndex);
}
},
[anchorMessageId, onAnchorReady],
);
const handleAnchorSizeChanged = useCallback(
(size: number) => {
if (anchorMessageId !== null) {
onAnchorSizeChanged(anchorMessageId, size);
}
},
[anchorMessageId, onAnchorSizeChanged],
);
const anchoredEndSpace = useMemo(() => {
const config = resolveChatListAnchoredEndSpace(rows, anchorMessageId, (row) =>
row.kind === "message" ? row.message.id : null,
);
return config
? { ...config, onReady: handleAnchorReady, onSizeChanged: handleAnchorSizeChanged }
: undefined;
}, [anchorMessageId, handleAnchorReady, handleAnchorSizeChanged, rows]);
const handleScroll = useCallback(() => {
const state = listRef.current?.getState?.();
@@ -322,6 +353,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onImageExpand,
onOpenTurnDiff,
onToggleTurnFold,
onToggleWorkGroup,
}),
[
timestampFormat,
@@ -335,6 +367,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onImageExpand,
onOpenTurnDiff,
onToggleTurnFold,
onToggleWorkGroup,
],
);
const activityState = useMemo<TimelineRowActivityState>(
@@ -380,11 +413,12 @@ export const MessagesTimeline = memo(function MessagesTimeline({
initialScrollAtEnd
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={contentInsetEndAdjustment}
maintainScrollAtEnd={!foldToggleSettling}
maintainScrollAtEndThreshold={0.1}
maintainVisibleContentPosition
maintainVisibleContentPosition={{
data: true,
size: false,
}}
onScroll={handleScroll}
className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 sm:px-5"
className="scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5"
ListHeaderComponent={TIMELINE_LIST_HEADER}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
@@ -417,7 +451,8 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
// Commentary (non-terminal assistant) rows carry no metadata row, so
// they sit closer to the work that follows them.
(row.kind === "message" && row.message.role === "assistant" && !row.showAssistantMeta) ||
row.kind === "work"
row.kind === "work" ||
row.kind === "work-toggle"
? "pb-2"
: "pb-4",
row.kind === "message" && row.message.role === "assistant" ? "group/assistant" : null,
@@ -428,6 +463,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
data-message-role={row.kind === "message" ? row.message.role : undefined}
>
{row.kind === "work" ? <WorkGroupSection groupedEntries={row.groupedEntries} /> : null}
{row.kind === "work-toggle" ? <WorkGroupToggleTimelineRow row={row} /> : null}
{row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
{row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
{row.kind === "message" && row.message.role === "assistant" ? (
@@ -720,26 +756,17 @@ function WorkingTimer({ createdAt }: { createdAt: string }) {
// re-render only the affected row, not the entire list.
// ---------------------------------------------------------------------------
/** Collapsed state shows the earliest chunk so "Show more" only appends rows downward. */
/** Renders one or more already-derived work log rows. Overflow expansion is modeled as LegendList data. */
const WorkGroupSection = memo(function WorkGroupSection({
groupedEntries,
}: {
groupedEntries: Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"];
}) {
const { workspaceRoot } = use(TimelineRowCtx);
const [isExpanded, setIsExpanded] = useState(false);
const sectionRef = useRef<HTMLElement>(null);
const anchorBottomBeforeToggleRef = useRef<number | null>(null);
const nonEmptyEntries = useMemo(
() => groupedEntries.filter((entry) => !workEntryIndicatesToolNeutralStatus(entry)),
[groupedEntries],
);
const hasOverflow = nonEmptyEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleEntries =
hasOverflow && !isExpanded
? nonEmptyEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
: nonEmptyEntries;
const hiddenCount = nonEmptyEntries.length - visibleEntries.length;
const onlyToolEntries = nonEmptyEntries.every((entry) => workLogEntryIsToolLike(entry));
const groupLabel = onlyToolEntries
? nonEmptyEntries.length === 1
@@ -747,49 +774,17 @@ const WorkGroupSection = memo(function WorkGroupSection({
: `${nonEmptyEntries.length} tool calls`
: "Work Log";
useLayoutEffect(() => {
const anchorBottomBeforeToggle = anchorBottomBeforeToggleRef.current;
anchorBottomBeforeToggleRef.current = null;
if (anchorBottomBeforeToggle === null) {
return;
}
const section = sectionRef.current;
if (!section) {
return;
}
const delta = section.getBoundingClientRect().bottom - anchorBottomBeforeToggle;
if (Math.abs(delta) < 0.5) {
return;
}
const scroller = findNearestVerticalScroller(section);
if (scroller) {
scroller.scrollTop += delta;
} else {
window.scrollBy(0, delta);
}
}, [isExpanded]);
const toggleExpanded = () => {
anchorBottomBeforeToggleRef.current =
sectionRef.current?.getBoundingClientRect().bottom ?? null;
setIsExpanded((v) => !v);
};
if (nonEmptyEntries.length === 0) return null;
return (
<section ref={sectionRef} className="-mx-1 space-y-0.5 px-1 py-0.5" aria-label={groupLabel}>
<section className="-mx-1 space-y-0.5 px-1 py-0.5" aria-label={groupLabel}>
{!onlyToolEntries && (
<p className="px-0.5 pb-0.5 font-medium text-[11px] text-muted-foreground/65">
{groupLabel}
</p>
)}
<div className="space-y-px">
{visibleEntries.map((workEntry) => (
{nonEmptyEntries.map((workEntry) => (
<SimpleWorkEntryRow
key={workEntry.id}
workEntry={workEntry}
@@ -797,45 +792,49 @@ const WorkGroupSection = memo(function WorkGroupSection({
/>
))}
</div>
{hasOverflow && (
<button
type="button"
className="flex w-full cursor-pointer items-center gap-1.5 rounded-md px-0.5 py-0.5 text-left text-[12px] leading-5 transition-colors duration-150 hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
onClick={toggleExpanded}
>
<span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground/65">
{isExpanded ? (
<ChevronUpIcon className="size-3.5 shrink-0 opacity-70" />
) : (
<ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
)}
</span>
{isExpanded ? (
<span className="font-medium text-foreground/82">Show fewer tool calls</span>
) : (
<span className="font-medium text-foreground/82">
+{hiddenCount} previous tool {hiddenCount === 1 ? "call" : "calls"}
</span>
)}
</button>
)}
</section>
);
});
function findNearestVerticalScroller(element: HTMLElement): HTMLElement | null {
let parent = element.parentElement;
while (parent) {
const { overflowY } = window.getComputedStyle(parent);
if (
(overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay") &&
parent.scrollHeight > parent.clientHeight
) {
return parent;
}
parent = parent.parentElement;
}
return null;
function WorkGroupToggleTimelineRow({
row,
}: {
row: Extract<TimelineRow, { kind: "work-toggle" }>;
}) {
const ctx = use(TimelineRowCtx);
const labelNoun = row.onlyToolEntries ? "tool call" : "log entry";
return (
<button
type="button"
className="flex w-full cursor-pointer items-center gap-1.5 rounded-md px-0.5 py-0.5 text-left text-[12px] leading-5 transition-colors duration-150 hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
aria-expanded={row.expanded}
onClick={(event) => {
const anchorElement =
event.currentTarget.closest<HTMLElement>("[data-timeline-row-id]") ?? event.currentTarget;
ctx.onToggleWorkGroup(row.groupId, anchorElement);
}}
>
<span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground/65">
<ChevronDownIcon
className={cn(
"size-3.5 shrink-0 opacity-70 transition-transform duration-200",
row.expanded && "rotate-180",
)}
/>
</span>
{row.expanded ? (
<span className="font-medium text-foreground/82">
Show fewer {row.onlyToolEntries ? "tool calls" : "log entries"}
</span>
) : (
<span className="font-medium text-foreground/82">
+{row.hiddenCount} previous {labelNoun}
{row.hiddenCount === 1 ? "" : "s"}
</span>
)}
</button>
);
}
/** Subscribes directly to the UI state store for expand/collapse state,
@@ -20,6 +20,8 @@ import {
AuthReviewWriteScope,
AuthStandardClientScopes,
AuthTerminalOperateScope,
type AuthConnectClient,
type AuthConnectSecurityMode,
type AuthClientSession,
type AuthEnvironmentScope,
type AuthPairingLink,
@@ -102,13 +104,19 @@ import { Textarea } from "../ui/textarea";
import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "../../pairingUrl";
import { readHostedPairingRequest } from "../../hostedPairing";
import {
approveServerConnectClient,
createServerPairingCredential,
rejectServerConnectClient,
revokeServerConnectClient,
revokeOtherServerClientSessions,
revokeServerClientSession,
revokeServerPairingLink,
isLoopbackHostname,
toServerConnectClientRecord,
updateServerConnectSecurityMode,
usePrimarySessionState,
type ServerClientSessionRecord,
type ServerConnectClientRecord,
type ServerPairingLinkRecord,
} from "~/environments/primary";
import { useUiStateStore } from "~/uiStateStore";
@@ -476,6 +484,21 @@ function toDesktopPairingLinkRecord(pairingLink: AuthPairingLink): ServerPairing
};
}
function sortDesktopConnectClients(
clients: ReadonlyArray<ServerConnectClientRecord>,
): ReadonlyArray<ServerConnectClientRecord> {
const statusRank: Record<ServerConnectClientRecord["status"], number> = {
pending: 0,
approved: 1,
rejected: 2,
};
return [...clients].sort((left, right) => {
const rankDelta = statusRank[left.status] - statusRank[right.status];
if (rankDelta !== 0) return rankDelta;
return new Date(right.updatedAt).getTime() - new Date(left.updatedAt).getTime();
});
}
function toDesktopClientSessionRecord(clientSession: AuthClientSession): ServerClientSessionRecord {
return {
...clientSession,
@@ -1029,6 +1052,125 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({
);
});
type ConnectClientListRowProps = {
connectClient: ServerConnectClientRecord;
presentation?: AccessSectionPresentation;
pendingActionKey: string | null;
onApprove: (clientProofKeyThumbprint: string) => void;
onReject: (clientProofKeyThumbprint: string) => void;
onRevoke: (clientProofKeyThumbprint: string) => void;
};
const ConnectClientListRow = memo(function ConnectClientListRow({
connectClient,
presentation = "current",
pendingActionKey,
onApprove,
onReject,
onRevoke,
}: ConnectClientListRowProps) {
const nowMs = useRelativeTimeTick(1_000);
const ago = (isoDate: string) => {
const elapsed = formatElapsedDurationLabel(isoDate, nowMs);
return elapsed === "just now" ? elapsed : `${elapsed} ago`;
};
const pendingApproveKey = `approve:${connectClient.clientProofKeyThumbprint}`;
const pendingRejectKey = `reject:${connectClient.clientProofKeyThumbprint}`;
const pendingRevokeKey = `revoke:${connectClient.clientProofKeyThumbprint}`;
const statusConfig =
connectClient.status === "approved"
? {
label: connectClient.lastSeenAt
? `Last connected ${ago(connectClient.lastSeenAt)}`
: connectClient.approvedAt
? `Approved ${ago(connectClient.approvedAt)}`
: "Approved",
dotClassName: "bg-success",
}
: connectClient.status === "pending"
? {
label: `Requested ${ago(connectClient.requestedAt)}`,
dotClassName: "bg-warning",
}
: {
label: connectClient.rejectedAt
? `Rejected ${ago(connectClient.rejectedAt)}`
: "Rejected",
dotClassName: "bg-destructive",
};
const deviceInfoBits = [
connectClient.client.deviceType !== "unknown"
? connectClient.client.deviceType[0]?.toUpperCase() + connectClient.client.deviceType.slice(1)
: null,
connectClient.client.os ?? null,
connectClient.deviceId ? `Device ${connectClient.deviceId}` : null,
].filter((value): value is string => value !== null);
const primaryLabel =
connectClient.client.label ??
connectClient.client.os ??
`Client ${connectClient.clientProofKeyThumbprint.slice(0, 8)}`;
return (
<div className={accessRowClassName(presentation)}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0 flex-1 space-y-1">
<div className="flex min-h-5 items-center gap-1.5">
<ConnectionStatusDot
tooltipText={formatAccessTimestamp(connectClient.updatedAt)}
dotClassName={statusConfig.dotClassName}
/>
<h3 className="text-sm font-medium text-foreground">{primaryLabel}</h3>
<span className="rounded-md border border-border/50 bg-muted/50 px-1 py-0.5 text-[10px] text-muted-foreground">
T3 Connect
</span>
</div>
<p className="text-xs text-muted-foreground">
{deviceInfoBits.length > 0 ? (
<>
{deviceInfoBits.join(" · ")}
<span aria-hidden> · </span>
</>
) : null}
{statusConfig.label}
</p>
</div>
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
{connectClient.status !== "approved" ? (
<Button
size="xs"
variant="outline"
disabled={pendingActionKey === pendingApproveKey}
onClick={() => void onApprove(connectClient.clientProofKeyThumbprint)}
>
{pendingActionKey === pendingApproveKey ? "Approving…" : "Approve"}
</Button>
) : null}
{connectClient.status === "pending" ? (
<Button
size="xs"
variant="outline"
disabled={pendingActionKey === pendingRejectKey}
onClick={() => void onReject(connectClient.clientProofKeyThumbprint)}
>
{pendingActionKey === pendingRejectKey ? "Rejecting…" : "Reject"}
</Button>
) : null}
{connectClient.status !== "pending" ? (
<Button
size="xs"
variant="destructive-outline"
disabled={pendingActionKey === pendingRevokeKey}
onClick={() => void onRevoke(connectClient.clientProofKeyThumbprint)}
>
{pendingActionKey === pendingRevokeKey ? "Revoking…" : "Revoke"}
</Button>
) : null}
</div>
</div>
</div>
);
});
type AuthorizedClientsHeaderActionProps = {
clientSessions: ReadonlyArray<ServerClientSessionRecord>;
isRevokingOtherClients: boolean;
@@ -1209,10 +1351,15 @@ type PairingClientsListProps = {
defaultEndpointKey: string | null;
presentation?: AccessSectionPresentation;
isLoading: boolean;
connectClients: ReadonlyArray<ServerConnectClientRecord>;
pairingLinks: ReadonlyArray<ServerPairingLinkRecord>;
clientSessions: ReadonlyArray<ServerClientSessionRecord>;
pendingConnectClientActionKey: string | null;
revokingPairingLinkId: string | null;
revokingClientSessionId: string | null;
onApproveConnectClient: (clientProofKeyThumbprint: string) => void;
onRejectConnectClient: (clientProofKeyThumbprint: string) => void;
onRevokeConnectClient: (clientProofKeyThumbprint: string) => void;
onRevokePairingLink: (id: string) => void;
onRevokeClientSession: (sessionId: ServerClientSessionRecord["sessionId"]) => void;
};
@@ -1223,15 +1370,32 @@ const PairingClientsList = memo(function PairingClientsList({
defaultEndpointKey,
presentation = "current",
isLoading,
connectClients,
pairingLinks,
clientSessions,
pendingConnectClientActionKey,
revokingPairingLinkId,
revokingClientSessionId,
onApproveConnectClient,
onRejectConnectClient,
onRevokeConnectClient,
onRevokePairingLink,
onRevokeClientSession,
}: PairingClientsListProps) {
return (
<>
{connectClients.map((connectClient) => (
<ConnectClientListRow
key={connectClient.clientProofKeyThumbprint}
connectClient={connectClient}
presentation={presentation}
pendingActionKey={pendingConnectClientActionKey}
onApprove={onApproveConnectClient}
onReject={onRejectConnectClient}
onRevoke={onRevokeConnectClient}
/>
))}
{pairingLinks.map((pairingLink) => (
<PairingLinkListRow
key={pairingLink.id}
@@ -1255,7 +1419,10 @@ const PairingClientsList = memo(function PairingClientsList({
/>
))}
{pairingLinks.length === 0 && clientSessions.length === 0 && !isLoading ? (
{connectClients.length === 0 &&
pairingLinks.length === 0 &&
clientSessions.length === 0 &&
!isLoading ? (
<div className={accessRowClassName(presentation)}>
<p className="text-xs text-muted-foreground/60">No pairing links or client sessions.</p>
</div>
@@ -2052,6 +2219,10 @@ export function ConnectionsSettings() {
string | null
>(null);
const [isRevokingOtherDesktopClients, setIsRevokingOtherDesktopClients] = useState(false);
const [isUpdatingConnectSecurityMode, setIsUpdatingConnectSecurityMode] = useState(false);
const [pendingConnectClientActionKey, setPendingConnectClientActionKey] = useState<string | null>(
null,
);
const [addBackendDialogOpen, setAddBackendDialogOpen] = useState(false);
const [savedBackendMode, setSavedBackendMode] = useState<"remote" | "ssh">("remote");
const [savedBackendHost, setSavedBackendHost] = useState("");
@@ -2145,6 +2316,19 @@ export function ConnectionsSettings() {
),
);
}, [authAccessChanges.data]);
const desktopConnectSecurityMode: AuthConnectSecurityMode = useMemo(() => {
const event = authAccessChanges.data;
return event?.type === "snapshot" ? event.payload.connectSecurityMode : "account";
}, [authAccessChanges.data]);
const desktopConnectClients = useMemo(() => {
const event = authAccessChanges.data;
if (event?.type !== "snapshot") return [];
return sortDesktopConnectClients(
event.payload.connectClients.map((client: AuthConnectClient) =>
toServerConnectClientRecord(client),
),
);
}, [authAccessChanges.data]);
const isLocalBackendNetworkAccessible = desktopBridge
? desktopServerExposureState?.mode === "network-accessible"
: currentAuthPolicy === "remote-reachable";
@@ -2341,6 +2525,58 @@ export function ConnectionsSettings() {
}
}, []);
const handleUpdateConnectSecurityMode = useCallback(async (requiresApproval: boolean) => {
setIsUpdatingConnectSecurityMode(true);
setDesktopAccessManagementMutationError(null);
try {
await updateServerConnectSecurityMode(requiresApproval ? "client-approval" : "account");
} catch (error) {
const message =
error instanceof Error ? error.message : "Failed to update T3 Connect security.";
setDesktopAccessManagementMutationError(message);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not update T3 Connect security",
description: message,
}),
);
} finally {
setIsUpdatingConnectSecurityMode(false);
}
}, []);
const handleConnectClientAction = useCallback(
async (action: "approve" | "reject" | "revoke", clientProofKeyThumbprint: string) => {
const actionKey = `${action}:${clientProofKeyThumbprint}`;
setPendingConnectClientActionKey(actionKey);
setDesktopAccessManagementMutationError(null);
try {
if (action === "approve") {
await approveServerConnectClient(clientProofKeyThumbprint);
} else if (action === "reject") {
await rejectServerConnectClient(clientProofKeyThumbprint);
} else {
await revokeServerConnectClient(clientProofKeyThumbprint);
}
} catch (error) {
const message =
error instanceof Error ? error.message : `Failed to ${action} T3 Connect client.`;
setDesktopAccessManagementMutationError(message);
toastManager.add(
stackedThreadToast({
type: "error",
title: `Could not ${action} T3 Connect client`,
description: message,
}),
);
} finally {
setPendingConnectClientActionKey(null);
}
},
[],
);
const handleAddSavedBackend = useCallback(async () => {
if (savedBackendMode === "ssh") {
setIsAddingSavedBackend(true);
@@ -2834,15 +3070,45 @@ export function ConnectionsSettings() {
defaultEndpointKey={defaultDesktopAdvertisedEndpointKey}
presentation={presentation}
isLoading={isLoadingDesktopAccessManagement}
connectClients={desktopConnectClients}
pairingLinks={visibleDesktopPairingLinks}
clientSessions={desktopClientSessions}
pendingConnectClientActionKey={pendingConnectClientActionKey}
revokingPairingLinkId={revokingDesktopPairingLinkId}
revokingClientSessionId={revokingDesktopClientSessionId}
onApproveConnectClient={(clientProofKeyThumbprint) =>
void handleConnectClientAction("approve", clientProofKeyThumbprint)
}
onRejectConnectClient={(clientProofKeyThumbprint) =>
void handleConnectClientAction("reject", clientProofKeyThumbprint)
}
onRevokeConnectClient={(clientProofKeyThumbprint) =>
void handleConnectClientAction("revoke", clientProofKeyThumbprint)
}
onRevokePairingLink={handleRevokeDesktopPairingLink}
onRevokeClientSession={handleRevokeDesktopClientSession}
/>
</>
);
const renderConnectSecurityModeRow = () =>
hasCloudPublicConfig() ? (
<SettingsRow
title="T3 Connect approval"
description={
desktopConnectSecurityMode === "client-approval"
? "New T3 Connect clients must be approved here before they can connect."
: "Any signed-in client on this T3 account can connect through T3 Connect."
}
control={
<Switch
checked={desktopConnectSecurityMode === "client-approval"}
disabled={isUpdatingConnectSecurityMode || isLoadingDesktopAccessManagement}
onCheckedChange={(checked) => void handleUpdateConnectSecurityMode(checked)}
aria-label="Require T3 Connect client approval"
/>
}
/>
) : null;
const renderNetworkAccessRow = () => (
<SettingsRow
title="Network access"
@@ -2929,11 +3195,13 @@ export function ConnectionsSettings() {
{renderEndpointRows("endpoint-rail")}
{renderTailscaleRow()}
<CloudLinkRow canManageRelay={canManageRelay} />
{renderConnectSecurityModeRow()}
</>
) : (
<>
{renderDisabledNetworkAccessRow()}
<CloudLinkRow canManageRelay={canManageRelay} />
{renderConnectSecurityModeRow()}
</>
)}
</SettingsSection>
+120
View File
@@ -1,5 +1,7 @@
import type {
AuthBrowserSessionResult,
AuthConnectClient,
AuthConnectSecurityMode,
AuthClientMetadata,
AuthEnvironmentScope,
AuthPairingCredentialResult,
@@ -32,6 +34,10 @@ const PrimaryEnvironmentRequestOperation = Schema.Literals([
"list-client-sessions",
"revoke-client-session",
"revoke-other-client-sessions",
"update-connect-security-mode",
"approve-connect-client",
"reject-connect-client",
"revoke-connect-client",
]);
type PrimaryEnvironmentRequestOperation = typeof PrimaryEnvironmentRequestOperation.Type;
@@ -140,6 +146,34 @@ export interface ServerClientSessionRecord {
readonly current: boolean;
}
export interface ServerConnectClientRecord {
readonly clientProofKeyThumbprint: string;
readonly cloudUserId: string;
readonly deviceId?: string;
readonly status: AuthConnectClient["status"];
readonly client: AuthConnectClient["client"];
readonly requestedAt: string;
readonly updatedAt: string;
readonly approvedAt: string | null;
readonly rejectedAt: string | null;
readonly lastSeenAt: string | null;
}
export function toServerConnectClientRecord(client: AuthConnectClient): ServerConnectClientRecord {
return {
clientProofKeyThumbprint: client.clientProofKeyThumbprint,
cloudUserId: client.cloudUserId,
...(client.deviceId ? { deviceId: client.deviceId } : {}),
status: client.status,
client: client.client,
requestedAt: DateTime.formatIso(client.requestedAt),
updatedAt: DateTime.formatIso(client.updatedAt),
approvedAt: client.approvedAt === null ? null : DateTime.formatIso(client.approvedAt),
rejectedAt: client.rejectedAt === null ? null : DateTime.formatIso(client.rejectedAt),
lastSeenAt: client.lastSeenAt === null ? null : DateTime.formatIso(client.lastSeenAt),
};
}
type ServerAuthGateState =
| { status: "authenticated" }
| {
@@ -501,6 +535,92 @@ export async function revokeOtherServerClientSessions(): Promise<number> {
}
}
export async function updateServerConnectSecurityMode(
mode: AuthConnectSecurityMode,
): Promise<AuthConnectSecurityMode> {
try {
const result = await runPrimaryHttp(
PrimaryEnvironmentHttpClient.pipe(
Effect.flatMap((client) =>
client.auth.connectSecurityMode({ headers: {}, payload: { mode } }),
),
),
);
return result.mode;
} catch (error) {
throw PrimaryEnvironmentRequestError.fromCause({
operation: "update-connect-security-mode",
cause: error,
});
}
}
export async function approveServerConnectClient(
clientProofKeyThumbprint: string,
): Promise<ServerConnectClientRecord | null> {
try {
const result = await runPrimaryHttp(
PrimaryEnvironmentHttpClient.pipe(
Effect.flatMap((client) =>
client.auth.approveConnectClient({
headers: {},
payload: { clientProofKeyThumbprint },
}),
),
),
);
return result.client === null ? null : toServerConnectClientRecord(result.client);
} catch (error) {
throw PrimaryEnvironmentRequestError.fromCause({
operation: "approve-connect-client",
cause: error,
});
}
}
export async function rejectServerConnectClient(
clientProofKeyThumbprint: string,
): Promise<ServerConnectClientRecord | null> {
try {
const result = await runPrimaryHttp(
PrimaryEnvironmentHttpClient.pipe(
Effect.flatMap((client) =>
client.auth.rejectConnectClient({
headers: {},
payload: { clientProofKeyThumbprint },
}),
),
),
);
return result.client === null ? null : toServerConnectClientRecord(result.client);
} catch (error) {
throw PrimaryEnvironmentRequestError.fromCause({
operation: "reject-connect-client",
cause: error,
});
}
}
export async function revokeServerConnectClient(clientProofKeyThumbprint: string): Promise<void> {
try {
await runPrimaryHttp(
PrimaryEnvironmentHttpClient.pipe(
Effect.flatMap((client) =>
client.auth.revokeConnectClient({
headers: {},
payload: { clientProofKeyThumbprint },
}),
),
),
);
} catch (error) {
throw PrimaryEnvironmentRequestError.fromCause({
operation: "revoke-connect-client",
cause: error,
});
}
}
export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {
if (resolvedAuthenticatedGateState?.status === "authenticated") {
return resolvedAuthenticatedGateState;
@@ -15,6 +15,7 @@ export {
export {
createServerPairingCredential,
approveServerConnectClient,
fetchSessionState,
isPrimaryEnvironmentPairingCredentialRejectedError,
isPrimaryEnvironmentRequestError,
@@ -25,11 +26,16 @@ export {
PrimaryEnvironmentRequestError,
resolveInitialServerAuthGateState,
revokeOtherServerClientSessions,
rejectServerConnectClient,
revokeServerConnectClient,
revokeServerClientSession,
revokeServerPairingLink,
toServerConnectClientRecord,
stripPairingTokenFromUrl,
submitServerAuthCredential,
updateServerConnectSecurityMode,
takePairingTokenFromUrl,
type ServerConnectClientRecord,
type ServerClientSessionRecord,
type ServerPairingLinkRecord,
__resetServerAuthBootstrapForTests,
+6 -1
View File
@@ -115,7 +115,12 @@ export async function installEnvironmentHttpTest(scenario: EnvironmentHttpTestSc
.handle("revokePairingLink", () => unexpectedEndpoint("auth.revokePairingLink"))
.handle("clients", () => unexpectedEndpoint("auth.clients"))
.handle("revokeClient", () => unexpectedEndpoint("auth.revokeClient"))
.handle("revokeOtherClients", () => unexpectedEndpoint("auth.revokeOtherClients")),
.handle("revokeOtherClients", () => unexpectedEndpoint("auth.revokeOtherClients"))
.handle("connectSecurityMode", () => unexpectedEndpoint("auth.connectSecurityMode"))
.handle("connectClients", () => unexpectedEndpoint("auth.connectClients"))
.handle("approveConnectClient", () => unexpectedEndpoint("auth.approveConnectClient"))
.handle("rejectConnectClient", () => unexpectedEndpoint("auth.rejectConnectClient"))
.handle("revokeConnectClient", () => unexpectedEndpoint("auth.revokeConnectClient")),
),
]),
Effect.provideService(EnvironmentAuthenticatedAuth, authenticatedAuth),
@@ -8,8 +8,9 @@ import {
RelayCloudMintCredentialProofPayload,
RelayEnvironmentHealthResponse,
RelayEnvironmentHealthResponseProofPayload,
RelayEnvironmentMintAuthorizedResponseProofPayload,
RelayEnvironmentMintPendingApprovalResponseProofPayload,
RelayEnvironmentMintResponse,
RelayEnvironmentMintResponseProofPayload,
} from "@t3tools/contracts/relay";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
@@ -95,7 +96,7 @@ function decodeRequestProof<T>(proof: string): T {
function signMintResponse(
request: RelayCloudMintCredentialRequest,
overrides: Partial<RelayEnvironmentMintResponseProofPayload> = {},
overrides: Partial<RelayEnvironmentMintAuthorizedResponseProofPayload> = {},
privateKey = environmentKeyPair.privateKey,
): RelayEnvironmentMintResponse {
const requestProof = decodeRequestProof<RelayCloudMintCredentialProofPayload>(request.proof);
@@ -111,7 +112,7 @@ function signMintResponse(
requestNonce: requestProof.nonce,
credential: "pairing_credential",
...overrides,
} satisfies RelayEnvironmentMintResponseProofPayload;
} satisfies RelayEnvironmentMintAuthorizedResponseProofPayload;
return {
credential: payload.credential,
expiresAt: DateTime.formatIso(DateTime.makeUnsafe(payload.exp * 1_000)),
@@ -119,6 +120,35 @@ function signMintResponse(
};
}
function signPendingMintResponse(
request: RelayCloudMintCredentialRequest,
overrides: Partial<RelayEnvironmentMintPendingApprovalResponseProofPayload> = {},
privateKey = environmentKeyPair.privateKey,
): RelayEnvironmentMintResponse {
const requestProof = decodeRequestProof<RelayCloudMintCredentialProofPayload>(request.proof);
const payload = {
iss: `t3-env:${requestProof.environmentId}`,
aud: "https://relay.example.test",
sub: requestProof.environmentId,
jti: "mint-pending-response-jti",
iat: requestProof.iat,
exp: requestProof.exp,
environmentId: requestProof.environmentId,
clientProofKeyThumbprint: requestProof.clientProofKeyThumbprint,
requestNonce: requestProof.nonce,
status: "pending_approval",
approvalStatus: "pending",
...overrides,
} satisfies RelayEnvironmentMintPendingApprovalResponseProofPayload;
return {
status: "pending_approval",
clientProofKeyThumbprint: payload.clientProofKeyThumbprint,
approvalStatus: payload.approvalStatus,
requestedAt: "2026-06-06T00:00:00.000Z",
proof: signTestJwt(payload, RELAY_MINT_RESPONSE_TYP, privateKey),
};
}
function signHealthResponse(
request: RelayCloudEnvironmentHealthRequest,
privateKey = environmentKeyPair.privateKey,
@@ -662,6 +692,7 @@ describe("EnvironmentConnector", () => {
environmentId: "env-connector-test",
clientProofKeyThumbprint: "client-proof-key-thumbprint",
deviceId: "device-123",
client: { label: "Mobile", deviceType: "mobile", os: "iOS" },
});
expect(seenUrls).toEqual(["https://env.example.test/api/t3-connect/mint-credential"]);
@@ -673,6 +704,7 @@ describe("EnvironmentConnector", () => {
clientProofKeyThumbprint: "client-proof-key-thumbprint",
cnf: { jkt: "client-proof-key-thumbprint" },
deviceId: "device-123",
client: { label: "Mobile", deviceType: "mobile", os: "iOS" },
scope: ["environment:connect"],
});
expect(result).toMatchObject({
@@ -686,6 +718,34 @@ describe("EnvironmentConnector", () => {
}).pipe(Effect.provide(connectorTestLayer(execute)));
});
it.effect("returns signed pending approval responses from the linked endpoint", () => {
const execute = (request: HttpClientRequest.HttpClientRequest) =>
Effect.sync(() => {
const mintRequest = decodeMintRequestBody(requestBodyText(request));
return HttpClientResponse.fromWeb(
request,
Response.json(signPendingMintResponse(mintRequest), { status: 200 }),
);
});
return Effect.gen(function* () {
const connector = yield* EnvironmentConnector.EnvironmentConnector;
const result = yield* connector.connect({
userId: "user_123",
environmentId: "env-connector-test",
clientProofKeyThumbprint: "client-proof-key-thumbprint",
});
expect(result).toMatchObject({
status: "pending_approval",
environmentId: "env-connector-test",
clientProofKeyThumbprint: "client-proof-key-thumbprint",
approvalStatus: "pending",
requestedAt: "2026-06-06T00:00:00.000Z",
});
}).pipe(Effect.provide(connectorTestLayer(execute)));
});
it.effect("only accepts mint responses signed by the user's linked environment key", () => {
const execute = (request: HttpClientRequest.HttpClientRequest) =>
Effect.sync(() => {
@@ -1,4 +1,5 @@
import {
type AuthClientPresentationMetadata,
EnvironmentHttpBadRequestError,
EnvironmentHttpConflictError,
EnvironmentHttpForbiddenError,
@@ -12,6 +13,7 @@ import {
RelayEnvironmentHealthResponseProofPayload,
RelayEnvironmentMintResponse,
RelayEnvironmentMintResponseProofPayload,
type RelayEnvironmentMintPendingApprovalResponse,
RelayCloudMintCredentialProofPayload,
type RelayEnvironmentConnectResponse,
type RelayEnvironmentStatusResponse,
@@ -149,6 +151,7 @@ export class EnvironmentConnector extends Context.Service<
readonly environmentId: string;
readonly clientProofKeyThumbprint: string;
readonly deviceId?: string;
readonly client?: AuthClientPresentationMetadata;
}) => Effect.Effect<RelayEnvironmentConnectResponse, EnvironmentConnectorError>;
readonly status: (input: {
readonly userId: string;
@@ -241,18 +244,37 @@ function verifyEnvironmentResponse(input: {
environmentPublicKeys: input.environmentPublicKeys,
decodePayload: decodeMintResponseProof,
}).pipe(
Effect.map(
(proof) =>
proof !== null &&
proof.environmentId === input.environmentId &&
proof.requestNonce === input.requestNonce &&
proof.clientProofKeyThumbprint === input.clientProofKeyThumbprint &&
proof.credential === input.response.credential &&
Option.match(DateTime.make(input.response.expiresAt), {
Effect.map((proof) => {
const response = input.response;
if (
proof === null ||
proof.environmentId !== input.environmentId ||
proof.requestNonce !== input.requestNonce ||
proof.clientProofKeyThumbprint !== input.clientProofKeyThumbprint
) {
return false;
}
if (!("credential" in response)) {
return (
"status" in proof &&
proof.status === "pending_approval" &&
proof.approvalStatus === response.approvalStatus &&
proof.clientProofKeyThumbprint === response.clientProofKeyThumbprint
);
}
if ("status" in proof) {
return false;
}
return (
proof.credential === response.credential &&
Option.match(DateTime.make(response.expiresAt), {
onNone: () => false,
onSome: (expiresAt) => Math.floor(expiresAt.epochMilliseconds / 1_000) === proof.exp,
}),
),
})
);
}),
);
}
@@ -615,6 +637,7 @@ const make = Effect.gen(function* () {
clientProofKeyThumbprint: input.clientProofKeyThumbprint,
cnf: { jkt: input.clientProofKeyThumbprint },
...(input.deviceId ? { deviceId: input.deviceId } : {}),
...(input.client ? { client: input.client } : {}),
nonce,
scope: ["environment:connect"],
} satisfies RelayCloudMintCredentialProofPayload;
@@ -674,6 +697,17 @@ const make = Effect.gen(function* () {
operation: "connect",
});
}
if (!("credential" in decoded)) {
const pending: RelayEnvironmentMintPendingApprovalResponse = decoded;
return {
status: "pending_approval",
environmentId: link.environmentId,
endpoint,
clientProofKeyThumbprint: pending.clientProofKeyThumbprint,
approvalStatus: pending.approvalStatus,
requestedAt: pending.requestedAt,
};
}
return {
environmentId: link.environmentId,
endpoint,
+1
View File
@@ -650,6 +650,7 @@ export const dpopClientApi = HttpApiBuilder.group(
environmentId: params.environmentId,
clientProofKeyThumbprint,
...(payload.deviceId ? { deviceId: payload.deviceId } : {}),
...(payload.client ? { client: payload.client } : {}),
});
},
mapRelayCommonApiErrors("invalid_dpop"),
@@ -179,6 +179,17 @@ const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((o
deviceId: Effect.succeed(Option.some("device-1")),
}),
),
Layer.succeed(
ClientCapabilities.ClientPresentation,
ClientCapabilities.ClientPresentation.of({
metadata: {
label: "Test Client",
deviceType: "desktop",
os: "Test OS",
},
scopes: [],
}),
),
Layer.succeed(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, remote),
Layer.succeed(ClientCapabilities.SshEnvironmentGateway, ssh),
Layer.succeed(
@@ -305,6 +316,11 @@ describe("ConnectionResolver", () => {
readonly clerkToken: string;
readonly scopes: ReadonlyArray<string>;
readonly deviceId?: string;
readonly client?: {
readonly label?: string;
readonly deviceType?: string;
readonly os?: string;
};
}>
>([]);
const bootstrapCredentials = yield* Ref.make<ReadonlyArray<string>>([]);
@@ -320,6 +336,7 @@ describe("ConnectionResolver", () => {
clerkToken: input.clerkToken,
scopes: input.scopes,
...(input.deviceId ? { deviceId: input.deviceId } : {}),
...(input.client ? { client: input.client } : {}),
},
]).pipe(
Effect.as({
@@ -354,12 +371,48 @@ describe("ConnectionResolver", () => {
clerkToken: "clerk-session",
scopes: [RelayEnvironmentConnectScope],
deviceId: "device-1",
client: {
label: "Test Client",
deviceType: "desktop",
os: "Test OS",
},
},
]);
expect(yield* Ref.get(bootstrapCredentials)).toEqual(["relay-bootstrap"]);
}),
);
it.effect("blocks relay connection attempts that are waiting for environment approval", () =>
Effect.gen(function* () {
const target = new RelayConnectionTarget({
environmentId: ENVIRONMENT_ID,
label: "Cloud",
});
const brokerLayer = yield* makeDependencies({
connectEnvironment: (input) =>
Effect.succeed({
status: "pending_approval" as const,
environmentId: input.environmentId,
endpoint: ENDPOINT,
clientProofKeyThumbprint: "client-proof-key-thumbprint",
approvalStatus: "pending" as const,
requestedAt: "2026-06-06T00:00:00.000Z",
}),
});
const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));
const result = yield* Effect.result(broker.prepare(catalogEntry(target)));
expect(result._tag).toBe("Failure");
if (result._tag === "Failure") {
expect(result.failure).toMatchObject({
_tag: "ConnectionBlockedError",
reason: "permission",
detail: "Waiting for this client to be approved in the environment settings.",
});
}
}),
);
it.effect("exports the complete relay authorization flow through the product tracer", () =>
Effect.gen(function* () {
const userSpans: Array<string> = [];
@@ -142,6 +142,7 @@ const makeRelayBroker = Effect.fn("clientRuntime.connection.broker.makeRelay")(f
const relay = yield* ManagedRelay.ManagedRelayClient;
const session = yield* ClientCapabilities.CloudSession;
const identity = yield* ClientCapabilities.RelayDeviceIdentity;
const presentation = yield* ClientCapabilities.ClientPresentation;
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
return Effect.fnUntraced(
@@ -161,6 +162,7 @@ const makeRelayBroker = Effect.fn("clientRuntime.connection.broker.makeRelay")(f
scopes: [RelayEnvironmentConnectScope],
environmentId: target.environmentId,
...(Option.isSome(deviceId) ? { deviceId: deviceId.value } : {}),
client: presentation.metadata,
})
.pipe(Effect.mapError(mapManagedRelayError));
if (connected.environmentId !== target.environmentId) {
@@ -169,6 +171,15 @@ const makeRelayBroker = Effect.fn("clientRuntime.connection.broker.makeRelay")(f
actual: connected.environmentId,
});
}
if ("status" in connected) {
return yield* new ConnectionBlockedError({
reason: "permission",
detail:
connected.approvalStatus === "rejected"
? "This client was rejected by the environment. Approve it in the environment settings to connect."
: "Waiting for this client to be approved in the environment settings.",
});
}
return connected;
}).pipe(Effect.withSpan("relay.connection.bootstrap.obtain")),
});
@@ -1,3 +1,4 @@
import { type AuthClientPresentationMetadata } from "@t3tools/contracts";
import {
RelayAccessTokenType,
RelayApi,
@@ -273,6 +274,7 @@ export class ManagedRelayClient extends Context.Service<
readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
readonly deviceId?: string;
readonly client?: AuthClientPresentationMetadata;
}) => Effect.Effect<RelayEnvironmentConnectResponse, ManagedRelayClientError>;
readonly registerDevice: (input: {
readonly clerkToken: string;
@@ -783,7 +785,8 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* (
(authorization) => {
const payload: RelayEnvironmentConnectRequest = {
...(input.deviceId ? { deviceId: input.deviceId } : {}),
clientKeyThumbprint: authorization.thumbprint,
clientProofKeyThumbprint: authorization.thumbprint,
...(input.client ? { client: input.client } : {}),
};
return client.dpopClient
.connectEnvironment({
+51 -1
View File
@@ -45,6 +45,8 @@ describe("applyAuthAccessStreamEvent", () => {
});
expect(withClient).toEqual({
connectSecurityMode: "account",
connectClients: [],
pairingLinks: [pairingLink],
clientSessions: [clientSession],
});
@@ -53,6 +55,8 @@ describe("applyAuthAccessStreamEvent", () => {
it("applies removals without disturbing unrelated access state", () => {
const snapshot = applyAuthAccessStreamEvent(
{
connectSecurityMode: "client-approval",
connectClients: [],
pairingLinks: [
{
id: "pairing-link",
@@ -74,6 +78,52 @@ describe("applyAuthAccessStreamEvent", () => {
},
);
expect(snapshot).toEqual(EMPTY_AUTH_ACCESS_SNAPSHOT);
expect(snapshot).toEqual({
...EMPTY_AUTH_ACCESS_SNAPSHOT,
connectSecurityMode: "client-approval",
});
});
it("applies Connect security mode and client updates", () => {
const connectClient = {
clientProofKeyThumbprint: "thumbprint",
cloudUserId: "user_123",
status: "pending",
client: {
label: "Phone",
deviceType: "mobile",
},
requestedAt: DateTime.makeUnsafe("2036-04-07T00:00:00.000Z"),
updatedAt: DateTime.makeUnsafe("2036-04-07T00:00:00.000Z"),
approvedAt: null,
rejectedAt: null,
lastSeenAt: null,
} as const;
const withMode = applyAuthAccessStreamEvent(EMPTY_AUTH_ACCESS_SNAPSHOT, {
version: 1,
revision: 1,
type: "connectSecurityModeUpdated",
payload: { mode: "client-approval" },
});
const withClient = applyAuthAccessStreamEvent(withMode, {
version: 1,
revision: 2,
type: "connectClientUpserted",
payload: connectClient,
});
const withoutClient = applyAuthAccessStreamEvent(withClient, {
version: 1,
revision: 3,
type: "connectClientRemoved",
payload: { clientProofKeyThumbprint: "thumbprint" },
});
expect(withClient.connectSecurityMode).toBe("client-approval");
expect(withClient.connectClients).toEqual([connectClient]);
expect(withoutClient).toEqual({
...EMPTY_AUTH_ACCESS_SNAPSHOT,
connectSecurityMode: "client-approval",
});
});
});
+23
View File
@@ -12,6 +12,8 @@ import { subscribe } from "../rpc/client.ts";
import { createEnvironmentSubscriptionAtomFamily } from "./runtime.ts";
export const EMPTY_AUTH_ACCESS_SNAPSHOT: AuthAccessSnapshot = {
connectSecurityMode: "account",
connectClients: [],
pairingLinks: [],
clientSessions: [],
};
@@ -58,6 +60,27 @@ export function applyAuthAccessStreamEvent(
(value) => value.sessionId !== event.payload.sessionId,
),
};
case "connectSecurityModeUpdated":
return {
...current,
connectSecurityMode: event.payload.mode,
};
case "connectClientUpserted":
return {
...current,
connectClients: upsertByKey(
current.connectClients,
event.payload,
(value) => value.clientProofKeyThumbprint,
),
};
case "connectClientRemoved":
return {
...current,
connectClients: current.connectClients.filter(
(value) => value.clientProofKeyThumbprint !== event.payload.clientProofKeyThumbprint,
),
};
}
}
@@ -9,7 +9,6 @@ import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
import { EnvironmentRegistry } from "../connection/registry.ts";
import {
environmentRpcKey,
createAtomCommandScheduler,
@@ -23,19 +22,6 @@ import {
settlePromise,
squashAtomCommandFailure,
} from "./runtime.ts";
import { createVcsEnvironmentAtoms } from "./vcs.ts";
describe("VCS status subscription lifecycle", () => {
it("removes the status subscription immediately after its last consumer unmounts", () => {
const runtime = Atom.runtime(Layer.effect(EnvironmentRegistry, Effect.never));
const statusAtom = createVcsEnvironmentAtoms(runtime).status({
environmentId: EnvironmentId.make("env-1"),
input: { cwd: "/repo" },
});
expect(statusAtom.idleTTL).toBe(0);
});
});
describe("settleAsyncResult", () => {
it("preserves successful values and typed failures", async () => {
-1
View File
@@ -23,7 +23,6 @@ export function createVcsEnvironmentAtoms<R, E>(
}),
status: createEnvironmentSubscriptionAtomFamily(runtime, {
label: "environment-data:vcs:status",
idleTtlMs: 0,
subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.subscribeVcsStatus>) =>
subscribe(WS_METHODS.subscribeVcsStatus, input).pipe(
Stream.mapAccum(
+66
View File
@@ -228,6 +228,26 @@ export const AuthClientMetadata = Schema.Struct({
});
export type AuthClientMetadata = typeof AuthClientMetadata.Type;
export const AuthConnectSecurityMode = Schema.Literals(["account", "client-approval"]);
export type AuthConnectSecurityMode = typeof AuthConnectSecurityMode.Type;
export const AuthConnectClientStatus = Schema.Literals(["pending", "approved", "rejected"]);
export type AuthConnectClientStatus = typeof AuthConnectClientStatus.Type;
export const AuthConnectClient = Schema.Struct({
clientProofKeyThumbprint: TrimmedNonEmptyString,
cloudUserId: TrimmedNonEmptyString,
deviceId: Schema.optionalKey(TrimmedNonEmptyString),
status: AuthConnectClientStatus,
client: AuthClientMetadata,
requestedAt: Schema.DateTimeUtc,
updatedAt: Schema.DateTimeUtc,
approvedAt: Schema.NullOr(Schema.DateTimeUtc),
rejectedAt: Schema.NullOr(Schema.DateTimeUtc),
lastSeenAt: Schema.NullOr(Schema.DateTimeUtc),
});
export type AuthConnectClient = typeof AuthConnectClient.Type;
export const AuthClientSession = Schema.Struct({
sessionId: AuthSessionId,
subject: TrimmedNonEmptyString,
@@ -243,6 +263,8 @@ export const AuthClientSession = Schema.Struct({
export type AuthClientSession = typeof AuthClientSession.Type;
export const AuthAccessSnapshot = Schema.Struct({
connectSecurityMode: AuthConnectSecurityMode,
connectClients: Schema.Array(AuthConnectClient),
pairingLinks: Schema.Array(AuthPairingLink),
clientSessions: Schema.Array(AuthClientSession),
});
@@ -309,12 +331,46 @@ export const AuthAccessStreamClientRemovedEvent = Schema.Struct({
});
export type AuthAccessStreamClientRemovedEvent = typeof AuthAccessStreamClientRemovedEvent.Type;
export const AuthAccessStreamConnectSecurityModeUpdatedEvent = Schema.Struct({
version: Schema.Literal(1),
revision: Schema.Number,
type: Schema.Literal("connectSecurityModeUpdated"),
payload: Schema.Struct({
mode: AuthConnectSecurityMode,
}),
});
export type AuthAccessStreamConnectSecurityModeUpdatedEvent =
typeof AuthAccessStreamConnectSecurityModeUpdatedEvent.Type;
export const AuthAccessStreamConnectClientUpsertedEvent = Schema.Struct({
version: Schema.Literal(1),
revision: Schema.Number,
type: Schema.Literal("connectClientUpserted"),
payload: AuthConnectClient,
});
export type AuthAccessStreamConnectClientUpsertedEvent =
typeof AuthAccessStreamConnectClientUpsertedEvent.Type;
export const AuthAccessStreamConnectClientRemovedEvent = Schema.Struct({
version: Schema.Literal(1),
revision: Schema.Number,
type: Schema.Literal("connectClientRemoved"),
payload: Schema.Struct({
clientProofKeyThumbprint: TrimmedNonEmptyString,
}),
});
export type AuthAccessStreamConnectClientRemovedEvent =
typeof AuthAccessStreamConnectClientRemovedEvent.Type;
export const AuthAccessStreamEvent = Schema.Union([
AuthAccessStreamSnapshotEvent,
AuthAccessStreamPairingLinkUpsertedEvent,
AuthAccessStreamPairingLinkRemovedEvent,
AuthAccessStreamClientUpsertedEvent,
AuthAccessStreamClientRemovedEvent,
AuthAccessStreamConnectSecurityModeUpdatedEvent,
AuthAccessStreamConnectClientUpsertedEvent,
AuthAccessStreamConnectClientRemovedEvent,
]);
export type AuthAccessStreamEvent = typeof AuthAccessStreamEvent.Type;
@@ -323,6 +379,16 @@ export const AuthRevokePairingLinkInput = Schema.Struct({
});
export type AuthRevokePairingLinkInput = typeof AuthRevokePairingLinkInput.Type;
export const AuthUpdateConnectSecurityModeInput = Schema.Struct({
mode: AuthConnectSecurityMode,
});
export type AuthUpdateConnectSecurityModeInput = typeof AuthUpdateConnectSecurityModeInput.Type;
export const AuthConnectClientDecisionInput = Schema.Struct({
clientProofKeyThumbprint: TrimmedNonEmptyString,
});
export type AuthConnectClientDecisionInput = typeof AuthConnectClientDecisionInput.Type;
export const AuthRevokeClientSessionInput = Schema.Struct({
sessionId: AuthSessionId,
});
+65
View File
@@ -12,6 +12,9 @@ import {
AuthAccessTokenResult,
AuthBrowserSessionRequest,
AuthBrowserSessionResult,
AuthConnectClient,
AuthConnectClientDecisionInput,
AuthConnectSecurityMode,
AuthClientSession,
AuthCreatePairingCredentialInput,
AuthPairingCredentialResult,
@@ -21,6 +24,7 @@ import {
AuthEnvironmentScope,
AuthTokenExchangeRequest,
AuthSessionState,
AuthUpdateConnectSecurityModeInput,
AuthWebSocketTicketResult,
ServerAuthSessionMethod,
} from "./auth.ts";
@@ -79,6 +83,12 @@ export const EnvironmentInternalErrorReason = Schema.Literals([
"pairing_link_revoke_failed",
"client_sessions_load_failed",
"client_session_revoke_failed",
"connect_security_mode_load_failed",
"connect_security_mode_update_failed",
"connect_clients_load_failed",
"connect_client_approval_failed",
"connect_client_rejection_failed",
"connect_client_revoke_failed",
"orchestration_snapshot_failed",
"orchestration_dispatch_failed",
"internal_error",
@@ -317,6 +327,7 @@ export const EnvironmentCloudLinkStateResult = Schema.Struct({
relayUrl: Schema.NullOr(Schema.String),
relayIssuer: Schema.NullOr(Schema.String),
publishAgentActivity: Schema.Boolean,
connectSecurityMode: AuthConnectSecurityMode,
});
export type EnvironmentCloudLinkStateResult = typeof EnvironmentCloudLinkStateResult.Type;
@@ -340,6 +351,21 @@ export const AuthOtherClientSessionsRevokeResult = Schema.Struct({
});
export type AuthOtherClientSessionsRevokeResult = typeof AuthOtherClientSessionsRevokeResult.Type;
export const AuthConnectSecurityModeUpdateResult = Schema.Struct({
mode: AuthUpdateConnectSecurityModeInput.fields.mode,
});
export type AuthConnectSecurityModeUpdateResult = typeof AuthConnectSecurityModeUpdateResult.Type;
export const AuthConnectClientDecisionResult = Schema.Struct({
client: Schema.NullOr(AuthConnectClient),
});
export type AuthConnectClientDecisionResult = typeof AuthConnectClientDecisionResult.Type;
export const AuthConnectClientRevokeResult = Schema.Struct({
revoked: Schema.Boolean,
});
export type AuthConnectClientRevokeResult = typeof AuthConnectClientRevokeResult.Type;
export class EnvironmentMetadataHttpApi extends HttpApiGroup.make("metadata").add(
HttpApiEndpoint.get("descriptor", "/.well-known/t3/environment", {
success: ExecutionEnvironmentDescriptor,
@@ -420,6 +446,45 @@ export class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth")
success: AuthOtherClientSessionsRevokeResult,
error: EnvironmentScopedOperationErrors,
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.post("connectSecurityMode", "/api/auth/connect-security-mode", {
headers: OptionalBearerHeaders,
payload: AuthUpdateConnectSecurityModeInput,
success: AuthConnectSecurityModeUpdateResult,
error: EnvironmentScopedOperationErrors,
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.get("connectClients", "/api/auth/connect-clients", {
headers: OptionalBearerHeaders,
success: Schema.Array(AuthConnectClient),
error: EnvironmentScopedOperationErrors,
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.post("approveConnectClient", "/api/auth/connect-clients/approve", {
headers: OptionalBearerHeaders,
payload: AuthConnectClientDecisionInput,
success: AuthConnectClientDecisionResult,
error: EnvironmentScopedOperationErrors,
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.post("rejectConnectClient", "/api/auth/connect-clients/reject", {
headers: OptionalBearerHeaders,
payload: AuthConnectClientDecisionInput,
success: AuthConnectClientDecisionResult,
error: EnvironmentScopedOperationErrors,
}).middleware(EnvironmentAuthenticatedAuth),
)
.add(
HttpApiEndpoint.post("revokeConnectClient", "/api/auth/connect-clients/revoke", {
headers: OptionalBearerHeaders,
payload: AuthConnectClientDecisionInput,
success: AuthConnectClientRevokeResult,
error: EnvironmentScopedOperationErrors,
}).middleware(EnvironmentAuthenticatedAuth),
) {}
export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration")
+63 -3
View File
@@ -10,6 +10,7 @@ import * as OpenApi from "effect/unstable/httpapi/OpenApi";
import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
import { ExecutionEnvironmentDescriptor } from "./environment.ts";
import { AuthClientPresentationMetadata, AuthConnectClientStatus } from "./auth.ts";
export const RelayAgentAwarenessPlatform = Schema.Literal("ios");
export type RelayAgentAwarenessPlatform = typeof RelayAgentAwarenessPlatform.Type;
@@ -604,6 +605,11 @@ export const RelayEnvironmentConnectRequest = Schema.Struct({
description: "JWK thumbprint that the minted environment credential must be bound to.",
}),
),
client: Schema.optional(
AuthClientPresentationMetadata.annotate({
description: "Optional user-facing client metadata for environment approval prompts.",
}),
),
}).annotate({ description: "Requests a short-lived credential for connecting to an environment." });
export type RelayEnvironmentConnectRequest = typeof RelayEnvironmentConnectRequest.Type;
@@ -689,12 +695,30 @@ export const RelayEnvironmentUnlinkParams = Schema.Struct({
});
export type RelayEnvironmentUnlinkParams = typeof RelayEnvironmentUnlinkParams.Type;
export const RelayEnvironmentConnectResponse = Schema.Struct({
export const RelayEnvironmentConnectAuthorizedResponse = Schema.Struct({
environmentId: EnvironmentId,
endpoint: RelayManagedEndpoint,
credential: TrimmedNonEmptyString,
expiresAt: TrimmedNonEmptyString,
});
export type RelayEnvironmentConnectAuthorizedResponse =
typeof RelayEnvironmentConnectAuthorizedResponse.Type;
export const RelayEnvironmentConnectPendingApprovalResponse = Schema.Struct({
status: Schema.Literal("pending_approval"),
environmentId: EnvironmentId,
endpoint: RelayManagedEndpoint,
clientProofKeyThumbprint: TrimmedNonEmptyString,
approvalStatus: AuthConnectClientStatus,
requestedAt: TrimmedNonEmptyString,
});
export type RelayEnvironmentConnectPendingApprovalResponse =
typeof RelayEnvironmentConnectPendingApprovalResponse.Type;
export const RelayEnvironmentConnectResponse = Schema.Union([
RelayEnvironmentConnectAuthorizedResponse,
RelayEnvironmentConnectPendingApprovalResponse,
]);
export type RelayEnvironmentConnectResponse = typeof RelayEnvironmentConnectResponse.Type;
export const RelayEnvironmentStatusValue = Schema.Literals(["online", "offline"]);
@@ -719,6 +743,7 @@ export const RelayCloudMintCredentialProofPayload = Schema.Struct({
jkt: TrimmedNonEmptyString,
}),
deviceId: Schema.optional(TrimmedNonEmptyString),
client: Schema.optional(AuthClientPresentationMetadata),
nonce: TrimmedNonEmptyString,
scope: Schema.Array(Schema.Literal("environment:connect")),
});
@@ -769,21 +794,56 @@ export const RelayEnvironmentHealthResponse = Schema.Struct({
});
export type RelayEnvironmentHealthResponse = typeof RelayEnvironmentHealthResponse.Type;
export const RelayEnvironmentMintResponseProofPayload = Schema.Struct({
export const RelayEnvironmentMintAuthorizedResponseProofPayload = Schema.Struct({
...RelaySignedJwtRegisteredClaims,
environmentId: EnvironmentId,
clientProofKeyThumbprint: TrimmedNonEmptyString,
requestNonce: TrimmedNonEmptyString,
credential: TrimmedNonEmptyString,
});
export type RelayEnvironmentMintAuthorizedResponseProofPayload =
typeof RelayEnvironmentMintAuthorizedResponseProofPayload.Type;
export const RelayEnvironmentMintPendingApprovalResponseProofPayload = Schema.Struct({
...RelaySignedJwtRegisteredClaims,
environmentId: EnvironmentId,
clientProofKeyThumbprint: TrimmedNonEmptyString,
requestNonce: TrimmedNonEmptyString,
status: Schema.Literal("pending_approval"),
approvalStatus: AuthConnectClientStatus,
});
export type RelayEnvironmentMintPendingApprovalResponseProofPayload =
typeof RelayEnvironmentMintPendingApprovalResponseProofPayload.Type;
export const RelayEnvironmentMintResponseProofPayload = Schema.Union([
RelayEnvironmentMintAuthorizedResponseProofPayload,
RelayEnvironmentMintPendingApprovalResponseProofPayload,
]);
export type RelayEnvironmentMintResponseProofPayload =
typeof RelayEnvironmentMintResponseProofPayload.Type;
export const RelayEnvironmentMintResponse = Schema.Struct({
export const RelayEnvironmentMintAuthorizedResponse = Schema.Struct({
credential: TrimmedNonEmptyString,
expiresAt: TrimmedNonEmptyString,
proof: TrimmedNonEmptyString,
});
export type RelayEnvironmentMintAuthorizedResponse =
typeof RelayEnvironmentMintAuthorizedResponse.Type;
export const RelayEnvironmentMintPendingApprovalResponse = Schema.Struct({
status: Schema.Literal("pending_approval"),
clientProofKeyThumbprint: TrimmedNonEmptyString,
approvalStatus: AuthConnectClientStatus,
requestedAt: TrimmedNonEmptyString,
proof: TrimmedNonEmptyString,
});
export type RelayEnvironmentMintPendingApprovalResponse =
typeof RelayEnvironmentMintPendingApprovalResponse.Type;
export const RelayEnvironmentMintResponse = Schema.Union([
RelayEnvironmentMintAuthorizedResponse,
RelayEnvironmentMintPendingApprovalResponse,
]);
export type RelayEnvironmentMintResponse = typeof RelayEnvironmentMintResponse.Type;
export const RelayDeliveryKind = Schema.Literals([