GeezerVison is showing github.com — fix(chat): refresh local images after file changes by MatthewFeroz · Pull Request #29690 · pingdotgg/t3code
fix(chat): refresh local images after file changes
#29690
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
bc4f6a7
fix(chat): refresh local images after file changes
MatthewFeroz Nov 2, 2026
a90e92f
test(mobile): include image revision context in preview mock
MatthewFeroz Nov 2, 2026
7e92a74
merge: sync main into local image refresh
maria-rcks Nov 3, 2026
1e212b9
fix(mobile): preserve workspace image refresh during turns
maria-rcks Nov 3, 2026
5c9c3b6
fix(mobile): retain image width context import
maria-rcks Nov 3, 2026
83bf9c8
merge: sync main into local image refresh
maria-rcks Nov 4, 2026
f6815ba
fix(web): refresh changed local videos without interrupting playback
maria-rcks Nov 4, 2026
226c856
test(web): prevent decoding fake video URLs in refresh coverage
maria-rcks Nov 4, 2026
fb41ce3
test(web): support shared video observer cleanup
maria-rcks Nov 4, 2026
9a8b3f7
merge: sync main into local image refresh
maria-rcks Nov 4, 2026
File filter
Filter by extension
.ts
(8)
.tsx
(5)
All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Original file line number
Diff line number
Diff line change
Expand Up
@@ -5,7 +5,7 @@ import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { AsyncResult, Atom } from "effect/reactivity";
import { Image } from "expo-image";
import { createContext, useContext, useId, useState } from "react";
import { createContext, use, useContext, useId, useState } from "react";
import { fetch } from "expo/fetch";
import { parse, SvgAst, type JsxAST } from "react-native-svg";
import { Pressable, StyleSheet, View, type ViewStyle } from "react-native";
Expand All
@@ -30,6 +30,7 @@ import {
/** Use known feed width immediately; later image measurement would move already-positioned rows. */
export const MarkdownImageAvailableWidthContext = createContext(0);
export const MarkdownImageRevisionContext = createContext<string | undefined>(undefined);
type ImageSize = { readonly width: number; readonly height: number };
Expand Down
Expand Up
@@ -278,12 +279,11 @@ export function ThreadMarkdownImage(props: {
readonly onPressPreview: (source: FilePreviewSource) => void;
}) {
const withGallery = useFilePreviewGallery();
const workspaceMutationId = useContext(WorkspaceMutationIdContext);
const assetUrl = useAssetUrlState(
props.environmentId,
props.resource,
props.resource._tag === "media-file" ? workspaceMutationId : undefined,
);
const revision =
props.resource._tag === "media-file" || props.resource._tag === "draft-workspace-file"
? JSON.stringify([use(WorkspaceMutationIdContext), use(MarkdownImageRevisionContext)])
: undefined;
const assetUrl = useAssetUrlState(props.environmentId, props.resource, revision);
const resourceKey =
props.resource._tag === "attachment"
? `attachment:${props.resource.attachmentId}`
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -7,7 +7,7 @@ import {
import type { ImageSource } from "expo-image";
/**
* Signed URLs change on each mint and reconnect, so a URL-keyed cache misses every time .
* Signed URLs can change without the underlying file changing .
* Content that cannot change caches under its identity, and host files under the revision the
* server read. Anything else stays keyed by URL.
*/
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -289,7 +289,10 @@ vi.mock("../features/threads/thread-workflow-opening", () => ({ useWorkflowOpeni
vi.mock("../features/threads/useFileChipShare", () => ({ useFileChipShare: () => vi.fn() }));
vi.mock("../features/threads/ThreadMarkdownImage", async () => {
const { createContext } = await import("react");
return { MarkdownImageAvailableWidthContext: createContext(390) };
return {
MarkdownImageAvailableWidthContext: createContext(390),
MarkdownImageRevisionContext: createContext<string | undefined>(undefined),
};
});
vi.mock("../features/review/ReviewCommentCard", () => ({ useReviewCommentColors: () => ({}) }));
vi.mock("../features/prompt-links/prompt-link-actions", () => ({}));
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -2,11 +2,11 @@ import { useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react
import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem";
import {
assetUrlStateFromResult,
makeRevisionedAssetUrlFamily,
blockedAssetUrlState,
createAssetEnvironmentAtoms,
createProjectFaviconUrlAtomFamily,
EMPTY_ASSET_URL_ATOM,
makeRevisionedAssetUrlFamily,
} from "@t3tools/client-runtime/state/assets";
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
Expand All
@@ -27,6 +27,7 @@ import { useAtomQueryRunner } from "./use-atom-query-runner";
export type { AssetUrlFailureReason, AssetUrlState } from "./asset-url-state";
export const assetEnvironment = createAssetEnvironmentAtoms(connectionAtomRuntime);
const revisionedAssetUrl = makeRevisionedAssetUrlFamily(assetEnvironment.createUrl);
export const projectFaviconUrlAtom = createProjectFaviconUrlAtomFamily({
imageCache: projectFaviconDatabaseCache,
Expand All
@@ -35,8 +36,6 @@ export const projectFaviconUrlAtom = createProjectFaviconUrlAtomFamily({
projectClones: environmentProjectCloneListAtom,
});
const revisionedAssetUrl = makeRevisionedAssetUrlFamily(assetEnvironment.createUrl);
/**
* Pass `revision` for a host file whose bytes can change under the same path; each new
* revision re-mints the URL so the image reloads.
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -853,7 +853,7 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(layerTest)),
);
it.effect("versions media by file changes rather than by re-signing", () =>
it.effect("versions media URLs by file changes rather than by re-signing", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
Expand All
@@ -868,17 +868,20 @@ describe("AssetAccess", () => {
path: filePath,
},
};
yield* TestClock.adjust("1 minute");
const original = yield* issueAssetUrl(input);
expect(original.fileRevision).toEqual(expect.any(String));
yield* TestClock.adjust("1 minute");
const renewed = yield* issueAssetUrl(input);
expect(renewed.relativeUrl).not. toBe(original.relativeUrl);
expect(renewed.relativeUrl).toBe(original.relativeUrl);
expect(renewed.fileRevision).toBe(original.fileRevision);
// Same size, so only the timestamps tell the rewrite apart.
yield* fs.writeFileString(filePath, "modified");
yield* Effect.promise(() => NodeFSP.utimes(filePath, 2_000, 2_000));
const edited = yield* issueAssetUrl(input);
expect(edited.relativeUrl).not.toBe(renewed.relativeUrl);
expect(edited.fileRevision).not.toBe(original.fileRevision);
const replacement = path.join(root, "replacement.mp4");
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -73,7 +73,7 @@ export const ASSET_ROUTE_PREFIX = "/api/assets";
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;
const HTML_ATTACHMENT_TOKEN_BUCKET_MS = 30 * 60 * 1000;
const STABLE_ASSET_TOKEN_BUCKET_MS = 30 * 60 * 1000;
const PROJECT_FAVICON_VERSION_PREFIX = "v";
const PROJECT_FAVICON_ICNS_MIN_SIZE = 96;
const INLINE_VIDEO_MIME_TYPE_PATTERN = /^video\/[\w!#$&^.+-]+$/i;
Expand Down
Expand Up
@@ -130,6 +130,8 @@ const AssetClaimsSchema = Schema.Union([
download: Schema.optionalKey(Schema.Boolean),
device: Schema.String,
inode: Schema.String,
// Only varies the URL when the file is rewritten in place; responses still read the file.
revision: Schema.optionalKey(Schema.String),
expiresAt: Schema.Number,
}),
Schema.Struct({
Expand Down
Expand Up
@@ -406,7 +408,11 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe
? readImageDimensionsFromOpenFile(canonicalFile, file)
: Effect.succeed(null),
(dimensions) => ({
identity: { device: file.info.dev.toString(), inode: file.info.ino.toString() },
identity: {
device: file.info.dev.toString(),
inode: file.info.ino.toString(),
revision: `${file.info.size}:${file.info.mtimeNs}:${file.info.ctimeNs}`,
},
fileRevision: `${file.info.dev}:${file.info.ino}:${file.info.size}:${file.info.mtimeNs}:${file.info.ctimeNs}`,
dimensions,
}),
Expand Down
Expand Up
@@ -865,10 +871,13 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
PROJECT_FAVICON_TOKEN_BUCKET_MS;
claims = { ...claims, expiresAt };
}
if (claims.kind === "attachment" && claims.mimeType === "text/html") {
// Stable URLs let immutable HTML reloads hit the cache; image retries need fresh URLs.
expiresAt =
Math.ceil(expiresAt / HTML_ATTACHMENT_TOKEN_BUCKET_MS) * HTML_ATTACHMENT_TOKEN_BUCKET_MS;
if (
claims.kind === "media-file-exact" ||
(claims.kind === "attachment" && claims.mimeType === "text/html")
) {
// Stable URLs let re-mints of unchanged host files and immutable HTML hit the cache;
// attachment image retries need fresh URLs.
expiresAt = Math.ceil(expiresAt / STABLE_ASSET_TOKEN_BUCKET_MS) * STABLE_ASSET_TOKEN_BUCKET_MS;
claims = { ...claims, expiresAt };
}
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -2,13 +2,13 @@ import { useAtomValue } from "@effect/atom-react";
import {
type AssetUrlState as RuntimeAssetUrlState,
assetUrlStateFromResult,
makeRevisionedAssetUrlFamily,
blockedAssetUrlState,
EMPTY_ASSET_URL_ATOM,
makeRevisionedAssetUrlFamily,
resolveAssetUrl,
} from "@t3tools/client-runtime/state/assets";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { AssetResource, EnvironmentId } from "@t3tools/contracts";
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
import { assetEnvironment } from "~/state/assets";
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -3387,7 +3387,13 @@ export default function ChatView(props: ChatViewProps) {
{...conversationArea}
className="relative flex min-h-0 flex-1 flex-col bg-background"
>
<WorkspaceMutationIdContext value={workspaceMutationId}>
<WorkspaceMutationIdContext
value={JSON.stringify([
workspaceMutationId,
serverVisibleTurnItems.findLast((row) => row.item.type === "assistant_message")
?.item.id,
])}
>
<ThreadTimeline
pendingApprovals={pendingApprovals}
heldApprovalRequestIds={heldApprovalRequestIds}
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -3,7 +3,7 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import { render } from "../../../test/render";
import { ChatMarkdownAssetImage } from "./ChatMarkdownMedia";
import { ChatMarkdownAssetImage, WorkspaceMutationIdContext } from "./ChatMarkdownMedia";
// Every evaluation of the URL query is one mint: the first read, then one per refresh.
const assetQuery = vi.hoisted(() => ({ mints: 0 }));
Expand All
@@ -13,8 +13,7 @@ vi.mock(import("~/state/assets"), async (original) => {
Atom.make(() => {
assetQuery.mints += 1;
return AsyncResult.success({
relativeUrl:
"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
relativeUrl: `data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7#${assetQuery.mints}`,
expiresAt: Number.MAX_SAFE_INTEGER,
});
}).pipe(Atom.keepAlive),
Expand Down
Expand Up
@@ -56,9 +55,45 @@ vi.mock(import("~/state/filesystem"), async (original) => ({
useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
}));
function setup() {
assetQuery.mints = 0;
}
describe("ChatMarkdownAssetImage", () => {
it("refreshes repeated local images together after a new chat revision", async () => {
setup();
const images = (revision: string) => (
<WorkspaceMutationIdContext value={revision}>
{["first", "second"].map((alt) => (
<ChatMarkdownAssetImage
key={alt}
environmentId={EnvironmentId.make("environment-1")}
resource={{
_tag: "media-file",
threadId: ThreadId.make("thread-1"),
path: "/tmp/render.png",
}}
alt={alt}
/>
))}
</WorkspaceMutationIdContext>
);
await using screen = await render(images("message-1"));
using errors = vi.spyOn(console, "error");
await vi.waitFor(() => expect(assetQuery.mints).toBe(2));
const previousSrc = screen.getByRole("img", { name: "first" }).element().getAttribute("src");
await screen.rerender(images("message-2"));
await vi.waitFor(() => expect(assetQuery.mints).toBe(3));
const first = screen.getByRole("img", { name: "first" });
const second = screen.getByRole("img", { name: "second" });
await expect.element(first).not.toHaveAttribute("src", previousSrc);
await expect.element(second).toHaveAttribute("src", first.element().getAttribute("src"));
expect(errors).not.toHaveBeenCalled();
});
it("does not re-mint an unchanged workspace image's URL on remount", async () => {
assetQuery.mints = 0 ;
setup() ;
const image = (
<ChatMarkdownAssetImage
environmentId={EnvironmentId.make("environment-1")}
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -72,7 +72,10 @@ const CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME = cn(
CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME,
);
export const MarkdownLinkContext = createContext(false);
/** The thread's workspace mutation id, so a host image the agent rewrites gets a fresh URL. */
/**
* A surface's workspace mutation id, for markdown that does not receive one as a prop.
* Read only by host-file images, so a change re-mints their URLs without re-rendering rows.
*/
export const WorkspaceMutationIdContext = createContext<string | null | undefined>(undefined);
function expandableMarkdownImageProps(
Expand Down
Expand Up
@@ -342,16 +345,19 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
}) {
const resource = props.resource;
const threadWorkspaceMutationId = use(WorkspaceMutationIdContext);
const workspaceMutationId = props.workspaceMutationId ?? threadWorkspaceMutationId;
const mutableImage =
props.kind !== "video" &&
(resource._tag === "media-file" || resource._tag === "workspace-file");
Comment thread
maria-rcks marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
const workspaceMutationId =
props.workspaceMutationId !== undefined
? props.workspaceMutationId
: mutableImage
? use(WorkspaceMutationIdContext)
: undefined;
const assetUrl = useAssetUrlState(
props.environmentId,
resource,
workspaceMutationId !== undefined &&
props.kind !== "video" &&
(resource._tag === "media-file" || resource._tag === "workspace-file")
? workspaceMutationId
: undefined,
mutableImage ? workspaceMutationId : undefined,
);
const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
const path =
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.