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(workspace): sync library visibility with its content and stop phantom agent-config saves (#17715)

Rdmclin2c3a51ec26bc1
diff --git a/apps/server/src/routers/lambda/__tests__/file.test.ts b/apps/server/src/routers/lambda/__tests__/file.test.ts
index 841d809fabc..af8299ab16b 100644
--- a/apps/server/src/routers/lambda/__tests__/file.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/file.test.ts
@@ -177,6 +177,14 @@ vi.mock('@/database/models/file', () => ({
})),
}));
+const mockKnowledgeBaseFindById = vi.fn();
+
+vi.mock('@/database/models/knowledgeBase', () => ({
+ KnowledgeBaseModel: vi.fn(() => ({
+ findById: mockKnowledgeBaseFindById,
+ })),
+}));
+
const mockFileServiceGetFullFileUrl = vi.fn();
const mockFileServiceGetFileAccessUrl = vi.fn();
const mockFileServiceGetFileMetadata = vi.fn();
@@ -237,6 +245,7 @@ describe('fileRouter', () => {
routerMocks.businessFileUploadCheck.mockResolvedValue(undefined);
routerMocks.businessFileTransferStorageCheck.mockResolvedValue(undefined);
routerMocks.hasWorkspaceScopedPermission.mockResolvedValue(true);
+ mockKnowledgeBaseFindById.mockResolvedValue({ id: 'kb-1', visibility: 'public' });
mockFile = {
id: 'test-id',
@@ -464,6 +473,53 @@ describe('fileRouter', () => {
);
});
+ it('should use workspace knowledge-base visibility over an explicit value', async () => {
+ ({ caller } = createCallerWithCtx({ workspaceId: 'workspace-1' }));
+ mockFileModelCheckHash.mockResolvedValue({ isExist: false });
+ mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });
+
+ await caller.createFile({
+ hash: 'test-hash',
+ fileType: 'text',
+ knowledgeBaseId: 'kb-1',
+ name: 'test.txt',
+ size: 100,
+ url: 'files/test.txt',
+ visibility: 'private',
+ metadata: {},
+ });
+
+ expect(mockKnowledgeBaseFindById).toHaveBeenCalledWith('kb-1');
+ expect(mockFileModelCreate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ knowledgeBaseId: 'kb-1',
+ visibility: 'public',
+ }),
+ true,
+ routerMocks.transactionClient,
+ );
+ });
+
+ it('should reject a workspace upload when the knowledge base is not accessible', async () => {
+ ({ caller } = createCallerWithCtx({ workspaceId: 'workspace-1' }));
+ mockFileModelCheckHash.mockResolvedValue({ isExist: false });
+ mockKnowledgeBaseFindById.mockResolvedValue(undefined);
+
+ await expect(
+ caller.createFile({
+ hash: 'test-hash',
+ fileType: 'text',
+ knowledgeBaseId: 'missing-kb',
+ name: 'test.txt',
+ size: 100,
+ url: 'files/test.txt',
+ metadata: {},
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+
+ expect(mockFileModelCreate).not.toHaveBeenCalled();
+ });
+
it('should use actual file size from S3 instead of client-provided size (security fix)', async () => {
// Setup: S3 returns actual size of 5000 bytes
mockFileServiceGetFileMetadata.mockResolvedValue({
diff --git a/apps/server/src/routers/lambda/agentBotProvider.ts b/apps/server/src/routers/lambda/agentBotProvider.ts
index 53f0617237f..a02eee6cce3 100644
--- a/apps/server/src/routers/lambda/agentBotProvider.ts
+++ b/apps/server/src/routers/lambda/agentBotProvider.ts
@@ -20,7 +20,13 @@ import {
mergeBotSettingsForPersist,
} from '@/server/services/bot/agentBotProviderSettings';
import { getBotMessageRouter } from '@/server/services/bot/BotMessageRouter';
-import { mergeWithDefaults, platformRegistry } from '@/server/services/bot/platforms';
+import {
+ type BotProviderFieldValues,
+ collectFieldFormatViolations,
+ formatFieldFormatViolations,
+ mergeWithDefaults,
+ platformRegistry,
+} from '@/server/services/bot/platforms';
import { GatewayService } from '@/server/services/gateway';
import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';
@@ -60,6 +66,30 @@ function assertAccessSettingsForTRPC(settings: Record<string, unknown> | undefin
}
}
+/**
+ * Reject credentials that can't possibly work before they reach the database.
+ *
+ * These fields attract the wrong value — an OAuth authorize URL in the
+ * public-key box, an API key in place of a bot token — and the bot then fails
+ * to connect with no obvious cause. The form enforces the same schema patterns
+ * client-side; this stops anything that skips it.
+ */
+function assertFieldFormatsForTRPC(
+ platform: string | undefined,
+ values: BotProviderFieldValues,
+): void {
+ if (!platform) return;
+
+ const entry = platformRegistry.getPlatform(platform);
+ const violations = collectFieldFormatViolations(entry?.schema, values);
+ if (violations.length === 0) return;
+
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Invalid format for ${formatFieldFormatViolations(violations)}`,
+ });
+}
+
export const agentBotProviderRouter = router({
listPlatforms: authedProcedure.query(async ({ ctx }) => {
return Promise.all(
@@ -92,6 +122,11 @@ export const agentBotProviderRouter = router({
workspaceId: ctx.workspaceId ?? undefined,
});
+ assertFieldFormatsForTRPC(input.platform, {
+ applicationId: input.applicationId,
+ credentials: input.credentials,
+ });
+
const payload = {
...input,
settings: mergeBotSettingsForPersist(input.platform, input.settings),
@@ -354,6 +389,13 @@ export const agentBotProviderRouter = router({
});
}
+ // Only the sections the caller actually sent are checked, so a partial
+ // update (e.g. toggling a setting) never trips on untouched fields.
+ assertFieldFormatsForTRPC(targetPlatform, {
+ applicationId: value.applicationId,
+ credentials: value.credentials,
+ });
+
if (value.settings !== undefined) {
value.settings = mergeBotSettingsForPersist(
value.platform ?? existing?.platform,
diff --git a/apps/server/src/routers/lambda/file.ts b/apps/server/src/routers/lambda/file.ts
index ff5af8aa5b3..c2e4d296b5f 100644
--- a/apps/server/src/routers/lambda/file.ts
+++ b/apps/server/src/routers/lambda/file.ts
@@ -18,6 +18,7 @@ import { AsyncTaskModel } from '@/database/models/asyncTask';
import { ChunkModel } from '@/database/models/chunk';
import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
+import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { KnowledgeRepo } from '@/database/repositories/knowledge';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
@@ -149,6 +150,7 @@ const fileProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
documentService: new DocumentService(ctx.serverDB, ctx.userId, wsId),
fileModel: new FileModel(ctx.serverDB, ctx.userId, wsId),
fileService: new FileService(ctx.serverDB, ctx.userId, wsId),
+ knowledgeBaseModel: new KnowledgeBaseModel(ctx.serverDB, ctx.userId, wsId),
knowledgeRepo: new KnowledgeRepo(ctx.serverDB, ctx.userId, wsId),
},
});
@@ -197,15 +199,25 @@ export const fileRouter = router({
}
}
+ let knowledgeBaseVisibility: 'private' | 'public' | undefined;
+ if (ctx.workspaceId && input.knowledgeBaseId) {
+ const knowledgeBase = await ctx.knowledgeBaseModel.findById(input.knowledgeBaseId);
+ if (!knowledgeBase) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Knowledge base not found' });
+ }
+ knowledgeBaseVisibility = knowledgeBase.visibility;
+ }
+
// Visibility precedence (workspace mode only — personal mode ignores the
// column entirely):
- // 1. Explicit caller value wins.
- // 2. Otherwise inherit the parent document's visibility so a file
+ // 1. A library upload always uses the knowledge base visibility.
+ // 2. Otherwise an explicit caller value wins.
+ // 3. Otherwise inherit the parent document's visibility so a file
// uploaded inside a private folder stays private.
- // 3. Otherwise default top-level uploads to 'private' so new content
+ // 4. Otherwise default top-level uploads to 'private' so new content
// starts in the creator's private space (mirrors the Pages spec).
const resolvedVisibility: 'private' | 'public' | undefined = ctx.workspaceId
- ? (input.visibility ?? parentVisibility ?? 'private')
+ ? (knowledgeBaseVisibility ?? input.visibility ?? parentVisibility ?? 'private')
: undefined;
let actualSize = input.size;
diff --git a/apps/server/src/routers/lambda/knowledgeBase.ts b/apps/server/src/routers/lambda/knowledgeBase.ts
index 0c2eca17f78..071b6b8630b 100644
--- a/apps/server/src/routers/lambda/knowledgeBase.ts
+++ b/apps/server/src/routers/lambda/knowledgeBase.ts
@@ -168,8 +168,6 @@ export const knowledgeBaseRouter = router({
});
}
- if (kb.visibility === 'public') return { success: true };
-
await ctx.knowledgeBaseModel.publishToWorkspace(input.id);
return { success: true };
}),
@@ -204,8 +202,6 @@ export const knowledgeBaseRouter = router({
});
}
- if (kb.visibility === input.visibility) return { success: true };
-
await ctx.knowledgeBaseModel.setVisibility(input.id, input.visibility);
return { success: true };
}),
diff --git a/apps/server/src/services/bot/platforms/__tests__/validateFieldFormats.test.ts b/apps/server/src/services/bot/platforms/__tests__/validateFieldFormats.test.ts
new file mode 100644
index 00000000000..cce9040c052
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/__tests__/validateFieldFormats.test.ts
@@ -0,0 +1,153 @@
+import { describe, expect, it } from 'vitest';
+
+import { schema as discordSchema } from '../discord/schema';
+import { schema as telegramSchema } from '../telegram/schema';
+import type { FieldSchema } from '../types';
+import { collectFieldFormatViolations, formatFieldFormatViolations } from '../validateFieldFormats';
+
+/**
+ * Every value here only imitates the SHAPE of a Discord credential; the bytes
+ * are invented, and each one is worded so it cannot be mistaken for a real
+ * secret. Never paste an actual credential into this file.
+ */
+const VALID_DISCORD = {
+ applicationId: '1000000000000000001',
+ credentials: {
+ botToken: 'ExampleDiscordBotToken00.Fake01.NotARealSecretValue000000',
+ publicKey: '4f1c8a2d9b30e7654c1de8ab72f09356d4ea18bc27309fd6a5b4c8e0173fa29d',
+ },
+};
+
+const fieldsOf = (violations: Array<{ field: string }>) => violations.map((v) => v.field);
+
+describe('collectFieldFormatViolations', () => {
+ it('accepts well-formed Discord credentials', () => {
+ expect(collectFieldFormatViolations(discordSchema, VALID_DISCORD)).toEqual([]);
+ });
+
+ // The three shapes below are the ones that actually get pasted into the
+ // Public Key box by mistake; the values themselves are invented.
+ it.each([
+ [
+ 'an OAuth authorize URL',
+ 'https://discord.com/oauth2/authorize?client_id=1000000000000000001',
+ ],
+ ['a block of prose', '## Summary - Endpoint or schema scope, consumers, version'],
+ ['a LobeHub API key', 'sk-lh-000000000000fake'],
+ ])('rejects %s pasted into publicKey', (_label, publicKey) => {
+ const violations = collectFieldFormatViolations(discordSchema, {
+ ...VALID_DISCORD,
+ credentials: { ...VALID_DISCORD.credentials, publicKey },
+ });
+
+ expect(fieldsOf(violations)).toEqual(['credentials.publicKey']);
+ });
+
+ it('rejects a public key of the wrong length or with non-hex characters', () => {
+ const tooShort = 'a'.repeat(63);
+ const nonHex = `${'a'.repeat(63)}z`;
+
+ for (const publicKey of [tooShort, nonHex, 'a'.repeat(65)]) {
+ const violations = collectFieldFormatViolations(discordSchema, {
+ credentials: { publicKey },
+ });
+ expect(fieldsOf(violations)).toEqual(['credentials.publicKey']);
+ }
+ });
+
+ it('rejects a bot token that is not three dot-separated segments', () => {
+ const violations = collectFieldFormatViolations(discordSchema, {
+ credentials: { botToken: 'sk-lh-000000000000fake' },
+ });
+
+ expect(fieldsOf(violations)).toEqual(['credentials.botToken']);
+ });
+
+ it('rejects an application ID that is not a snowflake', () => {
+ const violations = collectFieldFormatViolations(discordSchema, {
+ applicationId: 'https://discord.com/oauth2/authorize?client_id=1000000000000000001',
+ });
+
+ expect(fieldsOf(violations)).toEqual(['applicationId']);
+ });
+
+ it('reports every offending field at once so the caller can fix them in one pass', () => {
+ const violations = collectFieldFormatViolations(discordSchema, {
+ applicationId: 'my-bot',
+ credentials: { botToken: 'nope', publicKey: 'nope' },
+ });
+
+ expect(fieldsOf(violations).sort()).toEqual([
+ 'applicationId',
+ 'credentials.botToken',
+ 'credentials.publicKey',
+ ]);
+ });
+
+ it('skips sections the caller omitted, so partial updates stay valid', () => {
+ expect(collectFieldFormatViolations(discordSchema, {})).toEqual([]);
+ expect(
+ collectFieldFormatViolations(discordSchema, { applicationId: VALID_DISCORD.applicationId }),
+ ).toEqual([]);
+ });
+
+ it('treats an empty value as required-check territory, not a format error', () => {
+ expect(
+ collectFieldFormatViolations(discordSchema, { applicationId: '', credentials: {} }),
+ ).toEqual([]);
+ expect(collectFieldFormatViolations(discordSchema, { credentials: { publicKey: '' } })).toEqual(
+ [],
+ );
+ });
+
+ it('leaves platforms without declared patterns untouched', () => {
+ expect(
+ collectFieldFormatViolations(telegramSchema, {
+ applicationId: 'anything',
+ credentials: { botToken: 'anything at all' },
+ }),
+ ).toEqual([]);
+ });
+
+ it('returns nothing when the platform has no schema', () => {
+ expect(collectFieldFormatViolations(undefined, VALID_DISCORD)).toEqual([]);
+ });
+
+ it('walks nested credential groups', () => {
+ const nested: FieldSchema[] = [
+ {
+ key: 'credentials',
+ label: 'credentials',
+ properties: [
+ {
+ key: 'group',
+ label: 'group',
+ properties: [
+ { key: 'code', label: 'code', pattern: String.raw`^\d{4}$`, type: 'string' },
+ ],
+ type: 'object',
+ },
+ ],
+ type: 'object',
+ },
+ ];
+
+ const violations = collectFieldFormatViolations(nested, {
+ credentials: { group: { code: 'abcd' } } as unknown as Record<string, string>,
+ });
+
+ expect(fieldsOf(violations)).toEqual(['credentials.group.code']);
+ });
+});
+
+describe('formatFieldFormatViolations', () => {
+ it('names each field alongside the pattern it failed', () => {
+ const violations = collectFieldFormatViolations(discordSchema, {
+ credentials: { publicKey: 'nope' },
+ });
+
+ expect(formatFieldFormatViolations(violations)).toBe(
+ String.raw`"credentials.publicKey" (expected /^[\dA-Fa-f]{64}$/)`,
+ );
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/discord/client.ts b/apps/server/src/services/bot/platforms/discord/client.ts
index 30b79ab426b..f37c2f7f217 100644
--- a/apps/server/src/services/bot/platforms/discord/client.ts
+++ b/apps/server/src/services/bot/platforms/discord/client.ts
@@ -22,6 +22,7 @@ import {
} from '../types';
import { formatUsageStats } from '../utils';
import { DiscordApi } from './api';
+import { DISCORD_BOT_TOKEN_PATTERN, DISCORD_PUBLIC_KEY_PATTERN } from './const';
import { patchDiscordForwardedInteractions, patchDiscordThreadRecovery } from './patch';
import { batchDiscordFiles, materializeAttachmentsForDiscord } from './sendAttachments';
@@ -529,6 +530,22 @@ export class DiscordClientFactory extends ClientFactory {
if (errors.length > 0) return { errors, valid: false };
+ // Name the actual problem before spending a round-trip on it — a
+ // malformed public key can't be caught by the API call at all, and a
+ // malformed token would come back as a generic auth failure.
+ if (!new RegExp(DISCORD_PUBLIC_KEY_PATTERN).test(credentials.publicKey))
+ errors.push({
+ field: 'publicKey',
+ message: 'Public Key must be a 64-character hex string',
+ });
+ if (!new RegExp(DISCORD_BOT_TOKEN_PATTERN).test(credentials.botToken))
+ errors.push({
+ field: 'botToken',
+ message: 'Bot Token must be three dot-separated segments, as shown in the Discord portal',
+ });
+
+ if (errors.length > 0) return { errors, valid: false };
+
try {
const res = await fetch('https://discord.com/api/v10/users/@me', {
headers: { Authorization: `Bot ${credentials.botToken}` },
diff --git a/apps/server/src/services/bot/platforms/discord/const.ts b/apps/server/src/services/bot/platforms/discord/const.ts
index fc667853539..47d3987bd56 100644
--- a/apps/server/src/services/bot/platforms/discord/const.ts
+++ b/apps/server/src/services/bot/platforms/discord/const.ts
@@ -2,3 +2,25 @@
export const MAX_DISCORD_HISTORY_LIMIT = 100;
export const DEFAULT_DISCORD_CONNECTION_MODE = 'websocket';
+
+// --------------- Credential formats ---------------
+//
+// Operators routinely paste the wrong value into these fields — an OAuth
+// authorize URL, a LobeHub `sk-lh-…` API key, even a block of prose — and the
+// bot then fails to connect with no obvious cause. The patterns below are
+// deliberately shape-checks, not authenticity checks: they reject values that
+// could never work while staying loose enough to survive Discord widening its
+// own formats.
+
+/** Ed25519 public key — always exactly 64 hex characters. */
+export const DISCORD_PUBLIC_KEY_PATTERN = String.raw`^[\dA-Fa-f]{64}$`;
+
+/**
+ * Bot token — three base64url segments (`appId.timestamp.hmac`). Segment
+ * lengths are given generous lower bounds because Discord has lengthened them
+ * before; a real token has never been anywhere near this short.
+ */
+export const DISCORD_BOT_TOKEN_PATTERN = String.raw`^[\w-]{20,}\.[\w-]{5,}\.[\w-]{20,}$`;
+
+/** Application ID — a Discord snowflake. */
+export const DISCORD_APPLICATION_ID_PATTERN = String.raw`^\d{17,20}$`;
diff --git a/apps/server/src/services/bot/platforms/discord/schema.ts b/apps/server/src/services/bot/platforms/discord/schema.ts
index 7bfd50ab5d7..1a27c84e3f8 100644
--- a/apps/server/src/services/bot/platforms/discord/schema.ts
+++ b/apps/server/src/services/bot/platforms/discord/schema.ts
@@ -15,13 +15,21 @@ import {
watchKeywordsField,
} from '../const';
import type { FieldSchema } from '../types';
-import { MAX_DISCORD_HISTORY_LIMIT } from './const';
+import {
+ DISCORD_APPLICATION_ID_PATTERN,
+ DISCORD_BOT_TOKEN_PATTERN,
+ DISCORD_PUBLIC_KEY_PATTERN,
+ MAX_DISCORD_HISTORY_LIMIT,
+} from './const';
export const schema: FieldSchema[] = [
{
key: 'applicationId',
description: 'channel.applicationIdHint',
label: 'channel.applicationId',
+ pattern: DISCORD_APPLICATION_ID_PATTERN,
+ patternMessage: 'channel.applicationIdInvalid.discord',
+ placeholder: 'channel.applicationIdPlaceholder',
required: true,
type: 'string',
},
@@ -33,6 +41,9 @@ export const schema: FieldSchema[] = [
key: 'publicKey',
description: 'channel.publicKeyHint',
label: 'channel.publicKey',
+ pattern: DISCORD_PUBLIC_KEY_PATTERN,
+ patternMessage: 'channel.publicKeyInvalid',
+ placeholder: 'channel.publicKeyPlaceholder',
required: true,
type: 'string',
},
@@ -40,6 +51,9 @@ export const schema: FieldSchema[] = [
key: 'botToken',
description: 'channel.botTokenEncryptedHint',
label: 'channel.botToken',
+ pattern: DISCORD_BOT_TOKEN_PATTERN,
+ patternMessage: 'channel.botTokenInvalid.discord',
+ placeholder: 'channel.botTokenPlaceholderNew',
required: true,
type: 'password',
},
diff --git a/apps/server/src/services/bot/platforms/index.ts b/apps/server/src/services/bot/platforms/index.ts
index 9f1881e9933..d2203a37f38 100644
--- a/apps/server/src/services/bot/platforms/index.ts
+++ b/apps/server/src/services/bot/platforms/index.ts
@@ -78,6 +78,8 @@ export {
resolveBotProviderConfig,
resolveConnectionMode,
} from './utils';
+export type { BotProviderFieldValues, FieldFormatViolation } from './validateFieldFormats';
+export { collectFieldFormatViolations, formatFieldFormatViolations } from './validateFieldFormats';
// --------------- Platform definitions ---------------
export { discord } from './discord/definition';
diff --git a/apps/server/src/services/bot/platforms/types.ts b/apps/server/src/services/bot/platforms/types.ts
index 771b54a2f48..7cb4389ffe4 100644
--- a/apps/server/src/services/bot/platforms/types.ts
+++ b/apps/server/src/services/bot/platforms/types.ts
@@ -73,6 +73,18 @@ export interface FieldSchema {
* when the platform access meta reports the feature as not allowed.
*/
paidFeature?: string;
+ /**
+ * Format constraint for `string` / `password` fields, as a regex **source
+ * string** — the schema is serialized over TRPC to drive the frontend form,
+ * so it cannot carry a `RegExp` instance. Enforced on both sides: the form
+ * turns it into an antd rule, and the save mutation re-checks it so callers
+ * bypassing the UI can't persist a malformed credential.
+ *
+ * Empty values are exempt — `required` owns that check.
+ */
+ pattern?: string;
+ /** i18n key for the message shown when the value fails `pattern`. */
+ patternMessage?: string;
placeholder?: string;
/** Nested fields (for type: 'object') */
properties?: FieldSchema[];
diff --git a/apps/server/src/services/bot/platforms/validateFieldFormats.ts b/apps/server/src/services/bot/platforms/validateFieldFormats.ts
new file mode 100644
index 00000000000..ff902d43085
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/validateFieldFormats.ts
@@ -0,0 +1,97 @@
+import type { FieldSchema } from './types';
+
+export interface FieldFormatViolation {
+ /** Regex source the value failed against — echoed so API callers can self-correct. */
+ expected: string;
+ /** Dotted path of the offending field, e.g. `credentials.publicKey`. */
+ field: string;
+}
+
+/**
+ * Values submitted for a bot provider, shaped the way the form and the TRPC
+ * input carry them. Only the sections that declare `pattern` constraints today
+ * are inspected; `settings` is accepted so callers can pass the whole payload.
+ */
+export interface BotProviderFieldValues {
+ applicationId?: string;
+ credentials?: Record<string, string>;
+ settings?: Record<string, unknown>;
+}
+
+const testPattern = (pattern: string, value: unknown): boolean => {
+ // Only strings carry format constraints, and an empty value is `required`'s
+ // business — a blank optional field must not trip the format check.
+ if (typeof value !== 'string' || value === '') return true;
+
+ return new RegExp(pattern).test(value);
+};
+
+const collectSection = (
+ fields: FieldSchema[] | undefined,
+ values: Record<string, unknown> | undefined,
+ prefix: string,
+ violations: FieldFormatViolation[],
+): void => {
+ if (!fields || !values) return;
+
+ for (const field of fields) {
+ if (field.type === 'object' && field.properties) {
+ collectSection(
+ field.properties,
+ values[field.key] as Record<string, unknown> | undefined,
+ `${prefix}${field.key}.`,
+ violations,
+ );
+ continue;
+ }
+
+ if (!field.pattern) continue;
+ if (testPattern(field.pattern, values[field.key])) continue;
+
+ violations.push({ expected: field.pattern, field: `${prefix}${field.key}` });
+ }
+};
+
+/**
+ * Check a bot provider payload against the `pattern` constraints declared in
+ * its platform schema.
+ *
+ * The form applies the same patterns as antd rules, so this is the guard for
+ * everything that doesn't go through the form. Fields the caller omitted are
+ * skipped, which keeps partial updates working.
+ */
+export function collectFieldFormatViolations(
+ schema: FieldSchema[] | undefined,
+ values: BotProviderFieldValues,
+): FieldFormatViolation[] {
+ if (!schema) return [];
+
+ const violations: FieldFormatViolation[] = [];
+
+ for (const section of schema) {
+ switch (section.key) {
+ case 'applicationId': {
+ // Top-level scalar rather than a nested section — the form binds it to
+ // a bare `applicationId` name, so the value sits alongside the sections.
+ if (values.applicationId === undefined) break;
+ collectSection([section], { applicationId: values.applicationId }, '', violations);
+ break;
+ }
+ case 'credentials': {
+ if (values.credentials === undefined) break;
+ collectSection(section.properties, values.credentials, 'credentials.', violations);
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+ }
+
+ return violations;
+}
+
+/** Render violations as a single human-readable line for error messages. */
+export function formatFieldFormatViolations(violations: FieldFormatViolation[]): string {
+ return violations.map((v) => `"${v.field}" (expected /${v.expected}/)`).join(', ');
+}
diff --git a/apps/server/src/services/document/__tests__/index.test.ts b/apps/server/src/services/document/__tests__/index.test.ts
index 800eddec4a3..1c1ce3436e5 100644
--- a/apps/server/src/services/document/__tests__/index.test.ts
+++ b/apps/server/src/services/document/__tests__/index.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
+import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { EditLockService } from '../../editLock';
import { FileService } from '../../file';
@@ -14,6 +15,7 @@ import { DocumentService } from '../index';
vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => null }));
vi.mock('@/database/models/document');
vi.mock('@/database/models/file');
+vi.mock('@/database/models/knowledgeBase');
vi.mock('../../file');
vi.mock('../history');
// Spy on the realtime broadcast so we can assert lock.changed is published only
@@ -82,6 +84,7 @@ describe('DocumentService', () => {
let mockDocumentHistoryService: any;
let mockFileModel: any;
let mockFileService: any;
+ let mockKnowledgeBaseModel: any;
const userId = 'test-user-id';
beforeEach(() => {
@@ -127,10 +130,15 @@ describe('DocumentService', () => {
downloadFileToLocal: vi.fn(),
};
+ mockKnowledgeBaseModel = {
+ findById: vi.fn().mockResolvedValue({ id: 'kb-1', visibility: 'public' }),
+ };
+
vi.mocked(DocumentModel).mockImplementation(() => mockDocumentModel);
vi.mocked(DocumentHistoryService).mockImplementation(() => mockDocumentHistoryService);
vi.mocked(FileModel).mockImplementation(() => mockFileModel);
vi.mocked(FileService).mockImplementation(() => mockFileService);
+ vi.mocked(KnowledgeBaseModel).mockImplementation(() => mockKnowledgeBaseModel);
service = new DocumentService(mockDb, userId);
});
@@ -323,12 +331,17 @@ describe('DocumentService', () => {
mockDocumentModel.create.mockResolvedValue({ id: 'doc-1' });
});
- it('propagates explicit private visibility to the KB mirror file', async () => {
+ it('uses private knowledge-base visibility over an explicit public value', async () => {
+ mockKnowledgeBaseModel.findById.mockResolvedValue({
+ id: 'kb-1',
+ visibility: 'private',
+ });
+
await service.createDocument({
title: 'Private Doc',
editorData: {},
knowledgeBaseId: 'kb-1',
- visibility: 'private',
+ visibility: 'public',
});
expect(mockFileModel.create).toHaveBeenCalledWith(
@@ -340,7 +353,7 @@ describe('DocumentService', () => {
);
});
- it('defaults top-level KB documents to private in workspace mode', async () => {
+ it('inherits public visibility from the workspace knowledge base', async () => {
await service.createDocument({
title: 'Draft',
editorData: {},
@@ -348,15 +361,16 @@ describe('DocumentService', () => {
});
expect(mockFileModel.create).toHaveBeenCalledWith(
- expect.objectContaining({ visibility: 'private' }),
+ expect.objectContaining({ visibility: 'public' }),
false,
);
expect(mockDocumentModel.create).toHaveBeenCalledWith(
- expect.objectContaining({ visibility: 'private' }),
+ expect.objectContaining({ visibility: 'public' }),
);
+ expect(mockKnowledgeBaseModel.findById).toHaveBeenCalledWith('kb-1', undefined);
});
- it('keeps a nested document private regardless of parent visibility', async () => {
+ it('inherits library visibility without consulting the navigation parent', async () => {
mockDocumentModel.findById.mockResolvedValue({ id: 'parent-1', visibility: 'public' });
await service.createDocument({
@@ -368,15 +382,15 @@ describe('DocumentService', () => {
expect(mockDocumentModel.findById).not.toHaveBeenCalled();
expect(mockFileModel.create).toHaveBeenCalledWith(
- expect.objectContaining({ visibility: 'private' }),
+ expect.objectContaining({ visibility: 'public' }),
false,
);
expect(mockDocumentModel.create).toHaveBeenCalledWith(
- expect.objectContaining({ visibility: 'private' }),
+ expect.objectContaining({ visibility: 'public' }),
);
});
- it('falls back to private when parent lookup returns nothing', async () => {
+ it('uses the library visibility when the navigation parent is missing', async () => {
mockDocumentModel.findById.mockResolvedValue(undefined);
await service.createDocument({
@@ -386,10 +400,46 @@ describe('DocumentService', () => {
parentId: 'missing-parent',
});
+ expect(mockFileModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({ visibility: 'public' }),
+ false,
+ );
+ });
+
+ it('inherits private visibility from a private knowledge base', async () => {
+ mockKnowledgeBaseModel.findById.mockResolvedValue({
+ id: 'kb-private',
+ visibility: 'private',
+ });
+
+ await service.createDocument({
+ title: 'Private Library Doc',
+ editorData: {},
+ knowledgeBaseId: 'kb-private',
+ });
+
expect(mockFileModel.create).toHaveBeenCalledWith(
expect.objectContaining({ visibility: 'private' }),
false,
);
+ expect(mockDocumentModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({ visibility: 'private' }),
+ );
+ });
+
+ it('rejects creation when the knowledge base is not accessible', async () => {
+ mockKnowledgeBaseModel.findById.mockResolvedValue(undefined);
+
+ await expect(
+ service.createDocument({
+ title: 'Missing Library Doc',
+ editorData: {},
+ knowledgeBaseId: 'missing-kb',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+
+ expect(mockFileModel.create).not.toHaveBeenCalled();
+ expect(mockDocumentModel.create).not.toHaveBeenCalled();
});
});
diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.ts
index 4304af08683..b4841449961 100644
--- a/apps/server/src/services/document/index.ts
+++ b/apps/server/src/services/document/index.ts
@@ -12,6 +12,7 @@ import isEqual from 'fast-deep-equal';
import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
+import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { buildWorkspaceWhere } from '@/database/utils/workspace';
import { isValidEditorData } from '@/libs/editor/isValidEditorData';
import { normalizeEditorDataDiffNodes } from '@/libs/editor/normalizeDiffNodes';
@@ -55,6 +56,7 @@ export class DocumentService {
private documentModel: DocumentModel;
private documentHistoryServiceInstance?: DocumentHistoryService;
private fileServiceInstance?: FileService;
+ private knowledgeBaseModel: KnowledgeBaseModel;
private editLockService: EditLockService;
private db: LobeChatDatabase;
private callerAgentVisibility?: 'private' | 'public' | null;
@@ -72,6 +74,7 @@ export class DocumentService {
this.workspaceId = workspaceId;
this.callerAgentVisibility = callerAgentVisibility;
this.fileModel = new FileModel(db, userId, workspaceId);
+ this.knowledgeBaseModel = new KnowledgeBaseModel(db, userId, workspaceId);
this.documentModel = new DocumentModel(db, userId, workspaceId, callerAgentVisibility);
this.editLockService = new EditLockService(userId);
}
@@ -146,13 +149,22 @@ export class DocumentService {
const totalLineCount = content?.split('\n').length || 0;
// Resolve visibility upfront so the KB mirror file uses the same policy
- // as the document. Parent documents are navigation only and do not pass
- // visibility or ACL to children. Personal mode leaves it undefined —
- // the ownership filter ignores the column there.
+ // as the document. A library-root document inherits the KB visibility;
+ // parent documents remain navigation-only and do not pass visibility or
+ // ACL to children. Personal mode leaves it undefined — the ownership
+ // filter ignores the column there.
let resolvedVisibility: 'private' | 'public' | undefined = visibility;
- if (!resolvedVisibility && this.workspaceId) {
- resolvedVisibility = 'private';
+ if (this.workspaceId && knowledgeBaseId) {
+ const knowledgeBase = await this.knowledgeBaseModel.findById(
+ knowledgeBaseId,
+ this.callerAgentVisibility,
+ );
+ if (!knowledgeBase) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Knowledge base not found' });
+ }
+ resolvedVisibility = knowledgeBase.visibility;
}
+ if (!resolvedVisibility && this.workspaceId) resolvedVisibility = 'private';
let fileId: string | null = null;
diff --git a/locales/ar/agent.json b/locales/ar/agent.json
index 205c06cd4cf..b54f29fe680 100644
--- a/locales/ar/agent.json
+++ b/locales/ar/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "الصق سر التطبيق هنا",
"channel.applicationId": "معرف التطبيق / اسم المستخدم للبوت",
"channel.applicationIdHint": "معرف فريد لتطبيق البوت الخاص بك.",
+ "channel.applicationIdInvalid.discord": "يجب أن يكون معرف التطبيق هو الرقم المكون من 17 إلى 20 رقمًا الموجود في صفحة المعلومات العامة لتطبيق Discord الخاص بك.",
"channel.applicationIdPlaceholder": "مثال: 1234567890",
"channel.botToken": "رمز البوت / مفتاح API",
"channel.botTokenEncryptedHint": "سيتم تشفير الرمز وتخزينه بأمان.",
"channel.botTokenHowToGet": "كيف تحصل عليه؟",
+ "channel.botTokenInvalid.discord": "هذا لا يبدو كرمز مميز لبوت Discord. قم بإعادة تعيينه ونسخه من علامة تبويب البوت في تطبيق Discord الخاص بك — يتكون من ثلاثة أجزاء مفصولة بنقاط.",
"channel.botTokenPlaceholderExisting": "الرمز مخفي لأسباب أمنية",
"channel.botTokenPlaceholderNew": "الصق رمز البوت هنا",
"channel.charLimit": "حد الأحرف",
@@ -201,6 +203,7 @@
"channel.platforms": "المنصات",
"channel.publicKey": "المفتاح العام",
"channel.publicKeyHint": "اختياري. يُستخدم للتحقق من طلبات التفاعل من Discord.",
+ "channel.publicKeyInvalid": "يجب أن يكون المفتاح العام سلسلة سداسية مكونة من 64 حرفًا. قم بنسخه من صفحة المعلومات العامة لتطبيق Discord الخاص بك — وليس عنوان URL OAuth، وليس مفتاح API.",
"channel.publicKeyPlaceholder": "مطلوب للتحقق من التفاعل",
"channel.qq.appIdHint": "معرّف تطبيق QQ Bot الخاص بك من منصة QQ المفتوحة",
"channel.qq.description": "قم بتوصيل هذا المساعد بـ QQ للمحادثات الجماعية والرسائل المباشرة.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "معرّف الروبوت المخصص بعد تفويض رمز الاستجابة السريعة.",
"channel.wechatConnectedInfo": "حساب WeChat المتصل",
"channel.wechatGenerateQrCode": "إنشاء رمز QR",
- "channel.wechatIdleNotice": "إذا لم يرسل أي مستخدم رسائل لمدة تتجاوز 7 أيام، فسيتم إيقاف هذا الاتصال تلقائيًا. لاستئنافه، انقر على \"إعادة الربط عبر رمز الاستجابة السريعة\".",
"channel.wechatManagedCredentials": "تم توصيل هذه القناة بالفعل من خلال تفويض رمز الاستجابة السريعة. يتم إدارة بيانات الاعتماد تلقائيًا.",
"channel.wechatQrExpired": "انتهت صلاحية رمز الاستجابة السريعة. يرجى التحديث للحصول على رمز جديد.",
"channel.wechatQrLoadFailed": "فشل تحميل رمز QR. يرجى المحاولة مرة أخرى.",
diff --git a/locales/ar/setting.json b/locales/ar/setting.json
index bdcc3421ae3..ae5a9f20cae 100644
--- a/locales/ar/setting.json
+++ b/locales/ar/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "الاسم",
"settingAgent.prompt.desc": "يحدد من هو هذا الوكيل، وما هو مسؤوليته، وكيف يعمل ويستجيب. إنه بمثابة تعليمات أساسية في كل محادثة.",
"settingAgent.prompt.editorPlaceholder": "أدخل التعليمات الأساسية، اضغط / لفتح قائمة سلاش",
+ "settingAgent.prompt.mode.source": "مصدر Markdown",
+ "settingAgent.prompt.mode.visual": "محرر بصري",
"settingAgent.prompt.placeholder": "أدخل إعدادات الوكيل، اضغط / لفتح قائمة الأوامر",
"settingAgent.prompt.title": "ملف تعريف الوكيل",
"settingAgent.runtimeConfig.title": "النموذج والأدوات",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "إلغاء هذه الدعوة؟",
"workspace.members.pending.revokeFailed": "فشل في إلغاء الدعوة",
"workspace.members.seatChange.memberJoinBlocked": "وصل الأعضاء الحاليون إلى الحد المجدول للمقاعد، لذلك قد لا يتمكن الأعضاء المدفوعون الجدد من الانضمام إلى هذه المساحة",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} مقعد",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} مقاعد",
"workspace.members.subtitle": "إدارة أعضاء مساحة العمل والدعوات",
"workspace.members.tabs.members": "أعضاء الفريق",
"workspace.members.tabs.pending": "الدعوات المعلقة",
"workspace.members.title": "الأعضاء",
+ "workspace.members.totalCount_one": "{{total}} عضو",
+ "workspace.members.totalCount_other": "{{total}} أعضاء",
"workspace.name.placeholder": "اسم مساحة العمل",
"workspace.name.title": "الاسم",
"workspace.newWorkspace": "مساحة عمل جديدة",
diff --git a/locales/bg-BG/agent.json b/locales/bg-BG/agent.json
index 59967611a07..b1643bbd0ff 100644
--- a/locales/bg-BG/agent.json
+++ b/locales/bg-BG/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "Поставете вашия секрет на приложението тук",
"channel.applicationId": "ID на приложението / Потребителско име на бота",
"channel.applicationIdHint": "Уникален идентификатор за вашето бот приложение.",
+ "channel.applicationIdInvalid.discord": "Идентификаторът на приложението трябва да бъде 17–20-цифрен идентификатор от страницата с обща информация на вашето Discord приложение.",
"channel.applicationIdPlaceholder": "напр. 1234567890",
"channel.botToken": "Токен на бота / API ключ",
"channel.botTokenEncryptedHint": "Токенът ще бъде криптиран и съхранен сигурно.",
"channel.botTokenHowToGet": "Как да го получите?",
+ "channel.botTokenInvalid.discord": "Това не изглежда като токен за Discord бот. Нулирайте го и го копирайте от раздела Bot на вашето Discord приложение — той е съставен от три сегмента, разделени с точки.",
"channel.botTokenPlaceholderExisting": "Токенът е скрит за сигурност",
"channel.botTokenPlaceholderNew": "Поставете вашия токен на бота тук",
"channel.charLimit": "Ограничение на символите",
@@ -201,6 +203,7 @@
"channel.platforms": "Платформи",
"channel.publicKey": "Публичен ключ",
"channel.publicKeyHint": "По избор. Използва се за проверка на заявки за взаимодействие от Discord.",
+ "channel.publicKeyInvalid": "Публичният ключ трябва да бъде 64-символен хексадесичен низ. Копирайте го от страницата с обща информация на Discord приложението — не от OAuth URL и не от API ключ.",
"channel.publicKeyPlaceholder": "Задължително за проверка на взаимодействия",
"channel.qq.appIdHint": "Вашият QQ Bot App ID от QQ Open Platform",
"channel.qq.description": "Свържете този асистент с QQ за групови чатове и директни съобщения.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "Идентификатор на бота, присвоен след оторизация чрез QR код.",
"channel.wechatConnectedInfo": "Свързан WeChat акаунт",
"channel.wechatGenerateQrCode": "Генериране на QR код",
- "channel.wechatIdleNotice": "Ако няма изпратени съобщения от потребители повече от 7 дни, тази връзка ще бъде автоматично поставена на пауза. За да я възобновите, щракнете върху „Повторно свързване чрез QR код“.",
"channel.wechatManagedCredentials": "Този канал вече е свързан чрез оторизация с QR код. Удостоверенията се управляват автоматично.",
"channel.wechatQrExpired": "QR кодът е изтекъл. Моля, обновете, за да получите нов.",
"channel.wechatQrLoadFailed": "Неуспешно зареждане на QR кода. Моля, опитайте отново.",
diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.json
index dadff0c2544..9af7e9e1793 100644
--- a/locales/bg-BG/setting.json
+++ b/locales/bg-BG/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "Име",
"settingAgent.prompt.desc": "Определя кой е този агент, за какво е отговорен и как работи и реагира. Той служи като основна инструкция във всяка комуникация.",
"settingAgent.prompt.editorPlaceholder": "Въведете основни инструкции, натиснете / за да отворите менюто Slash",
+ "settingAgent.prompt.mode.source": "Markdown източник",
+ "settingAgent.prompt.mode.visual": "Визуален редактор",
"settingAgent.prompt.placeholder": "Въведете настройки на агента, натиснете / за отваряне на менюто с команди",
"settingAgent.prompt.title": "Профил на агента",
"settingAgent.runtimeConfig.title": "Модел и инструменти",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "Отмяна на тази покана?",
"workspace.members.pending.revokeFailed": "Неуспешно отмяна на поканата",
"workspace.members.seatChange.memberJoinBlocked": "Текущите членове са достигнали планирания лимит на местата, така че нови платени членове може да не могат да се присъединят към това работно пространство",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} място",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} места",
"workspace.members.subtitle": "Управление на членове и покани за работното пространство",
"workspace.members.tabs.members": "Членове на екипа",
"workspace.members.tabs.pending": "Чакащи покани",
"workspace.members.title": "Членове",
+ "workspace.members.totalCount_one": "{{total}} член",
+ "workspace.members.totalCount_other": "{{total}} членове",
"workspace.name.placeholder": "Име на работното пространство",
"workspace.name.title": "Име",
"workspace.newWorkspace": "Ново работно пространство",
diff --git a/locales/de-DE/agent.json b/locales/de-DE/agent.json
index 1a2c1d2699f..d2a5b4a4ffc 100644
--- a/locales/de-DE/agent.json
+++ b/locales/de-DE/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "Fügen Sie hier Ihr App-Geheimnis ein",
"channel.applicationId": "Anwendungs-ID / Bot-Benutzername",
"channel.applicationIdHint": "Eindeutige Kennung für Ihre Bot-Anwendung.",
+ "channel.applicationIdInvalid.discord": "Die Anwendungs-ID muss die 17–20-stellige ID auf der Seite Allgemeine Informationen Ihrer Discord-App sein.",
"channel.applicationIdPlaceholder": "z. B. 1234567890",
"channel.botToken": "Bot-Token / API-Schlüssel",
"channel.botTokenEncryptedHint": "Token wird verschlüsselt und sicher gespeichert.",
"channel.botTokenHowToGet": "Wie erhalten?",
+ "channel.botTokenInvalid.discord": "Das sieht nicht wie ein Discord-Bot-Token aus. Setzen Sie es zurück und kopieren Sie es aus dem Bot-Tab Ihrer Discord-App — es besteht aus drei durch Punkte getrennten Segmenten.",
"channel.botTokenPlaceholderExisting": "Token ist aus Sicherheitsgründen verborgen",
"channel.botTokenPlaceholderNew": "Fügen Sie hier Ihr Bot-Token ein",
"channel.charLimit": "Zeichenlimit",
@@ -201,6 +203,7 @@
"channel.platforms": "Plattformen",
"channel.publicKey": "Öffentlicher Schlüssel",
"channel.publicKeyHint": "Optional. Wird verwendet, um Interaktionsanfragen von Discord zu überprüfen.",
+ "channel.publicKeyInvalid": "Der öffentliche Schlüssel muss eine 64-stellige Hexadezimalzeichenfolge sein. Kopieren Sie ihn von der Seite Allgemeine Informationen Ihrer Discord-App — nicht aus der OAuth-URL und nicht aus einem API-Schlüssel.",
"channel.publicKeyPlaceholder": "Erforderlich für Interaktionsüberprüfung",
"channel.qq.appIdHint": "Ihre QQ-Bot-App-ID von der QQ Open Platform",
"channel.qq.description": "Verbinden Sie diesen Assistenten mit QQ für Gruppenchats und Direktnachrichten.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "Bot-Kennung, die nach der QR-Code-Autorisierung zugewiesen wurde.",
"channel.wechatConnectedInfo": "Verbundenes WeChat-Konto",
"channel.wechatGenerateQrCode": "QR-Code generieren",
- "channel.wechatIdleNotice": "Wenn 7 Tage lang keine Nachrichten von Nutzern eingehen, wird diese Verbindung automatisch pausiert. Zum Fortsetzen klicken Sie auf „Per QR-Code erneut verbinden“.",
"channel.wechatManagedCredentials": "Dieser Kanal ist bereits über die QR-Code-Autorisierung verbunden. Anmeldedaten werden automatisch verwaltet.",
"channel.wechatQrExpired": "QR-Code abgelaufen. Bitte aktualisieren Sie, um einen neuen zu erhalten.",
"channel.wechatQrLoadFailed": "Der QR-Code konnte nicht geladen werden. Bitte versuche es erneut.",
diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.json
index abe5f35ada9..5ef469c6b3f 100644
--- a/locales/de-DE/setting.json
+++ b/locales/de-DE/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "Name",
"settingAgent.prompt.desc": "Definiert, wer dieser Agent ist, wofür er verantwortlich ist und wie er arbeitet und reagiert. Es dient als zentrale Anweisung in jedem Gespräch.",
"settingAgent.prompt.editorPlaceholder": "Geben Sie zentrale Anweisungen ein, drücken Sie /, um das Slash-Menü zu öffnen",
+ "settingAgent.prompt.mode.source": "Markdown-Quelle",
+ "settingAgent.prompt.mode.visual": "Visueller Editor",
"settingAgent.prompt.placeholder": "Agenteneinstellungen eingeben, / drücken, um das Befehlsmenü zu öffnen",
"settingAgent.prompt.title": "Agentenprofil",
"settingAgent.runtimeConfig.title": "Modell & Werkzeuge",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "Diese Einladung widerrufen?",
"workspace.members.pending.revokeFailed": "Einladung konnte nicht widerrufen werden",
"workspace.members.seatChange.memberJoinBlocked": "Die aktuellen Mitglieder haben die geplante Platzgrenze erreicht, sodass neue zahlungspflichtige Mitglieder diesem Arbeitsbereich möglicherweise nicht beitreten können.",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} Platz",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} Plätze",
"workspace.members.subtitle": "Verwalten Sie Mitglieder und Einladungen des Arbeitsbereichs",
"workspace.members.tabs.members": "Teammitglieder",
"workspace.members.tabs.pending": "Ausstehende Einladungen",
"workspace.members.title": "Mitglieder",
+ "workspace.members.totalCount_one": "{{total}} Mitglied",
+ "workspace.members.totalCount_other": "{{total}} Mitglieder",
"workspace.name.placeholder": "Name des Arbeitsbereichs",
"workspace.name.title": "Name",
"workspace.newWorkspace": "Neuer Arbeitsbereich",
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 46bc5a3ec9a..471c4dca600 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "Paste your app secret here",
"channel.applicationId": "Application ID / Bot Username",
"channel.applicationIdHint": "Unique identifier for your bot application.",
+ "channel.applicationIdInvalid.discord": "Application ID must be the 17–20 digit ID on your Discord app's General Information page.",
"channel.applicationIdPlaceholder": "e.g. 1234567890",
"channel.botToken": "Bot Token / API Key",
"channel.botTokenEncryptedHint": "Token will be encrypted and stored securely.",
"channel.botTokenHowToGet": "How to get?",
+ "channel.botTokenInvalid.discord": "This does not look like a Discord bot token. Reset and copy it from the Bot tab of your Discord app — it is three segments separated by dots.",
"channel.botTokenPlaceholderExisting": "Token is hidden for security",
"channel.botTokenPlaceholderNew": "Paste your bot token here",
"channel.charLimit": "Character Limit",
@@ -200,8 +202,9 @@
"channel.platform.whatsapp.description": "Meet customers in familiar mobile chats for support and follow-ups—ideal for customer-facing teams.",
"channel.platforms": "Platforms",
"channel.publicKey": "Public Key",
- "channel.publicKeyHint": "Optional. Used to verify interaction requests from Discord.",
- "channel.publicKeyPlaceholder": "Required for interaction verification",
+ "channel.publicKeyHint": "Used to verify interaction requests from Discord. A 64-character hex string on your app's General Information page.",
+ "channel.publicKeyInvalid": "Public Key must be a 64-character hex string. Copy it from the Discord app's General Information page — not the OAuth URL, and not an API key.",
+ "channel.publicKeyPlaceholder": "64-character hex string",
"channel.qq.appIdHint": "Your QQ Bot App ID from QQ Open Platform",
"channel.qq.description": "Connect this agent to QQ for group chats and direct messages.",
"channel.qq.webhookMigrationDesc": "WebSocket mode provides real-time event delivery and automatic reconnection without needing a callback URL. To migrate, create a new bot on QQ Open Platform without configuring a callback URL, then switch the Connection Mode to WebSocket in Advanced Settings.",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 70d4b920734..44f78c01a93 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -2377,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "Revoke this invitation?",
"workspace.members.pending.revokeFailed": "Failed to revoke invitation",
"workspace.members.seatChange.memberJoinBlocked": "Current members have reached the scheduled seat limit, so new paid members may not be able to join this workspace",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} seat",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} seats",
"workspace.members.subtitle": "Manage workspace members and invitations",
"workspace.members.tabs.members": "Team Members",
"workspace.members.tabs.pending": "Pending Invitations",
"workspace.members.title": "Members",
+ "workspace.members.totalCount_one": "{{total}} member",
+ "workspace.members.totalCount_other": "{{total}} members",
"workspace.name.placeholder": "Workspace name",
"workspace.name.title": "Name",
"workspace.newWorkspace": "New Workspace",
diff --git a/locales/es-ES/agent.json b/locales/es-ES/agent.json
index 2fb3a61831b..d9f2535def8 100644
--- a/locales/es-ES/agent.json
+++ b/locales/es-ES/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "Pega tu secreto de la aplicación aquí",
"channel.applicationId": "ID de la Aplicación / Nombre de Usuario del Bot",
"channel.applicationIdHint": "Identificador único para tu aplicación de bot.",
+ "channel.applicationIdInvalid.discord": "El ID de la aplicación debe ser el número de 17–20 dígitos en la página de Información General de tu aplicación de Discord.",
"channel.applicationIdPlaceholder": "p. ej. 1234567890",
"channel.botToken": "Token del Bot / Clave API",
"channel.botTokenEncryptedHint": "El token será encriptado y almacenado de forma segura.",
"channel.botTokenHowToGet": "¿Cómo obtenerlo?",
+ "channel.botTokenInvalid.discord": "Esto no parece un token de bot de Discord. Restablece y cópialo desde la pestaña Bot de tu aplicación de Discord — son tres segmentos separados por puntos.",
"channel.botTokenPlaceholderExisting": "El token está oculto por seguridad",
"channel.botTokenPlaceholderNew": "Pega tu token del bot aquí",
"channel.charLimit": "Límite de caracteres",
@@ -201,6 +203,7 @@
"channel.platforms": "Plataformas",
"channel.publicKey": "Clave Pública",
"channel.publicKeyHint": "Opcional. Usada para verificar solicitudes de interacción desde Discord.",
+ "channel.publicKeyInvalid": "La clave pública debe ser una cadena hexadecimal de 64 caracteres. Cópiala desde la página de Información General de la aplicación de Discord — no desde la URL de OAuth ni desde una clave API.",
"channel.publicKeyPlaceholder": "Requerida para la verificación de interacciones",
"channel.qq.appIdHint": "Tu ID de aplicación de bot de QQ desde la Plataforma Abierta de QQ",
"channel.qq.description": "Conecta este asistente a QQ para chats grupales y mensajes directos.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "Identificador del bot asignado tras la autorización mediante código QR.",
"channel.wechatConnectedInfo": "Cuenta de WeChat Conectada",
"channel.wechatGenerateQrCode": "Generar código QR",
- "channel.wechatIdleNotice": "Si ningún usuario envía mensajes durante más de 7 días, esta conexión se pausará automáticamente. Para reanudarla, haz clic en \"Vincular de nuevo mediante código QR\".",
"channel.wechatManagedCredentials": "Este canal ya está conectado mediante autorización con código QR. Las credenciales se gestionan automáticamente.",
"channel.wechatQrExpired": "El código QR ha expirado. Por favor, actualiza para obtener uno nuevo.",
"channel.wechatQrLoadFailed": "No se pudo cargar el código QR. Por favor, inténtalo de nuevo.",
diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.json
index 5d9e5a675e7..4587a346ff9 100644
--- a/locales/es-ES/setting.json
+++ b/locales/es-ES/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "Nombre",
"settingAgent.prompt.desc": "Define quién es este agente, de qué es responsable y cómo funciona y responde. Sirve como una instrucción central en cada conversación.",
"settingAgent.prompt.editorPlaceholder": "Introduce las instrucciones principales, presiona / para abrir el Menú Slash",
+ "settingAgent.prompt.mode.source": "Fuente Markdown",
+ "settingAgent.prompt.mode.visual": "Editor visual",
"settingAgent.prompt.placeholder": "Introduce la configuración del agente, presiona / para abrir el menú de comandos",
"settingAgent.prompt.title": "Perfil del Agente",
"settingAgent.runtimeConfig.title": "Modelo y Herramientas",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "¿Revocar esta invitación?",
"workspace.members.pending.revokeFailed": "No se pudo revocar la invitación",
"workspace.members.seatChange.memberJoinBlocked": "Los miembros actuales han alcanzado el límite de asientos programados, por lo que nuevos miembros de pago pueden no poder unirse a este espacio de trabajo",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} asiento",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} asientos",
"workspace.members.subtitle": "Gestiona miembros e invitaciones del espacio de trabajo",
"workspace.members.tabs.members": "Miembros del equipo",
"workspace.members.tabs.pending": "Invitaciones pendientes",
"workspace.members.title": "Miembros",
+ "workspace.members.totalCount_one": "{{total}} miembro",
+ "workspace.members.totalCount_other": "{{total}} miembros",
"workspace.name.placeholder": "Nombre del espacio de trabajo",
"workspace.name.title": "Nombre",
"workspace.newWorkspace": "Nuevo espacio de trabajo",
diff --git a/locales/fa-IR/agent.json b/locales/fa-IR/agent.json
index e99386575a9..3acf703c9e6 100644
--- a/locales/fa-IR/agent.json
+++ b/locales/fa-IR/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "رمز برنامه خود را اینجا وارد کنید",
"channel.applicationId": "شناسه برنامه / نام کاربری ربات",
"channel.applicationIdHint": "شناسه منحصر به فرد برای برنامه ربات شما.",
+ "channel.applicationIdInvalid.discord": "شناسه برنامه باید یک شناسه ۱۷ تا ۲۰ رقمی در صفحه اطلاعات عمومی برنامه Discord شما باشد.",
"channel.applicationIdPlaceholder": "مثال: 1234567890",
"channel.botToken": "توکن ربات / کلید API",
"channel.botTokenEncryptedHint": "توکن رمزگذاری شده و به صورت امن ذخیره خواهد شد.",
"channel.botTokenHowToGet": "چگونه دریافت کنیم؟",
+ "channel.botTokenInvalid.discord": "این به نظر نمی‌رسد یک توکن ربات Discord باشد. آن را بازنشانی کرده و از تب ربات برنامه Discord خود کپی کنید — این توکن شامل سه بخش جدا شده با نقطه است.",
"channel.botTokenPlaceholderExisting": "توکن به دلایل امنیتی مخفی است",
"channel.botTokenPlaceholderNew": "توکن ربات خود را اینجا وارد کنید",
"channel.charLimit": "محدودیت کاراکتر",
@@ -201,6 +203,7 @@
"channel.platforms": "پلتفرم‌ها",
"channel.publicKey": "کلید عمومی",
"channel.publicKeyHint": "اختیاری. برای تأیید درخواست‌های تعامل از Discord استفاده می‌شود.",
+ "channel.publicKeyInvalid": "کلید عمومی باید یک رشته هگزادسیمال ۶۴ کاراکتری باشد. آن را از صفحه اطلاعات عمومی برنامه Discord کپی کنید — نه از URL OAuth و نه از کلید API.",
"channel.publicKeyPlaceholder": "برای تأیید تعامل مورد نیاز است",
"channel.qq.appIdHint": "شناسه برنامه ربات QQ شما از پلتفرم باز QQ",
"channel.qq.description": "این دستیار را به QQ متصل کنید برای چت‌های گروهی و پیام‌های مستقیم.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "شناسه ربات که پس از تأیید کد QR اختصاص داده شده است.",
"channel.wechatConnectedInfo": "حساب متصل شده وی‌چت",
"channel.wechatGenerateQrCode": "ایجاد کد QR",
- "channel.wechatIdleNotice": "اگر بیش از ۷ روز هیچ کاربری پیامی ارسال نکند، این اتصال به‌صورت خودکار متوقف می‌شود. برای فعال‌سازی دوباره، روی «اتصال مجدد با کد QR» کلیک کنید.",
"channel.wechatManagedCredentials": "این کانال از طریق تأیید کد QR متصل شده است. اطلاعات ورود به صورت خودکار مدیریت می‌شوند.",
"channel.wechatQrExpired": "کد QR منقضی شده است. لطفاً برای دریافت کد جدید آن را تازه کنید.",
"channel.wechatQrLoadFailed": "بارگذاری کد QR ناموفق بود. لطفاً دوباره تلاش کنید.",
diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.json
index 76ea2f39084..49092d45e23 100644
--- a/locales/fa-IR/setting.json
+++ b/locales/fa-IR/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "نام",
"settingAgent.prompt.desc": "تعریف می‌کند که این عامل کیست، چه مسئولیتی دارد و چگونه کار می‌کند و پاسخ می‌دهد. این به عنوان یک دستورالعمل اصلی در هر مکالمه عمل می‌کند.",
"settingAgent.prompt.editorPlaceholder": "دستورالعمل‌های اصلی را وارد کنید، / را فشار دهید تا منوی اسلش باز شود",
+ "settingAgent.prompt.mode.source": "منبع Markdown",
+ "settingAgent.prompt.mode.visual": "ویرایشگر بصری",
"settingAgent.prompt.placeholder": "تنظیمات عامل را وارد کنید، برای باز کردن منوی دستورات / را فشار دهید",
"settingAgent.prompt.title": "پروفایل عامل",
"settingAgent.runtimeConfig.title": "مدل و ابزارها",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "این دعوت‌نامه لغو شود؟",
"workspace.members.pending.revokeFailed": "لغو دعوت‌نامه ناموفق بود",
"workspace.members.seatChange.memberJoinBlocked": "اعضای فعلی به حد مجاز صندلی‌های زمان‌بندی‌شده رسیده‌اند، بنابراین ممکن است اعضای جدید پولی نتوانند به این فضای کاری بپیوندند.",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} صندلی",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} صندلی‌ها",
"workspace.members.subtitle": "مدیریت اعضای فضای کاری و دعوت‌نامه‌ها",
"workspace.members.tabs.members": "اعضای تیم",
"workspace.members.tabs.pending": "دعوت‌نامه‌های در انتظار",
"workspace.members.title": "اعضا",
+ "workspace.members.totalCount_one": "{{total}} عضو",
+ "workspace.members.totalCount_other": "{{total}} اعضا",
"workspace.name.placeholder": "نام فضای کاری",
"workspace.name.title": "نام",
"workspace.newWorkspace": "فضای کاری جدید",
diff --git a/locales/fr-FR/agent.json b/locales/fr-FR/agent.json
index 4fafcc93af2..4817cb1bf1f 100644
--- a/locales/fr-FR/agent.json
+++ b/locales/fr-FR/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "Collez votre secret d'application ici",
"channel.applicationId": "ID de l'application / Nom d'utilisateur du bot",
"channel.applicationIdHint": "Identifiant unique pour votre application bot.",
+ "channel.applicationIdInvalid.discord": "L'ID de l'application doit être un identifiant de 17 à 20 chiffres figurant sur la page d'informations générales de votre application Discord.",
"channel.applicationIdPlaceholder": "ex. 1234567890",
"channel.botToken": "Jeton du bot / Clé API",
"channel.botTokenEncryptedHint": "Le jeton sera crypté et stocké en toute sécurité.",
"channel.botTokenHowToGet": "Comment l'obtenir ?",
+ "channel.botTokenInvalid.discord": "Cela ne ressemble pas à un jeton de bot Discord. Réinitialisez-le et copiez-le depuis l'onglet Bot de votre application Discord — il se compose de trois segments séparés par des points.",
"channel.botTokenPlaceholderExisting": "Le jeton est masqué pour des raisons de sécurité",
"channel.botTokenPlaceholderNew": "Collez votre jeton de bot ici",
"channel.charLimit": "Limite de caractères",
@@ -201,6 +203,7 @@
"channel.platforms": "Plateformes",
"channel.publicKey": "Clé publique",
"channel.publicKeyHint": "Optionnel. Utilisé pour vérifier les requêtes d'interaction provenant de Discord.",
+ "channel.publicKeyInvalid": "La clé publique doit être une chaîne hexadécimale de 64 caractères. Copiez-la depuis la page d'informations générales de l'application Discord — pas l'URL OAuth, ni une clé API.",
"channel.publicKeyPlaceholder": "Requis pour la vérification des interactions",
"channel.qq.appIdHint": "Votre ID d'application Bot QQ de la plateforme QQ Open",
"channel.qq.description": "Connectez cet assistant à QQ pour des discussions de groupe et des messages directs.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "Identifiant du bot attribué après l'autorisation par code QR.",
"channel.wechatConnectedInfo": "Compte WeChat Connecté",
"channel.wechatGenerateQrCode": "Générer un code QR",
- "channel.wechatIdleNotice": "Si aucun utilisateur n’envoie de message pendant plus de 7 jours, cette connexion sera automatiquement mise en pause. Pour la reprendre, cliquez sur « Reconnecter via code QR ».",
"channel.wechatManagedCredentials": "Ce canal est déjà connecté via une autorisation par code QR. Les identifiants sont gérés automatiquement.",
"channel.wechatQrExpired": "Le code QR a expiré. Veuillez actualiser pour en obtenir un nouveau.",
"channel.wechatQrLoadFailed": "Échec du chargement du code QR. Veuillez réessayer.",
diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.json
index 02c0b6312fc..7aaf11a2dc9 100644
--- a/locales/fr-FR/setting.json
+++ b/locales/fr-FR/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "Nom",
"settingAgent.prompt.desc": "Définit qui est cet agent, ce dont il est responsable, comment il fonctionne et répond. Cela sert d'instruction principale dans chaque conversation.",
"settingAgent.prompt.editorPlaceholder": "Entrez les instructions principales, appuyez sur / pour ouvrir le menu Slash",
+ "settingAgent.prompt.mode.source": "Source Markdown",
+ "settingAgent.prompt.mode.visual": "Éditeur visuel",
"settingAgent.prompt.placeholder": "Saisissez les paramètres de l’agent, appuyez sur / pour ouvrir le menu de commandes",
"settingAgent.prompt.title": "Profil de l’agent",
"settingAgent.runtimeConfig.title": "Modèle & Outils",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "Révoquer cette invitation ?",
"workspace.members.pending.revokeFailed": "Échec de la révocation de l'invitation",
"workspace.members.seatChange.memberJoinBlocked": "Les membres actuels ont atteint la limite de sièges prévue, de sorte que de nouveaux membres payants pourraient ne pas pouvoir rejoindre cet espace de travail",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} place",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} places",
"workspace.members.subtitle": "Gérez les membres et les invitations de l'espace de travail",
"workspace.members.tabs.members": "Membres de l'équipe",
"workspace.members.tabs.pending": "Invitations en attente",
"workspace.members.title": "Membres",
+ "workspace.members.totalCount_one": "{{total}} membre",
+ "workspace.members.totalCount_other": "{{total}} membres",
"workspace.name.placeholder": "Nom de l'espace de travail",
"workspace.name.title": "Nom",
"workspace.newWorkspace": "Nouvel espace de travail",
diff --git a/locales/it-IT/agent.json b/locales/it-IT/agent.json
index 7c02c331583..c239bc11cc0 100644
--- a/locales/it-IT/agent.json
+++ b/locales/it-IT/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "Incolla qui il segreto della tua app",
"channel.applicationId": "ID Applicazione / Nome Utente Bot",
"channel.applicationIdHint": "Identificativo univoco per la tua applicazione bot.",
+ "channel.applicationIdInvalid.discord": "L'ID dell'applicazione deve essere l'ID di 17–20 cifre presente nella pagina delle Informazioni Generali della tua app Discord.",
"channel.applicationIdPlaceholder": "es. 1234567890",
"channel.botToken": "Token Bot / Chiave API",
"channel.botTokenEncryptedHint": "Il token sarà criptato e memorizzato in modo sicuro.",
"channel.botTokenHowToGet": "Come ottenerlo?",
+ "channel.botTokenInvalid.discord": "Questo non sembra essere un token bot di Discord. Resettalo e copialo dalla scheda Bot della tua app Discord — è composto da tre segmenti separati da punti.",
"channel.botTokenPlaceholderExisting": "Il token è nascosto per motivi di sicurezza",
"channel.botTokenPlaceholderNew": "Incolla qui il token del tuo bot",
"channel.charLimit": "Limite di caratteri",
@@ -201,6 +203,7 @@
"channel.platforms": "Piattaforme",
"channel.publicKey": "Chiave Pubblica",
"channel.publicKeyHint": "Opzionale. Utilizzata per verificare le richieste di interazione da Discord.",
+ "channel.publicKeyInvalid": "La chiave pubblica deve essere una stringa esadecimale di 64 caratteri. Copiala dalla pagina delle Informazioni Generali dell'app Discord — non dall'URL OAuth e non da una chiave API.",
"channel.publicKeyPlaceholder": "Richiesta per la verifica delle interazioni",
"channel.qq.appIdHint": "Il tuo ID App Bot QQ dalla Piattaforma Aperta QQ",
"channel.qq.description": "Collega questo assistente a QQ per chat di gruppo e messaggi diretti.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "Identificativo del bot assegnato dopo l'autorizzazione tramite codice QR.",
"channel.wechatConnectedInfo": "Account WeChat Connesso",
"channel.wechatGenerateQrCode": "Genera codice QR",
- "channel.wechatIdleNotice": "Se nessun utente invia messaggi per più di 7 giorni, questa connessione verrà messa in pausa automaticamente. Per riprendere, fai clic su \"Ricollega tramite codice QR\".",
"channel.wechatManagedCredentials": "Questo canale è già connesso tramite autorizzazione con codice QR. Le credenziali sono gestite automaticamente.",
"channel.wechatQrExpired": "Codice QR scaduto. Aggiorna per ottenerne uno nuovo.",
"channel.wechatQrLoadFailed": "Caricamento del codice QR non riuscito. Riprova.",
diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.json
index a7fcfcfd7f0..86a817b6553 100644
--- a/locales/it-IT/setting.json
+++ b/locales/it-IT/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "Nome",
"settingAgent.prompt.desc": "Definisce chi è questo agente, di cosa è responsabile, come funziona e risponde. Serve come istruzione principale in ogni conversazione.",
"settingAgent.prompt.editorPlaceholder": "Inserisci istruzioni principali, premi / per aprire il menu Slash",
+ "settingAgent.prompt.mode.source": "Sorgente Markdown",
+ "settingAgent.prompt.mode.visual": "Editor visivo",
"settingAgent.prompt.placeholder": "Inserisci le impostazioni dell'agente, premi / per aprire il menu comandi",
"settingAgent.prompt.title": "Profilo Agente",
"settingAgent.runtimeConfig.title": "Modello e Strumenti",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "Revocare questo invito?",
"workspace.members.pending.revokeFailed": "Impossibile revocare l'invito",
"workspace.members.seatChange.memberJoinBlocked": "I membri attuali hanno raggiunto il limite di posti programmati, quindi nuovi membri a pagamento potrebbero non essere in grado di unirsi a questo workspace",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} posto",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} posti",
"workspace.members.subtitle": "Gestisci i membri e gli inviti del workspace",
"workspace.members.tabs.members": "Membri del team",
"workspace.members.tabs.pending": "Inviti in sospeso",
"workspace.members.title": "Membri",
+ "workspace.members.totalCount_one": "{{total}} membro",
+ "workspace.members.totalCount_other": "{{total}} membri",
"workspace.name.placeholder": "Nome del workspace",
"workspace.name.title": "Nome",
"workspace.newWorkspace": "Nuovo workspace",
diff --git a/locales/ja-JP/agent.json b/locales/ja-JP/agent.json
index 5bb3cbaf614..044602ddeeb 100644
--- a/locales/ja-JP/agent.json
+++ b/locales/ja-JP/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "ここにアプリシークレットを貼り付けてください",
"channel.applicationId": "アプリケーションID / ボットユーザー名",
"channel.applicationIdHint": "ボットアプリケーションの一意の識別子。",
+ "channel.applicationIdInvalid.discord": "アプリケーションIDは、Discordアプリの一般情報ページにある17~20桁のIDである必要があります。",
"channel.applicationIdPlaceholder": "例: 1234567890",
"channel.botToken": "ボットトークン / APIキー",
"channel.botTokenEncryptedHint": "トークンは暗号化され、安全に保存されます。",
"channel.botTokenHowToGet": "取得方法は?",
+ "channel.botTokenInvalid.discord": "これはDiscordボットトークンの形式ではありません。ボットタブからリセットしてコピーしてください。トークンはドットで区切られた3つのセグメントで構成されています。",
"channel.botTokenPlaceholderExisting": "セキュリティのためトークンは非表示です",
"channel.botTokenPlaceholderNew": "ここにボットトークンを貼り付けてください",
"channel.charLimit": "文字数制限",
@@ -201,6 +203,7 @@
"channel.platforms": "プラットフォーム",
"channel.publicKey": "公開鍵",
"channel.publicKeyHint": "任意。Discordからのインタラクションリクエストを検証するために使用されます。",
+ "channel.publicKeyInvalid": "公開鍵は64文字の16進数文字列である必要があります。Discordアプリの一般情報ページからコピーしてください。OAuth URLやAPIキーではありません。",
"channel.publicKeyPlaceholder": "インタラクション検証に必要",
"channel.qq.appIdHint": "QQオープンプラットフォームから取得したQQボットのアプリID",
"channel.qq.description": "このアシスタントをQQに接続して、グループチャットやダイレクトメッセージを利用しましょう。",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "QRコード認証後に割り当てられるボット識別子。",
"channel.wechatConnectedInfo": "接続されたWeChatアカウント",
"channel.wechatGenerateQrCode": "QRコードを生成",
- "channel.wechatIdleNotice": "7日以上ユーザーからのメッセージがない場合、この接続は自動的に一時停止されます。再開するには「QRコードで再連携」をクリックしてください。",
"channel.wechatManagedCredentials": "このチャンネルはすでにQRコード認証を通じて接続されています。資格情報は自動的に管理されます。",
"channel.wechatQrExpired": "QRコードの有効期限が切れました。新しいコードを取得するには更新してください。",
"channel.wechatQrLoadFailed": "QRコードの読み込みに失敗しました。再試行してください。",
diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.json
index 589f8a3d56f..49666d28dd4 100644
--- a/locales/ja-JP/setting.json
+++ b/locales/ja-JP/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "名前",
"settingAgent.prompt.desc": "このエージェントが誰であるか、何を担当しているか、どのように動作し応答するかを定義します。これは、すべての会話における基本的な指示として機能します。",
"settingAgent.prompt.editorPlaceholder": "基本指示を入力してください。/ を押してスラッシュメニューを開きます。",
+ "settingAgent.prompt.mode.source": "Markdownソース",
+ "settingAgent.prompt.mode.visual": "ビジュアルエディター",
"settingAgent.prompt.placeholder": "アシスタントの設定を入力し、「/」でコマンドメニューを開く",
"settingAgent.prompt.title": "アシスタント設定",
"settingAgent.runtimeConfig.title": "モデルとツール",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "この招待を取り消しますか?",
"workspace.members.pending.revokeFailed": "招待の取り消しに失敗しました。",
"workspace.members.seatChange.memberJoinBlocked": "現在のメンバーが予定されたシート制限に達しているため、新しい有料メンバーはこのワークスペースに参加できない可能性があります",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} 席",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} 席",
"workspace.members.subtitle": "ワークスペースメンバーと招待を管理",
"workspace.members.tabs.members": "チームメンバー",
"workspace.members.tabs.pending": "保留中の招待",
"workspace.members.title": "メンバー",
+ "workspace.members.totalCount_one": "{{total}} 人",
+ "workspace.members.totalCount_other": "{{total}} 人",
"workspace.name.placeholder": "ワークスペース名",
"workspace.name.title": "名前",
"workspace.newWorkspace": "新しいワークスペース",
diff --git a/locales/ko-KR/agent.json b/locales/ko-KR/agent.json
index 0aacdd4d3fe..e0a7a58438e 100644
--- a/locales/ko-KR/agent.json
+++ b/locales/ko-KR/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "여기에 앱 비밀키를 붙여넣으세요",
"channel.applicationId": "애플리케이션 ID / 봇 사용자 이름",
"channel.applicationIdHint": "봇 애플리케이션의 고유 식별자입니다.",
+ "channel.applicationIdInvalid.discord": "애플리케이션 ID는 Discord 앱의 일반 정보 페이지에 있는 17–20자리 ID여야 합니다.",
"channel.applicationIdPlaceholder": "예: 1234567890",
"channel.botToken": "봇 토큰 / API 키",
"channel.botTokenEncryptedHint": "토큰은 암호화되어 안전하게 저장됩니다.",
"channel.botTokenHowToGet": "어떻게 얻나요?",
+ "channel.botTokenInvalid.discord": "이것은 Discord 봇 토큰처럼 보이지 않습니다. 봇 탭에서 재설정하고 복사하세요 — 세 부분이 점으로 구분되어 있습니다.",
"channel.botTokenPlaceholderExisting": "보안을 위해 토큰이 숨겨져 있습니다",
"channel.botTokenPlaceholderNew": "여기에 봇 토큰을 붙여넣으세요",
"channel.charLimit": "문자 제한",
@@ -201,6 +203,7 @@
"channel.platforms": "플랫폼",
"channel.publicKey": "공개 키",
"channel.publicKeyHint": "선택 사항. Discord의 상호작용 요청을 검증하는 데 사용됩니다.",
+ "channel.publicKeyInvalid": "공개 키는 64자 길이의 16진수 문자열이어야 합니다. Discord 앱의 일반 정보 페이지에서 복사하세요 — OAuth URL이나 API 키가 아닙니다.",
"channel.publicKeyPlaceholder": "상호작용 검증에 필요",
"channel.qq.appIdHint": "QQ 오픈 플랫폼에서 제공된 QQ 봇 앱 ID를 입력하세요.",
"channel.qq.description": "이 어시스턴트를 QQ에 연결하여 그룹 채팅 및 직접 메시지를 이용하세요.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "QR 코드 인증 후 할당된 봇 식별자입니다.",
"channel.wechatConnectedInfo": "연결된 WeChat 계정",
"channel.wechatGenerateQrCode": "QR 코드 생성",
- "channel.wechatIdleNotice": "7일 이상 사용자가 메시지를 보내지 않으면 이 연결이 자동으로 일시 중지됩니다. 다시 사용하려면 \"QR 코드로 다시 연결\"을 클릭하세요.",
"channel.wechatManagedCredentials": "이 채널은 이미 QR 코드 인증을 통해 연결되었습니다. 자격 증명은 자동으로 관리됩니다.",
"channel.wechatQrExpired": "QR 코드가 만료되었습니다. 새로 고침하여 새 코드를 받으세요.",
"channel.wechatQrLoadFailed": "QR 코드를 로드하지 못했습니다. 다시 시도해 주세요.",
diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.json
index fe859376b54..e93fa3784f4 100644
--- a/locales/ko-KR/setting.json
+++ b/locales/ko-KR/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "이름",
"settingAgent.prompt.desc": "이 에이전트가 누구인지, 무엇을 책임지는지, 어떻게 작동하고 응답하는지를 정의합니다. 모든 대화에서 핵심 지침으로 작용합니다.",
"settingAgent.prompt.editorPlaceholder": "핵심 지침을 입력하세요, /를 눌러 슬래시 메뉴를 여세요",
+ "settingAgent.prompt.mode.source": "마크다운 소스",
+ "settingAgent.prompt.mode.visual": "비주얼 에디터",
"settingAgent.prompt.placeholder": "도우미 설정을 입력하세요. / 키를 눌러 명령 메뉴를 여세요",
"settingAgent.prompt.title": "도우미 설정",
"settingAgent.runtimeConfig.title": "모델 및 도구",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "이 초대를 취소하시겠습니까?",
"workspace.members.pending.revokeFailed": "초대 취소에 실패했습니다.",
"workspace.members.seatChange.memberJoinBlocked": "현재 멤버가 예약된 좌석 한도에 도달하여 새로운 유료 멤버가 이 워크스페이스에 참여할 수 없습니다.",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} 좌석",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} 좌석들",
"workspace.members.subtitle": "워크스페이스 멤버 및 초대 관리",
"workspace.members.tabs.members": "팀 멤버",
"workspace.members.tabs.pending": "대기 중인 초대",
"workspace.members.title": "멤버",
+ "workspace.members.totalCount_one": "{{total}} 명의 멤버",
+ "workspace.members.totalCount_other": "{{total}} 명의 멤버들",
"workspace.name.placeholder": "워크스페이스 이름",
"workspace.name.title": "이름",
"workspace.newWorkspace": "새 워크스페이스",
diff --git a/locales/nl-NL/agent.json b/locales/nl-NL/agent.json
index d6927238c06..898c8107446 100644
--- a/locales/nl-NL/agent.json
+++ b/locales/nl-NL/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "Plak hier uw appgeheim",
"channel.applicationId": "Applicatie-ID / Botgebruikersnaam",
"channel.applicationIdHint": "Unieke identificatie voor uw botapplicatie.",
+ "channel.applicationIdInvalid.discord": "Applicatie-ID moet de 17–20-cijferige ID zijn op de Algemene Informatiepagina van je Discord-app.",
"channel.applicationIdPlaceholder": "Bijv. 1234567890",
"channel.botToken": "Bot-token / API-sleutel",
"channel.botTokenEncryptedHint": "Token wordt versleuteld en veilig opgeslagen.",
"channel.botTokenHowToGet": "Hoe verkrijg ik dit?",
+ "channel.botTokenInvalid.discord": "Dit lijkt niet op een Discord-bot token. Reset en kopieer het vanuit het Bot-tabblad van je Discord-app — het bestaat uit drie segmenten gescheiden door punten.",
"channel.botTokenPlaceholderExisting": "Token is verborgen om veiligheidsredenen",
"channel.botTokenPlaceholderNew": "Plak hier uw bot-token",
"channel.charLimit": "Tekenlimiet",
@@ -201,6 +203,7 @@
"channel.platforms": "Platformen",
"channel.publicKey": "Publieke sleutel",
"channel.publicKeyHint": "Optioneel. Gebruikt om interactieverzoeken van Discord te verifiëren.",
+ "channel.publicKeyInvalid": "Publieke sleutel moet een hexadecimale tekenreeks van 64 tekens zijn. Kopieer het van de Algemene Informatiepagina van de Discord-app — niet de OAuth-URL en niet een API-sleutel.",
"channel.publicKeyPlaceholder": "Vereist voor interactieverificatie",
"channel.qq.appIdHint": "Uw QQ Bot App ID van het QQ Open Platform",
"channel.qq.description": "Verbind deze assistent met QQ voor groepschats en directe berichten.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "Bot-identificatie toegewezen na QR-code autorisatie.",
"channel.wechatConnectedInfo": "Verbonden WeChat-account",
"channel.wechatGenerateQrCode": "QR-code genereren",
- "channel.wechatIdleNotice": "Als er meer dan 7 dagen geen berichten van gebruikers zijn ontvangen, wordt deze verbinding automatisch gepauzeerd. Klik op \"Opnieuw koppelen via QR-code\" om te hervatten.",
"channel.wechatManagedCredentials": "Dit kanaal is al verbonden via QR-code autorisatie. Inloggegevens worden automatisch beheerd.",
"channel.wechatQrExpired": "QR-code verlopen. Vernieuw om een nieuwe te krijgen.",
"channel.wechatQrLoadFailed": "Het laden van de QR-code is mislukt. Probeer het opnieuw.",
diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.json
index 6570270ec37..9121f405942 100644
--- a/locales/nl-NL/setting.json
+++ b/locales/nl-NL/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "Naam",
"settingAgent.prompt.desc": "Definieert wie deze agent is, waar hij verantwoordelijk voor is, en hoe hij werkt en reageert. Het dient als een kerninstructie in elk gesprek.",
"settingAgent.prompt.editorPlaceholder": "Voer kerninstructies in, druk op / om het Slash-menu te openen",
+ "settingAgent.prompt.mode.source": "Markdown-bron",
+ "settingAgent.prompt.mode.visual": "Visuele editor",
"settingAgent.prompt.placeholder": "Voer agentinstellingen in, druk op / om het opdrachtmenu te openen",
"settingAgent.prompt.title": "Agentprofiel",
"settingAgent.runtimeConfig.title": "Model & Tools",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "Deze uitnodiging intrekken?",
"workspace.members.pending.revokeFailed": "Uitnodiging intrekken mislukt",
"workspace.members.seatChange.memberJoinBlocked": "Huidige leden hebben de geplande plaatslimiet bereikt, waardoor nieuwe betaalde leden mogelijk niet kunnen deelnemen aan deze werkruimte",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} plek",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} plekken",
"workspace.members.subtitle": "Beheer werkruimteleden en uitnodigingen",
"workspace.members.tabs.members": "Teamleden",
"workspace.members.tabs.pending": "Openstaande uitnodigingen",
"workspace.members.title": "Leden",
+ "workspace.members.totalCount_one": "{{total}} lid",
+ "workspace.members.totalCount_other": "{{total}} leden",
"workspace.name.placeholder": "Naam van de werkruimte",
"workspace.name.title": "Naam",
"workspace.newWorkspace": "Nieuwe werkruimte",
diff --git a/locales/pl-PL/agent.json b/locales/pl-PL/agent.json
index 64e3dcead93..b7a298d9afa 100644
--- a/locales/pl-PL/agent.json
+++ b/locales/pl-PL/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "Wklej tutaj sekret aplikacji",
"channel.applicationId": "ID aplikacji / Nazwa użytkownika bota",
"channel.applicationIdHint": "Unikalny identyfikator dla aplikacji bota.",
+ "channel.applicationIdInvalid.discord": "Identyfikator aplikacji musi być 17–20-cyfrowym identyfikatorem znajdującym się na stronie Informacje Ogólne Twojej aplikacji Discord.",
"channel.applicationIdPlaceholder": "np. 1234567890",
"channel.botToken": "Token bota / Klucz API",
"channel.botTokenEncryptedHint": "Token zostanie zaszyfrowany i bezpiecznie przechowany.",
"channel.botTokenHowToGet": "Jak uzyskać?",
+ "channel.botTokenInvalid.discord": "To nie wygląda na token bota Discord. Zresetuj go i skopiuj z zakładki Bot w Twojej aplikacji Discord — składa się z trzech segmentów oddzielonych kropkami.",
"channel.botTokenPlaceholderExisting": "Token jest ukryty ze względów bezpieczeństwa",
"channel.botTokenPlaceholderNew": "Wklej tutaj token bota",
"channel.charLimit": "Limit znaków",
@@ -201,6 +203,7 @@
"channel.platforms": "Platformy",
"channel.publicKey": "Klucz publiczny",
"channel.publicKeyHint": "Opcjonalne. Używane do weryfikacji żądań interakcji z Discord.",
+ "channel.publicKeyInvalid": "Klucz publiczny musi być 64-znakowym ciągiem szesnastkowym. Skopiuj go ze strony Informacje Ogólne aplikacji Discord — nie z adresu URL OAuth ani klucza API.",
"channel.publicKeyPlaceholder": "Wymagane do weryfikacji interakcji",
"channel.qq.appIdHint": "Twój identyfikator aplikacji QQ Bot z platformy QQ Open Platform",
"channel.qq.description": "Połącz tego asystenta z QQ, aby prowadzić rozmowy grupowe i wiadomości bezpośrednie.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "Identyfikator bota przypisany po autoryzacji kodem QR.",
"channel.wechatConnectedInfo": "Połączone konto WeChat",
"channel.wechatGenerateQrCode": "Wygeneruj kod QR",
- "channel.wechatIdleNotice": "Jeśli przez ponad 7 dni nikt nie wyśle wiadomości, to połączenie zostanie automatycznie wstrzymane. Aby je wznowić, kliknij „Połącz ponownie przez kod QR”.",
"channel.wechatManagedCredentials": "Ten kanał jest już połączony poprzez autoryzację kodem QR. Poświadczenia są zarządzane automatycznie.",
"channel.wechatQrExpired": "Kod QR wygasł. Odśwież, aby uzyskać nowy.",
"channel.wechatQrLoadFailed": "Nie udało się załadować kodu QR. Spróbuj ponownie.",
diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.json
index 4f96c53efe9..802b58dfc09 100644
--- a/locales/pl-PL/setting.json
+++ b/locales/pl-PL/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "Nazwa",
"settingAgent.prompt.desc": "Określa, kim jest ten agent, za co jest odpowiedzialny, jak działa i odpowiada. Służy jako podstawowa instrukcja w każdej rozmowie.",
"settingAgent.prompt.editorPlaceholder": "Wprowadź podstawowe instrukcje, naciśnij /, aby otworzyć menu Slash",
+ "settingAgent.prompt.mode.source": "Źródło Markdown",
+ "settingAgent.prompt.mode.visual": "Edytor wizualny",
"settingAgent.prompt.placeholder": "Wprowadź ustawienia agenta, naciśnij /, aby otworzyć menu poleceń",
"settingAgent.prompt.title": "Profil agenta",
"settingAgent.runtimeConfig.title": "Model i Narzędzia",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "Cofnąć to zaproszenie?",
"workspace.members.pending.revokeFailed": "Nie udało się cofnąć zaproszenia",
"workspace.members.seatChange.memberJoinBlocked": "Obecni członkowie osiągnęli zaplanowany limit miejsc, więc nowi płatni członkowie mogą nie być w stanie dołączyć do tego workspace",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} miejsce",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} miejsc",
"workspace.members.subtitle": "Zarządzaj członkami miejsca pracy i zaproszeniami",
"workspace.members.tabs.members": "Członkowie zespołu",
"workspace.members.tabs.pending": "Oczekujące zaproszenia",
"workspace.members.title": "Członkowie",
+ "workspace.members.totalCount_one": "{{total}} członek",
+ "workspace.members.totalCount_other": "{{total}} członków",
"workspace.name.placeholder": "Nazwa miejsca pracy",
"workspace.name.title": "Nazwa",
"workspace.newWorkspace": "Nowe miejsce pracy",
diff --git a/locales/pt-BR/agent.json b/locales/pt-BR/agent.json
index 79064b23809..4e189470e03 100644
--- a/locales/pt-BR/agent.json
+++ b/locales/pt-BR/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "Cole o segredo do seu aplicativo aqui",
"channel.applicationId": "ID do Aplicativo / Nome de Usuário do Bot",
"channel.applicationIdHint": "Identificador único para o seu aplicativo de bot.",
+ "channel.applicationIdInvalid.discord": "O ID do aplicativo deve ser o número de 17–20 dígitos na página de Informações Gerais do seu aplicativo Discord.",
"channel.applicationIdPlaceholder": "ex.: 1234567890",
"channel.botToken": "Token do Bot / Chave API",
"channel.botTokenEncryptedHint": "O token será criptografado e armazenado com segurança.",
"channel.botTokenHowToGet": "Como obter?",
+ "channel.botTokenInvalid.discord": "Isso não parece ser um token de bot do Discord. Redefina e copie-o da aba Bot do seu aplicativo Discord — são três segmentos separados por pontos.",
"channel.botTokenPlaceholderExisting": "Token está oculto por segurança",
"channel.botTokenPlaceholderNew": "Cole o token do seu bot aqui",
"channel.charLimit": "Limite de Caracteres",
@@ -201,6 +203,7 @@
"channel.platforms": "Plataformas",
"channel.publicKey": "Chave Pública",
"channel.publicKeyHint": "Opcional. Usada para verificar solicitações de interação do Discord.",
+ "channel.publicKeyInvalid": "A chave pública deve ser uma string hexadecimal de 64 caracteres. Copie-a da página de Informações Gerais do aplicativo Discord — não da URL OAuth e não de uma chave de API.",
"channel.publicKeyPlaceholder": "Obrigatória para verificação de interação",
"channel.qq.appIdHint": "Seu ID do App Bot do QQ na Plataforma Aberta do QQ",
"channel.qq.description": "Conecte este assistente ao QQ para bate-papos em grupo e mensagens diretas.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "Identificador do bot atribuído após a autorização via código QR.",
"channel.wechatConnectedInfo": "Conta do WeChat Conectada",
"channel.wechatGenerateQrCode": "Gerar Código QR",
- "channel.wechatIdleNotice": "Se nenhum usuário enviar mensagens por mais de 7 dias, esta conexão será pausada automaticamente. Para retomar, clique em \"Vincular novamente via QR Code\".",
"channel.wechatManagedCredentials": "Este canal já está conectado por meio de autorização via código QR. As credenciais são gerenciadas automaticamente.",
"channel.wechatQrExpired": "Código QR expirado. Por favor, atualize para obter um novo.",
"channel.wechatQrLoadFailed": "Falha ao carregar o código QR. Por favor, tente novamente.",
diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.json
index 25adcfc158c..8db753039a7 100644
--- a/locales/pt-BR/setting.json
+++ b/locales/pt-BR/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "Nome",
"settingAgent.prompt.desc": "Define quem é este agente, o que ele é responsável por fazer, como funciona e responde. Serve como uma instrução central em cada conversa.",
"settingAgent.prompt.editorPlaceholder": "Insira instruções principais, pressione / para abrir o Menu de Atalhos",
+ "settingAgent.prompt.mode.source": "Fonte Markdown",
+ "settingAgent.prompt.mode.visual": "Editor visual",
"settingAgent.prompt.placeholder": "Insira as configurações do agente, pressione / para abrir o menu de comandos",
"settingAgent.prompt.title": "Perfil do Agente",
"settingAgent.runtimeConfig.title": "Modelo e Ferramentas",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "Revogar este convite?",
"workspace.members.pending.revokeFailed": "Falha ao revogar o convite",
"workspace.members.seatChange.memberJoinBlocked": "Os membros atuais atingiram o limite de assentos agendado, então novos membros pagos podem não conseguir ingressar neste espaço de trabalho",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} assento",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} assentos",
"workspace.members.subtitle": "Gerencie os membros e convites do workspace",
"workspace.members.tabs.members": "Membros da Equipe",
"workspace.members.tabs.pending": "Convites Pendentes",
"workspace.members.title": "Membros",
+ "workspace.members.totalCount_one": "{{total}} membro",
+ "workspace.members.totalCount_other": "{{total}} membros",
"workspace.name.placeholder": "Nome do workspace",
"workspace.name.title": "Nome",
"workspace.newWorkspace": "Novo workspace",
diff --git a/locales/ru-RU/agent.json b/locales/ru-RU/agent.json
index 39ac5d6c9a0..6d2977d354c 100644
--- a/locales/ru-RU/agent.json
+++ b/locales/ru-RU/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "Вставьте секрет вашего приложения здесь",
"channel.applicationId": "ID приложения / Имя пользователя бота",
"channel.applicationIdHint": "Уникальный идентификатор для вашего приложения-бота.",
+ "channel.applicationIdInvalid.discord": "ID приложения должен быть 17–20-значным идентификатором на странице Общей информации вашего приложения Discord.",
"channel.applicationIdPlaceholder": "например, 1234567890",
"channel.botToken": "Токен бота / API ключ",
"channel.botTokenEncryptedHint": "Токен будет зашифрован и сохранен безопасно.",
"channel.botTokenHowToGet": "Как получить?",
+ "channel.botTokenInvalid.discord": "Это не похоже на токен бота Discord. Сбросьте и скопируйте его с вкладки Bot вашего приложения Discord — он состоит из трех сегментов, разделенных точками.",
"channel.botTokenPlaceholderExisting": "Токен скрыт для безопасности",
"channel.botTokenPlaceholderNew": "Вставьте токен вашего бота здесь",
"channel.charLimit": "Ограничение символов",
@@ -201,6 +203,7 @@
"channel.platforms": "Платформы",
"channel.publicKey": "Открытый ключ",
"channel.publicKeyHint": "Необязательно. Используется для проверки запросов взаимодействия от Discord.",
+ "channel.publicKeyInvalid": "Публичный ключ должен быть 64-символьной шестнадцатеричной строкой. Скопируйте его со страницы Общей информации приложения Discord — не из URL OAuth и не из API-ключа.",
"channel.publicKeyPlaceholder": "Требуется для проверки взаимодействия",
"channel.qq.appIdHint": "Ваш App ID бота QQ с платформы QQ Open Platform",
"channel.qq.description": "Подключите этого ассистента к QQ для групповых чатов и личных сообщений.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "Идентификатор бота, назначенный после авторизации через QR-код.",
"channel.wechatConnectedInfo": "Подключенный аккаунт WeChat",
"channel.wechatGenerateQrCode": "Создать QR-код",
- "channel.wechatIdleNotice": "Если пользователи не отправляют сообщения более 7 дней, это подключение будет автоматически приостановлено. Чтобы возобновить работу, нажмите «Перепривязать по QR‑коду».",
"channel.wechatManagedCredentials": "Этот канал уже подключен через авторизацию по QR-коду. Учетные данные управляются автоматически.",
"channel.wechatQrExpired": "Срок действия QR-кода истек. Пожалуйста, обновите, чтобы получить новый.",
"channel.wechatQrLoadFailed": "Не удалось загрузить QR-код. Пожалуйста, попробуйте снова.",
diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.json
index 06adb39c92a..407e2393396 100644
--- a/locales/ru-RU/setting.json
+++ b/locales/ru-RU/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "Имя",
"settingAgent.prompt.desc": "Определяет, кто этот агент, за что он отвечает, как он работает и реагирует. Это служит основным инструктажем в каждом разговоре.",
"settingAgent.prompt.editorPlaceholder": "Введите основные инструкции, нажмите /, чтобы открыть меню Slash",
+ "settingAgent.prompt.mode.source": "Исходный код Markdown",
+ "settingAgent.prompt.mode.visual": "Визуальный редактор",
"settingAgent.prompt.placeholder": "Введите настройки агента, нажмите / для открытия меню команд",
"settingAgent.prompt.title": "Профиль агента",
"settingAgent.runtimeConfig.title": "Модель и инструменты",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "Отозвать это приглашение?",
"workspace.members.pending.revokeFailed": "Не удалось отозвать приглашение",
"workspace.members.seatChange.memberJoinBlocked": "Текущие участники достигли запланированного лимита мест, поэтому новые платные участники могут не иметь возможности присоединиться к этому рабочему пространству",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} место",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} мест",
"workspace.members.subtitle": "Управление участниками рабочей области и приглашениями",
"workspace.members.tabs.members": "Участники команды",
"workspace.members.tabs.pending": "Ожидающие приглашения",
"workspace.members.title": "Участники",
+ "workspace.members.totalCount_one": "{{total}} участник",
+ "workspace.members.totalCount_other": "{{total}} участников",
"workspace.name.placeholder": "Имя рабочей области",
"workspace.name.title": "Имя",
"workspace.newWorkspace": "Новая рабочая область",
diff --git a/locales/tr-TR/agent.json b/locales/tr-TR/agent.json
index d25cd47feff..abd0abc4756 100644
--- a/locales/tr-TR/agent.json
+++ b/locales/tr-TR/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "Uygulama sırrınızı buraya yapıştırın",
"channel.applicationId": "Uygulama Kimliği / Bot Kullanıcı Adı",
"channel.applicationIdHint": "Bot uygulamanız için benzersiz kimlik.",
+ "channel.applicationIdInvalid.discord": "Uygulama Kimliği, Discord uygulamanızın Genel Bilgi sayfasındaki 17–20 haneli kimlik olmalıdır.",
"channel.applicationIdPlaceholder": "ör. 1234567890",
"channel.botToken": "Bot Token / API Anahtarı",
"channel.botTokenEncryptedHint": "Token şifrelenerek güvenli bir şekilde saklanacaktır.",
"channel.botTokenHowToGet": "Nasıl alınır?",
+ "channel.botTokenInvalid.discord": "Bu, bir Discord bot tokenine benzemiyor. Bot sekmesinden sıfırlayın ve Discord uygulamanızdan kopyalayın — üç nokta ile ayrılmış üç segmentten oluşur.",
"channel.botTokenPlaceholderExisting": "Güvenlik için token gizlenmiştir",
"channel.botTokenPlaceholderNew": "Bot tokeninizi buraya yapıştırın",
"channel.charLimit": "Karakter Sınırı",
@@ -201,6 +203,7 @@
"channel.platforms": "Platformlar",
"channel.publicKey": "Genel Anahtar",
"channel.publicKeyHint": "Opsiyonel. Discord'dan gelen etkileşim isteklerini doğrulamak için kullanılır.",
+ "channel.publicKeyInvalid": "Genel Anahtar, 64 karakterlik bir hex dizesi olmalıdır. Discord uygulamanızın Genel Bilgi sayfasından kopyalayın — OAuth URL'si veya bir API anahtarı değil.",
"channel.publicKeyPlaceholder": "Etkileşim doğrulama için gerekli",
"channel.qq.appIdHint": "QQ Açık Platformundan QQ Bot Uygulama Kimliğiniz",
"channel.qq.description": "Bu asistanı grup sohbetleri ve doğrudan mesajlar için QQ'ya bağlayın.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "QR kodu yetkilendirmesinden sonra atanan bot tanımlayıcısı.",
"channel.wechatConnectedInfo": "Bağlı WeChat Hesabı",
"channel.wechatGenerateQrCode": "QR Kod Oluştur",
- "channel.wechatIdleNotice": "7 günden uzun süre kullanıcı mesajı gelmezse bu bağlantı otomatik olarak duraklatılır. Yeniden başlatmak için \"QR Kod ile Yeniden Bağla\"ya tıklayın.",
"channel.wechatManagedCredentials": "Bu kanal zaten QR kodu yetkilendirmesiyle bağlanmış durumda. Kimlik bilgileri otomatik olarak yönetiliyor.",
"channel.wechatQrExpired": "QR kodunun süresi doldu. Yeni bir kod almak için lütfen yenileyin.",
"channel.wechatQrLoadFailed": "QR kodu yüklenemedi. Lütfen tekrar deneyin.",
diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.json
index efccf07511b..acb6959fe06 100644
--- a/locales/tr-TR/setting.json
+++ b/locales/tr-TR/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "Ad",
"settingAgent.prompt.desc": "Bu ajanı tanımlar, neyle sorumlu olduğunu, nasıl çalıştığını ve nasıl yanıt verdiğini açıklar. Her konuşmada temel bir talimat olarak hizmet eder.",
"settingAgent.prompt.editorPlaceholder": "Temel talimatları girin, Slash Menüsünü açmak için / tuşuna basın",
+ "settingAgent.prompt.mode.source": "Markdown kaynağı",
+ "settingAgent.prompt.mode.visual": "Görsel düzenleyici",
"settingAgent.prompt.placeholder": "Temsilci ayarlarını girin, komut menüsünü açmak için / tuşuna basın",
"settingAgent.prompt.title": "Temsilci Profili",
"settingAgent.runtimeConfig.title": "Model ve Araçlar",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "Bu daveti iptal etmek istiyor musunuz?",
"workspace.members.pending.revokeFailed": "Davet iptal edilemedi",
"workspace.members.seatChange.memberJoinBlocked": "Mevcut üyeler planlanan koltuk sınırına ulaştı, bu nedenle yeni ücretli üyeler bu çalışma alanına katılamayabilir",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} koltuk",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} koltuklar",
"workspace.members.subtitle": "Çalışma alanı üyelerini ve davetlerini yönetin",
"workspace.members.tabs.members": "Ekip Üyeleri",
"workspace.members.tabs.pending": "Bekleyen Davetler",
"workspace.members.title": "Üyeler",
+ "workspace.members.totalCount_one": "{{total}} üye",
+ "workspace.members.totalCount_other": "{{total}} üyeler",
"workspace.name.placeholder": "Çalışma alanı adı",
"workspace.name.title": "Ad",
"workspace.newWorkspace": "Yeni çalışma alanı",
diff --git a/locales/vi-VN/agent.json b/locales/vi-VN/agent.json
index 0e6c15564d6..65a2f572295 100644
--- a/locales/vi-VN/agent.json
+++ b/locales/vi-VN/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "Dán mã bí mật ứng dụng của bạn vào đây",
"channel.applicationId": "ID ứng dụng / Tên người dùng bot",
"channel.applicationIdHint": "Định danh duy nhất cho ứng dụng bot của bạn.",
+ "channel.applicationIdInvalid.discord": "ID ứng dụng phải là ID gồm 17–20 chữ số trên trang Thông tin Chung của ứng dụng Discord của bạn.",
"channel.applicationIdPlaceholder": "ví dụ: 1234567890",
"channel.botToken": "Mã bot / Khóa API",
"channel.botTokenEncryptedHint": "Mã sẽ được mã hóa và lưu trữ an toàn.",
"channel.botTokenHowToGet": "Làm thế nào để lấy?",
+ "channel.botTokenInvalid.discord": "Đây không giống như một mã token bot Discord. Hãy đặt lại và sao chép nó từ tab Bot của ứng dụng Discord của bạn — nó gồm ba đoạn được phân tách bằng dấu chấm.",
"channel.botTokenPlaceholderExisting": "Mã được ẩn để bảo mật",
"channel.botTokenPlaceholderNew": "Dán mã bot của bạn vào đây",
"channel.charLimit": "Giới hạn ký tự",
@@ -201,6 +203,7 @@
"channel.platforms": "Nền tảng",
"channel.publicKey": "Khóa công khai",
"channel.publicKeyHint": "Tùy chọn. Dùng để xác minh yêu cầu tương tác từ Discord.",
+ "channel.publicKeyInvalid": "Khóa công khai phải là một chuỗi hex gồm 64 ký tự. Sao chép nó từ trang Thông tin Chung của ứng dụng Discord — không phải URL OAuth, và không phải khóa API.",
"channel.publicKeyPlaceholder": "Yêu cầu để xác minh tương tác",
"channel.qq.appIdHint": "ID ứng dụng Bot QQ của bạn từ Nền tảng Mở QQ",
"channel.qq.description": "Kết nối trợ lý này với QQ để trò chuyện nhóm và tin nhắn trực tiếp.",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "Định danh bot được cấp sau khi ủy quyền mã QR.",
"channel.wechatConnectedInfo": "Tài khoản WeChat đã kết nối",
"channel.wechatGenerateQrCode": "Tạo mã QR",
- "channel.wechatIdleNotice": "Nếu không có người dùng gửi tin nhắn trong hơn 7 ngày, kết nối này sẽ tự động tạm dừng. Để tiếp tục, hãy nhấp vào \"Liên kết lại bằng mã QR\".",
"channel.wechatManagedCredentials": "Kênh này đã được kết nối thông qua ủy quyền mã QR. Thông tin đăng nhập được quản lý tự động.",
"channel.wechatQrExpired": "Mã QR đã hết hạn. Vui lòng làm mới để nhận mã mới.",
"channel.wechatQrLoadFailed": "Không tải được mã QR. Vui lòng thử lại.",
diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.json
index 065e5a51725..0ab0c3bfa21 100644
--- a/locales/vi-VN/setting.json
+++ b/locales/vi-VN/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "Tên",
"settingAgent.prompt.desc": "Xác định ai là tác nhân này, trách nhiệm của nó, cách nó hoạt động và phản hồi. Đây là hướng dẫn cốt lõi trong mọi cuộc trò chuyện.",
"settingAgent.prompt.editorPlaceholder": "Nhập hướng dẫn cốt lõi, nhấn / để mở Menu Slash",
+ "settingAgent.prompt.mode.source": "Nguồn Markdown",
+ "settingAgent.prompt.mode.visual": "Trình chỉnh sửa trực quan",
"settingAgent.prompt.placeholder": "Nhập thiết lập tác nhân, nhấn / để mở menu lệnh",
"settingAgent.prompt.title": "Hồ sơ tác nhân",
"settingAgent.runtimeConfig.title": "Mô hình & Công cụ",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "Thu hồi lời mời này?",
"workspace.members.pending.revokeFailed": "Không thể hủy lời mời",
"workspace.members.seatChange.memberJoinBlocked": "Các thành viên hiện tại đã đạt giới hạn ghế đã lên lịch, vì vậy các thành viên trả phí mới có thể không tham gia được không gian làm việc này",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} chỗ ngồi",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} chỗ ngồi",
"workspace.members.subtitle": "Quản lý thành viên và lời mời trong không gian làm việc",
"workspace.members.tabs.members": "Thành viên đội ngũ",
"workspace.members.tabs.pending": "Lời mời đang chờ xử lý",
"workspace.members.title": "Thành viên",
+ "workspace.members.totalCount_one": "{{total}} thành viên",
+ "workspace.members.totalCount_other": "{{total}} thành viên",
"workspace.name.placeholder": "Tên không gian làm việc",
"workspace.name.title": "Tên",
"workspace.newWorkspace": "Không gian làm việc mới",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 0adf23c07b8..589977dfc12 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "在此粘贴你的 App Secret",
"channel.applicationId": "应用 ID / Bot 用户名",
"channel.applicationIdHint": "您的机器人应用程序的唯一标识符。",
+ "channel.applicationIdInvalid.discord": "应用 ID 必须是 Discord 应用 General Information 页面上的 17–20 位数字 ID。",
"channel.applicationIdPlaceholder": "例如 1234567890",
"channel.botToken": "Bot Token / API Key",
"channel.botTokenEncryptedHint": "Token 将被加密安全存储。",
"channel.botTokenHowToGet": "如何获取?",
+ "channel.botTokenInvalid.discord": "这看起来不是 Discord Bot Token。请到 Discord 应用的 Bot 标签页重置并复制,它由三段以点号分隔的字符组成。",
"channel.botTokenPlaceholderExisting": "出于安全考虑,Token 已隐藏",
"channel.botTokenPlaceholderNew": "在此粘贴你的 Bot Token",
"channel.charLimit": "字符限制",
@@ -200,8 +202,9 @@
"channel.platform.whatsapp.description": "在熟悉的移动聊天中提供支持和跟进,适合直接服务客户的团队。",
"channel.platforms": "平台",
"channel.publicKey": "公钥",
- "channel.publicKeyHint": "可选。用于验证来自 Discord 的交互请求。",
- "channel.publicKeyPlaceholder": "用于交互验证",
+ "channel.publicKeyHint": "用于验证来自 Discord 的交互请求。为应用 General Information 页面上的 64 位十六进制字符串。",
+ "channel.publicKeyInvalid": "公钥必须是 64 位十六进制字符串。请从 Discord 应用的 General Information 页面复制,不要填 OAuth 链接,也不要填 API Key。",
+ "channel.publicKeyPlaceholder": "64 位十六进制字符串",
"channel.qq.appIdHint": "您在 QQ 开放平台获取的机器人 App ID",
"channel.qq.description": "将助手连接到 QQ,支持群聊和私聊。",
"channel.qq.webhookMigrationDesc": "WebSocket 模式无需回调 URL,即可提供实时事件传递和自动重连。要进行迁移,请在 QQ 开放平台创建一个新的机器人且不要配置回调 URL,然后在高级设置中将连接模式切换为 WebSocket。",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index ad28f40bcbd..1b4c02aabfb 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -2377,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "撤销此邀请?",
"workspace.members.pending.revokeFailed": "撤销邀请失败",
"workspace.members.seatChange.memberJoinBlocked": "当前成员数量已达到排期后的席位上限,新成员可能无法加入该工作区",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} 个席位",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} 个席位",
"workspace.members.subtitle": "管理工作区成员和邀请",
"workspace.members.tabs.members": "团队成员",
"workspace.members.tabs.pending": "待处理邀请",
"workspace.members.title": "成员",
+ "workspace.members.totalCount_one": "{{total}} 位成员",
+ "workspace.members.totalCount_other": "{{total}} 位成员",
"workspace.name.placeholder": "工作区名称",
"workspace.name.title": "名称",
"workspace.newWorkspace": "新工作区",
diff --git a/locales/zh-TW/agent.json b/locales/zh-TW/agent.json
index 6cdba179d29..c07cb4ab4fb 100644
--- a/locales/zh-TW/agent.json
+++ b/locales/zh-TW/agent.json
@@ -13,10 +13,12 @@
"channel.appSecretPlaceholder": "在此貼上您的應用程式密鑰",
"channel.applicationId": "應用程式 ID / 機器人用戶名",
"channel.applicationIdHint": "您的機器人應用程式的唯一識別碼。",
+ "channel.applicationIdInvalid.discord": "應用程式 ID 必須是您 Discord 應用程式一般資訊頁面上的 17–20 位數字 ID。",
"channel.applicationIdPlaceholder": "例如:1234567890",
"channel.botToken": "機器人令牌 / API 金鑰",
"channel.botTokenEncryptedHint": "令牌將被加密並安全存儲。",
"channel.botTokenHowToGet": "如何獲取?",
+ "channel.botTokenInvalid.discord": "這看起來不像是 Discord 機器人 Token。請重設並從您的 Discord 應用程式的機器人標籤頁複製,它由三段以點分隔的字串組成。",
"channel.botTokenPlaceholderExisting": "為安全起見,令牌已隱藏",
"channel.botTokenPlaceholderNew": "在此貼上您的機器人令牌",
"channel.charLimit": "字元限制",
@@ -201,6 +203,7 @@
"channel.platforms": "平台",
"channel.publicKey": "公鑰",
"channel.publicKeyHint": "可選。用於驗證來自 Discord 的交互請求。",
+ "channel.publicKeyInvalid": "公鑰必須是 64 字元的十六進位字串。請從 Discord 應用程式的一般資訊頁面複製,而不是 OAuth URL,也不是 API 金鑰。",
"channel.publicKeyPlaceholder": "交互驗證所需",
"channel.qq.appIdHint": "來自 QQ 開放平台的 QQ 機器人應用 ID",
"channel.qq.description": "將此助手連接到 QQ,以進行群組聊天和私人訊息。",
@@ -275,7 +278,6 @@
"channel.wechatBotIdHint": "通過二維碼授權後分配的機器人標識符。",
"channel.wechatConnectedInfo": "已連接的微信帳號",
"channel.wechatGenerateQrCode": "生成 QR 碼",
- "channel.wechatIdleNotice": "若超過 7 天未收到使用者訊息,此連線將自動暫停。要重新啟用,請點擊「透過 QR Code 重新綁定」。",
"channel.wechatManagedCredentials": "此頻道已通過二維碼授權連接。憑證由系統自動管理。",
"channel.wechatQrExpired": "QR 碼已過期。請刷新以獲取新的 QR 碼。",
"channel.wechatQrLoadFailed": "加載 QR 碼失敗。請重試。",
diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.json
index ceb46b8af87..3a02829412d 100644
--- a/locales/zh-TW/setting.json
+++ b/locales/zh-TW/setting.json
@@ -666,6 +666,8 @@
"settingAgent.name.title": "名稱",
"settingAgent.prompt.desc": "定義此代理的身份、責任以及其運作和回應方式。它在每次對話中都作為核心指令。",
"settingAgent.prompt.editorPlaceholder": "輸入核心指令,按 / 開啟快捷選單",
+ "settingAgent.prompt.mode.source": "Markdown 原始碼",
+ "settingAgent.prompt.mode.visual": "視覺化編輯器",
"settingAgent.prompt.placeholder": "輸入助手設定,按 / 開啟指令選單",
"settingAgent.prompt.title": "助手設定",
"settingAgent.runtimeConfig.title": "模型與工具",
@@ -2375,10 +2377,14 @@
"workspace.members.pending.revokeConfirm.title": "撤銷此邀請?",
"workspace.members.pending.revokeFailed": "撤銷邀請失敗",
"workspace.members.seatChange.memberJoinBlocked": "當前成員已達到排定的席位限制,因此新付費成員可能無法加入此工作區",
+ "workspace.members.seatUsage_one": "{{used}} / {{capacity}} 席位",
+ "workspace.members.seatUsage_other": "{{used}} / {{capacity}} 席位",
"workspace.members.subtitle": "管理工作區成員和邀請",
"workspace.members.tabs.members": "團隊成員",
"workspace.members.tabs.pending": "待處理的邀請",
"workspace.members.title": "成員",
+ "workspace.members.totalCount_one": "{{total}} 位成員",
+ "workspace.members.totalCount_other": "{{total}} 位成員",
"workspace.name.placeholder": "工作區名稱",
"workspace.name.title": "名稱",
"workspace.newWorkspace": "新工作區",
diff --git a/packages/database/src/models/__tests__/knowledgeBase.test.ts b/packages/database/src/models/__tests__/knowledgeBase.test.ts
index 206b590222f..03b2fb75012 100644
--- a/packages/database/src/models/__tests__/knowledgeBase.test.ts
+++ b/packages/database/src/models/__tests__/knowledgeBase.test.ts
@@ -1247,7 +1247,109 @@ describe('KnowledgeBaseModel', () => {
});
});
+ it('should align newly added creator-owned content with the library visibility', async () => {
+ const created = await ownerModel.create({ name: 'Public Library', visibility: 'public' });
+ await serverDB.insert(files).values({
+ id: 'workspace-private-file-to-add',
+ fileType: 'text/plain',
+ name: 'Private file to add',
+ size: 10,
+ url: 'internal://private-file-to-add',
+ userId,
+ visibility: 'private',
+ workspaceId: wsId,
+ });
+
+ await ownerModel.addFilesToKnowledgeBase(created.id, ['workspace-private-file-to-add']);
+
+ const addedFile = await serverDB.query.files.findFirst({
+ where: eq(files.id, 'workspace-private-file-to-add'),
+ });
+ expect(addedFile?.visibility).toBe('public');
+ });
+
describe('publishToWorkspace', () => {
+ it('should synchronize creator-owned contents without rewriting another member’s file', async () => {
+ const created = await ownerModel.create({ name: 'Shared Contents', visibility: 'private' });
+ await serverDB.insert(files).values([
+ {
+ id: 'workspace-owner-file',
+ fileType: 'text/plain',
+ name: 'Owner file',
+ size: 10,
+ url: 'internal://owner-file',
+ userId,
+ visibility: 'private',
+ workspaceId: wsId,
+ },
+ {
+ id: 'workspace-member-file',
+ fileType: 'text/plain',
+ name: 'Member file',
+ size: 10,
+ url: 'internal://member-file',
+ userId: 'user2',
+ visibility: 'public',
+ workspaceId: wsId,
+ },
+ ]);
+ await serverDB.insert(documents).values({
+ id: 'docs_workspace_owner',
+ content: 'Owner page',
+ fileId: 'workspace-owner-file',
+ fileType: 'custom/document',
+ knowledgeBaseId: created.id,
+ source: 'document',
+ sourceType: 'api',
+ title: 'Owner page',
+ totalCharCount: 10,
+ totalLineCount: 1,
+ userId,
+ visibility: 'private',
+ workspaceId: wsId,
+ });
+ await serverDB.insert(knowledgeBaseFiles).values([
+ {
+ fileId: 'workspace-owner-file',
+ knowledgeBaseId: created.id,
+ userId,
+ workspaceId: wsId,
+ },
+ {
+ fileId: 'workspace-member-file',
+ knowledgeBaseId: created.id,
+ userId: 'user2',
+ workspaceId: wsId,
+ },
+ ]);
+
+ await ownerModel.publishToWorkspace(created.id);
+
+ const publishedOwnerFile = await serverDB.query.files.findFirst({
+ where: eq(files.id, 'workspace-owner-file'),
+ });
+ const publishedOwnerDocument = await serverDB.query.documents.findFirst({
+ where: eq(documents.id, 'docs_workspace_owner'),
+ });
+ expect(publishedOwnerFile?.visibility).toBe('public');
+ expect(publishedOwnerDocument?.visibility).toBe('public');
+
+ await ownerModel.setVisibility(created.id, 'private');
+
+ const privateOwnerFile = await serverDB.query.files.findFirst({
+ where: eq(files.id, 'workspace-owner-file'),
+ });
+ const privateOwnerDocument = await serverDB.query.documents.findFirst({
+ where: eq(documents.id, 'docs_workspace_owner'),
+ });
+ const untouchedMemberFile = await serverDB.query.files.findFirst({
+ where: eq(files.id, 'workspace-member-file'),
+ });
+ expect(privateOwnerFile?.visibility).toBe('private');
+ expect(privateOwnerDocument?.visibility).toBe('private');
+ expect(untouchedMemberFile?.visibility).toBe('public');
+ });
+
it('should flip the creator’s own private KB to public', async () => {
const created = await ownerModel.create({ name: 'To Publish', visibility: 'private' });
@@ -1259,8 +1361,24 @@ describe('KnowledgeBaseModel', () => {
expect(row?.visibility).toBe('public');
});
- it('should be a no-op when the KB is already public', async () => {
+ it('should reconcile stale content without touching an already-public KB timestamp', async () => {
const created = await ownerModel.create({ name: 'Already Public', visibility: 'public' });
+ await serverDB.insert(files).values({
+ id: 'workspace-stale-private-file',
+ fileType: 'text/plain',
+ name: 'Stale private file',
+ size: 10,
+ url: 'internal://stale-private-file',
+ userId,
+ visibility: 'private',
+ workspaceId: wsId,
+ });
+ await serverDB.insert(knowledgeBaseFiles).values({
+ fileId: 'workspace-stale-private-file',
+ knowledgeBaseId: created.id,
+ userId,
+ workspaceId: wsId,
+ });
const before = await serverDB.query.knowledgeBases.findFirst({
where: eq(knowledgeBases.id, created.id),
});
@@ -1270,8 +1388,12 @@ describe('KnowledgeBaseModel', () => {
const after = await serverDB.query.knowledgeBases.findFirst({
where: eq(knowledgeBases.id, created.id),
});
+ const reconciledFile = await serverDB.query.files.findFirst({
+ where: eq(files.id, 'workspace-stale-private-file'),
+ });
expect(after?.visibility).toBe('public');
expect(after?.updatedAt).toEqual(before?.updatedAt);
+ expect(reconciledFile?.visibility).toBe('public');
});
it('should refuse to publish another member’s private KB', async () => {
diff --git a/packages/database/src/models/knowledgeBase.ts b/packages/database/src/models/knowledgeBase.ts
index 81fc618395d..c604636a7b4 100644
--- a/packages/database/src/models/knowledgeBase.ts
+++ b/packages/database/src/models/knowledgeBase.ts
@@ -86,6 +86,42 @@ export class KnowledgeBaseModel {
return [];
}
+ // Adding content to a workspace library is an explicit move into that
+ // library's visibility boundary. Only rewrite rows owned by the current
+ // actor; a public library may contain resources contributed by multiple
+ // members, and one member must never change another member's permissions.
+ if (this.workspaceId) {
+ const now = new Date();
+ const creatorScope = { userId: this.userId, workspaceId: this.workspaceId };
+
+ await this.db
+ .update(files)
+ .set({ updatedAt: now, visibility: kb.visibility })
+ .where(
+ and(
+ inArray(files.id, resolvedFileIds),
+ eq(files.userId, this.userId),
+ buildWorkspaceWhere(creatorScope, files),
+ ),
+ );
+
+ const documentLink =
+ documentIds.length > 0
+ ? or(inArray(documents.id, documentIds), inArray(documents.fileId, resolvedFileIds))
+ : inArray(documents.fileId, resolvedFileIds);
+
+ await this.db
+ .update(documents)
+ .set({ updatedAt: now, visibility: kb.visibility })
+ .where(
+ and(
+ documentLink,
+ eq(documents.userId, this.userId),
+ buildWorkspaceWhere(creatorScope, documents),
+ ),
+ );
+ }
+
return this.db
.insert(knowledgeBaseFiles)
.values(
@@ -193,9 +229,9 @@ export class KnowledgeBaseModel {
return data as KnowledgeBaseItem[];
};
- findById = async (id: string) => {
+ findById = async (id: string, callerAgentVisibility?: 'private' | 'public' | null) => {
return this.db.query.knowledgeBases.findFirst({
- where: and(eq(knowledgeBases.id, id), this.ownership()),
+ where: and(eq(knowledgeBases.id, id), this.ownership(callerAgentVisibility)),
});
};
@@ -233,28 +269,91 @@ export class KnowledgeBaseModel {
/**
* Flip a knowledge base's `visibility`. Bidirectional companion to
- * `publishToWorkspace`. The combined `user_id = ?` +
- * `visibility = fromVisibility` guards keep the operation creator-only and
- * idempotent against rows already at the target visibility.
+ * `publishToWorkspace`. The knowledge base is the visibility boundary for
+ * content created inside it, so creator-owned linked files and documents
+ * move with the library. Foreign public resources are deliberately left
+ * untouched — changing a library must never rewrite another member's rows.
*
- * Unpublishing is safe by design — this column only gates KB list
- * enumeration; other members lose the sidebar entry immediately, while
- * downstream RAG paths handle a missing/unreachable KB.
+ * The content reconciliation also runs when the KB already has the requested
+ * visibility. This repairs rows created by older clients that published the
+ * library without promoting its contents, while keeping the KB timestamp
+ * itself idempotent.
*/
setVisibility = async (id: string, visibility: 'private' | 'public') => {
- const fromVisibility = visibility === 'public' ? 'private' : 'public';
+ return this.db.transaction(async (trx) => {
+ const [knowledgeBase] = await trx
+ .select({ id: knowledgeBases.id, visibility: knowledgeBases.visibility })
+ .from(knowledgeBases)
+ .where(
+ and(eq(knowledgeBases.id, id), this.ownership(), eq(knowledgeBases.userId, this.userId)),
+ )
+ .limit(1);
- return this.db
- .update(knowledgeBases)
- .set({ updatedAt: new Date(), visibility })
- .where(
- and(
- eq(knowledgeBases.id, id),
- this.ownership(),
- eq(knowledgeBases.userId, this.userId),
- eq(knowledgeBases.visibility, fromVisibility),
- ),
- );
+ if (!knowledgeBase) return [];
+
+ const now = new Date();
+ const result =
+ knowledgeBase.visibility === visibility
+ ? []
+ : await trx
+ .update(knowledgeBases)
+ .set({ updatedAt: now, visibility })
+ .where(
+ and(
+ eq(knowledgeBases.id, id),
+ eq(knowledgeBases.userId, this.userId),
+ eq(knowledgeBases.visibility, knowledgeBase.visibility),
+ ),
+ )
+ .returning({ id: knowledgeBases.id });
+
+ const linkedFiles = await trx
+ .select({ id: knowledgeBaseFiles.fileId })
+ .from(knowledgeBaseFiles)
+ .where(eq(knowledgeBaseFiles.knowledgeBaseId, id));
+ const linkedFileIds = linkedFiles.map((file) => file.id);
+ const creatorScope = {
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ };
+
+ if (linkedFileIds.length > 0) {
+ await trx
+ .update(files)
+ .set({ updatedAt: now, visibility })
+ .where(
+ and(
+ inArray(files.id, linkedFileIds),
+ eq(files.userId, this.userId),
+ buildWorkspaceWhere(creatorScope, {
+ userId: files.userId,
+ workspaceId: files.workspaceId,
+ }),
+ ),
+ );
+ }
+
+ const documentLink =
+ linkedFileIds.length > 0
+ ? or(eq(documents.knowledgeBaseId, id), inArray(documents.fileId, linkedFileIds))
+ : eq(documents.knowledgeBaseId, id);
+
+ await trx
+ .update(documents)
+ .set({ updatedAt: now, visibility })
+ .where(
+ and(
+ documentLink,
+ eq(documents.userId, this.userId),
+ buildWorkspaceWhere(creatorScope, {
+ userId: documents.userId,
+ workspaceId: documents.workspaceId,
+ }),
+ ),
+ );
+
+ return result;
+ });
};
private resolveAvailableName = async (
diff --git a/packages/database/src/schemas/file.ts b/packages/database/src/schemas/file.ts
index 29f3d9ac7bb..0851039930d 100644
--- a/packages/database/src/schemas/file.ts
+++ b/packages/database/src/schemas/file.ts
@@ -130,9 +130,10 @@ export const documents = pgTable(
* workspace member can see the document; `private` constrains it to the
* creator (`user_id`). Within a documents tree (folder/Page hierarchy) the
* value is kept strongly consistent across the whole subtree by the service
- * layer — children mirror the root's visibility, and the only legal
- * transition is `private → public` via `publishToWorkspace`. Ignored in
- * personal mode where the row is implicitly private to its owner.
+ * layer — children mirror the root's visibility. Standalone pages publish
+ * via `private → public`; creator-owned pages inside a library synchronize
+ * bidirectionally with the library. Ignored in personal mode where the row
+ * is implicitly private to its owner.
*/
visibility: text('visibility', { enum: ['private', 'public'] })
.default('public')
@@ -211,9 +212,10 @@ export const files = pgTable(
/**
* Visibility within the owning workspace. `public` (default) means every
* workspace member can see the file; `private` constrains it to the
- * creator (`user_id`). The only legal transition is `private → public`
- * via `publishToWorkspace`. Ignored in personal mode (`workspace_id IS NULL`)
- * where the row is implicitly private to its owner.
+ * creator (`user_id`). Standalone files publish via `private → public`;
+ * creator-owned files inside a library synchronize bidirectionally with
+ * the library. Ignored in personal mode (`workspace_id IS NULL`) where the
+ * row is implicitly private to its owner.
*/
visibility: text('visibility', { enum: ['private', 'public'] })
.default('public')
@@ -278,9 +280,10 @@ export const knowledgeBases = pgTable(
* `private → public` via `publishKnowledgeBaseToWorkspace`. Ignored in
* personal mode (`workspace_id IS NULL`).
*
- * Independent of `isPublic` (marketplace discovery) and `files.visibility`
- * (file-level workspace visibility). This column only gates *KB list*
- * enumeration; retrieval via a known KB id still goes through `ownership()`.
+ * Independent of `isPublic` (marketplace discovery). Files and documents
+ * keep their own visibility columns for direct-resource authorization, but
+ * creator-owned rows inside a KB are synchronized to this value when the
+ * library is published or made private.
*/
visibility: text('visibility', { enum: KNOWLEDGE_BASE_VISIBILITY }).default('public').notNull(),
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index e8ffa1b9d80..da31bb26a1a 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -1,12 +1,16 @@
export default {
'channel.applicationId': 'Application ID / Bot Username',
'channel.applicationIdHint': 'Unique identifier for your bot application.',
+ 'channel.applicationIdInvalid.discord':
+ "Application ID must be the 17–20 digit ID on your Discord app's General Information page.",
'channel.applicationIdPlaceholder': 'e.g. 1234567890',
'channel.appSecret': 'App Secret',
'channel.appSecretPlaceholder': 'Paste your app secret here',
'channel.botToken': 'Bot Token / API Key',
'channel.botTokenEncryptedHint': 'Token will be encrypted and stored securely.',
'channel.botTokenHowToGet': 'How to get?',
+ 'channel.botTokenInvalid.discord':
+ 'This does not look like a Discord bot token. Reset and copy it from the Bot tab of your Discord app — it is three segments separated by dots.',
'channel.botTokenPlaceholderExisting': 'Token is hidden for security',
'channel.botTokenPlaceholderNew': 'Paste your bot token here',
'channel.connectionConfig': 'Connection Configuration',
@@ -193,8 +197,11 @@ export default {
'channel.openPlatform': 'Open Platform',
'channel.platforms': 'Platforms',
'channel.publicKey': 'Public Key',
- 'channel.publicKeyHint': 'Optional. Used to verify interaction requests from Discord.',
- 'channel.publicKeyPlaceholder': 'Required for interaction verification',
+ 'channel.publicKeyHint':
+ "Used to verify interaction requests from Discord. A 64-character hex string on your app's General Information page.",
+ 'channel.publicKeyInvalid':
+ "Public Key must be a 64-character hex string. Copy it from the Discord app's General Information page — not the OAuth URL, and not an API key.",
+ 'channel.publicKeyPlaceholder': '64-character hex string',
'channel.qq.appIdHint': 'Your QQ Bot App ID from QQ Open Platform',
'channel.qq.description': 'Connect this agent to QQ for group chats and direct messages.',
'channel.qq.webhookMigrationTitle': 'Consider migrating to WebSocket mode',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 281fcc13d81..b946ef5a450 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -2561,10 +2561,14 @@ When I am ___, I need ___
'workspace.members.pending.revokeFailed': 'Failed to revoke invitation',
'workspace.members.seatChange.memberJoinBlocked':
'Current members have reached the scheduled seat limit, so new paid members may not be able to join this workspace',
+ 'workspace.members.seatUsage_one': '{{used}} / {{capacity}} seat',
+ 'workspace.members.seatUsage_other': '{{used}} / {{capacity}} seats',
'workspace.members.subtitle': 'Manage workspace members and invitations',
'workspace.members.tabs.members': 'Team Members',
'workspace.members.tabs.pending': 'Pending Invitations',
'workspace.members.title': 'Members',
+ 'workspace.members.totalCount_one': '{{total}} member',
+ 'workspace.members.totalCount_other': '{{total}} members',
'workspace.name.placeholder': 'Workspace name',
'workspace.name.title': 'Name',
'workspace.newWorkspace': 'New Workspace',
diff --git a/scripts/backfillWorkspaceKnowledgeBaseVisibility.ts b/scripts/backfillWorkspaceKnowledgeBaseVisibility.ts
new file mode 100644
index 00000000000..540fce59027
--- /dev/null
+++ b/scripts/backfillWorkspaceKnowledgeBaseVisibility.ts
@@ -0,0 +1,178 @@
+import pg from 'pg';
+
+const { Pool } = pg;
+
+const DEFAULT_BATCH_SIZE = 100;
+
+const args = new Set(process.argv.slice(2));
+const apply = args.has('--apply');
+const batchSizeArg = process.argv.find((arg) => arg.startsWith('--batch-size='));
+const batchSize = batchSizeArg
+ ? Number.parseInt(batchSizeArg.slice('--batch-size='.length), 10)
+ : DEFAULT_BATCH_SIZE;
+
+if (!Number.isInteger(batchSize) || batchSize < 1 || batchSize > 1000) {
+ throw new Error('--batch-size must be an integer between 1 and 1000');
+}
+
+const connectionString = process.env.DATABASE_URL;
+if (!connectionString) throw new Error('DATABASE_URL is required');
+
+const pool = new Pool({ connectionString });
+
+const run = async () => {
+ let cursor = '';
+ let processedKnowledgeBases = 0;
+ let reconciledFiles = 0;
+ let reconciledDocuments = 0;
+
+ while (true) {
+ const client = await pool.connect();
+
+ try {
+ await client.query('BEGIN');
+
+ const knowledgeBaseResult = await client.query<{ id: string }>(
+ `
+ SELECT id
+ FROM knowledge_bases
+ WHERE workspace_id IS NOT NULL
+ AND visibility = 'public'
+ AND id > $1
+ ORDER BY id
+ LIMIT $2
+ FOR UPDATE SKIP LOCKED
+ `,
+ [cursor, batchSize],
+ );
+ const knowledgeBaseIds = knowledgeBaseResult.rows.map((row) => row.id);
+
+ if (knowledgeBaseIds.length === 0) {
+ await client.query('COMMIT');
+ break;
+ }
+
+ const fileResult = apply
+ ? await client.query(
+ `
+ UPDATE files AS f
+ SET visibility = 'public', updated_at = NOW()
+ FROM knowledge_base_files AS kbf
+ INNER JOIN knowledge_bases AS kb ON kb.id = kbf.knowledge_base_id
+ WHERE kb.id = ANY($1::text[])
+ AND kb.workspace_id IS NOT NULL
+ AND kb.visibility = 'public'
+ AND f.id = kbf.file_id
+ AND f.user_id = kb.user_id
+ AND f.workspace_id = kb.workspace_id
+ AND f.visibility IS DISTINCT FROM 'public'
+ RETURNING f.id
+ `,
+ [knowledgeBaseIds],
+ )
+ : await client.query(
+ `
+ SELECT f.id
+ FROM files AS f
+ INNER JOIN knowledge_base_files AS kbf ON kbf.file_id = f.id
+ INNER JOIN knowledge_bases AS kb ON kb.id = kbf.knowledge_base_id
+ WHERE kb.id = ANY($1::text[])
+ AND kb.workspace_id IS NOT NULL
+ AND kb.visibility = 'public'
+ AND f.user_id = kb.user_id
+ AND f.workspace_id = kb.workspace_id
+ AND f.visibility IS DISTINCT FROM 'public'
+ `,
+ [knowledgeBaseIds],
+ );
+
+ const documentResult = apply
+ ? await client.query(
+ `
+ UPDATE documents AS d
+ SET visibility = 'public', updated_at = NOW()
+ FROM knowledge_bases AS kb
+ WHERE kb.id = ANY($1::text[])
+ AND kb.workspace_id IS NOT NULL
+ AND kb.visibility = 'public'
+ AND d.user_id = kb.user_id
+ AND d.workspace_id = kb.workspace_id
+ AND d.visibility IS DISTINCT FROM 'public'
+ AND (
+ d.knowledge_base_id = kb.id
+ OR EXISTS (
+ SELECT 1
+ FROM knowledge_base_files AS kbf
+ WHERE kbf.knowledge_base_id = kb.id
+ AND kbf.file_id = d.file_id
+ )
+ )
+ RETURNING d.id
+ `,
+ [knowledgeBaseIds],
+ )
+ : await client.query(
+ `
+ SELECT d.id
+ FROM documents AS d
+ INNER JOIN knowledge_bases AS kb
+ ON d.knowledge_base_id = kb.id
+ OR EXISTS (
+ SELECT 1
+ FROM knowledge_base_files AS kbf
+ WHERE kbf.knowledge_base_id = kb.id
+ AND kbf.file_id = d.file_id
+ )
+ WHERE kb.id = ANY($1::text[])
+ AND kb.workspace_id IS NOT NULL
+ AND kb.visibility = 'public'
+ AND d.user_id = kb.user_id
+ AND d.workspace_id = kb.workspace_id
+ AND d.visibility IS DISTINCT FROM 'public'
+ `,
+ [knowledgeBaseIds],
+ );
+
+ await client.query('COMMIT');
+
+ processedKnowledgeBases += knowledgeBaseIds.length;
+ reconciledFiles += fileResult.rowCount ?? 0;
+ reconciledDocuments += documentResult.rowCount ?? 0;
+ cursor = knowledgeBaseIds.at(-1)!;
+
+ console.log(
+ JSON.stringify({
+ apply,
+ cursor,
+ processedKnowledgeBases,
+ reconciledDocuments,
+ reconciledFiles,
+ }),
+ );
+ } catch (error) {
+ await client.query('ROLLBACK');
+ throw error;
+ } finally {
+ client.release();
+ }
+ }
+
+ console.log(
+ JSON.stringify({
+ apply,
+ complete: true,
+ processedKnowledgeBases,
+ reconciledDocuments,
+ reconciledFiles,
+ }),
+ );
+};
+
+run()
+ .catch((error) => {
+ console.error(error);
+ process.exitCode = 1;
+ })
+ .finally(async () => {
+ await pool.end();
+ });
diff --git a/src/features/ChatInput/ActionBar/Search/Controls.tsx b/src/features/ChatInput/ActionBar/Search/Controls.tsx
index 927511085a6..f5bb76262b4 100644
--- a/src/features/ChatInput/ActionBar/Search/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/Search/Controls.tsx
@@ -128,7 +128,10 @@ const Controls = memo(() => {
useEffect(() => {
if (!canCreate) return;
if (isModelBuiltinSearchInternal && (searchMode ?? 'auto') === 'off') {
- updateAgentChatConfig({ searchMode: 'auto' });
+ // Auto-correction for a model whose search can't be turned off — the user
+ // didn't touch the toggle, so a rejected write must stay silent instead of
+ // reporting a change they never made (LOBE-12459).
+ updateAgentChatConfig({ searchMode: 'auto' }, { showErrorMessage: false });
}
}, [canCreate, isModelBuiltinSearchInternal, searchMode, updateAgentChatConfig]);
diff --git a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
index d15dfe93518..b4a4067b162 100644
--- a/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroDeviceSwitcher.tsx
@@ -421,7 +421,9 @@ const HeteroDeviceSwitcher = memo<HeteroDeviceSwitcherProps>(({ agentId }) => {
if (agencyConfig?.executionTarget !== undefined) return;
if (agencyConfig?.boundDeviceId !== undefined) return;
if (!currentDeviceId) return;
- void selectExecutionTarget('local');
+ // `silent`: this is a mount-time default, so a rejected write must not
+ // surface a save-failure toast on an agent the user only opened.
+ void selectExecutionTarget('local', undefined, { silent: true });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
agencyConfig?.executionTarget,
diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
index 55b6c734f05..332f6f530a7 100644
--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.test.ts
@@ -149,6 +149,36 @@ describe('useSelectExecutionTarget', () => {
});
});
+ // LOBE-12459: the device switcher defaults an unset target to `local` on
+ // mount. In a workspace that write can be rejected (edit lock / resource
+ // access), and the generic failure toast then claims the user's change was
+ // not applied — on an agent they only opened, having changed nothing.
+ it('suppresses the failure toast when the target is being defaulted automatically', async () => {
+ testState.isDesktop = true;
+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('local', undefined, { silent: true });
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
+ 'agent-id',
+ { agencyConfig: { boundDeviceId: 'this-machine', executionTarget: 'local' } },
+ { showErrorMessage: false },
+ );
+ });
+
+ it("keeps the failure toast for a user's own pick", async () => {
+ testState.isDesktop = true;
+ testState.electron.gatewayDeviceInfo = { deviceId: 'this-machine' };
+ const { result } = renderHook(() => useSelectExecutionTarget('agent-id'));
+
+ await result.current('local');
+
+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {
+ agencyConfig: { boundDeviceId: 'this-machine', executionTarget: 'local' },
+ });
+ });
+
it('does not switch a heterogeneous agent to local when no device can be resolved', async () => {
testState.agent.isHetero = true;
testState.getDeviceInfo.mockRejectedValue(new Error('no gateway'));
diff --git a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
index e8013a64f74..509c6a2c5d3 100644
--- a/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
+++ b/src/features/ChatInput/hooks/useSelectExecutionTarget.ts
@@ -11,6 +11,15 @@ import { agentByIdSelectors } from '@/store/agent/selectors';
import { useElectronStore } from '@/store/electron';
import { useUserStore } from '@/store/user';
+export interface SelectExecutionTargetOptions {
+ /**
+ * The call is an automatic default (agent has no target yet), not a user's
+ * pick. Persistence failures stay silent — a generic "your change was not
+ * applied" toast would be about a change the user never made.
+ */
+ silent?: boolean;
+}
+
/**
* Persist an execution-target selection for an agent. Shared by the device
* switcher and the sandbox notice so the `local` device-id resolution (which
@@ -65,7 +74,11 @@ export const useSelectExecutionTarget = (agentId: string) => {
const currentDeviceId = isDesktop ? gatewayDeviceInfo?.deviceId : undefined;
return useCallback(
- async (target: DeviceExecutionTarget, deviceId?: string) => {
+ async (
+ target: DeviceExecutionTarget,
+ deviceId?: string,
+ options?: SelectExecutionTargetOptions,
+ ) => {
if (isAccessLoading) return;
// Fixed workspace agents are author-controlled. Keep any existing member
@@ -116,13 +129,23 @@ export const useSelectExecutionTarget = (agentId: string) => {
return;
}
- await updateAgentConfigById(agentId, {
+ const nextConfig = {
agencyConfig: {
...agencyConfig,
executionTarget: target,
...(nextBoundDeviceId ? { boundDeviceId: nextBoundDeviceId } : {}),
},
- });
+ };
+
+ // A silent caller is defaulting the target on mount, not answering a
+ // pick — telling the user "your change was not applied" would be
+ // reporting a change they never made (LOBE-12459).
+ if (options?.silent) {
+ await updateAgentConfigById(agentId, nextConfig, { showErrorMessage: false });
+ return;
+ }
+
+ await updateAgentConfigById(agentId, nextConfig);
},
[
agentId,
diff --git a/src/features/ChatInput/hooks/useUpdateAgentConfig.ts b/src/features/ChatInput/hooks/useUpdateAgentConfig.ts
index a75881d0544..1a12b9de7b2 100644
--- a/src/features/ChatInput/hooks/useUpdateAgentConfig.ts
+++ b/src/features/ChatInput/hooks/useUpdateAgentConfig.ts
@@ -25,8 +25,11 @@ export const useUpdateAgentConfig = () => {
);
const updateAgentChatConfig = useCallback(
- (config: Partial<LobeAgentChatConfig>) => {
- return updateAgentChatConfigById(agentId, config);
+ (
+ config: Partial<LobeAgentChatConfig>,
+ options?: Parameters<typeof updateAgentChatConfigById>[2],
+ ) => {
+ return updateAgentChatConfigById(agentId, config, options);
},
[agentId, updateAgentChatConfigById],
);
diff --git a/src/features/PageEditor/PageEditor.test.tsx b/src/features/PageEditor/PageEditor.test.tsx
index 5e26227b1f0..6945639821c 100644
--- a/src/features/PageEditor/PageEditor.test.tsx
+++ b/src/features/PageEditor/PageEditor.test.tsx
@@ -2,6 +2,18 @@ import { renderHook } from '@testing-library/react';
import { useEffect } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { getTitleTextAreaInteractionProps } from './TitleSection';
+
+describe('PageEditor title interaction', () => {
+ it('keeps a non-editable title visually enabled but read-only', () => {
+ const props = getTitleTextAreaInteractionProps(false);
+
+ expect(props).toEqual({ readOnly: true });
+ expect(props).not.toHaveProperty('disabled');
+ expect(getTitleTextAreaInteractionProps(true)).toEqual({ readOnly: false });
+ });
+});
+
describe('PageEditor beforeunload handler', () => {
let addEventListenerSpy: ReturnType<typeof vi.spyOn>;
let removeEventListenerSpy: ReturnType<typeof vi.spyOn>;
diff --git a/src/features/PageEditor/TitleSection.tsx b/src/features/PageEditor/TitleSection.tsx
index e4582387296..638ebbe188e 100644
--- a/src/features/PageEditor/TitleSection.tsx
+++ b/src/features/PageEditor/TitleSection.tsx
@@ -17,6 +17,10 @@ import { truncateByWeightedLength } from '@/utils/textLength';
import { usePageEditorStore } from './store';
import { usePageEditable } from './usePageEditable';
+export const getTitleTextAreaInteractionProps = (canEdit: boolean) => ({
+ readOnly: !canEdit,
+});
+
const TitleSection = memo(() => {
const { t } = useTranslation('file');
const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);
@@ -114,8 +118,8 @@ const TitleSection = memo(() => {
) : (
<TextArea
autoSize={{ minRows: 1 }}
- disabled={!canEdit}
placeholder={t('pageEditor.titlePlaceholder')}
+ {...getTitleTextAreaInteractionProps(canEdit)}
value={title}
variant={'borderless'}
style={{
diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsx
index 9d21870d67d..cb78746e9af 100644
--- a/src/features/ProfileEditor/AgentTool.tsx
+++ b/src/features/ProfileEditor/AgentTool.tsx
@@ -1,7 +1,7 @@
'use client';
import { COMPOSIO_APP_TYPES, LOBEHUB_SKILL_PROVIDERS } from '@lobechat/const';
-import { getActivePluginIds, parsePluginEntry, upsertPluginMode } from '@lobechat/types';
+import { getActivePluginIds, upsertPluginMode } from '@lobechat/types';
import type { ItemType } from '@lobehub/ui';
import { Avatar, Flexbox, Icon } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
@@ -23,6 +23,7 @@ import MarketAgentSkillPopoverContent from '@/features/ChatInput/ActionBar/Tools
import MarketSkillIcon from '@/features/ChatInput/ActionBar/Tools/MarketSkillIcon';
import ToolItem from '@/features/ChatInput/ActionBar/Tools/ToolItem';
import ToolItemDetailPopover from '@/features/ChatInput/ActionBar/Tools/ToolItemDetailPopover';
+import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { createSkillStoreModal } from '@/features/SkillStore';
import { useCheckPluginsIsInstalled } from '@/hooks/useCheckPluginsIsInstalled';
import { useFetchInstalledPlugins } from '@/hooks/useFetchInstalledPlugins';
@@ -43,6 +44,7 @@ import { connectorSelectors } from '@/store/tool/slices/connector';
import PluginTag from './PluginTag';
import PopoverContent from './PopoverContent';
import { getVisibleProfileToolIds } from './profileToolVisibility';
+import { resolveStalePluginCleanup } from './staleProfilePlugins';
export interface AgentToolProps {
/**
@@ -95,6 +97,17 @@ const AgentTool = memo<AgentToolProps>(
const effectiveAgentId = agentId || activeAgentId || '';
const config = useAgentStore(agentSelectors.getAgentConfigById(effectiveAgentId), isEqual);
const isManualSkillMode = config?.chatConfig?.skillActivateMode === 'manual';
+ // Workspace General access on this agent. A private agent is creator-only and
+ // has no shared access row, so skip the query for it (same shape as the
+ // prompt editor's gate). Only the automatic stale-plugin cleanup below reads
+ // this — the visible controls keep their own `canEdit` gating.
+ const isPrivateAgent = useAgentStore(
+ (s) => s.agentMap[effectiveAgentId]?.visibility === 'private',
+ );
+ const { canEditResource, isAccessResolved } = useResourceAccess(
+ 'agent',
+ isPrivateAgent ? undefined : effectiveAgentId || undefined,
+ );
// Plugin state management — pinned identifiers only (a disabled entry
// is a distinct, valid config state; this component has no tri-state UI
@@ -759,35 +772,35 @@ const AgentTool = memo<AgentToolProps>(
// Uses a short debounce to allow async data (SWR) to complete loading
useEffect(() => {
if (cleanupDoneRef.current) return;
- if (validIdentifiers.size === 0) return;
- const rawPlugins = config?.plugins ?? [];
- if (rawPlugins.length === 0) return;
- // Don't prune until the connector store has loaded — connector identifiers
- // are absent from validIdentifiers until fetchConnectors() resolves, so
- // running cleanup before that would incorrectly mark enabled connectors as stale.
- if (!isConnectorsInit) return;
// Defer cleanup to avoid race with async data loading (SWR, Composio, etc.)
const timer = setTimeout(() => {
- // Checked (and filtered) by identifier regardless of entry shape, so
- // a stale disabled/pinned object entry is pruned exactly like a
- // stale legacy string one — untouched valid entries keep their
- // original shape (lazy per-item upgrade).
- const isValid = (entry: (typeof rawPlugins)[number]) =>
- validIdentifiers.has(parsePluginEntry(entry).identifier);
- const hasStale = rawPlugins.some((entry) => !isValid(entry));
-
- if (hasStale && effectiveAgentId) {
- const cleanedPlugins = rawPlugins.filter(isValid);
- updateAgentConfigById(effectiveAgentId, { plugins: cleanedPlugins });
- }
+ const cleanedPlugins = resolveStalePluginCleanup({
+ canEditContent: canEdit,
+ canEditResource,
+ isAccessResolved,
+ isConnectorsInit,
+ plugins: config?.plugins,
+ validIdentifiers,
+ });
- cleanupDoneRef.current = true;
+ if (cleanedPlugins && effectiveAgentId) {
+ // Best-effort self-healing the user never asked for, so a rejection
+ // (edit lock held by another member, resource access revoked between
+ // render and write) must not claim "your change was not applied" —
+ // there was no change to apply. It retries on the next open.
+ updateAgentConfigById(
+ effectiveAgentId,
+ { plugins: cleanedPlugins },
+ { showErrorMessage: false },
+ );
+ cleanupDoneRef.current = true;
+ }
}, 500);
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [validIdentifiers]);
+ }, [validIdentifiers, canEdit, canEditResource, isAccessResolved, isConnectorsInit]);
// Only display tools that this profile surface actually manages. Runtime-
// managed entries remain untouched in config for compatibility with other
diff --git a/src/features/ProfileEditor/staleProfilePlugins.test.ts b/src/features/ProfileEditor/staleProfilePlugins.test.ts
new file mode 100644
index 00000000000..d3135ffbc61
--- /dev/null
+++ b/src/features/ProfileEditor/staleProfilePlugins.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveStalePluginCleanup, type StalePluginCleanupInput } from './staleProfilePlugins';
+
+const baseInput = (overrides: Partial<StalePluginCleanupInput> = {}): StalePluginCleanupInput => ({
+ canEditContent: true,
+ canEditResource: true,
+ isAccessResolved: true,
+ isConnectorsInit: true,
+ plugins: ['web-search', 'ghost-tool'],
+ validIdentifiers: new Set(['web-search']),
+ ...overrides,
+});
+
+describe('resolveStalePluginCleanup', () => {
+ it('drops entries whose identifier no longer resolves', () => {
+ expect(resolveStalePluginCleanup(baseInput())).toEqual(['web-search']);
+ });
+
+ it('keeps the original entry shape for surviving entries', () => {
+ const result = resolveStalePluginCleanup(
+ baseInput({
+ plugins: [{ identifier: 'web-search', mode: 'disabled' }, 'ghost-tool'],
+ }),
+ );
+
+ expect(result).toEqual([{ identifier: 'web-search', mode: 'disabled' }]);
+ });
+
+ it('returns null when nothing is stale, so no write is fired', () => {
+ expect(
+ resolveStalePluginCleanup(
+ baseInput({ plugins: ['web-search'], validIdentifiers: new Set(['web-search']) }),
+ ),
+ ).toBeNull();
+ });
+
+ it('returns null before the connector store has loaded', () => {
+ expect(resolveStalePluginCleanup(baseInput({ isConnectorsInit: false }))).toBeNull();
+ });
+
+ it('returns null when no identifiers are known yet', () => {
+ expect(resolveStalePluginCleanup(baseInput({ validIdentifiers: new Set() }))).toBeNull();
+ });
+
+ it('returns null for an agent with no plugins', () => {
+ expect(resolveStalePluginCleanup(baseInput({ plugins: undefined }))).toBeNull();
+ expect(resolveStalePluginCleanup(baseInput({ plugins: [] }))).toBeNull();
+ });
+
+ // LOBE-12459: the cleanup is automatic, so firing it without edit access made
+ // the server reject `agent.updateAgentConfig`; because the rejected write never
+ // persists, it fired and failed again on every open, toasting "Failed to save
+ // agent settings" on an agent the member had only opened.
+ describe('permission gate (LOBE-12459)', () => {
+ it('does not clean up when the workspace role cannot edit content', () => {
+ expect(resolveStalePluginCleanup(baseInput({ canEditContent: false }))).toBeNull();
+ });
+
+ it('does not clean up when General access on this agent is below edit', () => {
+ expect(resolveStalePluginCleanup(baseInput({ canEditResource: false }))).toBeNull();
+ });
+
+ it('fails closed while workspace access is still resolving', () => {
+ expect(
+ resolveStalePluginCleanup(
+ // `canEditResource` defaults permissive during loading, so the
+ // resolved flag is what keeps the doomed write from being fired.
+ baseInput({ canEditResource: true, isAccessResolved: false }),
+ ),
+ ).toBeNull();
+ });
+ });
+});
diff --git a/src/features/ProfileEditor/staleProfilePlugins.ts b/src/features/ProfileEditor/staleProfilePlugins.ts
new file mode 100644
index 00000000000..c647dca1132
--- /dev/null
+++ b/src/features/ProfileEditor/staleProfilePlugins.ts
@@ -0,0 +1,68 @@
+import { type AgentPluginEntry, parsePluginEntry } from '@lobechat/types';
+
+export interface StalePluginCleanupInput {
+ /**
+ * Workspace role permits editing own content (`edit_own_content`). Personal
+ * mode is always `true`.
+ */
+ canEditContent: boolean;
+ /**
+ * Workspace General access on this agent resolves to "may edit". Defaults
+ * permissive outside a workspace.
+ */
+ canEditResource: boolean;
+ /**
+ * The workspace access query has settled. Cleanup waits for it rather than
+ * running on the permissive loading default.
+ */
+ isAccessResolved: boolean;
+ /**
+ * Connector identifiers are absent from `validIdentifiers` until
+ * `fetchConnectors()` resolves, so pruning before that would mark enabled
+ * connectors as stale.
+ */
+ isConnectorsInit: boolean;
+ plugins: AgentPluginEntry[] | undefined;
+ validIdentifiers: ReadonlySet<string>;
+}
+
+/**
+ * Decide whether the agent profile should silently drop plugin entries whose
+ * identifier no longer resolves to any known tool, and to what.
+ *
+ * Returns the cleaned list when a write is warranted, or `null` to leave the
+ * config alone.
+ *
+ * The permission inputs matter as much as the staleness ones (LOBE-12459): this
+ * cleanup is automatic, so in a workspace a caller without resource edit access
+ * would fire an `agent.updateAgentConfig` the server rejects — and because the
+ * rejected write never persists, it would fire and fail again on *every* open,
+ * surfacing "Failed to save agent settings" on an agent the user only viewed.
+ * Fail closed while access is still resolving.
+ */
+export const resolveStalePluginCleanup = ({
+ canEditContent,
+ canEditResource,
+ isAccessResolved,
+ isConnectorsInit,
+ plugins,
+ validIdentifiers,
+}: StalePluginCleanupInput): AgentPluginEntry[] | null => {
+ if (!canEditContent || !isAccessResolved || !canEditResource) return null;
+ if (!isConnectorsInit) return null;
+ if (validIdentifiers.size === 0) return null;
+
+ const rawPlugins = plugins ?? [];
+ if (rawPlugins.length === 0) return null;
+
+ // Checked (and filtered) by identifier regardless of entry shape, so a stale
+ // disabled/pinned object entry is pruned exactly like a stale legacy string
+ // one — untouched valid entries keep their original shape (lazy per-item
+ // upgrade).
+ const isValid = (entry: AgentPluginEntry) =>
+ validIdentifiers.has(parsePluginEntry(entry).identifier);
+
+ if (rawPlugins.every(isValid)) return null;
+
+ return rawPlugins.filter(isValid);
+};
diff --git a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx
index b4124f72857..6252d8c34bb 100644
--- a/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx
+++ b/src/features/ResourceManager/components/Explorer/SearchResultsOverlay.tsx
@@ -14,6 +14,7 @@ import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { useClientDataSWR } from '@/libs/swr';
import { resourceKeys } from '@/libs/swr/keys';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
+import { getResourceQueryVisibility } from '@/routes/(main)/resource/features/store/selectors';
import { resourceService } from '@/services/resource';
import { useGlobalStore } from '@/store/global';
import {
@@ -48,8 +49,8 @@ const SearchResultsOverlay = memo(() => {
// Personal account has only one uploader (the user themselves), so hide the
// column entirely there — it only makes sense in a workspace with multiple members.
const activeWorkspaceId = useActiveWorkspaceId();
- const showUploader = !!activeWorkspaceId && listVisibility !== 'private';
- const visibility = listVisibility === 'private' ? ('private' as const) : ('public' as const);
+ const showUploader = !!activeWorkspaceId && (!!libraryId || listVisibility !== 'private');
+ const visibility = getResourceQueryVisibility(libraryId, listVisibility);
const {
data: rawData,
@@ -67,7 +68,7 @@ const SearchResultsOverlay = memo(() => {
: null,
async ([, params]: [
string,
- { category?: string; libraryId?: string; q: string; visibility: 'private' | 'public' },
+ { category?: string; libraryId?: string; q: string; visibility?: 'private' | 'public' },
]) => {
const response = await resourceService.queryResources({
...params,
diff --git a/src/features/ResourceManager/components/Explorer/index.test.tsx b/src/features/ResourceManager/components/Explorer/index.test.tsx
index 2171e661942..6df41116bd4 100644
--- a/src/features/ResourceManager/components/Explorer/index.test.tsx
+++ b/src/features/ResourceManager/components/Explorer/index.test.tsx
@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({
resourceManagerState: {
category: 'all' as FilesTabs,
libraryId: undefined as string | undefined,
+ listVisibility: 'private' as const,
searchQuery: null as string | null,
sorter: 'createdAt' as const,
sortType: 'desc' as SortType,
@@ -32,6 +33,10 @@ vi.mock('@/routes/(main)/resource/features/store', () => ({
}));
vi.mock('@/routes/(main)/resource/features/store/selectors', () => ({
+ getResourceQueryVisibility: (
+ libraryId: string | undefined,
+ visibility: 'private' | 'workspace',
+ ) => (libraryId ? undefined : visibility === 'private' ? 'private' : 'public'),
sortFileList: (items: unknown[]) => items,
}));
@@ -77,6 +82,7 @@ describe('ResourceExplorer', () => {
vi.clearAllMocks();
mocks.resourceManagerState.category = FilesTabs.All;
mocks.resourceManagerState.libraryId = undefined;
+ mocks.resourceManagerState.listVisibility = 'private';
mocks.resourceManagerState.searchQuery = null;
mocks.resourceManagerState.sorter = 'createdAt';
mocks.resourceManagerState.sortType = SortType.Desc;
@@ -96,4 +102,18 @@ describe('ResourceExplorer', () => {
}),
);
});
+
+ it('does not reuse the resource-home visibility filter inside a library', () => {
+ mocks.resourceManagerState.libraryId = 'kb-shared';
+ mocks.resourceManagerState.listVisibility = 'private';
+
+ render(<ResourceExplorer />);
+
+ expect(mocks.useFetchResources).toHaveBeenCalledWith(
+ expect.objectContaining({
+ libraryId: 'kb-shared',
+ visibility: undefined,
+ }),
+ );
+ });
});
diff --git a/src/features/ResourceManager/components/Explorer/index.tsx b/src/features/ResourceManager/components/Explorer/index.tsx
index 493edda4794..f48296b2d6f 100644
--- a/src/features/ResourceManager/components/Explorer/index.tsx
+++ b/src/features/ResourceManager/components/Explorer/index.tsx
@@ -7,7 +7,10 @@ import AsyncBoundary from '@/components/AsyncBoundary';
import { useFolderPath } from '@/routes/(main)/resource/features/hooks/useFolderPath';
import { useResourceManagerUrlSync } from '@/routes/(main)/resource/features/hooks/useResourceManagerUrlSync';
import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';
-import { sortFileList } from '@/routes/(main)/resource/features/store/selectors';
+import {
+ getResourceQueryVisibility,
+ sortFileList,
+} from '@/routes/(main)/resource/features/store/selectors';
import { useFetchResources, useResourceStore } from '@/store/file/slices/resource/hooks';
import { KnowledgeBaseListProvider } from '../KnowledgeBaseListProvider';
@@ -57,10 +60,10 @@ const ResourceExplorer = memo(() => {
showFilesInKnowledgeBase: false,
sortType,
sorter,
- // Two-mode narrowing: `'private'` shows own private rows, `'workspace'`
- // shows public rows. Personal mode ignores the value server-side so
- // sending it there is a harmless no-op.
- visibility: listVisibility === 'private' ? ('private' as const) : ('public' as const),
+ // The two-mode narrowing belongs to the resource home. A concrete
+ // library supplies its own visibility boundary and must not inherit the
+ // user's last home filter.
+ visibility: getResourceQueryVisibility(libraryId, listVisibility),
}),
[category, libraryId, currentFolderSlug, sortType, sorter, listVisibility],
);
diff --git a/src/features/ResourceManager/hooks/useTopLevelFileUpload.ts b/src/features/ResourceManager/hooks/useTopLevelFileUpload.ts
index acc3277a1e0..6767004966d 100644
--- a/src/features/ResourceManager/hooks/useTopLevelFileUpload.ts
+++ b/src/features/ResourceManager/hooks/useTopLevelFileUpload.ts
@@ -16,8 +16,8 @@ import { useFileStore } from '@/store/file';
* mode picks visibility (`'private'` → private drawer, `'workspace'` →
* team share). No modal, no prompt.
* - **inside a library or folder**: leave visibility `undefined`; the server
- * inherits the parent document's visibility so a private folder's uploads
- * stay private, and a workspace folder's uploads stay workspace-shared.
+ * resolves it from the parent document or library boundary so uploads stay
+ * in the same private/workspace-visible scope.
* - **personal mode** (no `activeWorkspaceId`): also `undefined`; personal
* rows have no visibility column semantics.
*/
diff --git a/src/routes/(main)/agent/channel/detail/Body.tsx b/src/routes/(main)/agent/channel/detail/Body.tsx
index 47ed05f0fbc..d68ee046bf0 100644
--- a/src/routes/(main)/agent/channel/detail/Body.tsx
+++ b/src/routes/(main)/agent/channel/detail/Body.tsx
@@ -124,6 +124,15 @@ function buildRules(field: FieldSchema, t: (key: string) => string) {
rules.push({ message: t(field.label), required: true });
}
+ // Format constraint declared by the platform schema. antd's validator skips
+ // `pattern` on empty values, so an untouched optional field stays valid.
+ if (field.pattern) {
+ rules.push({
+ message: field.patternMessage ? t(field.patternMessage) : t(field.label),
+ pattern: new RegExp(field.pattern),
+ });
+ }
+
if (field.type === 'number' || field.type === 'integer') {
if (typeof field.minimum === 'number') {
rules.push({
@@ -456,7 +465,7 @@ const ApplicationIdField = memo<{ disabled?: boolean; divider?: boolean; field:
label={renderFieldLabel(field, t)}
minWidth={'max(50%, 400px)'}
name="applicationId"
- rules={field.required ? [{ message: t(field.label), required: true }] : undefined}
+ rules={buildRules(field, t)}
variant="outlined"
>
<FormInput
diff --git a/src/routes/(main)/home/features/AgentSelect/AgentList.tsx b/src/routes/(main)/home/features/AgentSelect/AgentList.tsx
index f8f9feb0bb9..84ec6425779 100644
--- a/src/routes/(main)/home/features/AgentSelect/AgentList.tsx
+++ b/src/routes/(main)/home/features/AgentSelect/AgentList.tsx
@@ -1,19 +1,19 @@
'use client';
-import { type SidebarAgentItem } from '@lobechat/types';
-import { Avatar, Block, Flexbox, Text } from '@lobehub/ui';
+import { ActionIcon, Avatar, Block, Flexbox, Text } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import { memo, useMemo } from 'react';
+import { PinIcon } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
-import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';
+import { DEFAULT_AVATAR } from '@/const/meta';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
-import { useAgentStore } from '@/store/agent';
-import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
+import { type AgentRow, useHomeAgentRows } from './useHomeAgentRows';
+
const styles = createStaticStyles(({ css, cssVar }) => ({
active: css`
background: ${cssVar.colorFillTertiary};
@@ -31,6 +31,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
list: css`
padding: 8px;
`,
+ sectionHeader: css`
+ padding-block: 4px;
+ padding-inline: 8px;
+ line-height: 20px;
+ `,
}));
interface AgentListProps {
@@ -41,61 +46,60 @@ interface AgentListProps {
onSelect: (agentId: string) => void;
}
-interface AgentRow {
- avatar?: string;
- backgroundColor?: string;
- id: string;
- title: string;
-}
+// Same spec as the agent-detail SwitchPanel's section header.
+const SectionHeader = memo<{ children: ReactNode }>(({ children }) => (
+ <Flexbox className={styles.sectionHeader}>
+ <Text fontSize={12} type={'secondary'} weight={500}>
+ {children}
+ </Text>
+ </Flexbox>
+));
const AgentList = memo<AgentListProps>(({ activeAgentId, error, onRetry, onSelect }) => {
- const { t } = useTranslation('chat');
+ const { t } = useTranslation('common');
const isInit = useHomeStore(homeAgentListSelectors.isAgentListInit);
- const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
- const inboxMeta = useAgentStore(agentSelectors.getAgentMetaById(inboxAgentId ?? ''));
- const allAgents = useHomeStore(homeAgentListSelectors.allAgents);
-
- // Flat list: inbox first, then all sidebar agents (pinned + grouped + ungrouped)
- // de-duplicated by id (an agent can show in multiple buckets via grouping).
- const rows = useMemo<AgentRow[]>(() => {
- const seen = new Set<string>();
- const out: AgentRow[] = [];
+ const { privateRows, showPrivateSection, workspaceRows } = useHomeAgentRows();
- if (inboxAgentId) {
- out.push({
- avatar:
- (typeof inboxMeta?.avatar === 'string' ? inboxMeta.avatar : undefined) ??
- DEFAULT_INBOX_AVATAR,
- backgroundColor: inboxMeta?.backgroundColor || undefined,
- id: inboxAgentId,
- title: inboxMeta?.title || 'Lobe AI',
- });
- seen.add(inboxAgentId);
- }
-
- for (const item of allAgents as SidebarAgentItem[]) {
- // Skip chat groups — sendMessage / agent config lookups expect an agent id.
- // Groups go through their own chat-group flow under /group/:gid.
- if (item.type !== 'agent') continue;
- if (seen.has(item.id)) continue;
- seen.add(item.id);
- out.push({
- avatar: typeof item.avatar === 'string' ? item.avatar : undefined,
- backgroundColor: item.backgroundColor || undefined,
- id: item.id,
- title: item.title || t('untitledAgent'),
- });
- }
-
- return out;
- }, [inboxAgentId, inboxMeta, allAgents, t]);
+ const renderRow = (row: AgentRow) => {
+ const isActive = row.id === activeAgentId;
+ return (
+ <Block
+ clickable
+ horizontal
+ align={'center'}
+ className={`${styles.item} ${isActive ? styles.active : ''}`}
+ gap={8}
+ key={row.id}
+ variant={'borderless'}
+ onClick={() => onSelect(row.id)}
+ >
+ <Avatar
+ avatar={row.avatar || DEFAULT_AVATAR}
+ background={row.backgroundColor}
+ shape={'square'}
+ size={24}
+ />
+ <Text
+ ellipsis
+ color={isActive ? cssVar.colorText : cssVar.colorTextSecondary}
+ style={{ flex: 1 }}
+ weight={isActive ? 600 : 500}
+ >
+ {row.title}
+ </Text>
+ {row.pinned && (
+ <ActionIcon icon={PinIcon} size={12} style={{ opacity: 0.5, pointerEvents: 'none' }} />
+ )}
+ </Block>
+ );
+ };
// Error gated ahead of the skeleton so a failed list fetch shows Retry instead
// of a permanent skeleton (`isAgentListInit` only flips on success).
return (
<AsyncBoundary
- data={isInit ? allAgents : undefined}
+ data={isInit ? workspaceRows : undefined}
error={error}
errorVariant={'block'}
isLoading={!isInit && !error}
@@ -107,36 +111,16 @@ const AgentList = memo<AgentListProps>(({ activeAgentId, error, onRetry, onSelec
gap={2}
style={{ maxHeight: 360, overflowY: 'auto', width: '100%' }}
>
- {rows.map((row) => {
- const isActive = row.id === activeAgentId;
- return (
- <Block
- clickable
- horizontal
- align={'center'}
- className={`${styles.item} ${isActive ? styles.active : ''}`}
- gap={8}
- key={row.id}
- variant={'borderless'}
- onClick={() => onSelect(row.id)}
- >
- <Avatar
- avatar={row.avatar || DEFAULT_AVATAR}
- background={row.backgroundColor}
- shape={'square'}
- size={24}
- />
- <Text
- ellipsis
- color={isActive ? cssVar.colorText : cssVar.colorTextSecondary}
- style={{ flex: 1 }}
- weight={isActive ? 600 : 500}
- >
- {row.title}
- </Text>
- </Block>
- );
- })}
+ {showPrivateSection ? (
+ <>
+ <SectionHeader>{t('navPanel.privateAgents')}</SectionHeader>
+ {privateRows.map(renderRow)}
+ <SectionHeader>{t('navPanel.publicAgents')}</SectionHeader>
+ {workspaceRows.map(renderRow)}
+ </>
+ ) : (
+ [...workspaceRows, ...privateRows].map(renderRow)
+ )}
</Flexbox>
</AsyncBoundary>
);
diff --git a/src/routes/(main)/home/features/AgentSelect/useHomeAgentRows.test.ts b/src/routes/(main)/home/features/AgentSelect/useHomeAgentRows.test.ts
new file mode 100644
index 00000000000..c62e3720557
--- /dev/null
+++ b/src/routes/(main)/home/features/AgentSelect/useHomeAgentRows.test.ts
@@ -0,0 +1,180 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useHomeAgentRows } from './useHomeAgentRows';
+
+const mocks = vi.hoisted(() => ({
+ activeWorkspaceId: undefined as string | undefined,
+ agentState: {
+ agentMap: {} as Record<string, unknown>,
+ builtinAgentIdMap: { inbox: 'agt_inbox' } as Record<string, string>,
+ },
+ homeState: {
+ agentGroups: [] as any[],
+ pinnedAgents: [] as any[],
+ privateAgentGroups: [] as any[],
+ privatePinnedAgents: [] as any[],
+ privateUngroupedAgents: [] as any[],
+ ungroupedAgents: [] as any[],
+ },
+ sidebarHiddenAgentIds: [] as string[],
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ useActiveWorkspaceId: () => mocks.activeWorkspaceId,
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: typeof mocks.agentState) => unknown) =>
+ selector(mocks.agentState),
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentSelectors: {
+ getAgentMetaById: (id: string) => (state: typeof mocks.agentState) =>
+ (state.agentMap[id] as Record<string, unknown> | undefined) ?? {},
+ },
+ builtinAgentSelectors: {
+ inboxAgentId: (state: typeof mocks.agentState) => state.builtinAgentIdMap.inbox,
+ },
+}));
+
+vi.mock('@/store/home', () => ({
+ useHomeStore: (selector: (state: typeof mocks.homeState) => unknown) => selector(mocks.homeState),
+}));
+
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (state: unknown) => unknown) =>
+ selector({ preference: { sidebarHiddenAgentIds: mocks.sidebarHiddenAgentIds } }),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ workspaceUserSettingsSelectors: {
+ sidebarHiddenAgentIds: () => mocks.sidebarHiddenAgentIds,
+ },
+}));
+
+vi.mock('@/store/global', () => ({
+ useGlobalStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+
+vi.mock('@/store/global/selectors', () => ({
+ systemStatusSelectors: { agentPageSize: () => 10 },
+}));
+
+const agent = (id: string, title: string, extra: Record<string, unknown> = {}) => ({
+ id,
+ title,
+ type: 'agent',
+ ...extra,
+});
+
+const ids = (rows: { id: string }[]) => rows.map((row) => row.id);
+
+describe('useHomeAgentRows', () => {
+ beforeEach(() => {
+ mocks.activeWorkspaceId = undefined;
+ mocks.sidebarHiddenAgentIds = [];
+ mocks.agentState.agentMap = { agt_inbox: { title: 'Lobe AI' } };
+ mocks.homeState.agentGroups = [];
+ mocks.homeState.pinnedAgents = [];
+ mocks.homeState.privateAgentGroups = [];
+ mocks.homeState.privatePinnedAgents = [];
+ mocks.homeState.privateUngroupedAgents = [];
+ mocks.homeState.ungroupedAgents = [];
+ });
+
+ it('drops agents the caller removed from their sidebar', () => {
+ mocks.homeState.ungroupedAgents = [agent('agt_a', 'Visible'), agent('agt_b', 'Hidden')];
+ mocks.sidebarHiddenAgentIds = ['agt_b'];
+
+ const { result } = renderHook(() => useHomeAgentRows());
+
+ expect(ids(result.current.workspaceRows)).toEqual(['agt_inbox', 'agt_a']);
+ });
+
+ it('drops hidden private agents too', () => {
+ mocks.activeWorkspaceId = 'ws_1';
+ mocks.homeState.privateUngroupedAgents = [
+ agent('agt_p1', 'Private Kept'),
+ agent('agt_p2', 'Private Hidden'),
+ ];
+ mocks.sidebarHiddenAgentIds = ['agt_p2'];
+
+ const { result } = renderHook(() => useHomeAgentRows());
+
+ expect(ids(result.current.privateRows)).toEqual(['agt_p1']);
+ });
+
+ it('splits private and workspace buckets inside a workspace', () => {
+ mocks.activeWorkspaceId = 'ws_1';
+ mocks.homeState.privateUngroupedAgents = [agent('agt_p', 'Private')];
+ mocks.homeState.ungroupedAgents = [agent('agt_a', 'Shared')];
+
+ const { result } = renderHook(() => useHomeAgentRows());
+
+ expect(result.current.showPrivateSection).toBe(true);
+ expect(ids(result.current.privateRows)).toEqual(['agt_p']);
+ expect(ids(result.current.workspaceRows)).toEqual(['agt_inbox', 'agt_a']);
+ });
+
+ it('keeps a single flat bucket in personal mode', () => {
+ mocks.homeState.ungroupedAgents = [agent('agt_a', 'Shared')];
+
+ const { result } = renderHook(() => useHomeAgentRows());
+
+ expect(result.current.showPrivateSection).toBe(false);
+ expect(result.current.privateRows).toEqual([]);
+ });
+
+ it('hides the private section when every private agent is hidden', () => {
+ mocks.activeWorkspaceId = 'ws_1';
+ mocks.homeState.privateUngroupedAgents = [agent('agt_p', 'Private')];
+ mocks.sidebarHiddenAgentIds = ['agt_p'];
+
+ const { result } = renderHook(() => useHomeAgentRows());
+
+ expect(result.current.showPrivateSection).toBe(false);
+ expect(result.current.privateRows).toEqual([]);
+ });
+
+ it('orders each bucket pinned → folders → ungrouped and de-duplicates by id', () => {
+ mocks.homeState.pinnedAgents = [agent('agt_pinned', 'Pinned', { pinned: true })];
+ mocks.homeState.agentGroups = [
+ {
+ id: 'grp_1',
+ items: [agent('agt_pinned', 'Pinned', { pinned: true }), agent('agt_folder', 'In Folder')],
+ name: 'Folder',
+ },
+ ];
+ mocks.homeState.ungroupedAgents = [agent('agt_plain', 'Plain')];
+
+ const { result } = renderHook(() => useHomeAgentRows());
+
+ expect(ids(result.current.workspaceRows)).toEqual([
+ 'agt_inbox',
+ 'agt_pinned',
+ 'agt_folder',
+ 'agt_plain',
+ ]);
+ expect(result.current.workspaceRows.find((row) => row.id === 'agt_pinned')?.pinned).toBe(true);
+ });
+
+ it('excludes chat groups so only agent ids reach the home input', () => {
+ mocks.homeState.ungroupedAgents = [
+ agent('agt_a', 'Agent'),
+ { id: 'grp_chat', title: 'Chat Group', type: 'group' },
+ ];
+
+ const { result } = renderHook(() => useHomeAgentRows());
+
+ expect(ids(result.current.workspaceRows)).toEqual(['agt_inbox', 'agt_a']);
+ });
+});
diff --git a/src/routes/(main)/home/features/AgentSelect/useHomeAgentRows.ts b/src/routes/(main)/home/features/AgentSelect/useHomeAgentRows.ts
new file mode 100644
index 00000000000..004e3aa40c4
--- /dev/null
+++ b/src/routes/(main)/home/features/AgentSelect/useHomeAgentRows.ts
@@ -0,0 +1,131 @@
+'use client';
+
+import { type SidebarAgentItem } from '@lobechat/types';
+import isEqual from 'fast-deep-equal';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import { DEFAULT_INBOX_AVATAR } from '@/const/meta';
+import { useKeepSidebarListed } from '@/routes/(main)/home/_layout/Body/Agent/List/useAgentList';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+
+export interface AgentRow {
+ avatar?: string;
+ backgroundColor?: string;
+ id: string;
+ pinned?: boolean;
+ title: string;
+}
+
+export interface HomeAgentRows {
+ /** Workspace-private items owned by the caller. Always empty in personal mode. */
+ privateRows: AgentRow[];
+ /** Whether to render the 私人 / 工作区 section split. */
+ showPrivateSection: boolean;
+ /** Inbox + workspace-visible items. */
+ workspaceRows: AgentRow[];
+}
+
+/**
+ * Rows for the home Agent switcher, bucketed the same way the sidebar and the
+ * agent-detail switcher bucket theirs: private first, then workspace, each in
+ * pinned → folders → ungrouped order, with the caller's sidebar-hidden agents
+ * dropped. Kept out of the component so the bucketing is unit-testable.
+ */
+export const useHomeAgentRows = (): HomeAgentRows => {
+ const { t } = useTranslation('chat');
+
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const inboxMeta = useAgentStore(agentSelectors.getAgentMetaById(inboxAgentId ?? ''));
+
+ const pinnedAgents = useHomeStore(homeAgentListSelectors.pinnedAgents, isEqual);
+ const agentGroups = useHomeStore(homeAgentListSelectors.agentGroups, isEqual);
+ const ungroupedAgents = useHomeStore(homeAgentListSelectors.ungroupedAgents, isEqual);
+ const privatePinnedAgents = useHomeStore(homeAgentListSelectors.privatePinnedAgents, isEqual);
+ const privateAgentGroups = useHomeStore(homeAgentListSelectors.privateAgentGroups, isEqual);
+ const privateUngroupedAgents = useHomeStore(
+ homeAgentListSelectors.privateUngroupedAgents,
+ isEqual,
+ );
+
+ const activeWorkspaceId = useActiveWorkspaceId();
+
+ // Drop the caller's "removed from my sidebar" items, exactly like the sidebar
+ // lists and the agent-detail switcher do — a hidden agent must not resurface
+ // in the home switcher.
+ const keep = useKeepSidebarListed();
+
+ return useMemo(() => {
+ const seen = new Set<string>();
+
+ // An agent can sit in several buckets (pinned AND inside a folder), so
+ // de-duplicate by id across every bucket.
+ const collect = (buckets: SidebarAgentItem[][]): AgentRow[] => {
+ const out: AgentRow[] = [];
+ for (const bucket of buckets) {
+ for (const item of keep(bucket)) {
+ // Skip chat groups — sendMessage / agent config lookups expect an agent id.
+ // Groups go through their own chat-group flow under /group/:gid.
+ if (item.type !== 'agent') continue;
+ if (seen.has(item.id)) continue;
+ seen.add(item.id);
+ out.push({
+ avatar: typeof item.avatar === 'string' ? item.avatar : undefined,
+ backgroundColor: item.backgroundColor || undefined,
+ id: item.id,
+ pinned: item.pinned ?? false,
+ title: item.title || t('untitledAgent'),
+ });
+ }
+ }
+ return out;
+ };
+
+ const privateRows = collect([
+ privatePinnedAgents,
+ privateAgentGroups.flatMap((group) => group.items),
+ privateUngroupedAgents,
+ ]);
+
+ const workspaceRows: AgentRow[] = [];
+ if (inboxAgentId && !seen.has(inboxAgentId)) {
+ seen.add(inboxAgentId);
+ workspaceRows.push({
+ avatar:
+ (typeof inboxMeta?.avatar === 'string' ? inboxMeta.avatar : undefined) ??
+ DEFAULT_INBOX_AVATAR,
+ backgroundColor: inboxMeta?.backgroundColor || undefined,
+ id: inboxAgentId,
+ title: inboxMeta?.title || 'Lobe AI',
+ });
+ }
+ workspaceRows.push(
+ ...collect([pinnedAgents, agentGroups.flatMap((group) => group.items), ungroupedAgents]),
+ );
+
+ return {
+ privateRows,
+ // Same rule as the agent-detail SwitchPanel: only split into 私人 / 工作区
+ // when there is a workspace AND private items survive the hidden filter —
+ // a lone header above an empty section is noise.
+ showPrivateSection: Boolean(activeWorkspaceId) && privateRows.length > 0,
+ workspaceRows,
+ };
+ }, [
+ activeWorkspaceId,
+ agentGroups,
+ inboxAgentId,
+ inboxMeta,
+ keep,
+ pinnedAgents,
+ privateAgentGroups,
+ privatePinnedAgents,
+ privateUngroupedAgents,
+ t,
+ ungroupedAgents,
+ ]);
+};
diff --git a/src/routes/(main)/resource/features/store/selectors.test.ts b/src/routes/(main)/resource/features/store/selectors.test.ts
index 9e9ffc412db..eb259bb5775 100644
--- a/src/routes/(main)/resource/features/store/selectors.test.ts
+++ b/src/routes/(main)/resource/features/store/selectors.test.ts
@@ -3,10 +3,18 @@ import { describe, expect, it } from 'vitest';
import {
getExplorerSelectAllUiState,
getExplorerSelectedCount,
+ getResourceQueryVisibility,
isExplorerItemSelected,
} from './selectors';
describe('resource manager selectors', () => {
+ it('should apply the home visibility filter only outside a concrete library', () => {
+ expect(getResourceQueryVisibility(undefined, 'private')).toBe('private');
+ expect(getResourceQueryVisibility(undefined, 'workspace')).toBe('public');
+ expect(getResourceQueryVisibility('kb-shared', 'private')).toBeUndefined();
+ expect(getResourceQueryVisibility('kb-shared', 'workspace')).toBeUndefined();
+ });
+
it('should treat selected ids as exclusions in all-selection mode', () => {
expect(
isExplorerItemSelected({
diff --git a/src/routes/(main)/resource/features/store/selectors.ts b/src/routes/(main)/resource/features/store/selectors.ts
index d4a2e340274..90eed392d0e 100644
--- a/src/routes/(main)/resource/features/store/selectors.ts
+++ b/src/routes/(main)/resource/features/store/selectors.ts
@@ -2,7 +2,21 @@ import { fileManagerSelectors, useFileStore } from '@/store/file';
import { type FileListItem } from '@/types/files';
import { SortType } from '@/types/files';
-import { type SelectAllState, type State } from './initialState';
+import type { ResourceListVisibilityFilter, SelectAllState, State } from './initialState';
+
+/**
+ * The Private / Workspace switch scopes the resource home only. Once the user
+ * enters a concrete library, the library and server ownership rules define the
+ * visible pool; reusing the home filter there can hide the entire library.
+ */
+export const getResourceQueryVisibility = (
+ libraryId: string | undefined,
+ listVisibility: ResourceListVisibilityFilter,
+): 'private' | 'public' | undefined => {
+ if (libraryId) return undefined;
+
+ return listVisibility === 'private' ? 'private' : 'public';
+};
/**
* Sort a file list based on sort settings
diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.ts
index 1c0204553a8..8f72dac005d 100644
--- a/src/store/agent/slices/agent/action.test.ts
+++ b/src/store/agent/slices/agent/action.test.ts
@@ -691,6 +691,30 @@ describe('AgentSlice Actions', () => {
expect.any(AbortSignal),
);
});
+
+ // LOBE-12459: some chatConfig writes are automatic corrections (e.g. forcing
+ // `searchMode: 'auto'` for a model whose builtin search can't be turned off).
+ // A rejected correction must not toast "your change was not applied" for a
+ // change the user never made, so the option has to reach the write funnel.
+ it('should forward update options through the chatConfig wrapper', async () => {
+ const { result } = renderHook(() => useAgentStore());
+
+ vi.mocked(agentService.updateAgentConfig).mockRejectedValue(new Error('save failed'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ act(() => {
+ useAgentStore.setState({ activeAgentId: 'agent-1' });
+ });
+
+ await act(async () => {
+ await result.current.updateAgentChatConfig(
+ { searchMode: 'auto' },
+ { showErrorMessage: false },
+ );
+ });
+
+ expect(message.error).not.toHaveBeenCalled();
+ });
});
describe('optimisticUpdateAgentConfig', () => {
diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.ts
index bc97ea11f50..6d6ed255d94 100644
--- a/src/store/agent/slices/agent/action.ts
+++ b/src/store/agent/slices/agent/action.ts
@@ -250,29 +250,36 @@ export class AgentSliceActionImpl {
await updateAgentConfig({ plugins: newPlugins });
};
- updateAgentChatConfig = async (config: Partial<LobeAgentChatConfig>): Promise<void> => {
+ updateAgentChatConfig = async (
+ config: Partial<LobeAgentChatConfig>,
+ options?: AgentConfigUpdateOptions,
+ ): Promise<void> => {
const { activeAgentId } = this.#get();
if (!activeAgentId) return;
- await this.#get().updateAgentConfig({ chatConfig: config });
+ await this.#get().updateAgentConfig({ chatConfig: config }, options);
};
updateAgentChatConfigById = async (
agentId: string,
config: Partial<LobeAgentChatConfig>,
+ options?: AgentConfigUpdateOptions,
): Promise<void> => {
if (!agentId) return;
- await this.#get().updateAgentConfigById(agentId, { chatConfig: config });
+ await this.#get().updateAgentConfigById(agentId, { chatConfig: config }, options);
};
- updateAgentConfig = async (config: PartialDeep<LobeAgentConfig>): Promise<void> => {
+ updateAgentConfig = async (
+ config: PartialDeep<LobeAgentConfig>,
+ options?: AgentConfigUpdateOptions,
+ ): Promise<void> => {
const { activeAgentId } = this.#get();
if (!activeAgentId) return;
- await this.#get().updateAgentConfigById(activeAgentId, config);
+ await this.#get().updateAgentConfigById(activeAgentId, config, options);
};
updateAgentConfigById = async (