Skip to content
Closed
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
37 changes: 22 additions & 15 deletions apps/mobile/src/features/threads/ThreadFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ import {
import { fileChipMenu, resolveFileChipTarget, type FileChipAction } from "./fileChipMenu";
import { useFileChipShare } from "./useFileChipShare";
import {
MarkdownImageAssetScopeContext,
MarkdownImageAvailableWidthContext,
ThreadMarkdownImage,
ThreadMarkdownImageUnavailable,
Expand Down Expand Up @@ -1500,14 +1501,18 @@ function renderFeedEntry(
>
<View className="gap-3">
{messages.map((reasoningMessage) => (
<AssistantMarkdownContent
<MarkdownImageAssetScopeContext
key={reasoningMessage.id}
markdown={reasoningMessage.text}
markdownStyles={markdownStyles.assistant}
linkHandlers={props.markdownLinkHandlers}
renderImage={props.renderMarkdownImage}
skills={props.skills}
/>
value={reasoningMessage.id}
>
<AssistantMarkdownContent
markdown={reasoningMessage.text}
markdownStyles={markdownStyles.assistant}
linkHandlers={props.markdownLinkHandlers}
renderImage={props.renderMarkdownImage}
skills={props.skills}
/>
</MarkdownImageAssetScopeContext>
))}
</View>
</MarkdownImageAvailableWidthContext>
Expand Down Expand Up @@ -1697,14 +1702,16 @@ function renderFeedEntry(
>
{renderedText.trim().length > 0 ? (
<MarkdownImageAvailableWidthContext value={props.markdownContentWidth}>
<AssistantMarkdownContent
markdown={renderedText}
markdownStyles={styles}
linkHandlers={props.markdownLinkHandlers}
onUseArtifactTemplate={props.onUseArtifactTemplate}
renderImage={props.renderMarkdownImage}
skills={props.skills}
/>
<MarkdownImageAssetScopeContext value={message.id}>
<AssistantMarkdownContent
markdown={renderedText}
markdownStyles={styles}
linkHandlers={props.markdownLinkHandlers}
onUseArtifactTemplate={props.onUseArtifactTemplate}
renderImage={props.renderMarkdownImage}
skills={props.skills}
/>
</MarkdownImageAssetScopeContext>
</MarkdownImageAvailableWidthContext>
) : null}
{attachments.map((attachment) => {
Expand Down
13 changes: 12 additions & 1 deletion apps/mobile/src/features/threads/ThreadMarkdownImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ import {
*/
export const MarkdownImageAvailableWidthContext = createContext(0);

/**
* The message or work-log row that shows these images. Each one signs its own
* URL, so an agent that rewrites a file and shows it again shows the new file,
* not the cached one.
*/
export const MarkdownImageAssetScopeContext = createContext<string | undefined>(undefined);

export function ThreadMarkdownImageView(props: {
readonly uri: string | null;
readonly sourceKey: string;
Expand Down Expand Up @@ -184,7 +191,11 @@ export function ThreadMarkdownImage(props: {
readonly actionsSource?: MediaActionsSource;
readonly onPressPreview: (source: FilePreviewSource) => void;
}) {
const assetUrl = useAssetUrlState(props.environmentId, props.resource);
const assetUrl = useAssetUrlState(
props.environmentId,
props.resource,
useContext(MarkdownImageAssetScopeContext),
);

return (
<ThreadMarkdownImageView
Expand Down
5 changes: 4 additions & 1 deletion apps/mobile/src/features/threads/thread-work-log.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ import Animated, {
withTiming,
} from "react-native-reanimated";
import { useAssetUrl } from "../../state/assets";
import { MarkdownImageAssetScopeContext } from "./ThreadMarkdownImage";

const SHIMMER_WIDTH = 72;
const SHIMMER_SWEEP_MS = 1_350;
Expand Down Expand Up @@ -894,7 +895,9 @@ const ThreadWorkLogRow = memo(function ThreadWorkLogRow(
) : null}
{viewedImagePath ? (
<View className="pb-1.5">
{props.renderImage({ href: viewedImagePath, alt: null, title: null })}
<MarkdownImageAssetScopeContext value={row.workEntry.id}>
{props.renderImage({ href: viewedImagePath, alt: null, title: null })}
</MarkdownImageAssetScopeContext>
</View>
) : null}
<ScrollView
Expand Down
4 changes: 3 additions & 1 deletion apps/mobile/src/state/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,18 @@ function useConnectionPhase(environmentId: EnvironmentId | null): EnvironmentCon
return value === null ? "available" : presentConnectionState(value).phase;
}

/** `scope` gives the caller its own signed URL; see `AssetUrlQuery`. */
export function useAssetUrlState(
environmentId: EnvironmentId | null,
resource: AssetResource | null,
scope?: string,
): AssetUrlState {
const preparedConnection = usePreparedConnection(environmentId);
const connectionPhase = useConnectionPhase(environmentId);
const result = useAtomValue(
environmentId === null || resource === null
? EMPTY_ASSET_URL_ATOM
: assetEnvironment.createUrl({ environmentId, input: { resource } }),
: assetEnvironment.createUrl({ environmentId, input: { resource, scope } }),
);
const shared = assetUrlStateFromResult(
result,
Expand Down
9 changes: 6 additions & 3 deletions apps/web/src/assets/assetUrls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,17 @@ import { useAtomQueryRunner } from "~/state/use-atom-query-runner";

export { resolveAssetUrl, type AssetUrlState } from "@t3tools/client-runtime/state/assets";

/** `scope` gives the caller its own signed URL; see `AssetUrlQuery`. */
export function useAssetUrlState(
environmentId: EnvironmentId | null,
resource: AssetResource | null,
scope?: string,
): AssetUrlState {
const preparedConnection = usePreparedConnection(environmentId);
const result = useAtomValue(
environmentId === null || resource === null
? EMPTY_ASSET_URL_ATOM
: assetEnvironment.createUrl({ environmentId, input: { resource } }),
: assetEnvironment.createUrl({ environmentId, input: { resource, scope } }),
);
return assetUrlStateFromResult(
result,
Expand All @@ -35,6 +37,7 @@ export function useAssetUrlState(
export function useAssetUrlRefresh(
environmentId: EnvironmentId | null,
resource: AssetResource | null,
scope?: string,
): () => Promise<string | null> {
const connection = usePreparedConnection(environmentId);
const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null;
Expand All @@ -44,10 +47,10 @@ export function useAssetUrlRefresh(
});
return useCallback(async () => {
if (environmentId === null || resource === null || httpBaseUrl === null) return null;
const result = await refresh({ environmentId, input: { resource } });
const result = await refresh({ environmentId, input: { resource, scope } });
if (result._tag === "Failure") throw squashAtomCommandFailure(result);
return resolveAssetUrl(httpBaseUrl, result.value.relativeUrl);
}, [environmentId, resource, refresh, httpBaseUrl]);
}, [environmentId, resource, scope, refresh, httpBaseUrl]);
}

export function useAssetUrls(
Expand Down
16 changes: 13 additions & 3 deletions apps/web/src/components/ChatMarkdown.tsx
Comment thread
ishaanko marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,9 @@ interface ChatMarkdownProps {
text nests under the heading that introduces it, such as a chat message's
author. Rendered tags and their styling are unchanged. */
headingLevelOffset?: number | undefined;
/** Gives this text's workspace images their own signed URLs, such as per chat message. An agent
that rewrites a file and shows it again then shows the new file, not the cached one. */
assetScope?: string | undefined;
}

export interface ChatMarkdownContextReference {
Expand Down Expand Up @@ -1654,9 +1657,11 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
readonly fallbackSrc?: string | undefined;
readonly workspaceRoot?: string | undefined;
readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
/** See `ChatMarkdownProps.assetScope`. */
readonly assetScope?: string | undefined;
}) {
const assetUrl = useAssetUrlState(props.environmentId, props.resource);
const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, props.resource);
const assetUrl = useAssetUrlState(props.environmentId, props.resource, props.assetScope);
const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, props.resource, props.assetScope);
const resource = props.resource;
const path =
resource._tag === "media-file"
Expand Down Expand Up @@ -1694,7 +1699,7 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
name: props.alt || (props.kind ?? "image"),
src,
...(fallbackSrc === undefined
? { asset: { environmentId: props.environmentId, resource } }
? { asset: { environmentId: props.environmentId, resource, scope: props.assetScope } }
: {}),
...(reference ? { reference } : {}),
...(relativePath && (resource._tag === "media-file" || resource._tag === "workspace-file")
Expand Down Expand Up @@ -2302,6 +2307,7 @@ function useChatMarkdownState({
renderContextReference,
headingLevelOffset = 0,
githubMedia = false,
assetScope,
}: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
const [localMediaPreview, setLocalMediaPreview] = useState<ExpandedImagePreview | null>(null);
Expand Down Expand Up @@ -2688,6 +2694,7 @@ function useChatMarkdownState({

const componentState = useMemo(
() => ({
assetScope,
cwd,
diffThemeName,
environmentId,
Expand Down Expand Up @@ -2719,6 +2726,7 @@ function useChatMarkdownState({
updateThreadPullRequestLink,
}),
[
assetScope,
cwd,
diffThemeName,
environmentId,
Expand Down Expand Up @@ -3132,6 +3140,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
},
img: function MarkdownImage({ node, title, src, alt, ...props }) {
const {
assetScope,
expandMedia,
cwd,
environmentId,
Expand Down Expand Up @@ -3246,6 +3255,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
threadId: threadRef.threadId,
path: imageSource.path,
}}
assetScope={assetScope}
alt={altText}
kind={kind}
copyMarkdown={copyMarkdown}
Expand Down
12 changes: 10 additions & 2 deletions apps/web/src/components/chat/ExpandedImageDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,16 @@ function ExpandedMediaFailure({ children }: { children: ReactNode }) {

function ExpandedVideo({ item }: { readonly item: ExpandedImageItem }) {
const asset = item.actionsSource?.asset;
const assetUrl = useAssetUrlState(asset?.environmentId ?? null, asset?.resource ?? null);
const refreshAssetUrl = useAssetUrlRefresh(asset?.environmentId ?? null, asset?.resource ?? null);
const assetUrl = useAssetUrlState(
asset?.environmentId ?? null,
asset?.resource ?? null,
asset?.scope,
);
const refreshAssetUrl = useAssetUrlRefresh(
asset?.environmentId ?? null,
asset?.resource ?? null,
asset?.scope,
);
const src = asset
? assetUrl._tag === "Success"
? assetUrl.url + (item.srcFragment ?? "")
Expand Down
4 changes: 4 additions & 0 deletions apps/web/src/components/chat/MessagesTimeline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2397,6 +2397,7 @@ function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mess
text={messageText}
cwd={ctx.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
assetScope={row.message.id}
isStreaming={Boolean(row.message.streaming)}
lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}
skills={ctx.skills}
Expand Down Expand Up @@ -2815,6 +2816,7 @@ function ReasoningTraceBlock({
text={reasoningMessage.text}
cwd={ctx.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
assetScope={reasoningMessage.id}
isStreaming={streaming && reasoningMessage.streaming}
lineBreaks
skills={ctx.skills}
Expand Down Expand Up @@ -2883,6 +2885,7 @@ const ReasoningTimelineRow = memo(function ReasoningTimelineRow({
text={message.text}
cwd={ctx.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
assetScope={message.id}
lineBreaks
skills={ctx.skills}
headingLevelOffset={MESSAGE_HEADING_LEVEL}
Expand Down Expand Up @@ -4921,6 +4924,7 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
<ChatMarkdownAssetImage
environmentId={threadRef.environmentId}
resource={viewedImage.resource}
assetScope={workEntry.id}
alt={viewedImage.alt}
srcFragment={viewedImage.srcFragment}
workspaceRoot={workspaceRoot}
Expand Down
7 changes: 6 additions & 1 deletion apps/web/src/components/media/MediaActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ export interface MediaActionSource {
readonly name: string;
readonly src: string | null;
readonly reference?: MediaReference;
readonly asset?: { readonly environmentId: EnvironmentId; readonly resource: AssetResource };
/** `scope` is the signed URL scope of the rendering that opened the media; see `AssetUrlQuery`. */
readonly asset?: {
readonly environmentId: EnvironmentId;
readonly resource: AssetResource;
readonly scope?: string | undefined;
};
readonly onOpenFile?: () => void;
}

Expand Down
64 changes: 64 additions & 0 deletions packages/client-runtime/src/state/assets.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,70 @@ describe("createAssetEnvironmentAtoms", () => {
);
}

it.effect("signs a scoped query on its own and keeps the scope off the wire", () =>
Effect.gen(function* () {
const environmentId = EnvironmentId.make("remote");
const payloads: unknown[] = [];
const client = {
[WS_METHODS.assetsCreateUrl]: (payload: unknown) => {
payloads.push(payload);
return Effect.succeed({
relativeUrl: `/api/assets/token-${payloads.length}/shot.png`,
expiresAt: 999999,
});
},
} as unknown as WsRpcProtocolClient;
const supervisor = EnvironmentSupervisor.of({
target: new PrimaryConnectionTarget({
environmentId,
label: "remote",
httpBaseUrl: "https://remote.test",
wsBaseUrl: "wss://remote.test",
}),
state: yield* SubscriptionRef.make<SupervisorConnectionState>({
...AVAILABLE_CONNECTION_STATE,
phase: "connected" as const,
}),
session: yield* SubscriptionRef.make(Option.some({ client } as RpcSession)),
prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
});
const environments = EnvironmentRegistry.of({
run: (_id, effect) => Effect.provideService(effect, EnvironmentSupervisor, supervisor),
followStream: (_id, stream) =>
Stream.provideService(stream, EnvironmentSupervisor, supervisor),
} as EnvironmentRegistry["Service"]);
const registry = AtomRegistry.make();
yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
const assets = createAssetEnvironmentAtoms(
Atom.runtime(Layer.succeed(EnvironmentRegistry, environments)),
);
const resource = {
_tag: "media-file" as const,
threadId: ThreadId.make("thread-1"),
path: "shot.png",
};
const signedUrl = (scope?: string) =>
AtomRegistry.getResult(
registry,
assets.createUrl({ environmentId, input: { resource, scope } }),
{ suspendOnWaiting: true },
).pipe(Effect.map((result) => result.relativeUrl));

// Two messages that show one path each sign their own URL.
expect(yield* signedUrl("message-1")).toBe("/api/assets/token-1/shot.png");
expect(yield* signedUrl("message-2")).toBe("/api/assets/token-2/shot.png");
expect(yield* signedUrl("message-1")).toBe("/api/assets/token-1/shot.png");
expect(payloads).toEqual([{ resource }, { resource }]);
// An absent scope shares the unscoped query.
expect(assets.createUrl({ environmentId, input: { resource, scope: undefined } })).toBe(
assets.createUrl({ environmentId, input: { resource } }),
);
}).pipe(Effect.scoped),
);

it("keys asset URL queries by environment and resource", () => {
const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
EnvironmentRegistry,
Expand Down
12 changes: 11 additions & 1 deletion packages/client-runtime/src/state/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,24 @@ export function assetUrlStateFromResult(
};
}

/**
* A signed URL request. `scope` stays on the client: it gives one rendering its own cached URL,
* such as one chat message or work-log row. A later message that shows a file the agent rewrote
* then signs a fresh URL, instead of reusing the earlier one that the browser already cached.
*/
export type AssetUrlQuery = AssetCreateUrlInput & { readonly scope?: string | undefined };

export function createAssetEnvironmentAtoms<R, E>(
runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, E>,
localMediaEnvironment?: Atom.Atom<{
readonly environmentId: EnvironmentId;
readonly httpBaseUrl: string;
} | null>,
) {
const execute = Effect.fn("assets.createUrl")(function* (input: AssetCreateUrlInput) {
const execute = Effect.fn("assets.createUrl")(function* ({
scope: _scope,
...input
}: AssetUrlQuery) {
const result = yield* request(WS_METHODS.assetsCreateUrl, input).pipe(Effect.result);
if (Result.isSuccess(result)) return result.success;
const error = result.failure;
Expand Down
Loading