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(channel): upload attachments into the Channel's own workspace (#23499)

Arvin Xucf20ca9970b8
diff --git a/apps/workbench/app/stubs/surface.test.ts b/apps/workbench/app/stubs/surface.test.ts
index 33ab3a96f63..c7322224aed 100644
--- a/apps/workbench/app/stubs/surface.test.ts
+++ b/apps/workbench/app/stubs/surface.test.ts
@@ -41,6 +41,7 @@ describe('workbench stub surface', () => {
'createWorkspaceLambdaClient',
'lambdaClient',
'lambdaQuery',
+ 'scopedLambdaClient',
'toolsClient',
'withLlmRelay',
]);
diff --git a/apps/workbench/app/stubs/trpcClient.client.ts b/apps/workbench/app/stubs/trpcClient.client.ts
index 29a6efa73a3..2023fe9e666 100644
--- a/apps/workbench/app/stubs/trpcClient.client.ts
+++ b/apps/workbench/app/stubs/trpcClient.client.ts
@@ -16,6 +16,9 @@ export const lambdaClient = createTRPCClient<LambdaRouter>({
});
export const createWorkspaceLambdaClient = reject('createWorkspaceLambdaClient');
+// Workbench has one scope: an unpinned call uses it, a pinned one has no workspace to reach.
+export const scopedLambdaClient = (workspaceId?: string | null) =>
+ workspaceId === undefined ? lambdaClient : createWorkspaceLambdaClient(workspaceId);
export const asyncClient = reject('asyncClient');
export const toolsClient = reject('toolsClient');
export const lambdaQuery = reject('lambdaQuery');
diff --git a/apps/workbench/app/stubs/trpcClient.ts b/apps/workbench/app/stubs/trpcClient.ts
index 101c4527ee7..497e71fe088 100644
--- a/apps/workbench/app/stubs/trpcClient.ts
+++ b/apps/workbench/app/stubs/trpcClient.ts
@@ -2,6 +2,7 @@ import { reject } from './reject';
export const lambdaClient = reject('lambdaClient');
export const createWorkspaceLambdaClient = reject('createWorkspaceLambdaClient');
+export const scopedLambdaClient = reject('scopedLambdaClient');
export const asyncClient = reject('asyncClient');
export const toolsClient = reject('toolsClient');
export const lambdaQuery = reject('lambdaQuery');
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.json
index 0d4b221a9f2..3481b52a098 100644
--- a/locales/en-US/channel.json
+++ b/locales/en-US/channel.json
@@ -190,6 +190,7 @@
"profile.title": "Agent profile",
"profile.view": "View profile",
"projectAgents": "Project Agents",
+ "receipt.errorAttachmentUnavailable": "One or more attachments can't be sent here, for example because they were uploaded in another workspace. Delete this message and attach them again.",
"receipt.errorReason": "Failure reason",
"receipt.errorShareHeteroDevice": "The creator's device is offline. Try again later.",
"receipt.errorShareHeteroUnsupported": "This Agent can run for you only with its creator's permission. Ask its creator for access.",
diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.json
index 95add6073a3..9a0192c10bf 100644
--- a/locales/zh-CN/channel.json
+++ b/locales/zh-CN/channel.json
@@ -190,6 +190,7 @@
"profile.title": "Agent 资料",
"profile.view": "查看资料",
"projectAgents": "项目 Agent",
+ "receipt.errorAttachmentUnavailable": "有附件无法在这里发送,可能是在其他工作区上传的。请删除这条消息后重新添加附件。",
"receipt.errorReason": "失败原因",
"receipt.errorShareHeteroDevice": "创建者的设备当前离线,请稍后再试。",
"receipt.errorShareHeteroUnsupported": "这个 Agent 需要创建者授权后才能为你运行,请联系创建者开通。",
diff --git a/packages/database/src/repositories/channel/__tests__/peer.test.ts b/packages/database/src/repositories/channel/__tests__/peer.test.ts
index 1509607e1c0..1a7216aaae4 100644
--- a/packages/database/src/repositories/channel/__tests__/peer.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/peer.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { ChatErrorType } from '@lobechat/types';
import { and, eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -227,7 +228,7 @@ describe('a conversation with an external contact of a workspace', () => {
routing: 'fallback',
});
- await expect(send(bob, teamFile)).rejects.toThrow('One or more attachments are unavailable');
+ await expect(send(bob, teamFile)).rejects.toThrow(ChatErrorType.ChannelAttachmentUnavailable);
// His own upload, which the file router stores in his personal space, goes through.
expect(await send(bob, await upload(bob, null))).toBeDefined();
// A member still attaches the workspace's file.
diff --git a/packages/database/src/repositories/channel/send.ts b/packages/database/src/repositories/channel/send.ts
index 8340190e91c..907b307e3fb 100644
--- a/packages/database/src/repositories/channel/send.ts
+++ b/packages/database/src/repositories/channel/send.ts
@@ -1,5 +1,5 @@
import type { ChannelMessageMetadata, ChannelRoutingMode, ContactCardInput } from '@lobechat/types';
-import { CHANNEL_LIMITS, contactCardOf, contactCardText } from '@lobechat/types';
+import { CHANNEL_LIMITS, ChatErrorType, contactCardOf, contactCardText } from '@lobechat/types';
import { and, asc, eq, inArray, sql } from 'drizzle-orm';
import type { ChannelMessageItem } from '../../schemas';
@@ -232,7 +232,7 @@ export const sendMessage = async (
.orderBy(asc(files.id))
.for('update');
if (accessible.length !== fileIds.length)
- throw new ChannelError('BAD_REQUEST', 'One or more attachments are unavailable');
+ throw new ChannelError('BAD_REQUEST', ChatErrorType.ChannelAttachmentUnavailable);
}
const mentioned = quoteOnly ? [] : await activeMembers(tx, channel.id, mentions);
diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.ts
index 18426274cb6..7877c8ffc74 100644
--- a/packages/locales/src/default/channel.ts
+++ b/packages/locales/src/default/channel.ts
@@ -5,6 +5,8 @@ export default {
'people.noMatches': 'No matching workspace members',
'people.noOthers': 'No one else is in this workspace yet',
'people.searchMore': 'Showing the first 50 members. Search to find more.',
+ 'receipt.errorAttachmentUnavailable':
+ "One or more attachments can't be sent here, for example because they were uploaded in another workspace. Delete this message and attach them again.",
'receipt.errorReason': 'Failure reason',
'receipt.errorShareHeteroDevice': "The creator's device is offline. Try again later.",
'receipt.errorShareHeteroUnsupported':
diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.ts
index e0a6f8dcffb..775e6009232 100644
--- a/packages/trpc/src/client/lambda.ts
+++ b/packages/trpc/src/client/lambda.ts
@@ -395,6 +395,14 @@ export const createWorkspaceLambdaClient = (workspaceId: string | null) => {
});
};
+/**
+ * The lambda client for an optional scope: `undefined` follows the active workspace like
+ * `lambdaClient`; a workspace id or `null` (personal) pins it like
+ * {@link createWorkspaceLambdaClient}.
+ */
+export const scopedLambdaClient = (workspaceId?: string | null) =>
+ workspaceId === undefined ? lambdaClient : createWorkspaceLambdaClient(workspaceId);
+
export const lambdaQuery = createTRPCReact<LambdaRouter>();
export const lambdaQueryClient = lambdaQuery.createClient({ links });
diff --git a/packages/types/src/fetch.ts b/packages/types/src/fetch.ts
index 55582aaf18a..3c7ea986626 100644
--- a/packages/types/src/fetch.ts
+++ b/packages/types/src/fetch.ts
@@ -16,6 +16,7 @@ export const ChatErrorType = {
SharePromptTooLong: 'SharePromptTooLong', // Visitor's message to a shared agent is longer than SHARE_VISITOR_PROMPT_MAX_LENGTH
ShareHeterogeneousAgentUnsupported: 'ShareHeterogeneousAgentUnsupported', // This agent configuration is not supported for shared visitors
ShareHeteroDeviceUnavailable: 'ShareHeteroDeviceUnavailable', // The shared local CLI agent's device is offline or not set — visitor can retry later
+ ChannelAttachmentUnavailable: 'ChannelAttachmentUnavailable', // A Channel send names a file the sender cannot attach there (e.g. uploaded in another workspace) — resending the same files never succeeds
AgentShareProviderNotSupported: 'AgentShareProviderNotSupported', // This shared agent uses a provider that is not supported for shared visitors
SupervisorDecisionFailed: 'SupervisorDecisionFailed', // Supervisor decision failed
AgentConcurrencyLimitExceeded: 'AgentConcurrencyLimitExceeded', // The user already has as many agent runs in flight as allowed — recovers when one finishes
diff --git a/src/features/Channels/Composer.tsx b/src/features/Channels/Composer.tsx
index 4ea5e6ff026..0b7eb4f734a 100644
--- a/src/features/Channels/Composer.tsx
+++ b/src/features/Channels/Composer.tsx
@@ -18,6 +18,7 @@ import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { useWorkspaces } from '@/business/client/hooks/useWorkspaces';
import { useLocalDragUpload } from '@/components/DragUploadZone/useLocalDragUpload';
import { usePasteFile } from '@/components/DragUploadZone/usePasteFile';
import WideScreenContainer from '@/features/WideScreenContainer';
@@ -130,7 +131,21 @@ export function Composer({
/** The card the mention picker docks to, full width above the input like an IM. */
const [card, setCard] = useState<HTMLDivElement | null>(null);
const requests = useSingleton(createChannelSendRequest);
- const attachments = useAttachments(draftKey);
+ const workspaces = useWorkspaces();
+ /**
+ * Files upload into the Channel's own scope, not whichever one the app has active: the send
+ * accepts a member's files only from the Channel's workspace. An external contact, not a member
+ * there, attaches files from their personal space.
+ */
+ const channelWorkspaceId = channel?.workspaceId;
+ const uploadWorkspaceId = !channel
+ ? undefined
+ : channelWorkspaceId &&
+ (channelWorkspaceId === workspaceId ||
+ workspaces.some((workspace) => workspace.id === channelWorkspaceId))
+ ? channelWorkspaceId
+ : null;
+ const attachments = useAttachments(draftKey, uploadWorkspaceId);
const { allowed } = usePermission('create_content');
const knowledgeBase = useServerConfigStore((s) => featureFlagsSelectors(s).enableKnowledgeBase);
/** Files sent to another person's shared Agent are refused server-side, so offer no upload. */
diff --git a/src/features/Channels/MessageReceipts.tsx b/src/features/Channels/MessageReceipts.tsx
index 2505d3926a0..ef172721c60 100644
--- a/src/features/Channels/MessageReceipts.tsx
+++ b/src/features/Channels/MessageReceipts.tsx
@@ -18,6 +18,7 @@ import { useOpenReplyAgent } from './useOpenReplyAgent';
/** Failure categories with their own text; a shared Agent's visitor learns why only from these. */
const RECEIPT_ERROR_KEYS = {
+ [ChatErrorType.ChannelAttachmentUnavailable]: 'receipt.errorAttachmentUnavailable',
[ChatErrorType.ShareHeteroDeviceUnavailable]: 'receipt.errorShareHeteroDevice',
[ChatErrorType.ShareHeterogeneousAgentUnsupported]: 'receipt.errorShareHeteroUnsupported',
[ChatErrorType.ShareMessageLimitExceeded]: 'receipt.errorShareMessageLimit',
diff --git a/src/features/Channels/OutgoingStatus.test.tsx b/src/features/Channels/OutgoingStatus.test.tsx
index 681c9b833a6..a2ce1ed70ff 100644
--- a/src/features/Channels/OutgoingStatus.test.tsx
+++ b/src/features/Channels/OutgoingStatus.test.tsx
@@ -37,4 +37,17 @@ describe('OutgoingStatus', () => {
render(createElement(OutgoingStatus, { message: failed('offline'), onRetry: () => {} }));
expect(screen.getByText('outgoing.failed')).toBeTruthy();
});
+
+ // Retrying resends the same refused files, so only deleting and reattaching can help.
+ it('explains a refused attachment and offers no retry', () => {
+ render(
+ createElement(OutgoingStatus, {
+ message: failed(ChatErrorType.ChannelAttachmentUnavailable),
+ onRetry: () => {},
+ }),
+ );
+ expect(screen.getByRole('alert').textContent).toContain('receipt.errorAttachmentUnavailable');
+ expect(screen.queryByText('outgoing.retry')).toBeNull();
+ expect(screen.getByText('outgoing.discard')).toBeTruthy();
+ });
});
diff --git a/src/features/Channels/OutgoingStatus.tsx b/src/features/Channels/OutgoingStatus.tsx
index e1065a30791..1c90d5f3c15 100644
--- a/src/features/Channels/OutgoingStatus.tsx
+++ b/src/features/Channels/OutgoingStatus.tsx
@@ -1,3 +1,4 @@
+import { ChatErrorType } from '@lobechat/types';
import { Button, Icon } from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
import { CircleAlert } from 'lucide-react';
@@ -21,15 +22,19 @@ export function OutgoingStatus({
// A message still sending shows faded in place (`ChannelMessage` `pending`), with no line here.
if (message.status !== 'failed') return null;
const reasonKey = receiptErrorKey(message.errorType);
+ // A retry resends the same files, so a refused attachment can only be deleted and reattached.
+ const canRetry = message.errorType !== ChatErrorType.ChannelAttachmentUnavailable;
return (
<span role="alert" {...stylex.props(statusStyles.receipts, statusStyles.state)}>
<span {...stylex.props(statusStyles.state, toneStyles.error)}>
<Icon icon={CircleAlert} size={12} />
{reasonKey ? t(reasonKey) : t('outgoing.failed')}
</span>
- <Button size="small" type="text" onClick={() => onRetry(message)}>
- {t('outgoing.retry')}
- </Button>
+ {canRetry && (
+ <Button size="small" type="text" onClick={() => onRetry(message)}>
+ {t('outgoing.retry')}
+ </Button>
+ )}
<Button size="small" type="text" onClick={() => channelActions.discardSend(message)}>
{t('outgoing.discard')}
</Button>
diff --git a/src/features/Channels/useAttachments.ts b/src/features/Channels/useAttachments.ts
index 7d9fc4d5578..e6726fbb839 100644
--- a/src/features/Channels/useAttachments.ts
+++ b/src/features/Channels/useAttachments.ts
@@ -37,8 +37,12 @@ const draftFor = (key: string) => {
return draft;
};
-/** Each Channel/Thread composer owns its uploads; ordinary chat's global draft is untouched. */
-export function useAttachments(draftKey: string) {
+/**
+ * Each Channel/Thread composer owns its uploads; ordinary chat's global draft is untouched.
+ * `workspaceId` pins the scope files upload into (`null` personal); `undefined` follows the
+ * active workspace.
+ */
+export function useAttachments(draftKey: string, workspaceId?: string | null) {
const { t } = useTranslation('channel');
const upload = useFileStore((s) => s.uploadWithProgress);
const draft = draftFor(draftKey);
@@ -88,6 +92,7 @@ export function useAttachments(draftKey: string) {
file,
abortController,
uploadId: item.id,
+ workspaceId,
onStatusUpdate: (event) => {
if (abortController.signal.aborted) return;
if (event.type === 'updateFile') patch(item.id, event.value);
diff --git a/src/services/__tests__/upload.test.ts b/src/services/__tests__/upload.test.ts
index 55536bd810a..6b368c08a31 100644
--- a/src/services/__tests__/upload.test.ts
+++ b/src/services/__tests__/upload.test.ts
@@ -2,7 +2,7 @@ import { MAX_UPLOAD_FILE_SIZE, UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE } from '@lob
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { fileEnv } from '@/envs/file';
-import { lambdaClient } from '@/libs/trpc/client';
+import { lambdaClient, scopedLambdaClient } from '@/libs/trpc/client';
import { hashFile } from '../hashFile';
import { UPLOAD_NETWORK_ERROR, UploadRequestError, uploadService } from '../upload';
@@ -20,8 +20,8 @@ vi.mock('@lobechat/utils', () => ({
uuid: () => 'mock-uuid',
}));
-vi.mock('@/libs/trpc/client', () => ({
- lambdaClient: {
+vi.mock('@/libs/trpc/client', () => {
+ const lambdaClient = {
upload: {
abortS3MultipartUpload: {
mutate: vi.fn(),
@@ -42,8 +42,10 @@ vi.mock('@/libs/trpc/client', () => ({
mutate: vi.fn(),
},
},
- },
-}));
+ };
+ // Every scope shares one mock, so the assertions below see each call whichever scope made it.
+ return { lambdaClient, scopedLambdaClient: vi.fn(() => lambdaClient) };
+});
vi.mock('js-sha256', () => ({
sha256: {
@@ -449,6 +451,22 @@ describe('UploadService', () => {
expect(result.path).toBe(customPath);
});
+ it('reserves the upload in the pinned workspace instead of the active one', async () => {
+ const xhr = new XMLHttpRequest();
+ vi.spyOn(xhr, 'addEventListener').mockImplementation((event, handler) => {
+ if (event === 'load') {
+ // @ts-expect-error - mock implementation
+ handler({ target: { status: 200 } });
+ }
+ });
+ vi.mocked(scopedLambdaClient).mockClear();
+
+ await uploadService.uploadToServerS3(mockFile, { workspaceId: 'ws-channel' });
+
+ expect(scopedLambdaClient).toHaveBeenCalledWith('ws-channel');
+ expect(scopedLambdaClient).not.toHaveBeenCalledWith(undefined);
+ });
+
it('should upload large files as sequential S3 parts without buffering the whole file', async () => {
const largeFile = new File(['small fixture'], 'large.bin', {
type: 'application/octet-stream',
diff --git a/src/services/file/index.test.ts b/src/services/file/index.test.ts
index 1e9388efb43..9294c5154e7 100644
--- a/src/services/file/index.test.ts
+++ b/src/services/file/index.test.ts
@@ -9,16 +9,17 @@ const { mockGetDocumentById, mockGetFileItemById } = vi.hoisted(() => ({
mockGetFileItemById: vi.fn(),
}));
-vi.mock('@/libs/trpc/client', () => ({
- lambdaClient: {
+vi.mock('@/libs/trpc/client', () => {
+ const lambdaClient = {
document: {
getDocumentById: { query: mockGetDocumentById },
},
file: {
getFileItemById: { query: mockGetFileItemById },
},
- },
-}));
+ };
+ return { lambdaClient, scopedLambdaClient: () => lambdaClient };
+});
describe('FileService.getKnowledgeItem', () => {
const service = new FileService();
diff --git a/src/services/file/index.ts b/src/services/file/index.ts
index 147cbca2ca7..b0262d3a0b4 100644
--- a/src/services/file/index.ts
+++ b/src/services/file/index.ts
@@ -1,6 +1,6 @@
import { CUSTOM_DOCUMENT_FILE_TYPE, DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
-import { lambdaClient } from '@/libs/trpc/client';
+import { lambdaClient, scopedLambdaClient } from '@/libs/trpc/client';
import {
type CheckFileHashResult,
type FileItem,
@@ -35,8 +35,13 @@ export class FileService {
visibility?: 'private' | 'public';
},
knowledgeBaseId?: string,
+ /** Pins the scope the file is created in; `undefined` follows the active workspace. */
+ workspaceId?: string | null,
): Promise<{ id: string; url: string }> => {
- return lambdaClient.file.createFile.mutate({ ...params, knowledgeBaseId } as CreateFileParams);
+ return scopedLambdaClient(workspaceId).file.createFile.mutate({
+ ...params,
+ knowledgeBaseId,
+ } as CreateFileParams);
};
getFile = async (id: string): Promise<FileItem> => {
@@ -143,8 +148,11 @@ export class FileService {
return lambdaClient.document.getFolderBreadcrumb.query({ slug });
};
- checkFileHash = async (hash: string): Promise<CheckFileHashResult> => {
- return lambdaClient.file.checkFileHash.mutate({ hash });
+ checkFileHash = async (
+ hash: string,
+ workspaceId?: string | null,
+ ): Promise<CheckFileHashResult> => {
+ return scopedLambdaClient(workspaceId).file.checkFileHash.mutate({ hash });
};
removeFileAsyncTask = async (id: string, type: 'embedding' | 'chunk') => {
diff --git a/src/services/upload.ts b/src/services/upload.ts
index 98fd39b5620..f1ad853bb56 100644
--- a/src/services/upload.ts
+++ b/src/services/upload.ts
@@ -4,7 +4,7 @@ import { uuid } from '@lobechat/utils';
import dayjs from 'dayjs';
import { fileEnv } from '@/envs/file';
-import { lambdaClient } from '@/libs/trpc/client';
+import { scopedLambdaClient } from '@/libs/trpc/client';
import type { FileMetadata, UploadBase64ToS3Result } from '@/types/files';
import type { FileUploadState, FileUploadStatus } from '@/types/files/upload';
@@ -130,12 +130,16 @@ interface UploadFileToS3Options {
onProgress?: (status: FileUploadStatus, state: FileUploadState) => void;
pathname?: string;
skipCheckFileType?: boolean;
+ /** Pins the scope the upload is reserved in; `undefined` follows the active workspace. */
+ workspaceId?: string | null;
}
+type LambdaClient = ReturnType<typeof scopedLambdaClient>;
+
class UploadService {
- releaseUpload = async (pathname: string) => {
+ releaseUpload = async (pathname: string, workspaceId?: string | null) => {
try {
- await lambdaClient.upload.abortS3Upload.mutate({ pathname });
+ await scopedLambdaClient(workspaceId).upload.abortS3Upload.mutate({ pathname });
} catch (error) {
console.error('Failed to clean S3 upload:', error);
}
@@ -146,7 +150,7 @@ class UploadService {
*/
uploadFileToS3 = async (
file: File,
- { onProgress, directory, pathname, abortController }: UploadFileToS3Options,
+ { onProgress, directory, pathname, abortController, workspaceId }: UploadFileToS3Options,
): Promise<{ data: FileMetadata; success: boolean }> => {
if (file.size > MAX_UPLOAD_FILE_SIZE) throw new Error(UPLOAD_FILE_SIZE_LIMIT_ERROR_MESSAGE);
@@ -159,6 +163,7 @@ class UploadService {
directory,
onProgress,
pathname,
+ workspaceId,
});
return { data, success: true };
};
@@ -226,13 +231,16 @@ class UploadService {
directory,
pathname,
abortController,
+ workspaceId,
}: {
abortController?: AbortController;
directory?: string;
onProgress?: (status: FileUploadStatus, state: FileUploadState) => void;
pathname?: string;
+ workspaceId?: string | null;
},
): Promise<FileMetadata> => {
+ const client = scopedLambdaClient(workspaceId);
const {
date,
dirname,
@@ -244,11 +252,17 @@ class UploadService {
try {
if (file.size >= MULTIPART_UPLOAD_THRESHOLD) {
- await this.uploadMultipart(file, uploadPathname, abortController?.signal, (loaded) => {
- onProgress?.('uploading', this.getUploadState(loaded, file.size, startTime));
- });
+ await this.uploadMultipart(
+ client,
+ file,
+ uploadPathname,
+ abortController?.signal,
+ (loaded) => {
+ onProgress?.('uploading', this.getUploadState(loaded, file.size, startTime));
+ },
+ );
} else {
- const preSignUrl = await lambdaClient.upload.createS3PreSignedUrl.mutate({
+ const preSignUrl = await client.upload.createS3PreSignedUrl.mutate({
pathname: uploadPathname,
size: file.size,
});
@@ -264,7 +278,7 @@ class UploadService {
);
}
} catch (error) {
- await this.releaseUpload(uploadPathname);
+ await this.releaseUpload(uploadPathname, workspaceId);
if (abortController?.signal.aborted) {
onProgress?.('cancelled', { progress: 0, restTime: 0, speed: 0 });
}
@@ -379,6 +393,7 @@ class UploadService {
* with a freshly signed URL so a single dropped part does not fail a large file.
*/
private uploadPart = async ({
+ client,
blob,
onProgress,
partNumber,
@@ -387,6 +402,7 @@ class UploadService {
uploadId,
}: {
blob: Blob;
+ client: LambdaClient;
onProgress: (loaded: number) => void;
partNumber: number;
pathname: string;
@@ -394,7 +410,7 @@ class UploadService {
uploadId: string;
}): Promise<string | undefined> => {
for (let attempt = 1; ; attempt++) {
- const url = await lambdaClient.upload.createS3MultipartUploadPartUrl.mutate({
+ const url = await client.upload.createS3MultipartUploadPartUrl.mutate({
partNumber,
pathname,
uploadId,
@@ -418,13 +434,14 @@ class UploadService {
};
private uploadMultipart = async (
+ client: LambdaClient,
file: File,
pathname: string,
signal: AbortSignal | undefined,
onProgress: (loaded: number) => void,
): Promise<void> => {
const parts: Array<{ etag: string; partNumber: number }> = [];
- const upload = await lambdaClient.upload.createS3MultipartUpload.mutate({
+ const upload = await client.upload.createS3MultipartUpload.mutate({
contentType: file.type || undefined,
pathname,
size: file.size,
@@ -442,6 +459,7 @@ class UploadService {
const end = Math.min(offset + partSize, file.size);
const etag = await this.uploadPart({
blob: file.slice(offset, end),
+ client,
onProgress: (loaded) => onProgress(offset + loaded),
partNumber,
pathname,
@@ -454,7 +472,7 @@ class UploadService {
if (signal?.aborted) throw signal.reason ?? new Error('Upload cancelled by user');
// Removing the chip while the parts are being merged cancels this request too.
- await lambdaClient.upload.completeS3MultipartUpload.mutate(
+ await client.upload.completeS3MultipartUpload.mutate(
{
partCount,
parts: parts.length === partCount ? parts : undefined,
@@ -465,7 +483,7 @@ class UploadService {
);
} catch (error) {
try {
- await lambdaClient.upload.abortS3MultipartUpload.mutate({ pathname, uploadId });
+ await client.upload.abortS3MultipartUpload.mutate({ pathname, uploadId });
} catch (abortError) {
console.error('Failed to abort S3 multipart upload:', abortError);
}
diff --git a/src/store/file/slices/upload/action.test.ts b/src/store/file/slices/upload/action.test.ts
index 5545f32c99c..11ffecd7d5f 100644
--- a/src/store/file/slices/upload/action.test.ts
+++ b/src/store/file/slices/upload/action.test.ts
@@ -255,7 +255,7 @@ describe('FileUploadAction', () => {
});
});
- expect(fileService.checkFileHash).toHaveBeenCalledWith('mock-hash-value');
+ expect(fileService.checkFileHash).toHaveBeenCalledWith('mock-hash-value', undefined);
expect(uploadToS3Spy).not.toHaveBeenCalled();
expect(onStatusUpdate).toHaveBeenCalledWith({
id: mockFile.name,
@@ -276,6 +276,7 @@ describe('FileUploadAction', () => {
url: mockExistingMetadata.path, // Uses metadata.path when available
},
undefined,
+ undefined,
);
expect(uploadResult).toEqual({
...mockFileResponse,
@@ -323,6 +324,7 @@ describe('FileUploadAction', () => {
url: mockCheckResult.url,
},
undefined,
+ undefined,
);
expect(uploadResult).toEqual({
...mockFileResponse,
@@ -369,7 +371,7 @@ describe('FileUploadAction', () => {
});
});
- expect(fileService.checkFileHash).toHaveBeenCalledWith('mock-hash-value');
+ expect(fileService.checkFileHash).toHaveBeenCalledWith('mock-hash-value', undefined);
expect(uploadService.uploadFileToS3).toHaveBeenCalledWith(mockFile, {
onNotSupported: expect.any(Function),
onProgress: expect.any(Function),
@@ -385,6 +387,7 @@ describe('FileUploadAction', () => {
url: mockMetadata.path,
},
undefined,
+ undefined,
);
expect(onStatusUpdate).toHaveBeenCalledWith({
id: mockFile.name,
@@ -450,6 +453,7 @@ describe('FileUploadAction', () => {
},
}),
undefined,
+ undefined,
);
});
@@ -588,6 +592,7 @@ describe('FileUploadAction', () => {
fileType: 'image/png',
}),
undefined,
+ undefined,
);
});
@@ -638,6 +643,7 @@ describe('FileUploadAction', () => {
name: 'mislabelled.jpg',
}),
undefined,
+ undefined,
);
});
@@ -674,6 +680,7 @@ describe('FileUploadAction', () => {
fileType: 'image/png',
}),
undefined,
+ undefined,
);
});
@@ -709,6 +716,7 @@ describe('FileUploadAction', () => {
fileType: 'text/plain',
}),
undefined,
+ undefined,
);
});
@@ -745,6 +753,7 @@ describe('FileUploadAction', () => {
expect(fileService.createFile).toHaveBeenCalledWith(
expect.objectContaining({ fileType: 'audio/mp4' }),
undefined,
+ undefined,
);
});
@@ -777,6 +786,7 @@ describe('FileUploadAction', () => {
expect(fileService.createFile).toHaveBeenCalledWith(
expect.objectContaining({ fileType: 'audio/x-m4a' }),
undefined,
+ undefined,
);
});
});
@@ -815,6 +825,7 @@ describe('FileUploadAction', () => {
metadata: { ...mockMetadata, durationMs: 2501 },
}),
undefined,
+ undefined,
);
});
@@ -848,6 +859,7 @@ describe('FileUploadAction', () => {
expect(fileService.createFile).toHaveBeenCalledWith(
expect.objectContaining({ metadata: mockMetadata }),
undefined,
+ undefined,
);
});
});
@@ -885,6 +897,47 @@ describe('FileUploadAction', () => {
name: mockFile.name,
}),
knowledgeBaseId,
+ undefined,
+ );
+ });
+ });
+
+ describe('workspace scope', () => {
+ it('runs every step in the pinned scope instead of the active one', async () => {
+ const { result } = renderHook(() => useStore());
+
+ const mockFile = new File(['test content'], 'channel.txt', { type: 'text/plain' });
+ const mockMetadata = {
+ date: '12345',
+ dirname: '/files',
+ filename: 'channel.txt',
+ path: '/files/channel.txt',
+ };
+
+ vi.mocked(getImageDimensions).mockResolvedValue(undefined);
+ vi.spyOn(fileService, 'checkFileHash').mockResolvedValue({ isExist: false });
+ vi.spyOn(uploadService, 'uploadFileToS3').mockResolvedValue({
+ data: mockMetadata,
+ success: true,
+ });
+ vi.spyOn(fileService, 'createFile').mockResolvedValue({
+ id: 'file-id',
+ url: 'https://example.com/channel.txt',
+ });
+
+ await act(async () => {
+ await result.current.uploadWithProgress({ file: mockFile, workspaceId: 'ws-channel' });
+ });
+
+ expect(fileService.checkFileHash).toHaveBeenCalledWith('mock-hash-value', 'ws-channel');
+ expect(uploadService.uploadFileToS3).toHaveBeenCalledWith(
+ mockFile,
+ expect.objectContaining({ workspaceId: 'ws-channel' }),
+ );
+ expect(fileService.createFile).toHaveBeenCalledWith(
+ expect.anything(),
+ undefined,
+ 'ws-channel',
);
});
});
diff --git a/src/store/file/slices/upload/action.ts b/src/store/file/slices/upload/action.ts
index 50787fe8cf2..bc1f6ccde81 100644
--- a/src/store/file/slices/upload/action.ts
+++ b/src/store/file/slices/upload/action.ts
@@ -63,6 +63,11 @@ interface UploadWithProgressParams {
* `'private'`, children inherit their parent document's visibility).
*/
visibility?: 'private' | 'public';
+ /**
+ * Pins the scope every step of the upload runs in, `null` being the personal one. `undefined`
+ * follows the active workspace; a surface owned by a known scope (a Channel) passes its own.
+ */
+ workspaceId?: string | null;
}
interface UploadWithProgressResult {
@@ -160,6 +165,7 @@ export class FileUploadActionImpl {
visibility,
fileMetadata,
conversationAgentId,
+ workspaceId,
}: UploadWithProgressParams): Promise<UploadWithProgressResult | undefined> => {
const statusId = uploadId ?? file.name;
let uploadedPathname: string | undefined;
@@ -187,7 +193,7 @@ export class FileUploadActionImpl {
});
});
- const checkStatus = await fileService.checkFileHash(hash);
+ const checkStatus = await fileService.checkFileHash(hash, workspaceId);
let metadata: ExistingFileMetadata;
// 3. if file exist, just skip upload
@@ -222,6 +228,7 @@ export class FileUploadActionImpl {
});
},
skipCheckFileType,
+ workspaceId,
});
if (!success) return;
@@ -266,6 +273,7 @@ export class FileUploadActionImpl {
visibility,
},
knowledgeBaseId,
+ workspaceId,
);
uploadedPathname = undefined;
@@ -284,7 +292,7 @@ export class FileUploadActionImpl {
return { ...data, dimensions, filename: normalizedFile.name };
} catch (error) {
- if (uploadedPathname) await uploadService.releaseUpload(uploadedPathname);
+ if (uploadedPathname) await uploadService.releaseUpload(uploadedPathname, workspaceId);
if (abortController?.signal.aborted) {
onStatusUpdate?.({
id: statusId,