Procházet zdrojové kódy

feat(paas): preview generated files from chat cards

241880436@seecoder.cn před 4 dny
rodič
revize
a288571699

+ 17 - 1
packages/app/e2e/paas/fixture.tsx

@@ -258,7 +258,23 @@ const api: PaasPlatform = {
       run.output = "研究计划已完成"
       run.output = "研究计划已完成"
       return { ...run }
       return { ...run }
     }
     }
-    if (request.action === "run-files") return { files: [{ name: "研究计划.pdf", path: "final/研究计划.pdf" }] }
+    if (request.action === "run-files")
+      return {
+        files: [
+          { name: "研究计划.pdf", path: "final/研究计划.pdf" },
+          { name: "研究计划.md", path: "final/研究计划.md" },
+        ],
+      }
+    if (request.action === "preview-file") {
+      if (/\.md$/i.test(request.name))
+        return {
+          name: request.name,
+          mime: "text/markdown",
+          size: 46,
+          text: "## 可预览的研究计划\n\n这是 Agent 生成并保存在工作区的 Markdown 文档。",
+        }
+      return { name: request.name, mime: "application/pdf", size: 4, data: new Uint8Array([37, 80, 68, 70]) }
+    }
     if (request.action === "export-report")
     if (request.action === "export-report")
       return {
       return {
         saved: true,
         saved: true,

+ 10 - 6
packages/app/e2e/paas/workbench.spec.ts

@@ -35,12 +35,14 @@ test("independent workbench connects, uploads, confirms and saves without a deve
   await page.getByRole("button", { name: "同意并继续", exact: true }).click()
   await page.getByRole("button", { name: "同意并继续", exact: true }).click()
   await expect(page.getByRole("button", { name: "同意并继续", exact: true })).toHaveCount(0)
   await expect(page.getByRole("button", { name: "同意并继续", exact: true })).toHaveCount(0)
   await expect(page.getByRole("heading", { name: "成果 · 1", exact: true })).toBeVisible()
   await expect(page.getByRole("heading", { name: "成果 · 1", exact: true })).toBeVisible()
-  await expect(page.getByText("研究计划成果.pdf", { exact: true })).toBeVisible()
+  await expect(
+    page.getByLabel("任务进度与成果").getByText("研究计划成果.pdf", { exact: true }),
+  ).toBeVisible()
   await expect(page.getByText("没有可保存的工作文件。", { exact: true })).toHaveCount(0)
   await expect(page.getByText("没有可保存的工作文件。", { exact: true })).toHaveCount(0)
   await page.getByRole("button", { name: "保存成果", exact: true }).click()
   await page.getByRole("button", { name: "保存成果", exact: true }).click()
   await expect(page.getByText("文件已保存。", { exact: true })).toBeVisible()
   await expect(page.getByText("文件已保存。", { exact: true })).toBeVisible()
   await page.getByRole("button", { name: /^(查看|刷新)工作文件$/ }).click()
   await page.getByRole("button", { name: /^(查看|刷新)工作文件$/ }).click()
-  await page.getByRole("button", { name: "保存文件", exact: true }).click()
+  await page.getByRole("button", { name: "保存文件", exact: true }).first().click()
   await expect(page.getByText("文件已保存。", { exact: true })).toBeVisible()
   await expect(page.getByText("文件已保存。", { exact: true })).toBeVisible()
   await expect(page.getByText("没有可保存的工作文件。", { exact: true })).toHaveCount(0)
   await expect(page.getByText("没有可保存的工作文件。", { exact: true })).toHaveCount(0)
   const calls = await page.evaluate(
   const calls = await page.evaluate(
@@ -332,7 +334,7 @@ test("topbar actions are icon-only with accessible names and titles", async ({ p
   await expect(page.getByRole("button", { name: "重命名会话", exact: true })).toBeVisible()
   await expect(page.getByRole("button", { name: "重命名会话", exact: true })).toBeVisible()
 })
 })
 
 
-test("right preview shows the report, resizes and closes at its lower bound", async ({ page }) => {
+test("generated file cards open the right preview, resize and close at the lower bound", async ({ page }) => {
   await page.setViewportSize({ width: 1440, height: 900 })
   await page.setViewportSize({ width: 1440, height: 900 })
   await page.goto("/e2e/paas/index.html")
   await page.goto("/e2e/paas/index.html")
   await page.getByLabel("平台地址", { exact: true }).fill("https://research.example")
   await page.getByLabel("平台地址", { exact: true }).fill("https://research.example")
@@ -346,11 +348,13 @@ test("right preview shows the report, resizes and closes at its lower bound", as
   await page.getByRole("button", { name: "关闭预览", exact: true }).click()
   await page.getByRole("button", { name: "关闭预览", exact: true }).click()
 
 
   await page.getByRole("button", { name: /已有研究/ }).first().click()
   await page.getByRole("button", { name: /已有研究/ }).first().click()
-  await page.getByRole("button", { name: "右侧预览", exact: true }).first().click()
+  const card = page.getByRole("button", { name: "预览 研究计划.md", exact: true })
+  await card.waitFor()
+  await card.click()
   const preview = page.locator(".paas-preview")
   const preview = page.locator(".paas-preview")
   await expect(preview).toBeVisible()
   await expect(preview).toBeVisible()
-  await expect(preview.locator(".paas-preview-meta")).toContainText("已有研究")
-  await expect(preview.getByRole("heading", { name: "研究计划", exact: true })).toBeVisible()
+  await expect(preview.locator(".paas-preview-meta")).toContainText("研究计划.md")
+  await expect(preview.getByRole("heading", { name: "可预览的研究计划", exact: true })).toBeVisible()
   await expect(toggle).toHaveAttribute("aria-pressed", "true")
   await expect(toggle).toHaveAttribute("aria-pressed", "true")
 
 
   const splitter = page.locator(".paas-splitter-preview")
   const splitter = page.locator(".paas-splitter-preview")

+ 8 - 0
packages/app/src/paas.ts

@@ -24,6 +24,13 @@ export type PaasDownload = {
   artifactID?: string
   artifactID?: string
   path?: string
   path?: string
 }
 }
+export type PaasPreviewContent = {
+  name: string
+  mime: string
+  size: number
+  text?: string
+  data?: Uint8Array
+}
 export type PaasRequest =
 export type PaasRequest =
   | { action: "detach"; executionID?: string }
   | { action: "detach"; executionID?: string }
   | {
   | {
@@ -39,6 +46,7 @@ export type PaasRequest =
   | { action: "lookup-request"; agentID: string; requestID: string }
   | { action: "lookup-request"; agentID: string; requestID: string }
   | { action: "export-report"; name: string; text: string; format?: "md" | "docx" | "pdf" }
   | { action: "export-report"; name: string; text: string; format?: "md" | "docx" | "pdf" }
   | PaasDownload
   | PaasDownload
+  | { action: "preview-file"; agentID: string; runID: string; name: string; path?: string; artifactID?: string }
   | { action: "upload-file"; agentID: string; threadID?: string; name: string; data: Uint8Array; uploadID?: string }
   | { action: "upload-file"; agentID: string; threadID?: string; name: string; data: Uint8Array; uploadID?: string }
   | { action: "upload-selected"; agentID: string; threadID?: string; selectionID: string; uploadID: string }
   | { action: "upload-selected"; agentID: string; threadID?: string; selectionID: string; uploadID: string }
   | { action: "run-files" | "cancel" | "pause"; agentID: string; runID: string }
   | { action: "run-files" | "cancel" | "pause"; agentID: string; runID: string }

+ 23 - 24
packages/app/src/pages/paas/chat.tsx

@@ -28,7 +28,8 @@ import {
   type ResearchMessage,
   type ResearchMessage,
 } from "./chat-state"
 } from "./chat-state"
 import { createMaterials } from "./materials"
 import { createMaterials } from "./materials"
-import type { PaasPreviewReport } from "./preview"
+import { PaasGeneratedFiles } from "./generated-files"
+import type { PaasPreviewFile } from "./preview"
 
 
 export function PaasChat(props: {
 export function PaasChat(props: {
   api?: PaasPlatform
   api?: PaasPlatform
@@ -54,8 +55,8 @@ export function PaasChat(props: {
   registerNewSession?: (create: (() => void) | undefined) => void
   registerNewSession?: (create: (() => void) | undefined) => void
   registerRename?: (rename: ((title: string) => void) | undefined) => void
   registerRename?: (rename: ((title: string) => void) | undefined) => void
   onTitle?: (title: string) => void
   onTitle?: (title: string) => void
-  onReportSnapshot?: (report: PaasPreviewReport | undefined) => void
-  onPreviewReport?: (report: PaasPreviewReport) => void
+  onPreviewFile?: (file: PaasPreviewFile) => void
+  onChatChanged?: () => void
 }) {
 }) {
   const platform = usePlatform()
   const platform = usePlatform()
   const dialog = useDialog()
   const dialog = useDialog()
@@ -113,15 +114,16 @@ export function PaasChat(props: {
   const currentAgent = createMemo(() => props.agents.find((agent) => agent.id === current()?.agentID))
   const currentAgent = createMemo(() => props.agents.find((agent) => agent.id === current()?.agentID))
   const currentTitle = createMemo(() => current()?.title || paasText(currentAgent()?.name) || "科研工作台")
   const currentTitle = createMemo(() => current()?.title || paasText(currentAgent()?.name) || "科研工作台")
   createEffect(() => props.onTitle?.(currentTitle()))
   createEffect(() => props.onTitle?.(currentTitle()))
-  createEffect(() => {
-    const chat = current()
-    const message = chat?.messages.slice().reverse().find((item) => item.role === "assistant" && !!item.text)
-    props.onReportSnapshot?.(
-      chat && message
-        ? { agentID: chat.agentID, runID: message.runID, title: chat.title, text: message.text }
-        : undefined,
-    )
-  })
+  let previousChat: string | undefined
+  createEffect(
+    on(
+      () => current()?.id,
+      (id) => {
+        if (previousChat && id !== previousChat) props.onChatChanged?.()
+        previousChat = id
+      },
+    ),
+  )
   const materials = createMaterials({
   const materials = createMaterials({
     get api() {
     get api() {
       return props.api
       return props.api
@@ -861,18 +863,6 @@ export function PaasChat(props: {
                             >
                             >
                               阅读与对比
                               阅读与对比
                             </button>
                             </button>
-                            <button
-                              onClick={() =>
-                                props.onPreviewReport?.({
-                                  agentID,
-                                  runID: message.runID,
-                                  title: current()?.title || currentTitle(),
-                                  text: message.text,
-                                })
-                              }
-                            >
-                              右侧预览
-                            </button>
                             <button onClick={() => void copy(message)}>
                             <button onClick={() => void copy(message)}>
                               {ui.copied === message.id ? "已复制" : "复制报告"}
                               {ui.copied === message.id ? "已复制" : "复制报告"}
                             </button>
                             </button>
@@ -923,6 +913,15 @@ export function PaasChat(props: {
                             <p class="paas-muted">本机保留最近 80 条执行事件;更早的记录请查看平台任务日志。</p>
                             <p class="paas-muted">本机保留最近 80 条执行事件;更早的记录请查看平台任务日志。</p>
                           </Show>
                           </Show>
                         </Show>
                         </Show>
+                        <Show when={props.api}>
+                          <PaasGeneratedFiles
+                            api={props.api}
+                            agentID={agentID}
+                            runID={message.runID}
+                            status={message.status}
+                            onPreview={props.onPreviewFile}
+                          />
+                        </Show>
                         <Show when={message.runID && props.api}>
                         <Show when={message.runID && props.api}>
                           <ResearchRunDetails
                           <ResearchRunDetails
                             api={props.api!}
                             api={props.api!}

+ 121 - 0
packages/app/src/pages/paas/generated-files.tsx

@@ -0,0 +1,121 @@
+import { For, Show, createEffect, createSignal } from "solid-js"
+import { Icon } from "@opencode-ai/ui/icon"
+import {
+  paasRecord,
+  paasRows,
+  paasRunDetail,
+  paasTerminalStatuses,
+  paasText,
+  type PaasPlatform,
+} from "@/paas"
+import type { PaasPreviewFile } from "./preview"
+
+type GeneratedFile = {
+  name: string
+  path?: string
+  artifactID?: string
+  mime?: string
+  size?: number
+}
+
+const internal = new Set(["input.json", "output.json", "trace.json", "cost.json", "config.yml", "config.yaml"])
+
+function typeLabel(file: GeneratedFile) {
+  const extension = file.name.split(".").pop()?.toLowerCase()
+  return extension ? extension.toUpperCase() : "文件"
+}
+
+export function PaasGeneratedFiles(props: {
+  api?: PaasPlatform
+  agentID: string
+  runID?: string
+  status?: string
+  onPreview?: (file: PaasPreviewFile) => void
+}) {
+  const [files, setFiles] = createSignal<GeneratedFile[]>([])
+  let request = 0
+
+  createEffect(() => {
+    const api = props.api
+    const runID = props.runID
+    const status = props.status || ""
+    const ready = paasTerminalStatuses.has(status) || status.startsWith("waiting")
+    const current = ++request
+    if (!api || !runID || !ready) {
+      setFiles([])
+      return
+    }
+    void Promise.all([
+      paasRunDetail(api, props.agentID, runID).catch(() => undefined),
+      api.request({ action: "run-files", agentID: props.agentID, runID }).catch(() => undefined),
+    ]).then(([run, work]) => {
+      if (current !== request) return
+      const artifacts = paasRows(run, "artifacts").flatMap((value) => {
+        const file = paasRecord(value)
+        const name = paasText(file?.name) || paasText(file?.artifact_id)
+        if (!file || !name) return []
+        return [
+          {
+            name,
+            artifactID: paasText(file.artifact_id) || paasText(file.id),
+            mime: paasText(file.mime_type),
+            size: typeof file.size === "number" ? file.size : undefined,
+          } satisfies GeneratedFile,
+        ]
+      })
+      const artifactNames = new Set(artifacts.map((file) => file.name))
+      const workspace = paasRows(work, "files").flatMap((value) => {
+        const file = paasRecord(value)
+        const name = paasText(file?.name) || paasText(file?.path)?.split("/").at(-1)
+        if (!file || !name || internal.has(name.toLowerCase()) || artifactNames.has(name)) return []
+        return [
+          {
+            name,
+            path: paasText(file.path),
+            mime: paasText(file.mime_type),
+            size: typeof file.size === "number" ? file.size : undefined,
+          } satisfies GeneratedFile,
+        ]
+      })
+      setFiles([...artifacts, ...workspace])
+    })
+  })
+
+  return (
+    <Show when={files().length}>
+      <section class="paas-file-cards" aria-label="生成文件">
+        <header>
+          <strong>生成文件</strong>
+          <span>{files().length}</span>
+        </header>
+        <For each={files()}>
+          {(file) => (
+            <button
+              type="button"
+              class="paas-file-card"
+              aria-label={`预览 ${file.name}`}
+              onClick={() =>
+                props.onPreview?.({
+                  agentID: props.agentID,
+                  runID: props.runID!,
+                  name: file.name,
+                  path: file.path,
+                  artifactID: file.artifactID,
+                  mime: file.mime,
+                  size: file.size,
+                })
+              }
+            >
+              <span class="paas-file-card-icon" aria-hidden="true">
+                <Icon name="open-file" size="small" />
+              </span>
+              <span class="paas-file-card-name">{file.name}</span>
+              <small>{typeLabel(file)}</small>
+              <Icon name="layout-right" size="small" />
+            </button>
+          )}
+        </For>
+      </section>
+    </Show>
+  )
+}

+ 7 - 7
packages/app/src/pages/paas/index.tsx

@@ -27,7 +27,7 @@ import {
   resizeNav,
   resizeNav,
   resizePreview,
   resizePreview,
 } from "./layout"
 } from "./layout"
-import { PaasPreview, type PaasPreviewReport } from "./preview"
+import { PaasPreview, type PaasPreviewFile } from "./preview"
 import { PaasChat } from "./chat"
 import { PaasChat } from "./chat"
 import { createTaskIndex, PaasTasks } from "./tasks"
 import { createTaskIndex, PaasTasks } from "./tasks"
 import { PaasAgentEdit, type AgentEditDraft } from "./agent-edit"
 import { PaasAgentEdit, type AgentEditDraft } from "./agent-edit"
@@ -106,7 +106,7 @@ export default function PaasWorkspace(
   const storedPreview = readPreviewLayout(localStorage.getItem(previewLayoutKey(platform.windowID)))
   const storedPreview = readPreviewLayout(localStorage.getItem(previewLayoutKey(platform.windowID)))
   const [previewWidth, setPreviewWidth] = createSignal(storedPreview.width)
   const [previewWidth, setPreviewWidth] = createSignal(storedPreview.width)
   const [previewOpen, setPreviewOpen] = createSignal(storedPreview.open)
   const [previewOpen, setPreviewOpen] = createSignal(storedPreview.open)
-  const [previewReport, setPreviewReport] = createSignal<PaasPreviewReport>()
+  const [previewFile, setPreviewFile] = createSignal<PaasPreviewFile>()
   const [historyMount, setHistoryMount] = createSignal<HTMLElement>()
   const [historyMount, setHistoryMount] = createSignal<HTMLElement>()
   const [titleElement, setTitleElement] = createSignal<HTMLSpanElement>()
   const [titleElement, setTitleElement] = createSignal<HTMLSpanElement>()
   const [titleOverflow, setTitleOverflow] = createSignal(false)
   const [titleOverflow, setTitleOverflow] = createSignal(false)
@@ -193,8 +193,8 @@ export default function PaasWorkspace(
       // Storage can be unavailable in restricted webviews; the layout still works for this session.
       // Storage can be unavailable in restricted webviews; the layout still works for this session.
     }
     }
   }
   }
-  const openPreview = (report?: PaasPreviewReport) => {
-    if (report) setPreviewReport(report)
+  const openPreview = (file?: PaasPreviewFile) => {
+    if (file) setPreviewFile(file)
     setPreviewOpen(true)
     setPreviewOpen(true)
     savePreviewLayout()
     savePreviewLayout()
   }
   }
@@ -864,8 +864,8 @@ export default function PaasWorkspace(
               registerNewSession={(create) => (actions.newSession = create)}
               registerNewSession={(create) => (actions.newSession = create)}
               registerRename={(rename) => (actions.rename = rename)}
               registerRename={(rename) => (actions.rename = rename)}
               onTitle={(title) => setUI("chatTitle", title)}
               onTitle={(title) => setUI("chatTitle", title)}
-              onReportSnapshot={setPreviewReport}
-              onPreviewReport={openPreview}
+              onPreviewFile={openPreview}
+              onChatChanged={() => setPreviewFile(undefined)}
               visible={state.page === "chat"}
               visible={state.page === "chat"}
               agents={state.agents}
               agents={state.agents}
               openAgentID={ui.chatAgentID}
               openAgentID={ui.chatAgentID}
@@ -1409,7 +1409,7 @@ export default function PaasWorkspace(
             savePreviewLayout()
             savePreviewLayout()
           }}
           }}
         />
         />
-        <PaasPreview report={previewReport()} onClose={closePreview} />
+        <PaasPreview api={platform.paas} file={previewFile()} onClose={closePreview} />
       </Show>
       </Show>
     </div>
     </div>
   )
   )

+ 109 - 0
packages/app/src/pages/paas/paas.css

@@ -3314,3 +3314,112 @@
     padding-left: 84px;
     padding-left: 84px;
   }
   }
 }
 }
+
+/* Generated file cards open the right-side preview. */
+.paas-file-cards {
+  display: grid;
+  gap: 6px;
+  margin: 14px 0;
+}
+.paas-file-cards > header {
+  display: flex;
+  align-items: baseline;
+  gap: 8px;
+  color: var(--text-weak);
+  font-size: 12px;
+}
+.paas-file-cards > header strong {
+  color: var(--text-base);
+  font-size: 13px;
+}
+.paas-file-card {
+  display: flex;
+  align-items: center;
+  gap: 10px;
+  width: 100%;
+  min-height: 44px;
+  padding: 9px 12px;
+  border: 1px solid var(--border-weak-base);
+  border-radius: 10px;
+  background: var(--background-weak);
+  color: var(--text-base);
+  text-align: left;
+}
+.paas-file-card:hover {
+  border-color: var(--paas-accent);
+  background: color-mix(in srgb, var(--paas-accent) 7%, var(--background-weak));
+}
+.paas-file-card-icon {
+  display: grid;
+  place-items: center;
+  flex-shrink: 0;
+  width: 26px;
+  height: 26px;
+  border-radius: 7px;
+  background: var(--background-base);
+  color: var(--paas-accent);
+}
+.paas-file-card-name {
+  flex: 1;
+  min-width: 0;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+  font-size: 13px;
+}
+.paas-file-card small {
+  flex-shrink: 0;
+  color: var(--text-weak);
+  font-size: 11px;
+}
+.paas-file-card > [data-component="icon"]:last-child {
+  flex-shrink: 0;
+  color: var(--text-weak);
+}
+.paas-preview-heading span {
+  max-width: 220px;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+.paas-preview-meta small {
+  color: var(--text-weak);
+  font-size: 11px;
+}
+.paas-preview-status {
+  display: grid;
+  gap: 6px;
+  color: var(--text-weak);
+  font-size: 13px;
+  line-height: 1.6;
+}
+.paas-preview-status strong {
+  color: var(--text-base);
+}
+.paas-preview-status p {
+  margin: 0;
+}
+.paas-preview-text {
+  margin: 0;
+  white-space: pre-wrap;
+  overflow-wrap: anywhere;
+  color: var(--text-base);
+  font: 12px/1.65 "Cascadia Mono", Consolas, monospace;
+}
+.paas-preview-image {
+  display: block;
+  max-width: 100%;
+  height: auto;
+  border: 1px solid var(--border-weak-base);
+  border-radius: 8px;
+}
+.paas-preview-body {
+  display: flex;
+  flex-direction: column;
+}
+.paas-preview-pdf {
+  flex: 1;
+  width: 100%;
+  min-height: 420px;
+  border: 0;
+}

+ 145 - 18
packages/app/src/pages/paas/preview.tsx

@@ -1,24 +1,109 @@
-import { Show } from "solid-js"
+import { Show, createEffect, createSignal, onCleanup } from "solid-js"
 import { Icon } from "@opencode-ai/ui/icon"
 import { Icon } from "@opencode-ai/ui/icon"
 import { usePlatform } from "@/context/platform"
 import { usePlatform } from "@/context/platform"
+import type { PaasPlatform, PaasPreviewContent } from "@/paas"
 import { ResearchReport } from "./report"
 import { ResearchReport } from "./report"
 
 
-export type PaasPreviewReport = {
+export type PaasPreviewFile = {
   agentID: string
   agentID: string
-  runID?: string
-  title: string
-  text: string
+  runID: string
+  name: string
+  path?: string
+  artifactID?: string
+  mime?: string
+  size?: number
 }
 }
 
 
-export function PaasPreview(props: { report?: PaasPreviewReport; onClose: () => void }) {
+const textExtensions = /\.(txt|md|json|jsonl|ya?ml|csv|log|ts|tsx|js|jsx|py|sh|toml|ini|cfg|xml|html|css|sql|r|rb|go|rs|c|cpp|h|java)$/i
+const imageExtensions = /\.(png|jpe?g|webp|gif)$/i
+
+function formatSize(value?: number) {
+  if (!value || value < 0) return ""
+  if (value < 1024) return `${value} B`
+  if (value < 1024 * 1024) return `${Math.round(value / 1024)} KB`
+  return `${(value / 1024 / 1024).toFixed(1)} MB`
+}
+
+export function PaasPreview(props: { api?: PaasPlatform; file?: PaasPreviewFile; onClose: () => void }) {
   const platform = usePlatform()
   const platform = usePlatform()
-  const report = () => props.report
+  const [content, setContent] = createSignal<PaasPreviewContent>()
+  const [loading, setLoading] = createSignal(false)
+  const [error, setError] = createSignal("")
+  const [url, setUrl] = createSignal("")
+  let request = 0
+
+  const file = () => props.file
+  const kind = () => {
+    const name = file()?.name || ""
+    const mime = content()?.mime || file()?.mime || ""
+    if (/\.pdf$/i.test(name) || mime === "application/pdf") return "pdf"
+    if (imageExtensions.test(name) || mime.startsWith("image/")) return "image"
+    if (/\.md$/i.test(name) || mime === "text/markdown") return "markdown"
+    if (textExtensions.test(name) || mime.startsWith("text/")) return "text"
+    return "unsupported"
+  }
+  const text = () => {
+    const value = content()?.text || ""
+    if (!/\.jsonl?$/i.test(file()?.name || "")) return value
+    try {
+      return JSON.stringify(JSON.parse(value), null, 2)
+    } catch {
+      return value
+    }
+  }
+
+  createEffect(() => {
+    const target = file()
+    const api = props.api
+    const current = ++request
+    setContent(undefined)
+    setError("")
+    setLoading(!!target && !!api)
+    if (!target || !api) return
+    void api
+      .request({
+        action: "preview-file",
+        agentID: target.agentID,
+        runID: target.runID,
+        name: target.name,
+        path: target.path,
+        artifactID: target.artifactID,
+      })
+      .then((result) => {
+        if (current !== request) return
+        const value = result as PaasPreviewContent | undefined
+        if (!value || typeof value.name !== "string" || typeof value.mime !== "string") {
+          throw new Error("平台未返回可预览的文件内容。")
+        }
+        setContent(value)
+      })
+      .catch((reason: unknown) => {
+        if (current === request) setError(reason instanceof Error ? reason.message : "文件读取失败,请重试。")
+      })
+      .finally(() => {
+        if (current === request) setLoading(false)
+      })
+  })
+
+  createEffect(() => {
+    const value = content()
+    if (!value?.data || !(kind() === "image" || kind() === "pdf")) {
+      setUrl("")
+      return
+    }
+    const copy = new Uint8Array(value.data.byteLength)
+    copy.set(value.data)
+    const next = URL.createObjectURL(new Blob([copy.buffer], { type: value.mime }))
+    setUrl(next)
+    onCleanup(() => URL.revokeObjectURL(next))
+  })
+
   return (
   return (
     <aside class="paas-preview" id="paas-preview" aria-label="右侧预览">
     <aside class="paas-preview" id="paas-preview" aria-label="右侧预览">
       <header class="paas-preview-header">
       <header class="paas-preview-header">
         <div class="paas-preview-heading">
         <div class="paas-preview-heading">
           <strong>预览</strong>
           <strong>预览</strong>
-          <span>报告</span>
+          <span>{file()?.name || "文件"}</span>
         </div>
         </div>
         <button
         <button
           type="button"
           type="button"
@@ -31,25 +116,26 @@ export function PaasPreview(props: { report?: PaasPreviewReport; onClose: () =>
         </button>
         </button>
       </header>
       </header>
       <Show
       <Show
-        when={report()}
+        when={file()}
         fallback={
         fallback={
           <div class="paas-preview-empty">
           <div class="paas-preview-empty">
             <Icon name="layout-right" size="normal" />
             <Icon name="layout-right" size="normal" />
-            <strong>还没有可预览的报告</strong>
-            <p>在会话里打开一份研究报告后,这里会显示正文。</p>
+            <strong>还没有可预览的文件</strong>
+            <p>在会话里点击 Agent 生成的文件卡片后,这里会显示内容。</p>
           </div>
           </div>
         }
         }
       >
       >
-        {(value) => (
+        {(target) => (
           <>
           <>
             <div class="paas-preview-meta">
             <div class="paas-preview-meta">
-              <strong>{value().title}</strong>
-              <Show when={value().runID}>
-                <code>{value().runID}</code>
-              </Show>
+              <strong>{target().name}</strong>
+              <small>
+                {target().mime || kind()}
+                {formatSize(content()?.size || target().size) ? ` · ${formatSize(content()?.size || target().size)}` : ""}
+              </small>
             </div>
             </div>
             <div
             <div
-              class="paas-preview-body paas-report"
+              class="paas-preview-body"
               onClick={(event) => {
               onClick={(event) => {
                 const link = (event.target as HTMLElement).closest("a")
                 const link = (event.target as HTMLElement).closest("a")
                 if (!link || !/^https?:/.test(link.href)) return
                 if (!link || !/^https?:/.test(link.href)) return
@@ -57,7 +143,48 @@ export function PaasPreview(props: { report?: PaasPreviewReport; onClose: () =>
                 platform.openExternal(link.href)
                 platform.openExternal(link.href)
               }}
               }}
             >
             >
-              <ResearchReport text={value().text} />
+              <Show when={loading()}>
+                <p class="paas-preview-status" role="status">
+                  正在读取文件…
+                </p>
+              </Show>
+              <Show when={error()}>
+                <div class="paas-preview-status" role="alert">
+                  <strong>文件无法预览</strong>
+                  <p>{error()}</p>
+                </div>
+              </Show>
+              <Show when={!loading() && !error() && content()}>
+                {(value) => (
+                  <Show
+                    when={kind() !== "unsupported"}
+                    fallback={
+                      <div class="paas-preview-status">
+                        <strong>暂不支持预览此类型</strong>
+                        <p>
+                          {value().mime || "未知类型"}
+                          {formatSize(value().size) ? ` · ${formatSize(value().size)}` : ""}
+                        </p>
+                      </div>
+                    }
+                  >
+                    <Show when={kind() === "markdown"}>
+                      <div class="paas-report">
+                        <ResearchReport text={text()} />
+                      </div>
+                    </Show>
+                    <Show when={kind() === "text"}>
+                      <pre class="paas-preview-text">{text()}</pre>
+                    </Show>
+                    <Show when={kind() === "image"}>
+                      <img class="paas-preview-image" src={url()} alt={target().name} />
+                    </Show>
+                    <Show when={kind() === "pdf"}>
+                      <iframe class="paas-preview-pdf" title={target().name} src={url()} />
+                    </Show>
+                  </Show>
+                )}
+              </Show>
             </div>
             </div>
           </>
           </>
         )}
         )}

+ 42 - 0
packages/desktop/src/main/paas.test.ts

@@ -564,3 +564,45 @@ test("authenticated identity keeps equal-permission key rotations together and o
     await server.stop(true)
     await server.stop(true)
   }
   }
 })
 })
+
+test("workspace file previews are read-only and reuse the authenticated route", async () => {
+  const requests: string[] = []
+  const server = Bun.serve({
+    port: 0,
+    hostname: "127.0.0.1",
+    fetch(request) {
+      const path = new URL(request.url).pathname
+      if (path.endsWith("/auth/me")) return new Response("missing", { status: 404 })
+      expect(request.headers.get("Authorization")).toBe("Bearer test-only")
+      requests.push(path)
+      if (path.endsWith("/workspace/report.md"))
+        return new Response("# Draft\n\ncontent", { headers: { "content-type": "text/markdown" } })
+      return Response.json({ agents: [] })
+    },
+  })
+  const connections = createPaasConnections()
+  try {
+    await connections.connect(1, { url: server.url.origin, apiKey: "test-only" })
+    const preview = await connections.request(1, {
+      action: "preview-file",
+      agentID: "a",
+      runID: "r",
+      name: "report.md",
+      path: "report.md",
+    })
+    expect(preview).toMatchObject({ name: "report.md", mime: "text/markdown", text: "# Draft\n\ncontent" })
+    expect(requests.at(-1)).toBe("/api/v1/agents/a/runs/r/workspace/report.md")
+    await expect(
+      connections.request(1, {
+        action: "preview-file",
+        agentID: "a",
+        runID: "r",
+        name: "secret.md",
+        path: "../secret.md",
+      }),
+    ).rejects.toThrow("编号无效")
+  } finally {
+    connections.disconnect(1)
+    server.stop(true)
+  }
+})

+ 41 - 1
packages/desktop/src/main/paas.ts

@@ -292,10 +292,50 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
             : undefined,
             : undefined,
         )
         )
       }
       }
-      if (["run-files", "download", "cancel", "pause", "resume", "confirm"].includes(input?.action)) {
+      if (["run-files", "download", "preview-file", "cancel", "pause", "resume", "confirm"].includes(input?.action)) {
         if (!("agentID" in input) || !("runID" in input)) throw new Error("缺少任务编号。")
         if (!("agentID" in input) || !("runID" in input)) throw new Error("缺少任务编号。")
         const path = `/agents/${identifier(input.agentID)}/runs/${identifier(input.runID)}`
         const path = `/agents/${identifier(input.agentID)}/runs/${identifier(input.runID)}`
         if (input.action === "run-files") return request(connection, `${path}/workspace`)
         if (input.action === "run-files") return request(connection, `${path}/workspace`)
+        if (input.action === "preview-file") {
+          if (!input.path && !input.artifactID) throw new Error("缺少文件路径。")
+          const resource = input.artifactID
+            ? `artifacts/${identifier(input.artifactID)}/download`
+            : `workspace/${(input.path || "").split("/").map(identifier).join("/")}`
+          const response = await request(connection, `${path}/${resource}`, undefined, undefined, 120000, "GET", true)
+          if (!(response instanceof Response)) throw new Error("平台未返回可预览的文件。")
+          const header = response.headers.get("content-type")?.split(";")[0]?.trim() || ""
+          const extension = input.name.split(".").pop()?.toLowerCase() || ""
+          const known: Record<string, string> = {
+            md: "text/markdown",
+            txt: "text/plain",
+            csv: "text/csv",
+            json: "application/json",
+            jsonl: "application/x-ndjson",
+            yml: "text/yaml",
+            yaml: "text/yaml",
+            png: "image/png",
+            jpg: "image/jpeg",
+            jpeg: "image/jpeg",
+            webp: "image/webp",
+            gif: "image/gif",
+            pdf: "application/pdf",
+          }
+          const mime = header && header !== "application/octet-stream" ? header : known[extension] || "application/octet-stream"
+          const isText =
+            mime.startsWith("text/") ||
+            ["application/json", "application/x-ndjson", "application/xml", "application/javascript"].includes(mime) ||
+            ["md", "txt", "csv", "json", "jsonl", "yml", "yaml", "log", "ts", "tsx", "js", "jsx", "py"].includes(
+              extension,
+            )
+          const limit = isText ? 512 * 1024 : mime === "application/pdf" ? 50 * 1024 * 1024 : 20 * 1024 * 1024
+          const advertised = Number(response.headers.get("content-length") || 0)
+          if (advertised > limit) throw new Error("文件较大,请下载后查看。")
+          const data = new Uint8Array(await response.arrayBuffer())
+          if (data.byteLength > limit) throw new Error("文件较大,请下载后查看。")
+          return isText
+            ? { name: input.name, mime, size: data.byteLength, text: new TextDecoder().decode(data) }
+            : { name: input.name, mime, size: data.byteLength, data }
+        }
         if (input.action === "download") {
         if (input.action === "download") {
           const resource = input.artifactID
           const resource = input.artifactID
             ? `artifacts/${identifier(input.artifactID)}/download`
             ? `artifacts/${identifier(input.artifactID)}/download`