Repository navigation
feat(site): add a Preview tab for open_preview - #31286
DanielleMaywood wants to merge 1 commit into
Conversation
ibetitsmike
left a comment
There was a problem hiding this comment.
Adversarial security review — #31286 (Preview tab UI)
Part of the stack review; the stack-level roll-up (findings S1/S2, method, verified negatives) is on #31282. Line numbers at stack head 678b80103. No browser was available in the harness, so DOM/browser behaviours are from code reading and spec; server-side premises were validated end-to-end.
Contributes to S1 (P1, contested; validated) — zero-click render of model-chosen content in an unsandboxed, cookie-bearing frame
This PR is where the stack's new primitive is created:
useChatToolInvalidations.ts:173reports every freshopen_previewresult from an effect →AgentChatPageView.tsx:427showSingletonTab("preview")→onSetShowSidebarPanel(true)→RightPanel/PreviewPanel.tsx:174<WorkspaceIframe src={url}>. This is the only effect-driven tab activation in the Agents UI — all seven othershowSingletonTab/activateRightPanelTab/onOpenDesktop/handleOpenPortTabcall sites areonClick/onSelectand pre-exist at the base commit.site/src/modules/apps/WorkspaceAppFrame.tsx:166: nosandbox,allow="clipboard-read; clipboard-write",loading="eager", noreferrerpolicy. The frame therefore keeps the full default capability set of a cross-origin document: credentialed same-site subresource requests to every sibling app (thecoder_subdomain_app_session_token_<hash>cookie isDomain=.<wildcard>,SameSite=Lax— validated server-side that such requests are delivered), top-frame navigation after a user click inside the frame (phishing the dashboard tab), popups, clipboard write, cookie tossing onto.<wildcard>.- For port-mode previews
appSlug = String(selected.port)(PreviewPanel.tsx:67) →workspaceAppURLyields the exact existing port-forward URL shape, so the frame is a plain port-app origin and #31283'spreview--CORS denial does not apply (validated:ACAO+ACAC: trueagainst the owner's other workspace). - All right-panel panels stay mounted while hidden (
components/ChatsSidebar/tabs/SidebarTabView.tsx:354-358invisible absolute inset-0+inert;RightPanel.tsx:374hidden), andPreviewPanelhas noisVisiblegate (unlikeDesktopPanel) and defaults topreviews[0]— so once the tab is persisted the model-authored page executes in the background on every visit to the chat.
Suggested fixes (this PR):
- Do not auto-set
src. On a fresh result, open/badge the tab with a "Load preview" placeholder and setsrconly after an explicit click (the tool row's "Open preview" button is already a gesture path). At minimum never load while the panel isinert/hidden. - Use a dedicated frame for previews instead of
WorkspaceIframe:sandbox="allow-scripts allow-same-origin allow-forms allow-modals allow-downloads"(deliberately omitallow-top-navigation*,allow-popups*,allow-pointer-lock,allow-presentation); dropallow="clipboard-read; clipboard-write"for previews; addreferrerpolicy="no-referrer"; unmount when not visible. - Keep the "Open in new tab" link (
target="_blank" rel="noreferrer"is fine).
Contributes to S2 (P2, unanimous; validated) — no viewer-vs-owner check
openPreview/onOpenPreview is gated only on workspace && !isArchived (AgentChatPageView.tsx:430-434); PreviewPanel builds the URL from workspace.owner_name (the chat owner, not the viewer). A site owner viewing a victim's chat (supported flow: isOtherUserReadOnly banner; Workspaces page "Agent" badge) auto-loads (if watching live) or one-click-loads the victim's model-authored page with the admin's app cookie — validated server-side. Fix: only build/iframe the URL when currentUser.id === chat.owner_id; otherwise show "Previews render only for the chat owner" + external link; never auto-open for non-owners.
Unverified (single reviewer) — P3
workspaceAppURL(site/src/utils/portForward.ts:63) interpolatespreview_id/agent_namefrom the catalog without validation. Node PoC with the function body:preview_id="evil.com/#"→https://preview--evil.com/#--main--ws--user.apps.example.com(hostpreview--evil.com);agent_name="x@evil.com"→ userinfo swallowed. No real write path exists (validated across reviewers; server validatesIsPreviewIDat tool time; CSPframe-srcbackstops), so defence-in-depth only: validate/^[0-9a-f]{16}$/, port range and name regex client-side before building the URL.
nit
previewKeyusespreview_id ?? port(nullish) whilePreviewPanelbranches on truthiness ofpreview_id— an empty-stringpreview_idwould diverge.- A fresh result whose
workspace_id≠ the current workspace still opens the tab and shows an unrelatedpreviews[0]. Tool.test.tsxlacks the MCP-collision / error-result rows thatuseChatToolInvalidations.test.tsxcovers.- The hook fires for non-owner viewers (folds into the S2 fix).
Verified negatives (no action)
- Title/error rendering is React-escaped; no
dangerouslySetInnerHTML;showDebugDetail={false};startWorkspaceis click-only; localStorage holds onlyagent:previewId|portkeys; the threemessagelisteners insite/srccheckevent.origin/event.sourceand are not reachable from an app-origin frame; dashboard/api/v2accepts onlycoder_session_token.
5e8f066 to
dba155a
Compare
3a22453 to
f6b581f
Compare
2501317 to
5965b46
Compare
DanielleMaywood
left a comment
There was a problem hiding this comment.
This review was performed by ai-review, an automated review bot.
4 inline findings and 1 below.
whole PR
SCOPE-1: This PR changes 1033 lines in 19 files (limit 1000). Split it into smaller PRs.
Remedy: split
Coverage
Coverage: 19 of 19 files reviewed; 22 rules.
Candidates: 333 found, 303 outside changed lines, 0 already discussed, 30 evaluated.
Findings: 5 (8 sites, 1 pre-existing sites), 0 over budget, 0 failed.
Model: deepseek/deepseek-v4.1-flash; 26 questions, 26 answered, 0 abstained, 0 cached; 0 uncalibrated findings held back; 26578 input and 11239 output tokens.
Experiments: 1 run, 0 passed, 1 vetoed, 0 unverified, 0 skipped for time.
vetoed: TYPE-1 site/src/utils/portForward.ts:57: 2 new type errors, first src/pages/AgentsPage/components/RightPanel/PreviewPanel.tsx: TS2554 Expected 6-7 arguments, but got 5.
5965b46 to
4cf1a86
Compare
4cf1a86 to
dbeb516
Compare
|
Re SCOPE-1 (1033 lines, limit 1000): not split. The renderer, tab, list and iframe only work together, and about 320 of those lines are tests and stories. Splitting off the renderer would ship a button that opens nothing. The reasoning is now in the PR's decision log.$\n\n_Reply generated by Coder Agents on behalf of @DanielleMaywood._ |
dbeb516 to
6cde3b1
Compare
ibetitsmike
left a comment
There was a problem hiding this comment.
Follow-up (re-checked at 2c52e96): non-owner viewers still render the chat owner's agent-authored page — P2, validated at the earlier tip; mechanics unchanged here
The rebase adds the checkAuthorization(application_connect) gate in PreviewPanel.tsx:54-69 and the docs now say deployment owners can view previews. That gate hides the frame from org admins (who would 404 anyway) but passes for the site owner role by default, which is exactly the principal that also has chat read on other users' chats. So the chain I validated earlier still holds:
useOpenNewPreviews(AgentChatPage/AgentChatPageView.tsx:435-440) fires for whoever has the chat open;onOpenPreviewis gated only onworkspace && !isArchived(:432).openPreview→showSingletonTab("preview")(:425) →PreviewPanelactivates and iframespreview--<id>--agent--ws--<victim>(URL built fromworkspace.owner_name,:97-103).isOtherUserReadOnlyexists (:842) but is not consulted anywhere on this path.- Earlier end-to-end test (RBAC unchanged since): site owner →
GET /chats/{victim-chat}/previews200 → preview URL proxied to the victim's agent, victim's file body returned.--disable-owner-workspace-accesscloses it; default is off.
Why it still matters after the sandbox: the page now runs in the admin's browser with the admin's Domain=<wildcard> app cookie, which reaches every workspace on the deployment the admin can application_connect to. The isFromOtherPreview gate has bypasses (absent/null Origin, path-based apps — validated on #31283), and a service worker registered by the page persists on the admin's profile (#31283). An admin opening a low-privilege user's chat to look at a support issue is a routine action.
Fix: do not build or load the preview URL unless currentUser.id === chat.owner_id; for other viewers show "Previews only render for the chat owner" with the external link, and never auto-open for them. Defence in depth on #31285: return [] for non-owners.
Still open from the earlier review (P3, unverified, brief)
- Auto-open is still effect-driven;
activateddefers the load until the tab is shown, butshowSingletonTab("preview")shows it whenever the panel is already open, so a fresh result still loads script-enabled content with no gesture. - Once activated the frame stays mounted while hidden (by design per the comment at
PreviewPanel.tsx:43-48), so the page keeps executing in the background.
6cde3b1 to
9d8d334
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
This round adds a hidden sign-in frame before the preview wrapper, a header on the popout page, path-based keys for file previews, a below-lg gate on auto-open, and wrapper tests. Open findings: 1 P3, 3 P4, 1 Nit.
Verified fixed: the app sign-in redirect (reproduced against an emulation of the flow in Chromium and Firefox; WebKit not run), the wrapper test (it fails when escapeHTML is removed), the popout header, the path-based previewKey, the previewKey move, and auto-open below lg. The reviewers who raised them accept your defenses on the popout tests, the popout message, the popout agent check, getMatchingAgentOrFirst, the proxy wildcard gate and the archived-chat action. The split is no longer required; it stays an option. The cache-age history boundary and the stale-workspace preview list still have no ticket, so they need a human decision: file a ticket or accept the gap.
Correction: the first-round test-coverage comment asked for assertions in Storybook play functions. At this head FE1 puts behavior assertions in Vitest and says not to assert in play, so ignore that part of it.
🤖 This review was automatically generated with Coder Agents.
|
On the review body: both remaining items are accepted without a ticket. Results saved while the owner was on another page can auto-open on return. The preview list can show the old workspace for one render after a server-side workspace switch, and it corrects itself when the chat data refreshes.
|
|
/coder-agents-review |
There was a problem hiding this comment.
This round adds a positive auto-open test row, a widen-after-drop check, a port url_path key test, preview-list invalidation on new open_preview results in useChatStore, and the signInLoadedOrigin rename. Open findings: 1 P4.
Verified fixed: the missing positive auto-open row, the below-lg widen check, the port key test, the stale list for non-owners and narrow viewports, and the signedInOrigin name; the three behavior fixes were each checked by removing the change and watching the new test fail. The cache-age history boundary and the stale-workspace preview list still have no ticket, so they need a human decision: file a ticket or accept the gap.
The round 1 out-of-scope item about other clients getting no signal after an edit was wrong: coderd sends history_reset to every watcher. The gap that remains is in this PR's new invalidation and is the comment below.
Notes:
- The decision log says feature logic lives in the preview modules;
useChatStore.tsnow invalidates the preview list too, so that bullet should name it.
🤖 This review was automatically generated with Coder Agents.
|
@DanielleMaywood's decision on the cache-age history boundary and the stale-workspace preview list:
|
|
/coder-agents-review |
There was a problem hiding this comment.
This round makes replaceCacheMessages invalidate the preview list, so other viewers drop previews deleted by an edit. No new findings.
Verified fixed: the history_reset refresh. Removing the new line makes the "the history is replaced" row fail, and that row sends only a user message, so it cannot pass through the open_preview check in upsertCacheMessages. No in-scope findings remain open.
Two acknowledged gaps still have no ticket and need a human decision (file a ticket or accept the gap): the cache-age history boundary for auto-open, and the stale-workspace preview list while the chat's workspace changes.
Notes:
- The decision log still says feature logic lives in the preview modules;
useChatStore.tsnow holds both preview-list invalidations.
🤖 This review was automatically generated with Coder Agents.
|
/coder-agents-review |
There was a problem hiding this comment.
This push rebases the PR onto a new base; the PR diff is unchanged from the previous round. No new findings, and no in-scope findings remain open.
The new base changes only coderd/x/chatd/turn_environment.go and its internal test. It clears the cached workspace ID together with the agent conn, so the workspace_id in open_preview results still names the workspace that served the preview, which the current-workspace checks here rely on. Nothing else the PR depends on changed. The cache-age history boundary and the stale-workspace preview list are accepted without a ticket by @DanielleMaywood.
Out of scope (needs a ticket or explicit acceptance by a human):
coderd/x/chatd/turn_environment.go:1981: the comment ongetPreviewWorkspacesays it returns an agent ID, butchattool.PreviewWorkspacehas onlyConn,WorkspaceIDandAgentName, so a reader looks for a field that does not exist.
Notes:
- The decision log still says feature logic lives in the preview modules;
useChatStore.tsholds both preview-list invalidations.
🤖 This review was automatically generated with Coder Agents.
|
On the out-of-scope
|
|
/coder-agents-review |
There was a problem hiding this comment.
This push rebases the PR onto a new base; the PR diff is unchanged from the previous round. No new findings, and no in-scope findings remain open.
The new base changes only coderd/x/chatd/turn_environment.go: it renames resetCacheLocked to clearCachedWorkspaceStateLocked with no behavior change, and the corrected getPreviewWorkspace comment resolves the out-of-scope item from the previous round. The decision log now names the two preview-list invalidations in useChatStore.
🤖 This review was automatically generated with Coder Agents.
|
/coder-agents-review |
There was a problem hiding this comment.
This push replaces auto-open with a toast: a new open_preview result from the chat's current workspace raises "The agent shared a preview." with an "Open preview" action, and the owner-only and below-lg gates are removed. Findings: 1 P3, 2 P4, 2 Nit.
The design holds for every viewer kind the panel checked (owner, other readers, archived chats, narrow screens, results from another workspace): nothing loads or opens without a click, so the removed gates had nothing left to guard, and the toast test fails when the workspace check or the dismiss is removed.
P3 [CRF-59] The PR summary and the commit body still say "On screens wide enough to show the panel beside the chat, a fresh open_preview result selects its preview and shows the tab", while the decision log now says new results never open the panel. A reader of the summary or of git log looks for an auto-open and a breakpoint gate that no longer exist. Replace that sentence in both with the toast behavior, for example: "A fresh open_preview result raises a toast with an "Open preview" action; results already in chat history only join the list." (Netero, Leorio)
Notes:
- The info toast uses Sonner's default timer, so its action disappears after a few seconds; the tool row's "Open preview" button stays as the fallback.
🤖 This review was automatically generated with Coder Agents.
|
CRF-59: updated the PR summary to describe the toast. The commit body is left as is by the owner's choice.
|
|
/coder-agents-review |
|
@DanielleMaywood ⛔ This review has reached its per-chat spend limit ($118.39 / $100.00). Further review rounds are paused. To raise the limit and continue, comment: This is a per-chat budget, separate from any account-level usage limit.
|
|
/coder-agents-review set-spend-limit:150 |
|
/coder-agents-review |
There was a problem hiding this comment.
This push fixes CRF-61 and rewords the toast. Findings: 3 P4.
CRF-61 is verified: reverting toastId makes the toast test fail. CRF-59 is resolved, since the squash merge takes the PR description as the commit body. The rebuttals for CRF-60, CRF-62 and CRF-63 were accepted by the reviewers who raised them.
🤖 This review was automatically generated with Coder Agents.
There was a problem hiding this comment.
No commits since the last review (head 8674bea), and the three open P4 threads have no reply. Further review is blocked until the author pushes fixes or replies on each thread.
PreviewPanelContext.tsx:173: the toast heading "Opened a preview" says the preview opened, but nothing has opened and the button reads "Open preview".PreviewPanelContext.tsx:178: the toast action still runs theonOpenPreviewfrom before an archive made in another client, so it saves the selection again and shows the tab.PreviewFrame.tsx:13:previewKeyrepeats the server's merge key inchatPreviewsFromResultswith nothing checking that the two agree.
For each, fix it in this PR, file an issue, or reply with why it should not change.
🤖 This review was automatically generated with Coder Agents.
|
/coder-agents-review |
There was a problem hiding this comment.
This push dismisses the toast when the chat is archived or loses Preview tab support, and points previewKey at the server merge it must match. Findings: 1 P4.
The archive dismiss and the previewKey comment are verified; removing canOpenResults from the effect's dependencies makes the toast test fail. The reviewers who raised the toast heading accepted the owner's wording.
Out of scope (needs a ticket or explicit acceptance by a human):
coderd/exp_chats_previews.go:93:codersdk.ChatPreviewandOpenPreviewResultcarry no identity key, so each client rebuilds the server's merge key, and a later change to the server key breaks those clients without warning. The reply says this is not done in this stack and links no ticket.
🤖 This review was automatically generated with Coder Agents.
|
/coder-agents-review |
There was a problem hiding this comment.
This push removes the unused guard in the toast-dismiss effect and rebases onto 8d0d664. Findings: 1 P4.
The guard removal is verified, and the base change leaves the preview invalidations in useChatStore.ts and chats.ts unchanged.
Out of scope (needs a ticket or explicit acceptance by a human):
coderd/exp_chats_previews.go:93:codersdk.ChatPreviewandOpenPreviewResultcarry no identity key, so each client rebuilds the server's merge key, and a later change to the server key breaks those clients without warning.
🤖 This review was automatically generated with Coder Agents.
|
/coder-agents-review |
2 similar comments
|
/coder-agents-review |
|
/coder-agents-review |
Render open_preview tool calls with an "Open preview" action, add a Preview singleton tab to the right panel, and list the chat's previews in a dropdown above an iframe of the selected preview. On screens wide enough to show the panel beside the chat, a fresh open_preview result selects its preview and shows the tab.
Renders
open_previewtool calls with an "Open preview" action, adds a Preview singleton tab to the right panel, and lists the chat's previews in a dropdown above an iframe of the selected preview. A freshopen_previewresult raises a toast with an "Open preview" action; results already in chat history only join the list.Decision log
PreviewFrame: asrcdocwrapper iframe, sandboxed with the same flags coderd sets on preview responses (allow-scripts allow-same-origin allow-forms allow-modals allow-downloads: no top-level navigation, popups or clipboard). Its CSP isframe-src <exact preview origin>, and it holds the preview iframe, which inherits the sandbox and usesreferrerpolicy="no-referrer". The wrapper is what stops a preview from navigating itself to the owner's other apps, which the preview's own CSP can't do. In Chromium, Firefox and WebKit,locationchanges, redirects, form posts, meta refresh and link clicks to another origin were blocked, and same-origin navigation still worked. Both modes usepreview--<id|port>hostnames.frame-srcalso blocks coderd's app sign-in redirects through the dashboard, soPreviewFramefirst loads<preview origin>/?coder_preview_sign_inin a hiddensandbox=""iframe and mounts the wrapper once it loads. coderd answers that request with an empty page after sign-in (feat: route preview app hostnames to agent previews #31283), so the preview's server never answers or redirects the hidden frame. Verified in Chromium, Firefox and WebKit against an emulation of the flow; a 204 would not fireload, hence the empty 200./agents/:agentId/preview?key=<previewKey>, a full-screen page modeled on the/agents/:agentId/desktoppopout. The page renders only previews the server lists for that chat, so it can't frame an arbitrary URL. Because the address bar shows the dashboard, a header above the frame names the preview, its host, and that the agent opened it.application_connecton the workspace. The panel does not check this up front; the app proxy answers. Until the preview's agent connects, the panel shows a message instead of the frame. New results never open the panel on their own; a toast offers "Open preview", so a new agent-authored page loads in a viewer's browser only after a click.useChatStore.useChatPreviewPanelopens previews from tool actions and offers new ones in a toast, andAgentChatPageViewonly wires the tab, its key and that hook into the context. The one shared change is inuseChatStore: it invalidates the chat's preview list when a durableopen_previewresult arrives over the WebSocket and when ahistory_resetreplaces the history, so every viewer's list follows new results and edits that delete them.useChatToolInvalidationsandAgentChatPageare unchanged.useNewPreviewsreportsopen_previewresults from messages newer than the newest one loaded with the chat (older pages load below it), and only a result newer than the last one it reported.useChatPreviewPanelshows a toast with the preview's title and an "Open preview" action, for the chat you are viewing only, and dismisses it when you leave that chat. Messages can arrive out of ID order (a send response can land before a lower-ID stream result), so a result older than the last one reported is ignored. A result that is already in the messages the page has when it mounts, including a warm cache from in-app navigation, counts as history and gets no toast.url_path. It is part of the preview key, so the same port at another path is its own list entry. File previews are keyed by agent and path, because the agent gives a path a new ID after it restarts. The panel splits it at the first?into the pathname and query of the preview URL, and the list labels itport N<url_path>.Stack (proof of concept for the embedded previews RFC, review bottom-up):
coder_apptabs