Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { beforeEach, vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Effect from "effect/Effect";
import type { EnvironmentId } from "@t3tools/contracts";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
Expand Down Expand Up @@ -40,6 +42,16 @@ vi.mock("./remoteRegistration", () => ({
updateAgentAwarenessRegistrationPreferences: vi.fn(() => Effect.void),
}));

const updateEnvironment = vi.fn<
(
id: EnvironmentId,
enabled: boolean,
) => Effect.Effect<
"updated" | "unlinked" | "unsupported" | "disconnected",
CloudEnvironmentLinkError
>
>(() => Effect.succeed("updated"));

const connection: SavedRemoteConnection = {
environmentId: "env-1" as EnvironmentId,
environmentLabel: "Desktop",
Expand Down Expand Up @@ -75,54 +87,93 @@ describe("liveActivityPreferences", () => {
vi.clearAllMocks();
});

it.effect("restores relay preferences when an environment update fails", () => {
vi.mocked(linkEnvironmentToCloudWithPreference).mockImplementationOnce(() =>
it.effect("restores only the device preference when an environment update fails", () => {
const otherConnection = { ...connection, environmentId: "env-2" as EnvironmentId };
updateEnvironment.mockImplementationOnce(() =>
Effect.fail(new CloudEnvironmentLinkError({ message: "environment update failed" })),
);

return Effect.gen(function* () {
const exit = yield* Effect.exit(
setLiveActivityUpdatesEnabled({
updateEnvironment,
enabled: false,
previousEnabled: true,
clerkToken: "clerk-token",
connections: [connection],
canConfigureEnvironment: () => true,
connections: [connection, otherConnection],
canConfigureEnvironment: () => false,
canUpdateEnvironment: () => true,
}),
);

expect(exit._tag).toBe("Failure");
expect(Exit.findErrorOption(exit)).toEqual(
Option.some(
expect.objectContaining({ updatedEnvironments: [otherConnection.environmentLabel] }),
),
);
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(1, {
liveActivitiesEnabled: false,
});
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(2, {
liveActivitiesEnabled: true,
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenNthCalledWith(1, {
clerkToken: "clerk-token",
connection,
expect(updateEnvironment).toHaveBeenCalledTimes(2);
expect(updateEnvironment).toHaveBeenCalledWith(connection.environmentId, false);
expect(updateEnvironment).toHaveBeenCalledWith(otherConnection.environmentId, false);
expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
}).pipe(Effect.provide(layerTest));
});

it.effect("reports a relay preference committed before environment configuration fails", () => {
const failure = new CloudEnvironmentLinkError({
message: "environment configuration failed",
relayLinkCommitted: true,
});
updateEnvironment.mockReturnValueOnce(Effect.succeed("unlinked"));
vi.mocked(linkEnvironmentToCloudWithPreference).mockReturnValueOnce(Effect.fail(failure));

return Effect.gen(function* () {
const exit = yield* Effect.exit(
setLiveActivityUpdatesEnabled({
updateEnvironment,
enabled: true,
previousEnabled: false,
clerkToken: "clerk-token",
connections: [connection],
canConfigureEnvironment: () => true,
canUpdateEnvironment: () => true,
}),
);

expect(Exit.findErrorOption(exit)).toEqual(
Option.some(
expect.objectContaining({
updatedEnvironments: [connection.environmentLabel],
cause: failure,
}),
),
);
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenLastCalledWith({
liveActivitiesEnabled: false,
});
expect(linkEnvironmentToCloudWithPreference).toHaveBeenNthCalledWith(2, {
clerkToken: "clerk-token",
connection,
liveActivitiesEnabled: true,
});
}).pipe(Effect.provide(layerTest));
});

it.effect("only re-links environments with relay access when enabling updates", () => {
it.effect("only creates missing links when the session can configure Connect", () => {
updateEnvironment.mockReturnValueOnce(Effect.succeed("unlinked" as const));
const readOnlyConnection: SavedRemoteConnection = {
...connection,
environmentId: "read-only" as EnvironmentId,
};

return Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
updateEnvironment,
enabled: true,
previousEnabled: false,
clerkToken: "clerk-token",
connections: [readOnlyConnection, connection],
canUpdateEnvironment: (environmentId) => environmentId === connection.environmentId,
canConfigureEnvironment: (environmentId) => environmentId === connection.environmentId,
});

Expand All @@ -137,6 +188,28 @@ describe("liveActivityPreferences", () => {
}).pipe(Effect.provide(layerTest));
});

it.effect("reports older environments whose preferences could not be updated", () =>
Effect.gen(function* () {
const dpopConnection: SavedRemoteConnection = {
...connection,
bearerToken: null,
authenticationMethod: "dpop",
};
updateEnvironment.mockReturnValueOnce(Effect.succeed("unsupported"));
const partial = yield* setLiveActivityUpdatesEnabled({
updateEnvironment,
enabled: false,
previousEnabled: true,
clerkToken: "clerk-token",
connections: [dpopConnection],
canConfigureEnvironment: () => false,
canUpdateEnvironment: () => true,
});
expect(partial).toBe(true);
expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
}).pipe(Effect.provide(layerTest)),
);

it.effect("checks current relay access after updating the device registration", () => {
let canConfigureEnvironment = true;
vi.mocked(updateAgentAwarenessRegistrationPreferences).mockImplementationOnce(() =>
Expand All @@ -147,14 +220,17 @@ describe("liveActivityPreferences", () => {

return Effect.gen(function* () {
yield* setLiveActivityUpdatesEnabled({
updateEnvironment,
enabled: false,
previousEnabled: true,
clerkToken: "clerk-token",
connections: [connection],
canConfigureEnvironment: () => canConfigureEnvironment,
canUpdateEnvironment: () => canConfigureEnvironment,
});

expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();
expect(updateEnvironment).not.toHaveBeenCalled();
expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledTimes(1);
}).pipe(Effect.provide(layerTest));
});
Expand Down
107 changes: 69 additions & 38 deletions apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,63 @@
import * as Effect from "effect/Effect";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import type { EnvironmentId } from "@t3tools/contracts";

import type { SavedRemoteConnection } from "../../lib/connection";
import { linkEnvironmentToCloudWithPreference } from "../cloud/linkEnvironment";
import {
linkEnvironmentToCloudWithPreference,
type CloudEnvironmentLinkError,
} from "../cloud/linkEnvironment";
import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration";

export class LiveActivityEnvironmentUpdateError extends Schema.TaggedError<LiveActivityEnvironmentUpdateError>()(
"LiveActivityEnvironmentUpdateError",
{
updatedEnvironments: Schema.Array(Schema.String),
cause: Schema.Defect(),
},
) {}

export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEnabled")(
function* (input: {
readonly enabled: boolean;
readonly previousEnabled: boolean;
readonly clerkToken: string | null;
readonly connections: ReadonlyArray<SavedRemoteConnection>;
readonly updateEnvironment: (
environmentId: EnvironmentId,
enabled: boolean,
) => Effect.Effect<
"updated" | "unlinked" | "unsupported" | "disconnected",
CloudEnvironmentLinkError
>;
readonly canUpdateEnvironment: (environmentId: EnvironmentId) => boolean;
readonly canConfigureEnvironment: (environmentId: EnvironmentId) => boolean;
}) {
const linkedConnections = input.connections.filter(
(connection) => connection.bearerToken !== null,
);

const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* (
connection: SavedRemoteConnection,
enabled: boolean,
clerkToken: string,
clerkToken: string | null,
) {
if (!input.canConfigureEnvironment(connection.environmentId)) return;
const result = input.canUpdateEnvironment(connection.environmentId)
? yield* input.updateEnvironment(connection.environmentId, enabled)
: "unlinked";
if (result === "updated" || result === "disconnected") return result;
if (
!enabled ||
!clerkToken ||
!connection.bearerToken ||
!input.canConfigureEnvironment(connection.environmentId)
) {
return result;
}

yield* linkEnvironmentToCloudWithPreference({
clerkToken,
connection,
liveActivitiesEnabled: enabled,
});
return "updated" as const;
});

const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) {
Expand All @@ -37,44 +66,46 @@ export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEn
});

const clerkToken = input.clerkToken;
if (!clerkToken) return;

yield* Effect.forEach(
linkedConnections,
(connection) => updateEnvironmentPreference(connection, enabled, clerkToken),
{ concurrency: "unbounded" },
);
});

const restoreRelayPreference = Effect.fn("restoreRelayPreference")(function* () {
yield* updateAgentAwarenessRegistrationPreferences({
liveActivitiesEnabled: input.previousEnabled,
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Could not restore Live Activity device preference.", cause),
),
);

const clerkToken = input.clerkToken;
if (!clerkToken) return;
if (!clerkToken) return false;

yield* Effect.forEach(
linkedConnections,
const results = yield* Effect.forEach(
input.connections,
(connection) =>
updateEnvironmentPreference(connection, input.previousEnabled, clerkToken).pipe(
Effect.catchCause((cause) =>
Effect.logWarning(
`Could not restore Live Activity preference for environment ${connection.environmentId}.`,
cause,
),
),
updateEnvironmentPreference(connection, enabled, clerkToken).pipe(
Effect.result,
Effect.map((result) => ({ connection, result })),
),
{ concurrency: "unbounded" },
);
const failure = results.find(({ result }) => Result.isFailure(result));
if (failure && Result.isFailure(failure.result)) {
const updatedEnvironments = results.flatMap(({ connection, result }) => {
const changed = Result.isSuccess(result)
? result.success === "updated"
: result.failure.relayLinkCommitted === true;
return changed ? [connection.environmentLabel] : [];
});
if (updatedEnvironments.length === 0) return yield* failure.result.failure;
return yield* new LiveActivityEnvironmentUpdateError({
updatedEnvironments,
cause: failure.result.failure,
});
}
return results.some(
({ result }) => Result.isSuccess(result) && result.success === "unsupported",
);
});

yield* updateRelayPreference(input.enabled).pipe(
Effect.onError(() => restoreRelayPreference()),
return yield* updateRelayPreference(input.enabled).pipe(
Effect.onError(() =>
updateAgentAwarenessRegistrationPreferences({
liveActivitiesEnabled: input.previousEnabled,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("Could not restore Live Activity device preference.", cause),
),
),
),
);
},
);
42 changes: 40 additions & 2 deletions apps/mobile/src/features/cloud/linkEnvironment.test.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
import { beforeEach, vi } from "vite-plus/test";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as SubscriptionRef from "effect/SubscriptionRef";
import * as Layer from "effect/Layer";
import { EnvironmentId } from "@t3tools/contracts";
import { RelayMobileClientId } from "@t3tools/contracts/relay";
import {
EnvironmentSupervisor,
AVAILABLE_CONNECTION_STATE,
PrimaryConnectionTarget,
type PreparedConnection,
} from "@t3tools/client-runtime/connection";
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc";
import { layerRemoteHttpClient, type RpcSession } from "@t3tools/client-runtime/rpc";
import { HttpClient } from "effect/http";

import * as MobileStorage from "../../persistence/mobile-storage";

import { linkEnvironmentToCloudWithPreference } from "./linkEnvironment";
import {
linkEnvironmentToCloudWithPreference,
updateLinkedEnvironmentLiveActivityPreference,
} from "./linkEnvironment";

vi.mock("expo-constants", () => ({
default: {
Expand Down Expand Up @@ -146,6 +157,33 @@ describe("mobile cloud link environment client", () => {
createProofMock.mockClear();
});

it.effect("skips Live Activity updates when the environment has no prepared connection", () =>
Effect.gen(function* () {
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: new PrimaryConnectionTarget({
environmentId: savedConnection.environmentId,
label: savedConnection.environmentLabel,
httpBaseUrl: savedConnection.httpBaseUrl,
wsBaseUrl: savedConnection.wsBaseUrl,
}),
state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
});
const result = yield* updateLinkedEnvironmentLiveActivityPreference(true).pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("unexpected HTTP request")),
),
);
expect(result).toBe("disconnected");
}),
);

it.effect(
"rejects relay link credentials for a different environment before persisting relay config",
() =>
Expand Down
Loading
Loading