Compare commits

..
22 changed files with 581 additions and 158 deletions

No files matched your search

@@ -3,6 +3,7 @@ import { Image } from "expo-image";
import { useState } from "react";
import { View } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
import { useThemeColor } from "../lib/useThemeColor";
import { useAssetUrl } from "../state/assets";
@@ -24,11 +25,12 @@ export function ProjectFavicon(props: {
? null
: { _tag: "project-favicon", cwd: props.workspaceRoot },
);
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
return (
<ProjectFaviconImage
key={faviconUrl}
faviconUrl={faviconUrl}
faviconUrl={renderableFaviconUrl}
open={props.open}
projectTitle={props.projectTitle}
size={size}
+3 -1
View File
@@ -1,5 +1,6 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ThreadId } from "@t3tools/contracts";
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -228,6 +229,7 @@ describe("AssetAccess", () => {
const fallbackResult = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root },
});
expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
expect(
@@ -235,7 +237,7 @@ describe("AssetAccess", () => {
fallbackSuffix.slice(0, fallbackSeparatorIndex),
fallbackSuffix.slice(fallbackSeparatorIndex + 1),
),
).toEqual({ kind: "project-favicon-fallback" });
).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
+4 -8
View File
@@ -19,6 +19,7 @@ import {
WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,
WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,
} from "@t3tools/shared/filePreview";
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -40,7 +41,6 @@ import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
export const ASSET_ROUTE_PREFIX = "/api/assets";
export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
@@ -91,9 +91,7 @@ const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
export type ResolvedAsset =
| { readonly kind: "file"; readonly path: string }
| { readonly kind: "project-favicon-fallback" };
export type ResolvedAsset = { readonly kind: "file"; readonly path: string };
function decodeClaims(encodedPayload: string): AssetClaims | null {
try {
@@ -326,7 +324,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
relativePath,
expiresAt,
};
fileName = relativePath ? path.basename(relativePath) : "favicon.svg";
fileName = relativePath ? path.basename(relativePath) : PROJECT_FAVICON_FALLBACK_MARKER;
break;
}
}
@@ -391,9 +389,7 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
}
if (claims.kind === "project-favicon") {
if (claims.relativePath === null) {
return { kind: "project-favicon-fallback" } satisfies ResolvedAsset;
}
if (claims.relativePath === null) return null;
const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({
workspaceRoot: claims.workspaceRoot,
relativePath: claims.relativePath,
+1 -16
View File
@@ -25,11 +25,7 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { OtlpTracer } from "effect/unstable/observability";
import * as ServerConfig from "./config.ts";
import {
ASSET_ROUTE_PREFIX,
FALLBACK_PROJECT_FAVICON_SVG,
resolveAsset,
} from "./assets/AssetAccess.ts";
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
@@ -196,17 +192,6 @@ export const assetRouteLayer = HttpRouter.add(
if (!asset) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
if (asset.kind === "project-favicon-fallback") {
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
status: 200,
contentType: "image/svg+xml",
headers: {
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
});
}
return yield* HttpServerResponse.file(asset.path, {
status: 200,
headers: {
@@ -137,7 +137,7 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
expect(AgentAwarenessRelay.eventThreadId(event)).toBe(threadId);
});
it("does not publish streaming content or non-awareness activity events", () => {
it("does not publish start intents, streaming content, or non-awareness activity events", () => {
const now = "2026-05-25T00:00:00.000Z";
const base = {
sequence: 1,
@@ -191,7 +191,16 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
streaming: false,
},
} as unknown as OrchestrationEvent),
).toBe(true);
).toBe(false);
expect(
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
...base,
type: "thread.turn-start-requested",
payload: {
threadId: "thread-1" as ThreadId,
},
} as unknown as OrchestrationEvent),
).toBe(false);
});
it("deduplicates awareness state updates whose only change is their event timestamp", () => {
+7 -1
View File
@@ -67,7 +67,13 @@ export function eventThreadId(event: OrchestrationEvent): ThreadId | null {
export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean {
switch (event.type) {
case "thread.message-sent":
return !event.payload.streaming;
case "thread.turn-start-requested":
// These events express intent to start work, but the shell still contains
// the previous turn's terminal state until the provider acknowledges the
// new turn. Publishing that snapshot can queue a fresh "Done" alert just
// before the real running state arrives. Provider lifecycle events publish
// the authoritative starting/running state instead.
return false;
case "thread.proposed-plan-upserted":
case "thread.runtime-mode-set":
case "thread.interaction-mode-set":
+2 -1
View File
@@ -1,4 +1,5 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon";
import { FolderIcon } from "lucide-react";
import { useState } from "react";
import { useAssetUrl } from "../assets/assetUrls";
@@ -15,7 +16,7 @@ export function ProjectFavicon(input: {
cwd: input.cwd,
});
if (!src) {
if (!src || isProjectFaviconFallbackUrl(src)) {
return <ProjectFaviconFallback className={input.className} />;
}
@@ -24,7 +24,6 @@ interface Props {
url: string;
displayUrl?: string | undefined;
loading: boolean;
loadProgress: number;
canGoBack: boolean;
canGoForward: boolean;
refreshDisabled: boolean;
@@ -59,11 +58,33 @@ interface Props {
const NOOP = () => {};
function useFocusPreviewUrlInput(
inputRef: React.RefObject<HTMLInputElement | null>,
focusUrlNonce: number | undefined,
): void {
useEffect(() => {
if (focusUrlNonce == null) return;
inputRef.current?.focus();
}, [focusUrlNonce, inputRef]);
}
function PreviewLoadingProgress({ loading }: { loading: boolean }) {
return (
<div
aria-hidden
className={cn(
"pointer-events-none absolute bottom-0 left-0 z-10 h-0.5 w-full origin-left rounded-r-full bg-primary",
loading ? "preview-loading-progress-active" : "preview-loading-progress-idle",
)}
style={{ boxShadow: "0 0 6px 1px var(--color-ring)" }}
/>
);
}
export function PreviewChromeRow({
url,
displayUrl,
loading,
loadProgress,
canGoBack,
canGoForward,
refreshDisabled,
@@ -86,13 +107,7 @@ export function PreviewChromeRow({
const inputRef = useRef<HTMLInputElement | null>(null);
const [draft, setDraft] = useState(url);
const [inputFocused, setInputFocused] = useState(false);
useEffect(() => {
if (focusUrlNonce == null) return;
const node = inputRef.current;
if (!node) return;
node.focus();
}, [focusUrlNonce]);
useFocusPreviewUrlInput(inputRef, focusUrlNonce);
const submit = (event?: FormEvent | KeyboardEvent) => {
event?.preventDefault();
@@ -276,16 +291,7 @@ export function PreviewChromeRow({
) : null}
{trailingActions}
</form>
{loadProgress > 0 ? (
<div
aria-hidden
className="pointer-events-none absolute bottom-0 left-0 z-10 h-0.5 rounded-r-full bg-primary transition-all duration-150 ease-out"
style={{
width: `${loadProgress}%`,
boxShadow: "0 0 6px 1px var(--color-ring)",
}}
/>
) : null}
<PreviewLoadingProgress loading={loading} />
</div>
);
}
@@ -39,7 +39,6 @@ import { revealInFileExplorerLabel } from "./fileExplorerLabel";
import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
import { useLoadingProgress } from "./useLoadingProgress";
import { usePreviewSession } from "./usePreviewSession";
import { ZoomIndicator } from "./ZoomIndicator";
import { AgentBrowserCursor } from "./AgentBrowserCursor";
@@ -98,7 +97,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
const isUnreachable = navStatus._tag === "LoadFailed";
const showEmptyState = shouldShowPreviewEmptyState(snapshot);
const controller = desktopOverlay?.controller ?? "none";
const loadProgress = useLoadingProgress(loading);
const displayUrl =
url && environment && environmentHttpBaseUrl
? (formatPreviewUrl({
@@ -564,7 +562,6 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
url={url}
displayUrl={displayUrl}
loading={loading}
loadProgress={loadProgress}
canGoBack={canGoBack}
canGoForward={canGoForward}
refreshDisabled={refreshDisabled}
@@ -1,45 +0,0 @@
import { useEffect, useRef, useState } from "react";
const TICK_INTERVAL_MS = 120;
const FADE_OUT_DELAY_MS = 220;
const SEED_PERCENT = 4;
const ASYMPTOTE_PERCENT = 90;
const APPROACH_FACTOR = 0.08;
const MIN_INCREMENT = 0.5;
/**
* Indeterminate progress simulator for the preview chrome's loading bar.
* Animates 0 → 90% asymptotically while `loading` is true, snaps to 100%
* on release, then resets after a short pause.
*
* Uses a ref to thread the latest progress through interval ticks without
* needing `loading` to retrigger the effect, which sidesteps the stale-
* closure pitfalls of reading `progress` directly.
*/
export function useLoadingProgress(loading: boolean): number {
const [progress, setProgress] = useState(0);
const progressRef = useRef(0);
progressRef.current = progress;
useEffect(() => {
if (!loading) {
if (progressRef.current === 0) return;
setProgress(100);
const timer = window.setTimeout(() => setProgress(0), FADE_OUT_DELAY_MS);
return () => window.clearTimeout(timer);
}
setProgress((value) => (value > 0 && value < 95 ? value : SEED_PERCENT));
const interval = window.setInterval(() => {
const current = progressRef.current;
if (current >= ASYMPTOTE_PERCENT) return;
const remaining = ASYMPTOTE_PERCENT - current;
const increment = Math.max(MIN_INCREMENT, remaining * APPROACH_FACTOR);
setProgress(Math.min(ASYMPTOTE_PERCENT, current + increment));
}, TICK_INTERVAL_MS);
return () => window.clearInterval(interval);
}, [loading]);
return progress;
}
@@ -2,10 +2,13 @@ import { useNavigate } from "@tanstack/react-router";
import { useAtomValue } from "@effect/atom-react";
import type { ServerProvider } from "@t3tools/contracts";
import { CircleCheckIcon, DownloadIcon, LoaderIcon, TriangleAlertIcon, XIcon } from "lucide-react";
import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react";
import { useCallback, useEffect, useState, type CSSProperties } from "react";
import { primaryServerProvidersAtom } from "../../state/server";
import { getProviderUpdateSidebarPillView } from "../ProviderUpdateLaunchNotification.logic";
import {
getProviderUpdateSidebarPillView,
type ProviderUpdateSidebarPillView,
} from "../ProviderUpdateLaunchNotification.logic";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
const PROVIDER_UPDATE_PILL_STYLES = {
@@ -36,53 +39,32 @@ function latestProviderCheckedAt(
}
export function SidebarProviderUpdatePill() {
const providers = useAtomValue(primaryServerProvidersAtom);
if (providers.length === 0) {
return null;
}
return <SidebarProviderUpdatePillContent providers={providers} />;
}
function useProviderUpdatePillAutoDismiss(input: {
readonly dismissAfterVisibleMs: number | undefined;
readonly exitingKey: string | null;
readonly startExit: (key: string, dismissKey?: string) => void;
readonly viewKey: string | null;
}) {
useEffect(() => {
if (!input.dismissAfterVisibleMs || !input.viewKey) {
return;
}
if (input.exitingKey === input.viewKey) {
return;
}
const timeoutId = window.setTimeout(() => {
input.startExit(input.viewKey!, input.viewKey!);
}, input.dismissAfterVisibleMs);
return () => window.clearTimeout(timeoutId);
}, [input.dismissAfterVisibleMs, input.exitingKey, input.startExit, input.viewKey]);
}
function SidebarProviderUpdatePillContent(props: {
readonly providers: ReadonlyArray<ServerProvider>;
}) {
const navigate = useNavigate();
const providers = useAtomValue(primaryServerProvidersAtom);
const [dismissedKeys, setDismissedKeys] = useState<ReadonlySet<string>>(() => new Set());
const [renderedView, setRenderedView] = useState<ProviderUpdateSidebarPillView | null>(null);
const [pendingView, setPendingView] = useState<ProviderUpdateSidebarPillView | null>(null);
const [exitingKey, setExitingKey] = useState<string | null>(null);
const [visibleAfterIso] = useState(() => latestProviderCheckedAt(props.providers));
const dismissAfterExitKeyRef = useRef<string | null>(null);
const view = getProviderUpdateSidebarPillView(props.providers, {
...(visibleAfterIso !== undefined ? { visibleAfterIso } : {}),
const [dismissAfterExitKey, setDismissAfterExitKey] = useState<string | null>(null);
const [visibleAfterIso, setVisibleAfterIso] = useState<string | undefined>();
const effectiveVisibleAfterIso = visibleAfterIso ?? latestProviderCheckedAt(providers);
const view = getProviderUpdateSidebarPillView(providers, {
...(effectiveVisibleAfterIso !== undefined
? { visibleAfterIso: effectiveVisibleAfterIso }
: {}),
dismissedKeys,
});
useEffect(() => {
if (visibleAfterIso === undefined && effectiveVisibleAfterIso !== undefined) {
setVisibleAfterIso(effectiveVisibleAfterIso);
}
}, [effectiveVisibleAfterIso, visibleAfterIso]);
const openProviderSettings = useCallback(() => {
void navigate({ to: "/settings/providers" });
}, [navigate]);
const displayedView = view;
const displayedView = renderedView ?? view;
const dismissAfterVisibleMs = displayedView?.dismissAfterVisibleMs;
const viewKey = displayedView?.key ?? null;
const showDismissProgress =
@@ -91,22 +73,50 @@ function SidebarProviderUpdatePillContent(props: {
exitingKey !== viewKey;
const startExit = useCallback(
(key: string, dismissKey?: string) => {
(key: string, nextView: ProviderUpdateSidebarPillView | null, dismissKey?: string) => {
if (exitingKey === key) {
return;
}
dismissAfterExitKeyRef.current = dismissKey ?? null;
setPendingView(nextView);
setExitingKey(key);
setDismissAfterExitKey(dismissKey ?? null);
},
[exitingKey],
);
useProviderUpdatePillAutoDismiss({
dismissAfterVisibleMs,
exitingKey,
startExit,
viewKey,
});
useEffect(() => {
if (exitingKey !== null) {
return;
}
if (!renderedView) {
if (view) {
setRenderedView(view);
}
return;
}
if (!view) {
startExit(renderedView.key, null);
return;
}
if (view.key !== renderedView.key) {
startExit(renderedView.key, view);
return;
}
}, [exitingKey, renderedView, startExit, view]);
useEffect(() => {
if (!dismissAfterVisibleMs || !viewKey) {
return;
}
if (exitingKey === viewKey) {
return;
}
const timeoutId = window.setTimeout(() => {
startExit(viewKey, null, viewKey);
}, dismissAfterVisibleMs);
return () => window.clearTimeout(timeoutId);
}, [dismissAfterVisibleMs, exitingKey, startExit, viewKey]);
if (!displayedView) {
return null;
@@ -128,11 +138,13 @@ function SidebarProviderUpdatePillContent(props: {
if (!displayedView || exitingKey !== displayedView.key) {
return;
}
if (dismissAfterExitKeyRef.current === displayedView.key) {
if (dismissAfterExitKey === displayedView.key) {
setDismissedKeys((previous) => new Set(previous).add(displayedView.key));
}
setRenderedView(pendingView);
setPendingView(null);
setExitingKey(null);
dismissAfterExitKeyRef.current = null;
setDismissAfterExitKey(null);
}}
>
{showDismissProgress ? (
@@ -182,7 +194,7 @@ function SidebarProviderUpdatePillContent(props: {
type="button"
aria-label="Dismiss provider update notice"
className="relative z-[1] mr-1 inline-flex size-5 items-center justify-center rounded-md opacity-70 transition-opacity hover:opacity-100"
onClick={() => startExit(displayedView.key, displayedView.key)}
onClick={() => startExit(displayedView.key, null, displayedView.key)}
>
<XIcon className="size-3.5" />
</button>
+30
View File
@@ -891,3 +891,33 @@ label:has(> select#reasoning-effort) select {
.dark .model-picker-list::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.15);
}
@keyframes preview-loading-progress {
from {
transform: scaleX(0.04);
}
to {
transform: scaleX(0.9);
}
}
.preview-loading-progress-active {
opacity: 1;
animation: preview-loading-progress 10s cubic-bezier(0.1, 0.5, 0.2, 1) forwards;
}
.preview-loading-progress-idle {
opacity: 0;
transform: scaleX(1);
transition:
transform 150ms ease-out,
opacity 150ms ease-out 220ms;
}
@media (prefers-reduced-motion: reduce) {
.preview-loading-progress-active {
transform: scaleX(0.9);
animation: none;
}
}
@@ -64,6 +64,7 @@ function makeAgentActivityRows(
remove: () => Effect.void,
pruneTerminal: () => Effect.void,
listForUser: () => Effect.succeed([state]),
getForUserThread: () => Effect.succeed(state),
...overrides,
};
}
@@ -75,6 +75,15 @@ describe("AgentActivityRows", () => {
const listError = yield* rows.listForUser({ userId: "user-2" }).pipe(Effect.flip);
expect(listError).toMatchObject({ userId: "user-2", cause });
expect(listError.message).toBe("Failed to list agent activity state for user user-2.");
const getError = yield* rows
.getForUserThread({
userId: "user-2",
environmentId: "env-1",
threadId: "thread-1",
})
.pipe(Effect.flip);
expect(getError).toMatchObject({ userId: "user-2", cause });
}).pipe(
Effect.provide(
AgentActivityRows.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, failingDb))),
@@ -83,6 +83,11 @@ export class AgentActivityRows extends Context.Service<
ReadonlyArray<RelayAgentActivityState>,
AgentActivityRowListPersistenceError
>;
readonly getForUserThread: (input: {
readonly userId: string;
readonly environmentId: string;
readonly threadId: string;
}) => Effect.Effect<RelayAgentActivityState | null, AgentActivityRowListPersistenceError>;
}
>()("t3code-relay/agentActivity/AgentActivityRows") {}
@@ -241,6 +246,54 @@ export const make = Effect.gen(function* () {
),
);
}),
getForUserThread: Effect.fn("relay.agent_activity_rows.get_for_user_thread")(function* (input) {
return yield* db
.select({ stateJson: relayAgentActivityRows.stateJson })
.from(relayAgentActivityRows)
.innerJoin(
relayEnvironmentLinks,
and(
eq(relayEnvironmentLinks.environmentId, relayAgentActivityRows.environmentId),
eq(
relayEnvironmentLinks.environmentPublicKey,
relayAgentActivityRows.environmentPublicKey,
),
),
)
.where(
and(
eq(relayEnvironmentLinks.userId, input.userId),
isNull(relayEnvironmentLinks.revokedAt),
eq(relayAgentActivityRows.environmentId, input.environmentId),
eq(relayAgentActivityRows.threadId, input.threadId),
),
)
.orderBy(desc(relayAgentActivityRows.updatedAt))
.pipe(
Effect.flatMap((rows) =>
Effect.forEach(rows, (row) => encodeJsonValue(row.stateJson), {
concurrency: "unbounded",
}),
),
Effect.map((rows) => {
for (const row of rows) {
const decoded = decodeRelayAgentActivityStateJson(row);
if (Option.isSome(decoded)) {
return decoded.value;
}
}
return null;
}),
Effect.mapError(
(cause) =>
new AgentActivityRowListPersistenceError({
userId: input.userId,
cause,
}),
),
);
}),
});
});
@@ -5,7 +5,6 @@ import type {
import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
import { describe, expect, it } from "@effect/vitest";
import * as NodeCrypto from "node:crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
@@ -161,10 +160,13 @@ function makeLayer(input: {
>;
readonly currentTargets?: ReadonlyArray<LiveActivities.TargetRow>;
readonly config?: RelayConfiguration.RelayConfiguration["Service"];
// Live agent-activity rows returned by the delivery-time start recheck.
// Defaults to one freshly-updated running thread so queued starts stay
// deliverable in tests that don't care about the recheck.
// Live agent-activity rows returned by delivery-time state rechecks.
// Defaults to the fixture row so queued updates match unless a test is
// explicitly exercising stale-state behavior.
readonly activityStates?: ReadonlyArray<RelayAgentActivityState>;
// Current per-thread rows used to reject queued updates/notifications that
// have been superseded before APNs delivery.
readonly currentActivityStates?: ReadonlyArray<RelayAgentActivityState>;
readonly execute?: (
request: HttpClientRequest.HttpClientRequest,
) => Effect.Effect<HttpClientResponse.HttpClientResponse>;
@@ -182,9 +184,14 @@ function makeLayer(input: {
listForUser: () =>
input.activityStates !== undefined
? Effect.succeed([...input.activityStates])
: DateTime.now.pipe(
Effect.map((now) => [{ ...state, updatedAt: DateTime.formatIso(now) }]),
),
: Effect.succeed([state]),
getForUserThread: ({ environmentId, threadId }) =>
Effect.succeed(
(input.currentActivityStates ?? input.activityStates ?? [state]).find(
(current) =>
current.environmentId === environmentId && current.threadId === threadId,
) ?? null,
),
} satisfies AgentActivityRows.AgentActivityRows["Service"]),
Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, {
send: (body) =>
@@ -674,6 +681,8 @@ describe("ApnsDeliveries", () => {
environmentId: "env",
threadId: "thread",
deepLink: "/",
phase: "waiting_for_input",
updatedAt: state.updatedAt,
},
},
},
@@ -778,6 +787,30 @@ describe("ApnsDeliveries", () => {
},
);
it.effect("does not queue a push notification when a thread starts working", () => {
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
const queuedJobs: Array<SignedApnsDeliveryJob> = [];
return Effect.gen(function* () {
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
const result = yield* deliveries.sendForTarget({
target: {
...target,
push_token: "apns-device-token",
push_to_start_token: null,
activity_push_token: null,
remote_started_at: null,
},
aggregate,
nowMs: 5_000,
});
expect(result).toBeNull();
expect(queuedJobs).toEqual([]);
expect(attempts).toEqual([]);
}).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));
});
it.effect("queues bounded alert notification payloads", () => {
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
const queuedJobs: Array<SignedApnsDeliveryJob> = [];
@@ -1176,6 +1209,150 @@ describe("ApnsDeliveries", () => {
);
});
it.effect("skips a queued Done Live Activity update after the thread resumes working", () => {
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
let executeCount = 0;
const completedAt = "1970-01-01T00:00:01.000Z";
const completedAggregate: RelayAgentActivityAggregateState = {
...aggregate,
activeCount: 0,
updatedAt: completedAt,
activities: [
{
...aggregate.activities[0]!,
phase: "completed",
status: "Done",
updatedAt: completedAt,
},
],
};
const payload = makeApnsDeliveryJobPayload({
kind: "live_activity_update",
userId: target.user_id,
deviceId: target.device_id,
token: target.activity_push_token ?? "activity-token",
aggregate: completedAggregate,
alert: { title: "Thread", body: "Done: Project" },
createdAt: completedAt,
expiresAt: "1970-01-01T00:10:00.000Z",
jobId: "job-update-superseded-by-running",
});
const signed = signApnsDeliveryJob({
secret: config.apnsDeliveryJobSigningSecret,
payload,
});
const execute = (request: HttpClientRequest.HttpClientRequest) =>
Effect.sync(() => {
executeCount += 1;
return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
});
return Effect.gen(function* () {
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
const result = yield* deliveries.processSignedJob(signed);
expect(result).toMatchObject({
kind: "live_activity_update",
ok: true,
apnsStatus: null,
apnsReason: "Stale APNs delivery job skipped.",
});
expect(executeCount).toBe(0);
expect(attempts).toMatchObject([
{
sourceJobId: "job-update-superseded-by-running",
apnsReason: "Stale agent activity state skipped.",
},
]);
}).pipe(
Effect.provide(
makeLayer({
attempts,
activityStates: [
{
...state,
phase: "running",
headline: "Running",
updatedAt: "1970-01-01T00:00:02.000Z",
},
],
config: signingConfig,
execute,
}),
),
);
});
it.effect("skips a queued Done notification after the thread resumes working", () => {
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
let executeCount = 0;
const completedAt = "1970-01-01T00:00:01.000Z";
const payload = makeApnsDeliveryJobPayload({
kind: "push_notification",
userId: target.user_id,
deviceId: target.device_id,
token: "apns-device-token",
aggregate: null,
notification: {
title: "Thread",
body: "Done: Project",
environmentId: "env",
threadId: "thread",
deepLink: "/",
phase: "completed",
updatedAt: completedAt,
},
createdAt: completedAt,
expiresAt: "1970-01-01T00:10:00.000Z",
jobId: "job-push-superseded-by-running",
});
const signed = signApnsDeliveryJob({
secret: config.apnsDeliveryJobSigningSecret,
payload,
});
const execute = (request: HttpClientRequest.HttpClientRequest) =>
Effect.sync(() => {
executeCount += 1;
return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
});
return Effect.gen(function* () {
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
const result = yield* deliveries.processSignedJob(signed);
expect(result).toMatchObject({
kind: "push_notification",
ok: true,
apnsStatus: null,
apnsReason: "Stale APNs delivery job skipped.",
});
expect(executeCount).toBe(0);
expect(attempts).toMatchObject([
{
sourceJobId: "job-push-superseded-by-running",
apnsReason: "Stale agent activity state skipped.",
},
]);
}).pipe(
Effect.provide(
makeLayer({
attempts,
currentTargets: [{ ...target, push_token: "apns-device-token" }],
currentActivityStates: [
{
...state,
phase: "running",
headline: "Running",
updatedAt: "1970-01-01T00:00:02.000Z",
},
],
config: signingConfig,
execute,
}),
),
);
});
it.effect("retries signed queue jobs that are already claimed but not completed", () => {
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
let executeCount = 0;
@@ -1327,7 +1504,15 @@ describe("ApnsDeliveries", () => {
deviceId: target.device_id,
},
]);
}).pipe(Effect.provide(makeLayer({ attempts, clearedStarts })));
}).pipe(
Effect.provide(
makeLayer({
attempts,
clearedStarts,
activityStates: [{ ...state, updatedAt: "9999-01-01T00:00:00.000Z" }],
}),
),
);
});
it.effect("invalidates dead push-to-start tokens after permanent APNs start failures", () => {
@@ -1373,7 +1558,15 @@ describe("ApnsDeliveries", () => {
},
]);
}).pipe(
Effect.provide(makeLayer({ attempts, invalidatedTokens, config: signingConfig, execute })),
Effect.provide(
makeLayer({
attempts,
invalidatedTokens,
activityStates: [{ ...state, updatedAt: "9999-01-01T00:00:00.000Z" }],
config: signingConfig,
execute,
}),
),
);
});
@@ -369,6 +369,8 @@ function notificationForAggregate(input: {
environmentId: activity.environmentId,
threadId: activity.threadId,
deepLink: activity.deepLink,
phase: activity.phase,
updatedAt: activity.updatedAt,
};
}
@@ -722,6 +724,87 @@ export const make = Effect.gen(function* () {
);
});
const stateIdentityIsCurrent = Effect.fnUntraced(function* (input: {
readonly userId: string;
readonly environmentId: string;
readonly threadId: string;
readonly phase: RelayAgentActivityAggregateState["activities"][number]["phase"];
readonly updatedAt: string;
}) {
return yield* activityRows
.getForUserThread({
userId: input.userId,
environmentId: input.environmentId,
threadId: input.threadId,
})
.pipe(
Effect.map(
(current) =>
current !== null &&
current.phase === input.phase &&
current.updatedAt === input.updatedAt,
),
// A transient persistence failure must not permanently discard a
// legitimate alert. Fail open and let the signed job's retry/dedupe
// protections handle transport failures as usual.
Effect.catchCause((cause) =>
Effect.logWarning("agent-activity state recheck failed; allowing queued delivery", {
cause,
environmentId: input.environmentId,
threadId: input.threadId,
}).pipe(Effect.as(true)),
),
);
});
const aggregateRowsAreCurrent = Effect.fnUntraced(function* (input: {
readonly userId: string;
readonly aggregate: RelayAgentActivityAggregateState;
}) {
return yield* activityRows.listForUser({ userId: input.userId }).pipe(
Effect.map((currentStates) => {
const currentByThread = new Map(
currentStates.map((current) => [
`${current.environmentId}\u0000${current.threadId}`,
current,
]),
);
return input.aggregate.activities.every((row) => {
const current = currentByThread.get(`${row.environmentId}\u0000${row.threadId}`);
return (
current !== undefined &&
current.phase === row.phase &&
current.updatedAt === row.updatedAt
);
});
}),
Effect.catchCause((cause) =>
Effect.logWarning("agent-activity aggregate recheck failed; allowing queued delivery", {
cause,
userId: input.userId,
}).pipe(Effect.as(true)),
),
);
});
const notificationStateIsCurrent = Effect.fnUntraced(function* (input: {
readonly userId: string;
readonly notification: ApnsNotificationPayload;
}) {
// Jobs from older relay versions do not carry a state identity. Preserve
// backwards compatibility and only revalidate newly queued jobs.
if (input.notification.phase === undefined || input.notification.updatedAt === undefined) {
return true;
}
return yield* stateIdentityIsCurrent({
userId: input.userId,
environmentId: input.notification.environmentId,
threadId: input.notification.threadId,
phase: input.notification.phase,
updatedAt: input.notification.updatedAt,
});
});
const isCurrentSignedJobToken = Effect.fnUntraced(function* (input: {
readonly target: LiveActivityDeliveryTarget;
readonly kind: RelayDeliveryKind;
@@ -791,6 +874,20 @@ export const make = Effect.gen(function* () {
});
return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
}
if (
input.kind !== "live_activity_start" &&
aggregate !== null &&
!(yield* aggregateRowsAreCurrent({
userId: input.target.user_id,
aggregate,
}))
) {
yield* attempts.completeSourceJob({
sourceJobId: input.sourceJobId,
apnsReason: "Stale agent activity state skipped.",
});
return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });
}
}
if (
input.kind === "live_activity_start" &&
@@ -930,6 +1027,21 @@ export const make = Effect.gen(function* () {
kind: "push_notification",
});
}
if (
!(yield* notificationStateIsCurrent({
userId: input.target.user_id,
notification,
}))
) {
yield* attempts.completeSourceJob({
sourceJobId: input.sourceJobId,
apnsReason: "Stale agent activity state skipped.",
});
return staleJobResult({
deviceId: input.target.device_id,
kind: "push_notification",
});
}
}
const result = yield* apns
.sendPushNotificationRequest({
@@ -86,6 +86,7 @@ function makeAgentActivityRows(
};
return Effect.succeed([activeState]);
},
getForUserThread: () => Effect.succeed(null),
...overrides,
};
}
@@ -1,6 +1,10 @@
import * as NodeCrypto from "node:crypto";
import { RelayAgentActivityAggregateState, type RelayDeliveryKind } from "@t3tools/contracts/relay";
import {
RelayAgentActivityAggregateState,
RelayAgentAwarenessPhase,
type RelayDeliveryKind,
} from "@t3tools/contracts/relay";
import { stableStringify } from "@t3tools/shared/relaySigning";
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
@@ -38,6 +42,11 @@ export const ApnsNotificationPayload = Schema.Struct({
environmentId: Schema.String,
threadId: Schema.String,
deepLink: Schema.String,
// Optional so delivery jobs queued by older relay builds still decode.
// New jobs use these fields to avoid delivering a stale Done/attention
// notification after the thread has moved to another phase.
phase: Schema.optional(RelayAgentAwarenessPhase),
updatedAt: Schema.optional(Schema.String),
});
export type ApnsNotificationPayload = typeof ApnsNotificationPayload.Type;
+4
View File
@@ -3,6 +3,10 @@
"private": true,
"type": "module",
"exports": {
"./projectFavicon": {
"types": "./src/projectFavicon.ts",
"import": "./src/projectFavicon.ts"
},
"./model": {
"types": "./src/model.ts",
"import": "./src/model.ts"
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vite-plus/test";
import { isProjectFaviconFallbackUrl, PROJECT_FAVICON_FALLBACK_MARKER } from "./projectFavicon.ts";
describe("project favicon", () => {
it("identifies fallback asset URLs by their dedicated filename", () => {
expect(
isProjectFaviconFallbackUrl(
`https://environment.example/api/assets/signed-token/${PROJECT_FAVICON_FALLBACK_MARKER}`,
),
).toBe(true);
expect(
isProjectFaviconFallbackUrl(`/api/assets/signed-token/${PROJECT_FAVICON_FALLBACK_MARKER}`),
).toBe(true);
});
it("does not mistake real favicons or query parameters for fallbacks", () => {
expect(
isProjectFaviconFallbackUrl("https://environment.example/api/assets/token/favicon.svg"),
).toBe(false);
expect(
isProjectFaviconFallbackUrl(
`https://environment.example/api/assets/token/favicon.svg?name=${PROJECT_FAVICON_FALLBACK_MARKER}`,
),
).toBe(false);
expect(isProjectFaviconFallbackUrl(null)).toBe(false);
});
});
+12
View File
@@ -0,0 +1,12 @@
export const PROJECT_FAVICON_FALLBACK_MARKER = "project-favicon-missing";
export function isProjectFaviconFallbackUrl(url: string | null | undefined): boolean {
if (!url) return false;
try {
const pathname = new URL(url, "https://t3.invalid").pathname;
return pathname.slice(pathname.lastIndexOf("/") + 1) === PROJECT_FAVICON_FALLBACK_MARKER;
} catch {
return false;
}
}