Skip to content

Commit 1af5979

Browse files
Merge remote-tracking branch 'origin/main' into pr-32913
2 parents ecb0db2 + f12bb62 commit 1af5979

15 files changed

Lines changed: 631 additions & 36 deletions

‎apps/mobile/src/components/ui/FilePreviewSession.test.tsx‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
import { act, useState } from "react";
22
import { createRoot } from "react-dom/client";
33
import { expect, it, vi } from "vite-plus/test";
4-
import { EnvironmentId, SOURCE_CONTROL_MEDIA_ASSET } from "@t3tools/contracts";
4+
import {
5+
AssetWorkspaceAssetNotFoundError,
6+
EnvironmentId,
7+
SOURCE_CONTROL_MEDIA_ASSET,
8+
ThreadId,
9+
} from "@t3tools/contracts";
510

611
const harness = vi.hoisted(() => ({
7-
refreshAssetUrl: vi.fn<(environmentId: string, resource: { url: string }) => Promise<string>>(),
12+
refreshAssetUrl:
13+
vi.fn<(environmentId: string, resource: { url: string }) => Promise<string | null>>(),
814
alert: vi.fn(),
915
previews: [] as unknown[],
1016
mounts: 0,
@@ -144,3 +150,24 @@ it("closes the preview when the selected image cannot be resolved", async () =>
144150
expect(preview.onRequestClose).toHaveBeenCalledOnce();
145151
expect(harness.alert).toHaveBeenCalledOnce();
146152
});
153+
154+
it("names the checked path when the server cannot find the file", async () => {
155+
const resource = {
156+
_tag: "media-file" as const,
157+
threadId: ThreadId.make("thread"),
158+
path: "v2/extended/duo-color-3-extended-FINAL.png",
159+
};
160+
const checkedPath = "/repo/v2/extended/duo-color-3-extended-FINAL.png";
161+
harness.refreshAssetUrl.mockRejectedValue(
162+
new AssetWorkspaceAssetNotFoundError({ resource, checkedPath }),
163+
);
164+
const selected: FilePreviewItem = { kind: "image", environmentId, resource };
165+
await using preview = await openGallery(selected, [selected], false);
166+
167+
expect(preview.onRequestClose).toHaveBeenCalledOnce();
168+
expect(harness.alert).toHaveBeenCalledWith(
169+
"Could not open preview",
170+
expect.stringContaining(checkedPath),
171+
);
172+
expect(harness.alert.mock.calls[0]?.[1]).not.toMatch(/reconnect/i);
173+
});

‎apps/mobile/src/components/ui/FilePreviewSession.tsx‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { AssetWorkspaceAssetNotFoundError } from "@t3tools/contracts";
12
import * as Schema from "effect/Schema";
23
import * as Dialog from "./Dialog";
34
import { useContext, useEffect, useEffectEvent, useState, type ComponentType } from "react";
@@ -36,6 +37,15 @@ class PreviewResolutionError extends Schema.TaggedError<PreviewResolutionError>(
3637
}
3738

3839
const isPreviewResolutionError = Schema.is(PreviewResolutionError);
40+
const isAssetNotFoundError = Schema.is(AssetWorkspaceAssetNotFoundError);
41+
42+
function remotePreviewFailureMessage(error: unknown): string {
43+
if (!isAssetNotFoundError(error)) {
44+
return "Reconnect to this environment and try again. The file may have been moved or deleted.";
45+
}
46+
const path = error.checkedPath ?? ("path" in error.resource ? error.resource.path : undefined);
47+
return path ? `The file was not found at ${path}.` : error.message;
48+
}
3949

4050
interface ResolvedPreviewUri {
4151
readonly uri: string;
@@ -64,8 +74,7 @@ async function resolvePreviewUri(
6474
.catch((error: unknown) => {
6575
throw new PreviewResolutionError({
6676
cause: error,
67-
fallbackMessage:
68-
"Reconnect to this environment and try again. The file may have been moved or deleted.",
77+
fallbackMessage: remotePreviewFailureMessage(error),
6978
});
7079
});
7180
return { uri: url + (item.srcFragment ?? "") };

‎apps/mobile/src/components/ui/VideoPreviewModal.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ function NativeVideoPreview(props: {
5050
const resolvePlaybackUrl = useEffectEvent(async (): Promise<string> => {
5151
if (source.type !== "media") throw new Error("Could not load this video.");
5252
if (!("resource" in source)) return source.uri;
53-
const url = await refreshAssetUrl(source.environmentId, source.resource);
53+
const url = await refreshAssetUrl(source.environmentId, source.resource).catch(() => null);
5454
const playbackUrl = mediaVideoPreviewUri(source, url);
5555
if (playbackUrl !== null) return playbackUrl;
5656
throw new Error(
@@ -61,7 +61,7 @@ function NativeVideoPreview(props: {
6161
});
6262
const reauthorize = useEffectEvent(() => {
6363
if (source.type === "media" && "resource" in source) {
64-
void refreshAssetUrl(source.environmentId, source.resource);
64+
void refreshAssetUrl(source.environmentId, source.resource).catch(() => {});
6565
}
6666
});
6767

‎apps/mobile/src/lib/attachmentDocument.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ async function readAttachmentText(key: AttachmentTextKey, signal: AbortSignal) {
4444
const refreshed =
4545
key.environmentId === null
4646
? null
47-
: await refreshAssetUrl(key.environmentId, key.resource, signal);
47+
: await refreshAssetUrl(key.environmentId, key.resource, signal).catch(() => null);
4848
if (!refreshed) throw new Error("Reconnect to this environment and try again.");
4949
target = refreshed;
5050
}

‎apps/mobile/src/state/assets.test.ts‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import {
2+
AssetWorkspaceAssetNotFoundError,
23
AuthFilesystemReadScope,
34
EnvironmentAuthorizationError,
45
EnvironmentId,
56
ThreadId,
67
type AuthSessionState,
78
} from "@t3tools/contracts";
89
import * as Cause from "effect/Cause";
9-
import { AsyncResult } from "effect/reactivity";
10+
import { Atom, AsyncResult } from "effect/reactivity";
1011
import { beforeEach, expect, it, vi } from "vite-plus/test";
1112

1213
const state = vi.hoisted(() => ({
@@ -15,6 +16,8 @@ const state = vi.hoisted(() => ({
1516
assetAtom: {},
1617
mint: vi.fn(),
1718
assetQuery: vi.fn(),
19+
executeQuery: vi.fn(),
20+
preparedConnectionAtom: null as unknown,
1821
}));
1922

2023
vi.mock("react", () => ({ useCallback: <A>(callback: A) => callback }));
@@ -27,7 +30,10 @@ vi.mock("@effect/atom-react", () => ({
2730
: AsyncResult.initial(false),
2831
}));
2932
vi.mock("./session", () => ({
30-
environmentSession: { sessionStateAtom: () => ({}) },
33+
environmentSession: {
34+
sessionStateAtom: () => ({}),
35+
preparedConnectionValueAtom: () => state.preparedConnectionAtom,
36+
},
3137
usePreparedConnection: () => ({ _tag: "Some", value: { httpBaseUrl: "https://host.test" } }),
3238
}));
3339
vi.mock("./presentation", () => ({
@@ -48,9 +54,13 @@ vi.mock("@t3tools/client-runtime/state/assets", async (importOriginal) => ({
4854
...(await importOriginal<typeof import("@t3tools/client-runtime/state/assets")>()),
4955
createAssetEnvironmentAtoms: () => ({ createUrl: state.assetQuery }),
5056
}));
57+
vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
58+
...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
59+
executeAtomQuery: state.executeQuery,
60+
}));
5161
vi.mock("./use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.mint }));
5262

53-
import { useRefreshAssetUrl, useAssetUrlState } from "./assets";
63+
import { refreshAssetUrl, useRefreshAssetUrl, useAssetUrlState } from "./assets";
5464

5565
const environmentId = EnvironmentId.make("asset-environment");
5666
const threadId = ThreadId.make("asset-thread");
@@ -107,3 +117,19 @@ it("lets the server authorize an explicit refresh before the client grant loads"
107117
state.mint.mockResolvedValue(AsyncResult.failure(Cause.fail(denied)));
108118
await expect(useRefreshAssetUrl(environmentId, resource)()).resolves.toBeNull();
109119
});
120+
121+
it("rejects with the server's error and resolves null only without a connection", async () => {
122+
const missing = new AssetWorkspaceAssetNotFoundError({
123+
resource,
124+
checkedPath: "/repo/missing.png",
125+
});
126+
state.executeQuery.mockResolvedValue(AsyncResult.failure(Cause.fail(missing)));
127+
state.preparedConnectionAtom = Atom.make({
128+
_tag: "Some",
129+
value: { httpBaseUrl: "https://host.test" },
130+
});
131+
await expect(refreshAssetUrl(environmentId, resource)).rejects.toBe(missing);
132+
133+
state.preparedConnectionAtom = Atom.make({ _tag: "None" });
134+
await expect(refreshAssetUrl(environmentId, resource)).resolves.toBeNull();
135+
});

‎apps/mobile/src/state/assets.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
EMPTY_ASSET_URL_ATOM,
99
makeRevisionedAssetUrlFamily,
1010
} from "@t3tools/client-runtime/state/assets";
11-
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
11+
import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
1212
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
1313
import * as Clock from "effect/Clock";
1414
import * as Effect from "effect/Effect";
@@ -109,7 +109,10 @@ export function useRefreshAssetUrl(
109109
};
110110
}
111111

112-
/** {@link useRefreshAssetUrl} for async tasks that resolve several resources at once. */
112+
/**
113+
* {@link useRefreshAssetUrl} for async tasks that resolve several resources at once. Resolves
114+
* null without a connection and rejects with the server's error when it refuses the URL.
115+
*/
113116
export async function refreshAssetUrl(
114117
environmentId: EnvironmentId,
115118
resource: AssetResource,
@@ -124,6 +127,7 @@ export async function refreshAssetUrl(
124127
reportFailure: false,
125128
...(signal ? { signal } : {}),
126129
});
130+
if (result._tag === "Failure") throw squashAtomCommandFailure(result);
127131
// A route can change while the query runs; resolve against the connection now current.
128132
const connection = appAtomRegistry.get(connectionAtom);
129133
if (connection._tag === "None") return null;
@@ -160,7 +164,7 @@ const freshAssetUrlFamily = Atom.family((key: FreshAssetUrlKey) =>
160164
try: async (signal) =>
161165
key.environmentId === null
162166
? null
163-
: await refreshAssetUrl(key.environmentId, key.resource, signal),
167+
: await refreshAssetUrl(key.environmentId, key.resource, signal).catch(() => null),
164168
catch: (cause) =>
165169
new AssetUrlUnavailableError({
166170
message: cause instanceof Error ? cause.message : "The attachment is unavailable.",

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6064,7 +6064,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
60646064
command.dispatchMode,
60656065
command.deliveryIntent,
60666066
);
6067-
if (dispatchMode.type === "steer_active") {
6067+
if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") {
60686068
const targetRunId = dispatchMode.targetRunId;
60696069
const target = projection.runs.find((run) => run.id === targetRunId);
60706070
const turn = latestProviderTurnForAttempt(
@@ -6076,24 +6076,36 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
60766076
if (
60776077
target !== undefined &&
60786078
(target.status === "completed" ||
6079+
(dispatchMode.type === "restart_active" && !isActiveRun(target)) ||
60796080
((target.status === "running" || target.status === "waiting") &&
60806081
turn !== undefined &&
6081-
turn.status === "completed"))
6082+
(turn.status === "completed" ||
6083+
(dispatchMode.type === "restart_active" &&
6084+
turn.status !== "pending" &&
6085+
turn.status !== "running"))))
60826086
) {
60836087
dispatchMode = { type: "start_immediately" };
60846088
}
60856089
}
60866090
// Stop leaves the run reading as running until its provider stops. A plain
60876091
// send in that window queues behind the stopped queue instead of steering
60886092
// text the agent never receives, and like any user send it releases the
6089-
// hold; an explicit steer or restart still fails below.
6093+
// hold; an explicit steer still fails below.
60906094
if (
60916095
command.deliveryIntent === "auto" &&
60926096
(dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") &&
60936097
(yield* stopReachedRun(command, command.threadId, dispatchMode.targetRunId))
60946098
) {
60956099
dispatchMode = { type: "queue_after_active" };
60966100
}
6101+
// An explicit restart that Stop reached has only its start left, so it
6102+
// queues behind the stopping run like any other start.
6103+
if (
6104+
dispatchMode.type === "restart_active" &&
6105+
(yield* stopReachedRun(command, command.threadId, dispatchMode.targetRunId))
6106+
) {
6107+
dispatchMode = { type: "start_immediately" };
6108+
}
60976109
const freshContext = command.freshContext === true;
60986110
if (
60996111
freshContext &&

0 commit comments

Comments
 (0)