Compare commits

...
20 changed files with 487 additions and 56 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,
+11 -7
View File
@@ -74,7 +74,9 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeout: Duration.millis(100),
});
assertSome(payload, {
mode: "desktop",
});
@@ -100,7 +102,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
try {
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
timeout: Duration.millis(100),
}).pipe(Effect.provideService(HostProcessPlatform, "linux"));
assertSome(payload, {
mode: "desktop",
@@ -125,7 +127,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
openSyncInterceptor.errorCode = "EIO";
try {
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
timeout: Duration.millis(100),
}).pipe(Effect.provideService(HostProcessPlatform, "linux"), Effect.flip);
assert.instanceOf(error, BootstrapInputStreamOpenError);
@@ -149,7 +151,9 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
const fd = NodeFS.openSync("/dev/null", "r");
NodeFS.closeSync(fd);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeout: Duration.millis(100),
});
assertNone(payload);
}),
);
@@ -164,7 +168,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
fstatSyncInterceptor.failFd = fd;
try {
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
timeout: Duration.millis(100),
}).pipe(Effect.flip);
assert.instanceOf(error, BootstrapFdStatError);
@@ -188,7 +192,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
(fd) => Effect.sync(() => NodeFS.closeSync(fd)),
);
const error = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
timeout: Duration.millis(100),
}).pipe(Effect.flip);
assert.instanceOf(error, BootstrapEnvelopeDecodeError);
@@ -227,7 +231,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
);
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
timeout: Duration.millis(100),
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
+4 -3
View File
@@ -4,6 +4,7 @@ import * as NodeNet from "node:net";
import * as NodeReadline from "node:readline";
import type * as NodeStream from "node:stream";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
@@ -75,7 +76,7 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
schema: Schema.Codec<A, I>,
fd: number,
options?: {
timeoutMs?: number;
readonly timeout?: Duration.Duration;
},
): Effect.fn.Return<Option.Option<A>, BootstrapError> {
const fdReady = yield* isFdReady(fd);
@@ -83,7 +84,7 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
const stream = yield* makeBootstrapInputStream(fd);
const timeoutMs = options?.timeoutMs ?? 1000;
const timeout = options?.timeout ?? Duration.seconds(1);
return yield* Effect.callback<
Option.Option<A>,
@@ -142,7 +143,7 @@ export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function
input.once("close", handleClose);
return Effect.sync(cleanup);
}).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
}).pipe(Effect.timeoutOption(timeout), Effect.map(Option.flatten));
});
const isUnavailableBootstrapFdError = Predicate.compose(
+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} />;
}
@@ -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"
+9 -6
View File
@@ -1,15 +1,18 @@
import * as NodeNet from "node:net";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Context from "effect/Context";
import * as Predicate from "effect/Predicate";
import * as Schema from "effect/Schema";
export class NetError extends Data.TaggedError("NetError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export class NetError extends Schema.TaggedErrorClass<NetError>()("NetError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect()),
}) {}
const LISTENER_PROBE_TIMEOUT = Duration.millis(250);
const isErrnoExceptionWithCode = (
cause: unknown,
@@ -110,7 +113,7 @@ export const make = () => {
};
socket.unref();
socket.setTimeout(250);
socket.setTimeout(Duration.toMillis(LISTENER_PROBE_TIMEOUT));
socket.once("connect", () => {
settle(true);
});
@@ -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;
}
}