Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(work): show file Works live in chat and share, preview in portal (#20535)

YuTengjing974d87d284e6
diff --git a/.agents/skills/agent-work/SKILL.md b/.agents/skills/agent-work/SKILL.md
index d9a69e72156..049cd712123 100644
--- a/.agents/skills/agent-work/SKILL.md
+++ b/.agents/skills/agent-work/SKILL.md
@@ -19,6 +19,11 @@ Two tables (`packages/database/src/schemas/work.ts`):
**Read-path compatibility gate**: `OPT_IN_WORK_TYPES` (currently `{'file'}`) hides newer types from clients that did not opt in (`includeFileWorks`). Released Electron clients lag by weeks and crash on unknown type descriptors (`descriptor.getIcon` on `undefined`), so a request without the opt-in receives exactly the pre-`file` set. Any NEW Work type must ship behind the same kind of opt-in.
+The gate has two kinds of emission points, and both must honor the client's declaration:
+
+- **Pulled reads** (`message.getMessages`, `work.*` lists, `shareChat.getMessages`): the client service passes `includeFileWorks: true` on the request.
+- **Pushed payloads** (the `uiMessages` snapshots and `message_patch` revisions built by `AgentRuntimeService.queryUiMessages`): no request carries the opt-in, so the starting client declares the `file_works` stream feature and the run stores it as `state.host.acceptsFileWorks`; approval continuations and group members inherit it. A pushed path that skips this check drops the card until the user reloads the page.
+
## Access scope (Agent Share visitors)
A share visitor's run executes as the creator, so owner scope alone cannot separate its Works. Every Work read and write takes a `WorkAccessScope` (`packages/types/src/work.ts`): `ordinary` sees only rows without share provenance; `agentShare` sees only rows stamped in `works.metadata.agentShare` with exactly that share/topic/visitor.
@@ -87,7 +92,7 @@ The whole scan returns `{attempted, failed}` and the completion backstop (`Compl
## Key decisions (from the Work PRs)
- **Only successful create/edit results become Works** (LOBE-10967). Read-only queries, comments, merges/closes, and branch/repo operations are excluded β€” `gh pr view` printing an entity URL must NOT register.
-- **`owner/repo#number` is the canonical github identity**, not node\_id: the gh CLI surface never returns node\_id, and the same entity touched via REST tools and CLI must land on one Work row.
+- **`owner/repo#number` is the canonical github identity**, not node_id: the gh CLI surface never returns node_id, and the same entity touched via REST tools and CLI must land on one Work row.
- **stdout is the source of truth for identity** on the CLI path (`gh … create/edit` prints the entity URL); the command's edit target is the fallback. The LAST gh create/edit segment of a chained command owns the trailing URL.
- **Persisted URLs are http(s)-allowlisted** (`sanitizeExternalUrl`): gh stdout / tool results are member-controlled and the URL reaches `shell.openExternal` on desktop.
- **The tokenizer is deliberately hand-rolled** (no `shell-quote` dep): a real parser would expand what must stay literal, and the worst failure mode is skipping a bookkeeping registration.
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
index 81d8bb4fc77..5c0778d2362 100644
--- a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts
@@ -219,6 +219,34 @@ describe('AI Agent Router Integration Tests', () => {
expect(createOperationCalls()).toEqual([false, false]);
});
+ // Only a client that declares `file_works` gets file Work cards in the
+ // pushed snapshots; a released desktop crashes on that Work type.
+ it('forwards a declared file_works stream feature on both routes', async () => {
+ const { AgentRuntimeService } = await import('@/server/services/agentRuntime');
+ const caller = aiAgentRouter.createCaller(createTestContext());
+ const createOperationCalls = () =>
+ vi
+ .mocked(AgentRuntimeService)
+ .mock.results.flatMap((r) => (r.value as any).createOperation.mock.calls)
+ .map(([params]) => params.acceptsFileWorks);
+
+ vi.mocked(AgentRuntimeService).mockClear();
+ await caller.execAgent({
+ agentId: testAgentId,
+ prompt: 'single',
+ streamFeatures: ['file_works'],
+ });
+ await caller.execAgents({
+ tasks: [{ agentId: testAgentId, prompt: 'batch', streamFeatures: ['file_works'] }],
+ });
+ expect(createOperationCalls()).toEqual([true, true]);
+
+ vi.mocked(AgentRuntimeService).mockClear();
+ await caller.execAgent({ agentId: testAgentId, prompt: 'undeclared single' });
+ await caller.execAgents({ tasks: [{ agentId: testAgentId, prompt: 'undeclared' }] });
+ expect(createOperationCalls()).toEqual([false, false]);
+ });
+
it('should create a new topic when topicId is not provided', async () => {
const caller = aiAgentRouter.createCaller(createTestContext());
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 5cc4ba8bbcb..77a594af178 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -550,9 +550,10 @@ export const dispatchClaimedAgentIntervention = async (
* `acceptsMemberRuntimeEnd`: the resolving client's own declaration when that
* client is the one subscribing to the continuation (the Web source bridge).
* Left unset for a resolver that isn't (token Review), so the continuation
- * inherits the parked operation's declaration.
+ * inherits the parked operation's declaration. `acceptsFileWorks` follows
+ * the same rule.
*/
- options: { acceptsMemberRuntimeEnd?: boolean } = {},
+ options: { acceptsFileWorks?: boolean; acceptsMemberRuntimeEnd?: boolean } = {},
): Promise<{ execution?: ExecAgentResult; status: AgentInterventionReviewStatus }> => {
const { runtimeAction } = resolution;
let execution: ExecAgentResult | undefined;
@@ -636,6 +637,7 @@ export const dispatchClaimedAgentIntervention = async (
const skipped = customAction.type === 'skipped';
execution = await ctx.aiAgentService.execAgent({
agentId: runtimeAction.agentId,
+ acceptsFileWorks: options.acceptsFileWorks,
acceptsMemberRuntimeEnd: options.acceptsMemberRuntimeEnd,
approvalResolutionRequestId: resolution.resolutionRequestId,
approvalSourceOperationId: runtimeAction.operationId,
@@ -672,6 +674,7 @@ export const dispatchClaimedAgentIntervention = async (
const [singleDecision] = runtimeAction.decisions;
execution = await ctx.aiAgentService.execAgent({
agentId: runtimeAction.agentId,
+ acceptsFileWorks: options.acceptsFileWorks,
acceptsMemberRuntimeEnd: options.acceptsMemberRuntimeEnd,
approvalResolutionRequestId: resolution.resolutionRequestId,
approvalSourceOperationId: runtimeAction.operationId,
@@ -694,6 +697,7 @@ export const dispatchClaimedAgentIntervention = async (
case 'resume_tool_result': {
execution = await ctx.aiAgentService.execAgent({
agentId: runtimeAction.agentId,
+ acceptsFileWorks: options.acceptsFileWorks,
acceptsMemberRuntimeEnd: options.acceptsMemberRuntimeEnd,
approvalResolutionRequestId: resolution.resolutionRequestId,
approvalSourceOperationId: runtimeAction.operationId,
@@ -1053,6 +1057,14 @@ const StartExecutionSchema = z.object({
const acceptsMemberRuntimeEndOf = (streamFeatures: string[] | undefined): boolean =>
streamFeatures?.includes('member_runtime_end') ?? false;
+/**
+ * Whether the calling client declared it renders `file` Works in pushed
+ * snapshots (`streamFeatures`). Same boolean contract as
+ * {@link acceptsMemberRuntimeEndOf}.
+ */
+const acceptsFileWorksOf = (streamFeatures: string[] | undefined): boolean =>
+ streamFeatures?.includes('file_works') ?? false;
+
/** A client's declaration that it can run relayed LLM attempts (`agent_llm_relay`). */
const LlmExecutorSchema = z.object({
capabilities: z.array(z.string()).max(16),
@@ -1173,7 +1185,8 @@ const ExecAgentSchema = z
/**
* Gateway stream features the calling client handles. `member_runtime_end`:
* a group member's terminal arrives on the supervisor's channel under that
- * name instead of `agent_runtime_end`. Free-form strings so an older server
+ * name instead of `agent_runtime_end`. `file_works`: pushed snapshots may
+ * carry `file` Work summaries. Free-form strings so an older server
* ignores features it does not know rather than rejecting the run.
*/
streamFeatures: z.array(z.string()).optional(),
@@ -1373,7 +1386,7 @@ export const bridgeLegacyResumeToSourceIntervention = async (
},
ctx: AgentInterventionDispatchContext,
/** Forwarded to {@link dispatchClaimedAgentIntervention}; see its `options`. */
- options: { acceptsMemberRuntimeEnd?: boolean } = {},
+ options: { acceptsFileWorks?: boolean; acceptsMemberRuntimeEnd?: boolean } = {},
): Promise<ExecAgentResult | undefined> => {
const {
messageModel,
@@ -2527,11 +2540,15 @@ export const aiAgentRouter = router({
resumeToolResult,
},
ctx,
- { acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures) },
+ {
+ acceptsFileWorks: acceptsFileWorksOf(input.streamFeatures),
+ acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),
+ },
);
if (bridged) return bridged;
const result = await ctx.aiAgentService.execAgent({
+ acceptsFileWorks: acceptsFileWorksOf(input.streamFeatures),
acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),
agentId,
appContext,
@@ -2700,6 +2717,7 @@ export const aiAgentRouter = router({
workspaceId: ctx.workspaceId,
});
const result = await ctx.aiAgentService.execAgent({
+ acceptsFileWorks: acceptsFileWorksOf(task.streamFeatures),
acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(task.streamFeatures),
clientProtocol: task.clientProtocol,
includeFinalState: task.includeFinalState,
@@ -3653,6 +3671,7 @@ export const aiAgentRouter = router({
}
const dispatch = await dispatchClaimedAgentIntervention(resolution, ctx, {
+ acceptsFileWorks: acceptsFileWorksOf(input.streamFeatures),
acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),
});
return {
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index 5b9435a6e53..7dce326318d 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -536,6 +536,34 @@ describe('AgentRuntimeService', () => {
},
);
+ describe('file Works declaration (host.acceptsFileWorks)', () => {
+ it('stores the declaration the client made', async () => {
+ await service.createOperation({ ...mockParams, acceptsFileWorks: true, autoStart: false });
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.host.acceptsFileWorks).toBe(true);
+ });
+
+ it("lets a group member inherit its supervisor's declaration", async () => {
+ await mockCoordinator.saveAgentState('parent-op', { host: { acceptsFileWorks: true } });
+ mockCoordinator.saveAgentState.mockClear();
+
+ await service.createOperation({
+ ...mockParams,
+ appContext: { ...mockParams.appContext, orchestrationRole: 'member' },
+ autoStart: false,
+ parentOperationId: 'parent-op',
+ });
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.host.acceptsFileWorks).toBe(true);
+ });
+
+ it.each([undefined, false])('carries no declaration for %s', async (acceptsFileWorks) => {
+ await service.createOperation({ ...mockParams, acceptsFileWorks, autoStart: false });
+ const savedState = mockCoordinator.saveAgentState.mock.calls[0][1];
+ expect(savedState.host).not.toHaveProperty('acceptsFileWorks');
+ });
+ });
+
describe('relay executor (host.llmExecutor)', () => {
const executor = { capabilities: ['llm_relay@1'], clientId: 'tab-a', providers: ['ollama'] };
@@ -2873,6 +2901,60 @@ describe('AgentRuntimeService', () => {
expect(result).toEqual(stubMessages);
});
+ it('assembles a share visitor run snapshot under the visitor share Work scope', async () => {
+ // Regression: the visitor's Works are registered under their share scope,
+ // which the ordinary scope never resolves. Without it the terminal
+ // snapshot carried no Work card, so a sandbox-exported pptx only showed
+ // its card after the visitor reloaded the page.
+ const queryMessages = vi.fn().mockResolvedValue([]);
+ stubMessageService(service, queryMessages);
+
+ await service.queryUiMessages({
+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },
+ principal: {
+ actor: { shareVisitor: { shareId: 'share_1', visitorUserId: 'visitor_1' } },
+ },
+ } as any);
+
+ expect(queryMessages).toHaveBeenCalledWith(
+ expect.objectContaining({ includeFileWorks: true, topicId: 'tpc_1' }),
+ {
+ allowShareVisitor: true,
+ workAccessScope: {
+ shareId: 'share_1',
+ topicId: 'tpc_1',
+ type: 'agentShare',
+ visitorUserId: 'visitor_1',
+ },
+ },
+ );
+ });
+
+ it('keeps the ordinary Work scope and file-Work gate for a non-share run', async () => {
+ const queryMessages = vi.fn().mockResolvedValue([]);
+ stubMessageService(service, queryMessages);
+
+ await service.queryUiMessages({ origin: { agentId: 'agt_1', topicId: 'tpc_1' } } as any);
+
+ expect(queryMessages.mock.calls[0][0].includeFileWorks).toBeUndefined();
+ expect(queryMessages.mock.calls[0][1]).toEqual({ allowShareVisitor: true });
+ });
+
+ it('includes file Works for an ordinary run whose client declared it renders them', async () => {
+ // Regression: an ordinary run's terminal snapshot/patch dropped the
+ // exported pptx card until the user reloaded the conversation.
+ const queryMessages = vi.fn().mockResolvedValue([]);
+ stubMessageService(service, queryMessages);
+
+ await service.queryUiMessages({
+ host: { acceptsFileWorks: true },
+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },
+ } as any);
+
+ expect(queryMessages.mock.calls[0][0].includeFileWorks).toBe(true);
+ expect(queryMessages.mock.calls[0][1]).toEqual({ allowShareVisitor: true });
+ });
+
it.each([undefined, 'visitor_1'])(
'includes visitor rows (visitor=%s)',
async (visitorUserId) => {
@@ -2892,7 +2974,10 @@ describe('AgentRuntimeService', () => {
// The pushed snapshot always carries whole tool payloads now: it only
// reaches a client that did not ask for protocol 2, which has no way to
// fetch an omitted payload back.
- expect(queryMessages).toHaveBeenCalledWith(expect.anything(), { allowShareVisitor: true });
+ expect(queryMessages).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ allowShareVisitor: true }),
+ );
},
);
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index dddeb82afed..03280232011 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -95,7 +95,10 @@ import { QueueService } from '@/server/services/queue';
import { LocalQueueServiceImpl } from '@/server/services/queue/impls';
import { ToolExecutionService } from '@/server/services/toolExecution';
import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';
-import { stateHasEntityFileEdits } from '@/server/services/workRegistration';
+import {
+ resolveRunWorkAccessScope,
+ stateHasEntityFileEdits,
+} from '@/server/services/workRegistration';
import { resolveMessageFileUrls } from '../message/resolveMessageFileUrls';
import { isAbortError, throwIfAborted } from './abort';
@@ -830,6 +833,21 @@ export class AgentRuntimeService {
}
}
+ /**
+ * Whether the client that started this operation declared it renders `file`
+ * Works. An unknown or expired operation reads as `false`, so a continuation
+ * then keeps the pushed snapshot every client can render.
+ */
+ async acceptsFileWorks(operationId: string): Promise<boolean> {
+ try {
+ const state = await this.coordinator.loadAgentState(operationId);
+ return state?.host?.acceptsFileWorks === true;
+ } catch (error) {
+ log('[%s] Failed to read the file Works declaration: %O', operationId, error);
+ return false;
+ }
+ }
+
/**
* Whether the client that started this operation declared it handles
* `member_runtime_end`. An unknown or expired operation reads as `false`, so
@@ -1153,6 +1171,7 @@ export class AgentRuntimeService {
*/
async createOperation(params: OperationCreationParams): Promise<OperationCreationResult> {
const {
+ acceptsFileWorks,
acceptsMemberRuntimeEnd,
activeDeviceId,
activeDeviceScope,
@@ -1312,6 +1331,13 @@ export class AgentRuntimeService {
parentOperationId,
appContext?.orchestrationRole === 'member',
);
+ // A member's pushes reach the supervisor's client, so it renders what
+ // that client declared.
+ const fileWorksAccepted =
+ acceptsFileWorks ??
+ (parentOperationId && appContext?.orchestrationRole === 'member'
+ ? await this.acceptsFileWorks(parentOperationId)
+ : undefined);
const initialState = {
activatedStepTools,
@@ -1334,6 +1360,7 @@ export class AgentRuntimeService {
// What the host needs to deliver and retry the run. Hooks are stamped
// right after creation once the dispatcher has serialized them.
host: {
+ ...(fileWorksAccepted === true && { acceptsFileWorks: true }),
...(params.clientProtocol === 2 && { clientProtocol: 2 as const }),
...(params.includeFinalState === true && { includeFinalState: true }),
...(llmExecutor && { llmExecutor }),
@@ -1625,11 +1652,27 @@ export class AgentRuntimeService {
const threadId: string | undefined = agentState?.origin?.threadId ?? undefined;
if (!agentId || !topicId) return undefined;
+ // A share visitor's Works are registered under the visitor's share scope
+ // (`registerFileWorks`), which the ordinary scope never resolves β€” without
+ // it the terminal snapshot carries no Work card and the visitor only sees
+ // it after a reload through `shareChat.getMessages`. The visitor surface
+ // always opts in to file Works on that read path, and visitor runs never
+ // use message patches, so this snapshot only ever reaches that client.
+ const workAccessScope = resolveRunWorkAccessScope({
+ shareVisitor: agentState?.principal?.actor?.shareVisitor,
+ topicId,
+ });
+ const isShareVisitorRun = !!workAccessScope;
+ // `file` Works stay out of the push unless the receiving client declared
+ // it renders them: released desktop builds crash on the unknown type.
+ const includeFileWorks = isShareVisitorRun || agentState?.host?.acceptsFileWorks === true;
+
try {
return await this.messageService.queryMessages(
{
agentId,
groupId,
+ ...(includeFileWorks && { includeFileWorks: true }),
skipWorks: options?.skipWorks,
threadId,
topicId,
@@ -1641,7 +1684,7 @@ export class AgentRuntimeService {
// terminal Source of Truth β€” wiping the conversation the run just
// produced. Visitor-facing redaction of the pushed snapshot happens in
// `GatewayStreamNotifier`.
- { allowShareVisitor: true },
+ { allowShareVisitor: true, ...(workAccessScope && { workAccessScope }) },
);
} catch (error) {
// Stream events must never fail the step. If the DB hiccups, fall back
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 58385f654cd..3f5e4321fbc 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -419,6 +419,13 @@ export interface ExecGroupMemberResult {
}
export interface OperationCreationParams {
+ /**
+ * The client starting this run renders `file` Works (declared via
+ * `aiAgent.execAgent`'s `streamFeatures`). Stored on
+ * `state.host.acceptsFileWorks`; a group member run streaming on its
+ * supervisor's channel inherits the supervisor's when it declares none.
+ */
+ acceptsFileWorks?: boolean;
/**
* The client starting this run handles `member_runtime_end` (declared via
* `aiAgent.execAgent`'s `streamFeatures`). Persisted on the op's metadata so
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts
index 8c2a5339d3e..4c6f2c49d8e 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts
@@ -152,6 +152,7 @@ vi.mock('@/database/models/userMemory/persona', () => ({
vi.mock('@/server/services/agentRuntime', () => ({
AgentRuntimeService: vi.fn().mockImplementation(function () {
return {
+ acceptsFileWorks: vi.fn().mockResolvedValue(false),
acceptsMemberRuntimeEnd: vi.fn().mockResolvedValue(false),
getLlmExecutor: vi.fn().mockResolvedValue(undefined),
completeGroupActionMember: mockCompleteGroupActionMember,
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 91195361f98..2b5d12f634c 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1548,6 +1548,7 @@ export class AiAgentService {
},
runContext,
{
+ acceptsFileWorks: params.acceptsFileWorks,
acceptsMemberRuntimeEnd: params.acceptsMemberRuntimeEnd,
approvalClaim,
approvalSourceOperationId,
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts
index fbdaf370287..71eb14a2f14 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts
@@ -11,6 +11,7 @@ const sourceExecutor = { capabilities: ['llm_relay@1'], clientId: 'tab-a', provi
const setup = (sourceAccepts: boolean) => {
const calls: string[] = [];
const agentRuntimeService = {
+ acceptsFileWorks: vi.fn(async () => sourceAccepts),
acceptsMemberRuntimeEnd: vi.fn(async () => {
calls.push('read-source');
return sourceAccepts;
@@ -146,3 +147,31 @@ describe('startOperation β€Ί relay executor', () => {
);
});
});
+
+describe('startOperation β€Ί file_works declaration', () => {
+ it('carries the parked operation declaration over to an approval continuation', async () => {
+ const { agentRuntimeService, ctx, deps, input } = setup(true);
+
+ await startOperation(deps, ctx, input({ approvalSourceOperationId: 'op-parked' }));
+
+ expect(agentRuntimeService.acceptsFileWorks).toHaveBeenCalledWith('op-parked');
+ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(
+ expect.objectContaining({ acceptsFileWorks: true }),
+ );
+ });
+
+ it('keeps a resuming client explicit false over the parked operation declaration', async () => {
+ const { agentRuntimeService, ctx, deps, input } = setup(true);
+
+ await startOperation(
+ deps,
+ ctx,
+ input({ acceptsFileWorks: false, approvalSourceOperationId: 'op-parked' }),
+ );
+
+ expect(agentRuntimeService.acceptsFileWorks).not.toHaveBeenCalled();
+ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(
+ expect.objectContaining({ acceptsFileWorks: false }),
+ );
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index 6150e5f7d2a..9e9f99d2a57 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -26,6 +26,8 @@ export interface StartOperationDeps {
}
export interface StartOperationInput {
+ /** See {@link InternalExecAgentParams.acceptsFileWorks}. */
+ acceptsFileWorks?: boolean;
/** See {@link InternalExecAgentParams.acceptsMemberRuntimeEnd}. */
acceptsMemberRuntimeEnd?: boolean;
approvalClaim: ApprovalClaimState;
@@ -100,6 +102,7 @@ export const startOperation = async (
userMessageId,
} = ctx;
const {
+ acceptsFileWorks,
acceptsMemberRuntimeEnd,
approvalClaim,
approvalSourceOperationId,
@@ -169,7 +172,15 @@ export const startOperation = async (
(approvalSourceOperationId
? await deps.agentRuntimeService.getLlmExecutor(approvalSourceOperationId)
: undefined);
+ // Its `file_works` declaration too, or the continuation's terminal push
+ // would drop the file Work card the parked client can render.
+ const fileWorksAccepted =
+ acceptsFileWorks ??
+ (approvalSourceOperationId
+ ? await deps.agentRuntimeService.acceptsFileWorks(approvalSourceOperationId)
+ : undefined);
const result = await deps.agentRuntimeService.createOperation({
+ acceptsFileWorks: fileWorksAccepted,
acceptsMemberRuntimeEnd: memberRuntimeEndAccepted,
clientProtocol: input.clientProtocol,
includeFinalState: input.includeFinalState,
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index 502ea8499da..651125ba137 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -74,6 +74,12 @@ export interface ExecRunContext {
* This extends the public ExecAgentParams with server-side only options
*/
export interface InternalExecAgentParams extends ExecAgentParams {
+ /**
+ * The calling client renders `file` Works in pushed snapshots, derived from
+ * the `streamFeatures` it declared on `aiAgent.execAgent`. See
+ * `OperationCreationParams.acceptsFileWorks`.
+ */
+ acceptsFileWorks?: boolean;
/**
* The calling client handles `member_runtime_end`, derived from the
* `streamFeatures` it declared on `aiAgent.execAgent`. See
diff --git a/apps/server/src/services/message/index.ts b/apps/server/src/services/message/index.ts
index bb8b0d180f0..4dca1e8796c 100644
--- a/apps/server/src/services/message/index.ts
+++ b/apps/server/src/services/message/index.ts
@@ -8,6 +8,7 @@ import {
type QueryMessageParams,
type UIChatMessage,
type UpdateMessageParams,
+ type WorkAccessScope,
} from '@lobechat/types';
import { createTimingHelpers, getDurationMs } from '@lobechat/utils';
@@ -188,11 +189,14 @@ export class MessageService {
* authorized may opt in.
*/
allowShareVisitor?: boolean;
+ /** Agent Share boundary for the Work summaries (see `MessageModel.query`). */
+ workAccessScope?: WorkAccessScope;
},
): Promise<UIChatMessage[]> {
return this.messageModel.query(params, {
...this.getQueryOptions(),
...(options?.allowShareVisitor && { allowShareVisitor: true }),
+ ...(options?.workAccessScope && { workAccessScope: options.workAccessScope }),
});
}
diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.ts
index 0d702909a42..ce9742c6e1b 100644
--- a/packages/agent-gateway-client/src/types.ts
+++ b/packages/agent-gateway-client/src/types.ts
@@ -9,8 +9,11 @@ import type { UIChatMessage } from '@lobechat/types';
*
* - `member_runtime_end`: a mirrored group member's terminal arrives on the
* supervisor's channel as `member_runtime_end` instead of `agent_runtime_end`.
+ * - `file_works`: pushed message snapshots and patches may carry `file` Work
+ * summaries. Released desktop builds predate that Work type and crash on it,
+ * so the server keeps it out of the push unless the client declares this.
*/
-export type AgentStreamClientFeature = 'member_runtime_end';
+export type AgentStreamClientFeature = 'file_works' | 'member_runtime_end';
export type AgentStreamEventType =
| 'agent_runtime_init'
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index d432eaf5902..478e2b31062 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -168,6 +168,13 @@ export interface AgentRunPlan {
* carried by the runtime without interpretation.
*/
export interface AgentRunHostEnvelope {
+ /**
+ * The client that started this run renders `file` Works, so the pushed
+ * `uiMessages` snapshots and `message_patch` revisions may carry them.
+ * Declared by the client, like `clientProtocol`; absent keeps them out, which
+ * is what a released desktop build without the `file` descriptor needs.
+ */
+ acceptsFileWorks?: boolean;
/**
* Wire protocol the client that started this run asked for. `2` means that
* client reconciles its message list from `message_patch` revisions, so the
diff --git a/src/features/Conversation/Messages/MessageWorks/index.tsx b/src/features/Conversation/Messages/MessageWorks/index.tsx
index 3741932508a..df08b39fb5b 100644
--- a/src/features/Conversation/Messages/MessageWorks/index.tsx
+++ b/src/features/Conversation/Messages/MessageWorks/index.tsx
@@ -4,13 +4,12 @@ import type { WorkSummaryItem } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import isEqual from 'fast-deep-equal';
-import { memo, useCallback } from 'react';
+import { memo } from 'react';
-import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';
-import { createShareVisitorDocumentModal } from '@/features/Work/ShareVisitorDocumentModal';
import WorkSummaryCard from '@/features/Work/WorkSummaryCard';
import { dataSelectors, useConversationStore } from '../../store';
+import { useVisitorWorkOpen } from './useVisitorWorkOpen';
const styles = createStaticStyles(({ css }) => ({
container: css`
@@ -32,42 +31,8 @@ const MessageWorks = memo<MessageWorksProps>(({ rootOperationId }) => {
isEqual,
);
- // Agent-share visitor surface: the card's default open targets (Portal
- // document viewer, file preview, task detail) are all owner-scoped and the
- // page mounts no Portal, so route opens through share-authorized paths
- // instead. `/f/:id` is public by id, so file URLs open directly.
const agentShareId = useConversationStore((s) => s.context.agentShareId);
- const topicId = useConversationStore((s) => s.context.topicId);
- const handleVisitorOpen = useCallback(
- (item: WorkSummaryItem) => {
- if (!agentShareId || !topicId) return;
- const descriptor = getWorkTypeDescriptor(item);
- const target = descriptor.getOpenTarget(item);
- if (!target) return;
-
- switch (target.kind) {
- case 'document': {
- createShareVisitorDocumentModal({
- documentId: target.documentId,
- shareId: agentShareId,
- title: descriptor.getTitle(item)?.trim() || descriptor.getIdentifier(item) || item.id,
- topicId,
- });
- return;
- }
- case 'external':
- case 'filePreview': {
- if (isSafeExternalUrl(target.url))
- window.open(target.url, '_blank', 'noopener,noreferrer');
- return;
- }
- default: {
- return;
- }
- }
- },
- [agentShareId, topicId],
- );
+ const handleVisitorOpen = useVisitorWorkOpen();
if (data.length === 0) return null;
diff --git a/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.test.ts b/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.test.ts
new file mode 100644
index 00000000000..55def30aae6
--- /dev/null
+++ b/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.test.ts
@@ -0,0 +1,58 @@
+import type { WorkSummaryItem } from '@lobechat/types';
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useVisitorWorkOpen } from './useVisitorWorkOpen';
+
+const openFilePreview = vi.fn();
+const conversationState = { context: { agentShareId: 'share_1', topicId: 'tpc_1' } };
+
+vi.mock('../../store', () => ({
+ useConversationStore: (selector: (s: unknown) => unknown) => selector(conversationState),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: unknown) => unknown) => selector({ openFilePreview }),
+}));
+
+vi.mock('@/features/Work/ShareVisitorDocumentModal', () => ({
+ createShareVisitorDocumentModal: vi.fn(),
+}));
+
+const fileWork = (fileUrl: string) =>
+ ({
+ event: { metadata: { fileId: 'file_1', filePath: '/hello_world.pptx', fileUrl } },
+ id: 'wk_1',
+ title: 'hello_world.pptx',
+ type: 'file',
+ }) as unknown as WorkSummaryItem;
+
+describe('useVisitorWorkOpen', () => {
+ beforeEach(() => {
+ openFilePreview.mockReset();
+ });
+
+ it('previews a file Work in the portal from its public URL instead of a new tab', () => {
+ // Regression: the visitor handler used to `window.open` the file URL,
+ // leaving the share page for a bare download tab.
+ const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null);
+ const { result } = renderHook(() => useVisitorWorkOpen());
+
+ result.current(fileWork('https://app.lobehub.com/f/file_1'));
+
+ expect(openFilePreview).toHaveBeenCalledWith({
+ fileId: 'file_1',
+ source: { name: 'hello_world.pptx', url: 'https://app.lobehub.com/f/file_1' },
+ });
+ expect(windowOpen).not.toHaveBeenCalled();
+ windowOpen.mockRestore();
+ });
+
+ it('does not open a preview for a non-http(s) file URL', () => {
+ const { result } = renderHook(() => useVisitorWorkOpen());
+
+ result.current(fileWork('javascript:alert(1)'));
+
+ expect(openFilePreview).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.ts b/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.ts
new file mode 100644
index 00000000000..b5c7f1c021c
--- /dev/null
+++ b/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.ts
@@ -0,0 +1,59 @@
+import type { WorkSummaryItem } from '@lobechat/types';
+import { useCallback } from 'react';
+
+import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';
+import { createShareVisitorDocumentModal } from '@/features/Work/ShareVisitorDocumentModal';
+import { useChatStore } from '@/store/chat';
+
+import { useConversationStore } from '../../store';
+
+/**
+ * Open handler for Work cards on the agent-share visitor surface. The card's
+ * default open targets (Portal document viewer, owner file fetch, task detail)
+ * are all owner-scoped, so opens route through share-authorized paths instead.
+ * `/f/:id` is public by id, so a file previews in the visitor page's portal
+ * straight from its URL.
+ */
+export const useVisitorWorkOpen = () => {
+ const agentShareId = useConversationStore((s) => s.context.agentShareId);
+ const topicId = useConversationStore((s) => s.context.topicId);
+ const openFilePreview = useChatStore((s) => s.openFilePreview);
+
+ return useCallback(
+ (item: WorkSummaryItem) => {
+ if (!agentShareId || !topicId) return;
+ const descriptor = getWorkTypeDescriptor(item);
+ const target = descriptor.getOpenTarget(item);
+ if (!target) return;
+
+ switch (target.kind) {
+ case 'document': {
+ createShareVisitorDocumentModal({
+ documentId: target.documentId,
+ shareId: agentShareId,
+ title: descriptor.getTitle(item)?.trim() || descriptor.getIdentifier(item) || item.id,
+ topicId,
+ });
+ return;
+ }
+ case 'filePreview': {
+ if (!isSafeExternalUrl(target.url)) return;
+ openFilePreview({
+ fileId: target.fileId,
+ source: { name: descriptor.getTitle(item) || target.fileId, url: target.url },
+ });
+ return;
+ }
+ case 'external': {
+ if (isSafeExternalUrl(target.url))
+ window.open(target.url, '_blank', 'noopener,noreferrer');
+ return;
+ }
+ default: {
+ return;
+ }
+ }
+ },
+ [agentShareId, openFilePreview, topicId],
+ );
+};
diff --git a/src/features/FileViewer/Renderer/PDF/index.tsx b/src/features/FileViewer/Renderer/PDF/index.tsx
index b8ea5d8b11f..ef9ec26eaa4 100644
--- a/src/features/FileViewer/Renderer/PDF/index.tsx
+++ b/src/features/FileViewer/Renderer/PDF/index.tsx
@@ -8,10 +8,10 @@ import { Spin } from '@lobehub/ui/base-ui';
import { Fragment, memo, useCallback, useState } from 'react';
import { Document, Page, pdfjs } from '@/libs/pdfjs';
-import { lambdaQuery } from '@/libs/trpc/client';
import HighlightLayer from './HighlightLayer';
import { styles } from './style';
+import { useChunkHighlights } from './useChunkHighlights';
import useResizeObserver from './useResizeObserver';
const options = {
@@ -23,10 +23,16 @@ const maxWidth = 1200;
export interface PDFViewerProps {
fileId: string;
+ /**
+ * Overlay the file's retrieval chunks on the pages. Turn off for a file the
+ * viewer does not own; see {@link useChunkHighlights}.
+ * @default true
+ */
+ showChunkHighlights?: boolean;
url: string | null;
}
-const PDFViewer = memo<PDFViewerProps>(({ url, fileId }) => {
+const PDFViewer = memo<PDFViewerProps>(({ url, fileId, showChunkHighlights = true }) => {
const [numPages, setNumPages] = useState<number>(0);
const [containerRef, setContainerRef] = useState<HTMLElement | null>(null);
const [containerWidth, setContainerWidth] = useState<number>();
@@ -47,12 +53,7 @@ const PDFViewer = memo<PDFViewerProps>(({ url, fileId }) => {
setIsLoaded(true);
};
- const { data } = lambdaQuery.chunk.getChunksByFileId.useInfiniteQuery(
- { id: fileId },
- { getNextPageParam: (lastPage) => lastPage.nextCursor },
- );
-
- const dataSource = data?.pages.flatMap((page) => page.items) || [];
+ const dataSource = useChunkHighlights(fileId, showChunkHighlights);
return (
<Flexbox className={styles.container}>
diff --git a/src/features/FileViewer/Renderer/PDF/useChunkHighlights.test.ts b/src/features/FileViewer/Renderer/PDF/useChunkHighlights.test.ts
new file mode 100644
index 00000000000..eb1d3c3b48d
--- /dev/null
+++ b/src/features/FileViewer/Renderer/PDF/useChunkHighlights.test.ts
@@ -0,0 +1,41 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useChunkHighlights } from './useChunkHighlights';
+
+const { useInfiniteQuery } = vi.hoisted(() => ({ useInfiniteQuery: vi.fn() }));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaQuery: { chunk: { getChunksByFileId: { useInfiniteQuery } } },
+}));
+
+describe('useChunkHighlights', () => {
+ beforeEach(() => {
+ useInfiniteQuery.mockReset();
+ useInfiniteQuery.mockReturnValue({ data: undefined });
+ });
+
+ it('flattens the chunk pages of the viewer own file', () => {
+ useInfiniteQuery.mockReturnValue({
+ data: { pages: [{ items: [{ id: 'c1' }] }, { items: [{ id: 'c2' }] }] },
+ });
+
+ const { result } = renderHook(() => useChunkHighlights('file_1', true));
+
+ expect(useInfiniteQuery).toHaveBeenCalledWith(
+ { id: 'file_1' },
+ expect.objectContaining({ enabled: true }),
+ );
+ expect(result.current).toEqual([{ id: 'c1' }, { id: 'c2' }]);
+ });
+
+ it('skips the owner-scoped chunk query when disabled', () => {
+ // A share visitor previewing the creator's file cannot read its chunks.
+ renderHook(() => useChunkHighlights('file_1', false));
+
+ expect(useInfiniteQuery).toHaveBeenCalledWith(
+ { id: 'file_1' },
+ expect.objectContaining({ enabled: false }),
+ );
+ });
+});
diff --git a/src/features/FileViewer/Renderer/PDF/useChunkHighlights.ts b/src/features/FileViewer/Renderer/PDF/useChunkHighlights.ts
new file mode 100644
index 00000000000..86674e1033c
--- /dev/null
+++ b/src/features/FileViewer/Renderer/PDF/useChunkHighlights.ts
@@ -0,0 +1,16 @@
+import { lambdaQuery } from '@/libs/trpc/client';
+
+/**
+ * Retrieval chunks overlaid on a PDF's pages. The chunk query is scoped to the
+ * viewer's own files, so a host previewing a file it does not own (a public
+ * source such as a share visitor's file Work) disables it instead of issuing a
+ * request that can only come back empty or rejected.
+ */
+export const useChunkHighlights = (fileId: string, enabled: boolean) => {
+ const { data } = lambdaQuery.chunk.getChunksByFileId.useInfiniteQuery(
+ { id: fileId },
+ { enabled, getNextPageParam: (lastPage) => lastPage.nextCursor },
+ );
+
+ return data?.pages.flatMap((page) => page.items) || [];
+};
diff --git a/src/features/FileViewer/__tests__/imageToolHosts.test.tsx b/src/features/FileViewer/__tests__/imageToolHosts.test.tsx
index d11d8e90c56..9cc19bee093 100644
--- a/src/features/FileViewer/__tests__/imageToolHosts.test.tsx
+++ b/src/features/FileViewer/__tests__/imageToolHosts.test.tsx
@@ -50,6 +50,7 @@ vi.mock('@/store/chat/selectors', () => ({
chatPortalSelectors: {
chunkText: (s: { chunkText?: string }) => s.chunkText,
previewFileId: (s: { previewFileId?: string }) => s.previewFileId,
+ previewFileSource: () => undefined,
},
}));
diff --git a/src/features/FileViewer/index.tsx b/src/features/FileViewer/index.tsx
index f32c319a8d6..d36f0f7e567 100644
--- a/src/features/FileViewer/index.tsx
+++ b/src/features/FileViewer/index.tsx
@@ -108,6 +108,8 @@ interface FileViewerProps extends FileListItem {
imageTools?: ReactNode;
/** Host close action, surfaced in the image viewer's top bar. */
onClose?: () => void;
+ /** Forwarded to the PDF renderer; see {@link PDFViewerProps.showChunkHighlights}. */
+ showChunkHighlights?: boolean;
style?: CSSProperties;
}
@@ -151,7 +153,7 @@ const usePDFRenderer = (enabled: boolean) => {
* Preview any file type.
*/
const FileViewer = memo<FileViewerProps>((props) => {
- const { id, style, fileType, url, name, imageTools, onClose } = props;
+ const { id, style, fileType, url, name, imageTools, onClose, showChunkHighlights } = props;
const isPDF = isPdfFile({ fileName: name, fileType, path: url });
const { retry: retryPDFRenderer, state: pdfRendererState } = usePDFRenderer(isPDF);
@@ -166,7 +168,7 @@ const FileViewer = memo<FileViewerProps>((props) => {
if (pdfRendererState.status === 'ready') {
const { Renderer } = pdfRendererState;
- return <Renderer fileId={id} url={url} />;
+ return <Renderer fileId={id} showChunkHighlights={showChunkHighlights} url={url} />;
}
return (
diff --git a/src/features/Portal/FilePreview/Body/index.tsx b/src/features/Portal/FilePreview/Body/index.tsx
index f945f0bb130..dc2ab9ffd8a 100644
--- a/src/features/Portal/FilePreview/Body/index.tsx
+++ b/src/features/Portal/FilePreview/Body/index.tsx
@@ -12,7 +12,8 @@ import ImageEditTools from '@/features/FileViewer/ImageEditTools';
import { normalizeAsyncError } from '@/libs/swr/normalizeError';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
-import { useFileStore } from '@/store/file';
+
+import { usePreviewFileItem } from '../usePreviewFileItem';
enum FilePreviewTab {
Chunk = 'chunk',
@@ -28,13 +29,12 @@ const FilePreview = () => {
const previewFileId = useChatStore(chatPortalSelectors.previewFileId);
const chunkText = useChatStore(chatPortalSelectors.chunkText);
const activeTopicId = useChatStore((s) => s.activeTopicId);
- const useFetchFileItem = useFileStore((s) => s.useFetchKnowledgeItem);
const { t } = useTranslation('portal');
const topicKey = activeTopicId ?? NO_TOPIC_KEY;
const [tabByTopic, setTabByTopic] = useState<Record<string, FilePreviewTab>>({});
const tab = tabByTopic[topicKey] ?? getDefaultTab(chunkText);
- const { data, error, isLoading, mutate } = useFetchFileItem(previewFileId);
+ const { data, error, fromSource, isLoading, mutate } = usePreviewFileItem();
useEffect(() => {
setTabByTopic((prev) => ({ ...prev, [topicKey]: getDefaultTab(chunkText) }));
@@ -47,7 +47,7 @@ const FilePreview = () => {
if (error && normalizeAsyncError(error).status !== 404) {
return (
<Flexbox flex={1} padding={16}>
- <AsyncError error={error} variant={'block'} onRetry={() => void mutate()} />
+ <AsyncError error={error} variant={'block'} onRetry={() => void mutate?.()} />
</Flexbox>
);
}
@@ -90,7 +90,12 @@ const FilePreview = () => {
<Markdown style={{ overflow: 'scroll', paddingInline: 8 }}>{chunkText}</Markdown>
) : (
<Flexbox flex={1} paddingBlock={8} style={{ overflow: 'scroll' }}>
- <FileViewer {...data} imageTools={<ImageEditTools />} />
+ {/* Image editing and chunk highlights act on the viewer's own library file. */}
+ <FileViewer
+ {...data}
+ imageTools={fromSource ? undefined : <ImageEditTools />}
+ showChunkHighlights={!fromSource}
+ />
</Flexbox>
)}
</Flexbox>
diff --git a/src/features/Portal/FilePreview/Title.tsx b/src/features/Portal/FilePreview/Title.tsx
index 6662eba7d2e..cf73e3cf2d2 100644
--- a/src/features/Portal/FilePreview/Title.tsx
+++ b/src/features/Portal/FilePreview/Title.tsx
@@ -1,17 +1,12 @@
import { Flexbox } from '@lobehub/ui';
import { Skeleton, Text } from '@lobehub/ui/base-ui';
-import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors } from '@/store/chat/selectors';
-import { useFileStore } from '@/store/file';
import { oneLineEllipsis } from '@/styles';
-const Title = () => {
- const previewFileId = useChatStore(chatPortalSelectors.previewFileId);
-
- const useFetchFileItem = useFileStore((s) => s.useFetchKnowledgeItem);
+import { usePreviewFileItem } from './usePreviewFileItem';
- const { data, isLoading } = useFetchFileItem(previewFileId);
+const Title = () => {
+ const { data, isLoading } = usePreviewFileItem();
return (
<Flexbox horizontal align={'center'} gap={4} style={{ minWidth: 0, overflow: 'hidden' }}>
diff --git a/src/features/Portal/FilePreview/useMoreMenu.tsx b/src/features/Portal/FilePreview/useMoreMenu.tsx
index 3eeaff4819a..d8f2ee2dfeb 100644
--- a/src/features/Portal/FilePreview/useMoreMenu.tsx
+++ b/src/features/Portal/FilePreview/useMoreMenu.tsx
@@ -5,15 +5,14 @@ import { useTranslation } from 'react-i18next';
import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
-import { useFileStore } from '@/store/file';
import { downloadFile } from '@/utils/client/downloadFile';
+import { usePreviewFileItem } from './usePreviewFileItem';
+
export const useFilePreviewMoreMenu = (): PortalMoreMenuConfig | undefined => {
const { t } = useTranslation('portal');
const previewFileId = useChatStore(chatPortalSelectors.previewFileId);
- const useFetchFileItem = useFileStore((s) => s.useFetchKnowledgeItem);
- // Same SWR key as the title and body, so this shares their request.
- const { data, mutate } = useFetchFileItem(previewFileId);
+ const { data, mutate } = usePreviewFileItem();
if (!previewFileId) return;
@@ -29,6 +28,6 @@ export const useFilePreviewMoreMenu = (): PortalMoreMenuConfig | undefined => {
},
]
: undefined,
- refresh: () => mutate(),
+ refresh: mutate ? () => mutate() : undefined,
};
};
diff --git a/src/features/Portal/FilePreview/usePreviewFileItem.test.ts b/src/features/Portal/FilePreview/usePreviewFileItem.test.ts
new file mode 100644
index 00000000000..5f6e4cb3574
--- /dev/null
+++ b/src/features/Portal/FilePreview/usePreviewFileItem.test.ts
@@ -0,0 +1,63 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { usePreviewFileItem } from './usePreviewFileItem';
+
+const useFetchKnowledgeItem = vi.fn();
+let portalFile: { fileId: string; source?: { name: string; url: string } } | undefined;
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/chat/selectors', () => ({
+ chatPortalSelectors: {
+ previewFileId: () => portalFile?.fileId,
+ previewFileSource: () => portalFile?.source,
+ },
+}));
+
+vi.mock('@/store/file', () => ({
+ useFileStore: (selector: (s: unknown) => unknown) => selector({ useFetchKnowledgeItem }),
+}));
+
+describe('usePreviewFileItem', () => {
+ beforeEach(() => {
+ useFetchKnowledgeItem.mockReset();
+ useFetchKnowledgeItem.mockReturnValue({ data: undefined, isLoading: false });
+ });
+
+ it('renders a pre-resolved source without the owner-scoped file fetch', () => {
+ // A share visitor cannot read the creator's file item; the fetch would 404
+ // and the portal would show "file not found" instead of the preview.
+ portalFile = {
+ fileId: 'file_1',
+ source: { name: 'hello_world.pptx', url: 'https://app.lobehub.com/f/file_1' },
+ };
+
+ const { result } = renderHook(() => usePreviewFileItem());
+
+ expect(useFetchKnowledgeItem).toHaveBeenCalledWith(undefined);
+ expect(result.current).toMatchObject({
+ data: {
+ id: 'file_1',
+ name: 'hello_world.pptx',
+ url: 'https://app.lobehub.com/f/file_1',
+ },
+ fromSource: true,
+ isLoading: false,
+ });
+ });
+
+ it('fetches the file item when the view carries no source', () => {
+ portalFile = { fileId: 'file_2' };
+ const data = { id: 'file_2', name: 'report.pdf' };
+ useFetchKnowledgeItem.mockReturnValue({ data, isLoading: false, mutate: vi.fn() });
+
+ const { result } = renderHook(() => usePreviewFileItem());
+
+ expect(useFetchKnowledgeItem).toHaveBeenCalledWith('file_2');
+ expect(result.current.data).toBe(data);
+ expect(result.current.fromSource).toBe(false);
+ });
+});
diff --git a/src/features/Portal/FilePreview/usePreviewFileItem.ts b/src/features/Portal/FilePreview/usePreviewFileItem.ts
new file mode 100644
index 00000000000..a5ee33dc8d7
--- /dev/null
+++ b/src/features/Portal/FilePreview/usePreviewFileItem.ts
@@ -0,0 +1,50 @@
+import { useMemo } from 'react';
+
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+import { useFileStore } from '@/store/file';
+import { type FileListItem } from '@/types/files';
+
+/**
+ * The file the FilePreview portal shows, shared by its title, body and menu.
+ *
+ * A view opened with a pre-resolved `source` renders from it and skips the
+ * owner-scoped file fetch (the SWR key is null); every other view reads the
+ * file item from the file store, all three callers sharing one request.
+ */
+export const usePreviewFileItem = () => {
+ const previewFileId = useChatStore(chatPortalSelectors.previewFileId);
+ const source = useChatStore(chatPortalSelectors.previewFileSource);
+ const useFetchFileItem = useFileStore((s) => s.useFetchKnowledgeItem);
+ const fetched = useFetchFileItem(source ? undefined : previewFileId);
+
+ const sourceItem = useMemo<FileListItem | undefined>(() => {
+ if (!source || !previewFileId) return;
+ const createdAt = new Date(0);
+ return {
+ chunkCount: null,
+ chunkingError: null,
+ createdAt,
+ embeddingError: null,
+ // FileViewer falls back to the name's extension when the type is empty.
+ fileType: '',
+ finishEmbedding: false,
+ id: previewFileId,
+ name: source.name,
+ size: 0,
+ sourceType: 'file',
+ updatedAt: createdAt,
+ url: source.url,
+ };
+ }, [previewFileId, source]);
+
+ if (sourceItem) return { data: sourceItem, fromSource: true, isLoading: false } as const;
+
+ return {
+ data: fetched.data,
+ error: fetched.error,
+ fromSource: false,
+ isLoading: fetched.isLoading,
+ mutate: fetched.mutate,
+ } as const;
+};
diff --git a/src/services/aiAgent.execAgentTask.test.ts b/src/services/aiAgent.execAgentTask.test.ts
index 5cd8205d7f3..a9eed4984b1 100644
--- a/src/services/aiAgent.execAgentTask.test.ts
+++ b/src/services/aiAgent.execAgentTask.test.ts
@@ -17,14 +17,14 @@ describe('aiAgentService.execAgentTask', () => {
// The server renames a mirrored group member terminal to `member_runtime_end`
// only for a client that declares it handles the new event.
- it('declares that this client handles member_runtime_end', async () => {
+ it('declares the stream features this client handles', async () => {
mocks.execAgent.mockResolvedValueOnce({ success: true });
const signal = new AbortController().signal;
await aiAgentService.execAgentTask({ agentId: 'agt-1', prompt: 'hi' }, { signal });
expect(mocks.execAgent).toHaveBeenCalledWith(
- { agentId: 'agt-1', prompt: 'hi', streamFeatures: ['member_runtime_end'] },
+ { agentId: 'agt-1', prompt: 'hi', streamFeatures: ['file_works', 'member_runtime_end'] },
{ signal },
);
});
diff --git a/src/services/aiAgent.intervention.test.ts b/src/services/aiAgent.intervention.test.ts
index f262a8d8d4a..6b22a923d4e 100644
--- a/src/services/aiAgent.intervention.test.ts
+++ b/src/services/aiAgent.intervention.test.ts
@@ -38,7 +38,7 @@ describe('aiAgentService.resolveAgentInterventionBySource', () => {
expect(mocks.resolveAgentInterventionBySource).toHaveBeenCalledWith({
...params,
- streamFeatures: ['member_runtime_end'],
+ streamFeatures: ['file_works', 'member_runtime_end'],
});
});
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 534f4617800..9947b4edb8f 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -19,7 +19,7 @@ import { buildLlmExecutorDeclaration } from '@/services/llmRelay';
export type { ExecAgentResult, ScheduleAgentRunParams, ScheduleAgentRunResult };
/** Gateway stream features every run started from this client handles. */
-const STREAM_FEATURES: AgentStreamClientFeature[] = ['member_runtime_end'];
+const STREAM_FEATURES: AgentStreamClientFeature[] = ['file_works', 'member_runtime_end'];
/** An older server's strict input schema rejected the `streamFeatures` key. */
const isUnknownStreamFeaturesError = (error: unknown): boolean => {
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
index 5db8d8561e2..fbcc3588493 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -1129,7 +1129,7 @@ describe('ConversationControl actions', () => {
batchId: 'batch-durable',
operationId: 'operation-durable',
resolutionRequestId: expect.any(String),
- streamFeatures: ['member_runtime_end'],
+ streamFeatures: ['file_works', 'member_runtime_end'],
targets: [{ toolCallId: 'call-durable', toolMessageId: 'tool-msg-durable' }],
});
expect(result.current.dbMessagesMap[chatKey][0].plugin?.arguments).toBe(
@@ -3265,7 +3265,7 @@ describe('ConversationControl actions', () => {
batchId: `batch-${interactionKind}`,
operationId: `server-operation-${interactionKind}`,
resolutionRequestId: expect.any(String),
- streamFeatures: ['member_runtime_end'],
+ streamFeatures: ['file_works', 'member_runtime_end'],
targets: [{ toolCallId: `call-${interactionKind}`, toolMessageId: toolMessage.id }],
});
const resolvingIntervention = {
diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.ts
index fb14a7ca829..447066288f8 100644
--- a/src/store/chat/slices/portal/initialState.ts
+++ b/src/store/chat/slices/portal/initialState.ts
@@ -37,10 +37,27 @@ export enum PortalViewType {
VerifyResult = 'verifyResult',
}
+/**
+ * A file preview the opener has already resolved, for surfaces that cannot read
+ * the file through the owner-scoped file store.
+ */
+export interface PortalFileSource {
+ /** Display name; its extension also selects the renderer. */
+ name: string;
+ /** Publicly readable file URL. */
+ url: string;
+}
+
export interface PortalFile {
chunkId?: string;
chunkText?: string;
fileId: string;
+ /**
+ * Render from this source instead of fetching the file item. An agent-share
+ * visitor previews files the creator's run produced, which the visitor's
+ * own file store cannot read.
+ */
+ source?: PortalFileSource;
}
export interface OpenLocalFileParams {
diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.ts
index dc8690f9f36..55e1a63cd69 100644
--- a/src/store/chat/slices/portal/selectors.ts
+++ b/src/store/chat/slices/portal/selectors.ts
@@ -159,6 +159,7 @@ const currentFile = (s: ChatStoreState): PortalFile | undefined => {
const previewFileId = (s: ChatStoreState) => currentFile(s)?.fileId;
const chunkText = (s: ChatStoreState) => currentFile(s)?.chunkText;
+const previewFileSource = (s: ChatStoreState) => currentFile(s)?.source;
// Local File selectors
const currentLocalFileScopeWorkingDirectory = (s: ChatStoreState): string | undefined =>
@@ -349,6 +350,7 @@ export const chatPortalSelectors = {
// File preview data
currentFile,
previewFileId,
+ previewFileSource,
chunkText,
// Goal drill-down data