Compare commits

..
22 changed files with 571 additions and 255 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,4 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -42,7 +42,7 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
);
assert.deepEqual(rows, [
expect(rows).toEqual([
{
pid: 10,
ppid: 1,
@@ -126,21 +126,15 @@ describe("ProcessDiagnostics", () => {
],
});
assert.equal(diagnostics.serverPid, 100);
assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
assert.equal(diagnostics.processCount, 2);
assert.equal(diagnostics.totalRssBytes, 6_000);
assert.equal(diagnostics.totalCpuPercent, 4.75);
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102],
);
assert.deepEqual(
diagnostics.processes.map((process) => process.depth),
[0, 1],
);
assert.equal(Option.getOrNull(diagnostics.processes[0]!.pgid), 100);
assert.deepEqual(diagnostics.processes[0]?.childPids, [102]);
expect(diagnostics.serverPid).toBe(100);
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
expect(diagnostics.processCount).toBe(2);
expect(diagnostics.totalRssBytes).toBe(6_000);
expect(diagnostics.totalCpuPercent).toBe(4.75);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
}),
);
@@ -183,10 +177,7 @@ describe("ProcessDiagnostics", () => {
],
});
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102, 103],
);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
}),
);
@@ -219,11 +210,8 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[4242],
);
assert.deepEqual(commands, [
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
expect(commands).toEqual([
{
command: "ps",
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
@@ -253,7 +241,7 @@ describe("ProcessDiagnostics", () => {
Effect.flip,
);
assert.deepInclude(error, {
expect(error).toMatchObject({
_tag: "ProcessDiagnosticsQueryFailedError",
command: "ps",
argCount: 2,
@@ -264,8 +252,7 @@ describe("ProcessDiagnostics", () => {
stdoutTruncated: false,
stderrTruncated: false,
});
assert.equal(
error.message,
expect(error.message).toBe(
`Process diagnostics query 'ps' failed with exit code 17 in '${process.cwd()}'.`,
);
}),
@@ -293,7 +280,7 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepEqual(result, {
expect(result).toEqual({
pid: 4242,
signal: "SIGINT",
signaled: false,
@@ -301,85 +288,4 @@ describe("ProcessDiagnostics", () => {
});
}),
);
it.effect("parses Windows JSON process rows through Schema", () =>
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
commands.push({ command: childProcess.command, args: childProcess.args });
return Effect.succeed(
mockHandle({
stdout: JSON.stringify([
{
ProcessId: 4242,
ParentProcessId: process.pid,
Name: "agent.exe",
CommandLine: "agent.exe --flag",
Status: "Running",
WorkingSetSize: 4096,
PercentProcessorTime: 12.5,
},
{
ProcessId: 4243,
ParentProcessId: 4242,
Name: "fallback.exe",
CommandLine: null,
Status: null,
WorkingSetSize: null,
PercentProcessorTime: null,
},
{
ProcessId: "not-a-number",
ParentProcessId: process.pid,
Name: "ignored.exe",
CommandLine: "ignored.exe",
},
]),
}),
);
}),
);
const rows = yield* ProcessDiagnostics.readProcessRows.pipe(
Effect.provide(spawnerLayer),
Effect.provideService(HostProcessPlatform, "win32"),
);
assert.deepEqual(rows, [
{
pid: 4242,
ppid: process.pid,
pgid: null,
status: "Running",
cpuPercent: 12.5,
rssBytes: 4096,
elapsed: "",
command: "agent.exe --flag",
},
{
pid: 4243,
ppid: 4242,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "fallback.exe",
},
]);
assert.equal(commands[0]?.command, "powershell.exe");
assert.deepEqual(commands[0]?.args.slice(0, 3), [
"-NoProfile",
"-NonInteractive",
"-Command",
]);
}),
);
});
@@ -32,19 +32,6 @@ const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
const WindowsProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
Name: Schema.optional(Schema.NullOr(Schema.String)),
Status: Schema.optional(Schema.NullOr(Schema.String)),
WorkingSetSize: Schema.optional(Schema.NullOr(Schema.Number)),
PercentProcessorTime: Schema.optional(Schema.NullOr(Schema.Number)),
});
type WindowsProcessRecord = typeof WindowsProcessRecord.Type;
const decodeWindowsProcessJson = Schema.decodeOption(Schema.UnknownFromJsonString);
const decodeWindowsProcessRecord = Schema.decodeUnknownOption(WindowsProcessRecord);
export class ProcessDiagnostics extends Context.Service<
ProcessDiagnostics,
{
@@ -134,47 +121,19 @@ const ProcessDiagnosticsError = Schema.Union([
type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
function parsePositiveInt(value: string): Option.Option<number> {
function parsePositiveInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed > 0 ? Option.some(parsed) : Option.none();
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
}
function parseNonNegativeInt(value: string): Option.Option<number> {
function parseNonNegativeInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed >= 0 ? Option.some(parsed) : Option.none();
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
}
function parseInteger(value: string): Option.Option<number> {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) ? Option.some(parsed) : Option.none();
}
function parseNumber(value: string): Option.Option<number> {
function parseNumber(value: string): number | null {
const parsed = Number.parseFloat(value);
return Number.isFinite(parsed) ? Option.some(parsed) : Option.none();
}
function positiveInteger(value: number): Option.Option<number> {
return Number.isInteger(value) && value > 0 ? Option.some(value) : Option.none();
}
function nonNegativeInteger(value: number): Option.Option<number> {
return Number.isInteger(value) && value >= 0 ? Option.some(value) : Option.none();
}
function trimNonEmpty(value: string | null | undefined): Option.Option<string> {
return Option.fromNullishOr(value).pipe(
Option.map((text) => text.trim()),
Option.filter((text) => text.length > 0),
);
}
function finiteNonNegativeNumberOrZero(value: number | null | undefined): number {
return Option.fromNullishOr(value).pipe(
Option.filter(Number.isFinite),
Option.map((number) => Math.max(0, number)),
Option.getOrElse(() => 0),
);
return Number.isFinite(parsed) ? parsed : null;
}
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
@@ -209,24 +168,31 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
continue;
}
const parsed = Option.all({
pid: parsePositiveInt(pidText),
ppid: parseNonNegativeInt(ppidText),
pgid: parseInteger(pgidText),
cpuPercent: parseNumber(cpuText),
rssKiB: parseNonNegativeInt(rssText),
});
if (Option.isNone(parsed) || !status || !elapsed || !command) {
const pid = parsePositiveInt(pidText);
const ppid = parseNonNegativeInt(ppidText);
const pgid = Number.parseInt(pgidText, 10);
const cpuPercent = parseNumber(cpuText);
const rssKiB = parseNonNegativeInt(rssText);
if (
pid === null ||
ppid === null ||
!Number.isInteger(pgid) ||
cpuPercent === null ||
rssKiB === null ||
!status ||
!elapsed ||
!command
) {
continue;
}
rows.push({
pid: parsed.value.pid,
ppid: parsed.value.ppid,
pgid: parsed.value.pgid,
pid,
ppid,
pgid,
status,
cpuPercent: parsed.value.cpuPercent,
rssBytes: parsed.value.rssKiB * 1024,
cpuPercent,
rssBytes: rssKiB * 1024,
elapsed,
command,
});
@@ -235,38 +201,51 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function normalizeWindowsProcessRow(value: unknown): Option.Option<ProcessRow> {
return Option.gen(function* () {
const record: WindowsProcessRecord = yield* decodeWindowsProcessRecord(value);
const pid = yield* positiveInteger(record.ProcessId);
const ppid = yield* nonNegativeInteger(record.ParentProcessId);
const command = yield* Option.firstSomeOf([
trimNonEmpty(record.CommandLine),
trimNonEmpty(record.Name),
]);
const status = Option.getOrElse(trimNonEmpty(record.Status), () => "Live");
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
? record.CommandLine
: typeof record.Name === "string"
? record.Name
: null;
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
return {
pid,
ppid,
pgid: null,
status,
cpuPercent: finiteNonNegativeNumberOrZero(record.PercentProcessorTime),
rssBytes: Math.round(finiteNonNegativeNumberOrZero(record.WorkingSetSize)),
elapsed: "",
command,
};
});
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
const parsed = decodeWindowsProcessJson(output);
if (Option.isNone(parsed)) return [];
const records = Array.isArray(parsed.value) ? parsed.value : [parsed.value];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return Option.isSome(row) ? [row.value] : [];
});
if (output.trim().length === 0) return [];
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
}
}
export function buildDescendantEntries(
+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;
}
}