🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: new tier plans integration (copy, run and document limits, rollout flag) (#22115)
YuTengjing7b537ee1867e
diff --git a/apps/cli/src/utils/error.test.ts b/apps/cli/src/utils/error.test.tsindex 1a7d6818f5a..7c33b6c285d 100644--- a/apps/cli/src/utils/error.test.ts+++ b/apps/cli/src/utils/error.test.ts@@ -10,6 +10,19 @@ describe('error utilities', () => {expect(formatError(error)).toBe('fetch failed: Could not connect: ConnectionRefused');});+ it('prints the page character-limit refusal with its numbers', () => {+ const message =+ 'This document would have 120,500 characters, over the 100,000-character limit per document on your plan.';+ const error = Object.assign(new Error(message), {+ data: {+ code: 'BAD_REQUEST',+ errorData: { actual: 120_500, code: 'DocumentCharLimitExceeded', limit: 100_000 },+ },+ });++ expect(formatError(error)).toBe(message);+ });+it('handles error-like objects and circular cause chains', () => {const error: { cause?: unknown; code: string; message: string; name: string } = {code: 'ECONNRESET',diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.tsindex e4bd2243179..cff721106f9 100644--- a/apps/server/src/modules/Redis/keys.ts+++ b/apps/server/src/modules/Redis/keys.ts@@ -20,6 +20,10 @@ export const RedisKeyNamespace = {* stores (receipts, dedupe, policy state) already use.*/AGENT_SIGNAL: 'agent-signal',+ /**+ * Leases on the agent runs a user has in flight, used to cap how many run at once.+ */+ AGENT_RUN: 'agentRun',/*** Follow-ups a user queued behind a running agent turn ("steer"). The server* drains them into the next turn itself when the running one hands back.@@ -146,6 +150,16 @@ export const RedisKeys = {*/schedulerLock: (key: string): string => `scheduler_lock:v1:${key}`,},+ /**+ * Run lease scope — see {@link RedisKeyNamespace.AGENT_RUN}.+ */+ agentRun: {+ /**+ * One user's in-flight run leases (field = holder id, value = expiry in ms).+ * Full key: agentRun:run_slots:v1:{userId}+ */+ runSlots: (userId: string): string => `run_slots:v1:${userId}`,+ },/*** Steer queue scope — see {@link RedisKeyNamespace.AGENT_STEER}.*/@@ -260,6 +274,7 @@ export const RedisKeys = {*/export const RedisKeyScopeNamespace = {agentIdentity: RedisKeyNamespace.AGENT_IDENTITY,+ agentRun: RedisKeyNamespace.AGENT_RUN,agentSignal: RedisKeyNamespace.AGENT_SIGNAL,agentSteer: RedisKeyNamespace.AGENT_STEER,aiGeneration: RedisKeyNamespace.AI_GENERATION,diff --git a/apps/server/src/routers/lambda/_schema/__tests__/documentHistory.test.ts b/apps/server/src/routers/lambda/_schema/__tests__/documentHistory.test.tsnew file mode 100644index 00000000000..70e88702a19--- /dev/null+++ b/apps/server/src/routers/lambda/_schema/__tests__/documentHistory.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest';++import {+ DOCUMENT_CONTENT_MAX_LENGTH,+ DOCUMENT_EDITOR_DATA_MAX_LENGTH,+ saveDocumentHistoryInputSchema,+ updateDocumentInputSchema,+} from '../documentHistory';++describe('document input size backstops', () => {+ it('rejects update content over the content cap', () => {+ const result = updateDocumentInputSchema.safeParse({+ content: 'x'.repeat(DOCUMENT_CONTENT_MAX_LENGTH + 1),+ id: 'doc-1',+ });+ expect(result.success).toBe(false);+ });++ it('accepts update content at the cap', () => {+ const result = updateDocumentInputSchema.safeParse({+ content: 'x'.repeat(DOCUMENT_CONTENT_MAX_LENGTH),+ id: 'doc-1',+ });+ expect(result.success).toBe(true);+ });++ it('rejects update editorData over the editorData cap', () => {+ const result = updateDocumentInputSchema.safeParse({+ editorData: 'x'.repeat(DOCUMENT_EDITOR_DATA_MAX_LENGTH + 1),+ id: 'doc-1',+ });+ expect(result.success).toBe(false);+ });++ it('rejects history editorData over the editorData cap', () => {+ const result = saveDocumentHistoryInputSchema.safeParse({+ documentId: 'doc-1',+ editorData: 'x'.repeat(DOCUMENT_EDITOR_DATA_MAX_LENGTH + 1),+ saveSource: 'manual',+ });+ expect(result.success).toBe(false);+ });+});diff --git a/apps/server/src/routers/lambda/_schema/documentHistory.ts b/apps/server/src/routers/lambda/_schema/documentHistory.tsindex 597980b832b..c7a27d1e57a 100644--- a/apps/server/src/routers/lambda/_schema/documentHistory.ts+++ b/apps/server/src/routers/lambda/_schema/documentHistory.ts@@ -1,5 +1,14 @@import { z } from 'zod';+/**+ * Transport backstop for document markdown, in UTF-16 code units. The plan limit+ * is enforced in the service; this only bounds what the router will parse.+ */+export const DOCUMENT_CONTENT_MAX_LENGTH = 10_000_000;++/** Transport backstop for serialized editor state, which is larger than its markdown. */+export const DOCUMENT_EDITOR_DATA_MAX_LENGTH = 50_000_000;+export const documentHistorySaveSourceSchema = z.enum(['autosave','manual',@@ -37,8 +46,8 @@ export const compareDocumentHistoryItemsInputSchema = z.object({export const updateDocumentInputSchema = z.object({breakAutosaveWindow: z.boolean().optional(),- content: z.string().optional(),- editorData: z.string().optional(),+ content: z.string().max(DOCUMENT_CONTENT_MAX_LENGTH).optional(),+ editorData: z.string().max(DOCUMENT_EDITOR_DATA_MAX_LENGTH).optional(),/*** Optimistic-concurrency predicate: when set, the save succeeds only if the* stored row's `updatedAt` still equals this value (compared atomically@@ -59,7 +68,7 @@ export const updateDocumentInputSchema = z.object({export const saveDocumentHistoryInputSchema = z.object({documentId: z.string(),- editorData: z.string(),+ editorData: z.string().max(DOCUMENT_EDITOR_DATA_MAX_LENGTH),lockOwnerId: z.string().optional(),saveSource: documentHistorySaveSourceSchema,});diff --git a/apps/server/src/routers/lambda/document.ts b/apps/server/src/routers/lambda/document.tsindex 85ac697ecdb..70e8d29b891 100644--- a/apps/server/src/routers/lambda/document.ts+++ b/apps/server/src/routers/lambda/document.ts@@ -43,6 +43,8 @@ import {import { resolveRootOperation } from './_helpers/runProvenance';import {compareDocumentHistoryItemsInputSchema,+ DOCUMENT_CONTENT_MAX_LENGTH,+ DOCUMENT_EDITOR_DATA_MAX_LENGTH,getDocumentHistoryItemInputSchema,listDocumentHistoryInputSchema,saveDocumentHistoryInputSchema,@@ -203,8 +205,8 @@ export const documentRouter = router({.use(withScopedPermission('document:create')).input(z.object({- content: z.string().optional(),- editorData: z.string().optional(),+ content: z.string().max(DOCUMENT_CONTENT_MAX_LENGTH).optional(),+ editorData: z.string().max(DOCUMENT_EDITOR_DATA_MAX_LENGTH).optional(),fileType: z.string().optional(),knowledgeBaseId: z.string().optional(),metadata: z.record(z.string(), z.any()).optional(),@@ -266,8 +268,8 @@ export const documentRouter = router({z.object({documents: z.array(z.object({- content: z.string().optional(),- editorData: z.string().optional(),+ content: z.string().max(DOCUMENT_CONTENT_MAX_LENGTH).optional(),+ editorData: z.string().max(DOCUMENT_EDITOR_DATA_MAX_LENGTH).optional(),fileType: z.string().optional(),knowledgeBaseId: z.string().optional(),metadata: z.record(z.string(), z.any()).optional(),@@ -469,6 +471,7 @@ export const documentRouter = router({saveSource: input.saveSource,userId: ctx.userId,workspaceId: ctx.workspaceId ?? undefined,+ writeSource: 'user',});return { recorded };}),diff --git a/apps/server/src/routers/lambda/notebook.test.ts b/apps/server/src/routers/lambda/notebook.test.tsindex 250d462032c..15486d34bfe 100644--- a/apps/server/src/routers/lambda/notebook.test.ts+++ b/apps/server/src/routers/lambda/notebook.test.ts@@ -7,6 +7,8 @@ import { createContextInner } from '@/libs/trpc/lambda/context';import { notebookRouter } from './notebook';const mocks = vi.hoisted(() => ({+ assertWrite: vi.fn(),+ update: vi.fn(),associate: vi.fn(),create: vi.fn(),findDocumentById: vi.fn(),@@ -18,7 +20,7 @@ const mocks = vi.hoisted(() => ({vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn().mockResolvedValue({}) }));vi.mock('@/database/models/document', () => ({DocumentModel: vi.fn().mockImplementation(function () {- return { create: mocks.create, findById: mocks.findDocumentById };+ return { create: mocks.create, findById: mocks.findDocumentById, update: mocks.update };}),}));vi.mock('@/database/models/topicDocument', () => ({@@ -41,6 +43,13 @@ vi.mock('@/database/models/work', () => ({return { registerDocument: mocks.registerDocument };}),}));+vi.mock('@/server/services/document/writeLimit', () => ({+ assertDocumentWriteWithinLimit: mocks.assertWrite,+}));+vi.mock('@/server/services/resourcePermission', () => ({+ assertCanEditResource: vi.fn(),+ assertCanPerformResourceAction: vi.fn(),+}));vi.mock('@/server/services/notebook', () => ({ NotebookRuntimeService: vi.fn() }));const createCaller = createCallerFactory(notebookRouter);@@ -180,3 +189,78 @@ describe('notebook.associateDocument', () => {expect(mocks.associate).not.toHaveBeenCalled();});});++describe('notebook document character limit', () => {+ beforeEach(() => {+ for (const mock of Object.values(mocks)) mock.mockReset();+ mocks.create.mockResolvedValue({ id: 'doc-1' });+ });++ const caller = async () => createCaller(await createContextInner({ userId: 'user-1' }));++ it('checks a new document as a user write before creating the row', async () => {+ await (await caller()).createDocument(input);++ expect(mocks.assertWrite).toHaveBeenCalledWith({+ charCount: input.content.length,+ source: 'user',+ userId: 'user-1',+ workspaceId: undefined,+ });+ });++ it('creates nothing when the limit refuses the write', async () => {+ mocks.assertWrite.mockRejectedValue(new Error('Document is too long'));++ await expect((await caller()).createDocument(input)).rejects.toThrow('too long');+ expect(mocks.create).not.toHaveBeenCalled();+ expect(mocks.associate).not.toHaveBeenCalled();+ });++ it('rejects content above the request backstop', async () => {+ await expect(+ (await caller()).createDocument({ ...input, content: 'a'.repeat(10_000_001) }),+ ).rejects.toThrow();+ expect(mocks.create).not.toHaveBeenCalled();+ });++ it('checks an append against the combined length and the previous length', async () => {+ mocks.findDocumentById.mockResolvedValue({ content: 'old' });++ await (await caller()).updateDocument({ append: true, content: 'new', id: 'doc-1' });++ expect(mocks.assertWrite).toHaveBeenCalledWith(+ expect.objectContaining({ charCount: 8, previousCharCount: 3, source: 'user' }),+ );+ expect(mocks.update).toHaveBeenCalledWith(+ 'doc-1',+ expect.objectContaining({ content: 'old\n\nnew' }),+ );+ });++ it('loads the existing row to pass the previous length on a replace', async () => {+ mocks.findDocumentById.mockResolvedValue({ content: 'a'.repeat(50) });++ await (await caller()).updateDocument({ content: 'short', id: 'doc-1' });++ expect(mocks.assertWrite).toHaveBeenCalledWith(+ expect.objectContaining({ charCount: 5, previousCharCount: 50 }),+ );+ });++ it('does not update when the limit refuses the write', async () => {+ mocks.findDocumentById.mockResolvedValue({ content: 'old' });+ mocks.assertWrite.mockRejectedValue(new Error('Document is too long'));++ await expect(+ (await caller()).updateDocument({ content: 'longer content', id: 'doc-1' }),+ ).rejects.toThrow('too long');+ expect(mocks.update).not.toHaveBeenCalled();+ });++ it('skips the check for a title-only update', async () => {+ await (await caller()).updateDocument({ id: 'doc-1', title: 'New' });++ expect(mocks.assertWrite).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/notebook.ts b/apps/server/src/routers/lambda/notebook.tsindex b67f1096a88..df9afdad2c9 100644--- a/apps/server/src/routers/lambda/notebook.ts+++ b/apps/server/src/routers/lambda/notebook.ts@@ -12,6 +12,7 @@ import { TopicDocumentModel } from '@/database/models/topicDocument';import { WorkModel } from '@/database/models/work';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { assertDocumentWriteWithinLimit } from '@/server/services/document/writeLimit';import { NotebookRuntimeService } from '@/server/services/notebook';import {assertCanEditResource,@@ -21,6 +22,9 @@ import {import { isWorkspaceNonOwner } from './_helpers/assertWorkspaceRowManageable';import { resolveRootOperation } from './_helpers/runProvenance';+/** Request-size backstop for document content, independent of the per-plan limit. */+const DOCUMENT_CONTENT_INPUT_MAX = 10_000_000;+const notebookProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;const wsId = ctx.workspaceId ?? undefined;@@ -68,7 +72,8 @@ export const notebookRouter = router({.use(withScopedPermission('document:create')).input(z.object({- content: z.string(),+ // Hard backstop above any plan limit; the plan limit is enforced below.+ content: z.string().max(DOCUMENT_CONTENT_INPUT_MAX),description: z.string(),metadata: z.record(z.string(), z.any()).optional(),operationId: z.string().optional(),@@ -116,6 +121,14 @@ export const notebookRouter = router({});if (twin) return twin;+ // Refuse before any row exists so a rejected write leaves nothing behind.+ await assertDocumentWriteWithinLimit({+ charCount: input.content.length,+ source: 'user',+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+// Create the documentconst document = await ctx.documentModel.create({content: input.content,@@ -226,7 +239,7 @@ export const notebookRouter = router({.input(z.object({append: z.boolean().optional(),- content: z.string().optional(),+ content: z.string().max(DOCUMENT_CONTENT_INPUT_MAX).optional(),description: z.string().optional(),id: z.string(),metadata: z.record(z.string(), z.any()).optional(),@@ -244,15 +257,29 @@ export const notebookRouter = router({});let contentToUpdate = input.content;+ let previousCharCount = 0;- // Handle append mode- if (input.append && input.content) {+ if (input.content !== undefined) {const existing = await ctx.documentModel.findById(input.id);- if (existing?.content) {+ previousCharCount = existing?.content?.length ?? 0;++ // Handle append mode+ if (input.append && input.content && existing?.content) {contentToUpdate = existing.content + '\n\n' + input.content;}}+ // Check the post-write total before persisting anything.+ if (contentToUpdate !== undefined) {+ await assertDocumentWriteWithinLimit({+ charCount: contentToUpdate.length,+ previousCharCount,+ source: 'user',+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ });+ }+await ctx.documentModel.update(input.id, {...(contentToUpdate !== undefined && {content: contentToUpdate,diff --git a/apps/server/src/services/agentDocumentVfs/deps.ts b/apps/server/src/services/agentDocumentVfs/deps.tsindex 84a7a24f590..767f9913585 100644--- a/apps/server/src/services/agentDocumentVfs/deps.ts+++ b/apps/server/src/services/agentDocumentVfs/deps.ts@@ -1,3 +1,5 @@+import type { DocumentWriteSource } from '@lobechat/types';+import type { AgentDocumentModel } from '@/database/models/agentDocuments';import type { FileService } from '../file';@@ -16,11 +18,24 @@ import type { SkillMount } from './mounts/skills/SkillMount';*/export interface AgentDocumentVfsDeps {agentDocumentModel: AgentDocumentModel;+ /**+ * Refuses a write that would leave a document over the plan's character limit.+ * Run it before anything is persisted or pushed to a collaboration room.+ */+ assertWithinCharLimit: (params: {+ charCount: number;+ previousCharCount?: number;+ source: DocumentWriteSource;+ }) => Promise<void>;getFileService: () => FileService;skillMount: SkillMount;/*** Writes a body into the document's live collaboration room, whose projection* would otherwise overwrite a row write. False when there is no live room.*/- writeThroughRoom: (documentId: string, body: PageBody) => Promise<boolean>;+ writeThroughRoom: (+ documentId: string,+ body: PageBody,+ writeSource: DocumentWriteSource,+ ) => Promise<boolean>;}diff --git a/apps/server/src/services/agentDocumentVfs/index.ts b/apps/server/src/services/agentDocumentVfs/index.tsindex 75db144b7d6..6f882dea68f 100644--- a/apps/server/src/services/agentDocumentVfs/index.ts+++ b/apps/server/src/services/agentDocumentVfs/index.ts@@ -5,6 +5,7 @@ import { AgentDocumentModel } from '@/database/models/agentDocuments';import { DOCUMENT_FOLDER_TYPE } from '@/database/schemas';import { getAgentDocumentContentType } from '../agentDocuments/contentFormat';+import { assertDocumentWriteWithinLimit } from '../document/writeLimit';import { FileService } from '../file';import { writePageBodyThroughRoom } from '../pageCollab/bodyWriter';import type { AgentDocumentVfsDeps } from './deps';@@ -98,14 +99,17 @@ export class AgentDocumentVfsService {this.agentDocumentModel = new AgentDocumentModel(db, userId, workspaceId);this.skillMount = createSkillMount(db, userId, workspaceId);this.deps = {+ assertWithinCharLimit: (params) =>+ assertDocumentWriteWithinLimit({ ...params, userId, workspaceId }),agentDocumentModel: this.agentDocumentModel,getFileService: () => this.fileService,skillMount: this.skillMount,- writeThroughRoom: (documentId, body) =>+ writeThroughRoom: (documentId, body, writeSource) =>writePageBodyThroughRoom(db, documentId, body, {saveSource: 'llm_call',userId,workspaceId,+ writeSource,}),};}@@ -299,6 +303,7 @@ export class AgentDocumentVfsService {ctx,createMode,options.contentFormat ?? 'markdown',+ options.source ?? 'user',);}@@ -484,6 +489,8 @@ export class AgentDocumentVfsService {const { content } = await this.read(resolveReadablePath(sourcePath), ctx);return this.write(destinationPath, content, ctx, {createMode: options.overwrite ? 'if-missing' : 'always-new',+ // A copy has the length of its source, so it is exempt from the character limit.+ source: 'system',});}diff --git a/apps/server/src/services/agentDocumentVfs/index.writeLimit.test.ts b/apps/server/src/services/agentDocumentVfs/index.writeLimit.test.tsnew file mode 100644index 00000000000..226d61e3af3--- /dev/null+++ b/apps/server/src/services/agentDocumentVfs/index.writeLimit.test.ts@@ -0,0 +1,141 @@+// @vitest-environment node+import { AGENT_DOCUMENT_FILE_TYPE } from '@lobechat/const';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { checkDocumentCharLimit } from '@/business/server/document/writeLimit';+import { AgentAccess } from '@/database/models/agentDocuments';++import { AgentDocumentVfsService } from './index';+import { db, mockAgentDocumentModel, resetVfsMocks, userId } from './testUtils';++vi.mock('@/business/server/document/writeLimit', () => ({+ checkDocumentCharLimit: vi.fn(),+}));++vi.mock('@/database/models/agentDocuments', () => ({+ AgentAccess: { DELETE: 16, EXECUTE: 1, LIST: 8, READ: 2, WRITE: 4 },+ AgentDocumentModel: vi.fn(),+ buildDocumentFilename: vi.fn(function (title: string) {+ return title;+ }),+}));++vi.mock('./mounts/skills/createSkillMount', () => ({+ createSkillMount: vi.fn(),+}));++vi.mock('../file', () => ({+ FileService: vi.fn(function () {+ return {};+ }),+}));++const check = vi.mocked(checkDocumentCharLimit);++const ctx = { agentId: 'agent-1' };++const existingDoc = (content: string) => ({+ accessSelf: AgentAccess.READ | AgentAccess.WRITE | AgentAccess.LIST,+ content,+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ documentId: 'documents-1',+ fileType: AGENT_DOCUMENT_FILE_TYPE,+ filename: 'notes.md',+ id: 'agent-doc-1',+ metadata: null,+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+});++describe('AgentDocumentVfsService per-document character limit', () => {+ beforeEach(() => {+ resetVfsMocks();+ check.mockReset();+ check.mockResolvedValue({ allowed: false, limit: 10, plan: 'free' });+ mockAgentDocumentModel.create.mockResolvedValue(existingDoc('x'));+ mockAgentDocumentModel.update.mockResolvedValue(undefined);+ });++ it('refuses a new file over the limit before creating it', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(undefined);++ const service = new AgentDocumentVfsService(db, userId);++ await expect(service.write('./notes.md', 'x'.repeat(50), ctx)).rejects.toMatchObject({+ cause: { data: { code: 'DocumentCharLimitExceeded', limit: 10 } },+ });+ expect(mockAgentDocumentModel.create).not.toHaveBeenCalled();+ });++ it('refuses a raw rewrite that grows past the limit and keeps the stored body', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(existingDoc('short'));++ const service = new AgentDocumentVfsService(db, userId);++ await expect(+ service.write('./notes.md', 'x'.repeat(50), ctx, { contentFormat: 'raw' }),+ ).rejects.toMatchObject({ cause: { data: { code: 'DocumentCharLimitExceeded' } } });+ expect(mockAgentDocumentModel.update).not.toHaveBeenCalled();+ });++ it('leaves a live room to check the limit against its own body', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(existingDoc('short'));+ const writeThroughRoom = vi.fn().mockResolvedValue(true);+ const service = new AgentDocumentVfsService(db, userId);+ (service as any).deps.writeThroughRoom = writeThroughRoom;++ await service.write('./notes.md', 'x'.repeat(50), ctx);++ expect(writeThroughRoom).toHaveBeenCalledWith('documents-1', expect.anything(), 'user');+ expect(mockAgentDocumentModel.update).not.toHaveBeenCalled();+ });++ it('refuses a markdown rewrite of a page without a live room before the row write', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(existingDoc('short'));+ const writeThroughRoom = vi.fn().mockResolvedValue(false);+ const service = new AgentDocumentVfsService(db, userId);+ (service as any).deps.writeThroughRoom = writeThroughRoom;++ await expect(service.write('./notes.md', 'x'.repeat(50), ctx)).rejects.toMatchObject({+ cause: { data: { code: 'DocumentCharLimitExceeded' } },+ });+ expect(mockAgentDocumentModel.update).not.toHaveBeenCalled();+ });++ it('allows a rewrite that does not make an over-limit document longer', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(existingDoc('x'.repeat(100)));++ const service = new AgentDocumentVfsService(db, userId);+ await service.write('./notes.md', 'x'.repeat(40), ctx, { contentFormat: 'raw' });++ expect(mockAgentDocumentModel.update).toHaveBeenCalled();+ });++ it('skips the limit for a system write', async () => {+ mockAgentDocumentModel.findByParentAndFilename.mockResolvedValue(undefined);++ const service = new AgentDocumentVfsService(db, userId);+ await service.write('./notes.md', 'x'.repeat(50), ctx, {+ contentFormat: 'raw',+ source: 'system',+ });++ expect(check).not.toHaveBeenCalled();+ expect(mockAgentDocumentModel.create).toHaveBeenCalled();+ });++ it('copies a file as a system write', async () => {+ const service = new AgentDocumentVfsService(db, userId);+ vi.spyOn(service, 'stat')+ .mockResolvedValueOnce({ type: 'file' } as any)+ .mockResolvedValueOnce(undefined);+ vi.spyOn(service, 'read').mockResolvedValue({ content: 'x'.repeat(50) } as any);+ const write = vi.spyOn(service, 'write').mockResolvedValue({} as any);++ await service.copy('./a.md', './b.md', ctx);++ expect(write).toHaveBeenCalledWith('./b.md', 'x'.repeat(50), ctx, {+ createMode: 'always-new',+ source: 'system',+ });+ });+});diff --git a/apps/server/src/services/agentDocumentVfs/ordinaryWrites.ts b/apps/server/src/services/agentDocumentVfs/ordinaryWrites.tsindex a8b3f2f08cc..0a6d1a6ffdd 100644--- a/apps/server/src/services/agentDocumentVfs/ordinaryWrites.ts+++ b/apps/server/src/services/agentDocumentVfs/ordinaryWrites.ts@@ -1,3 +1,5 @@+import type { DocumentWriteSource } from '@lobechat/types';+import { buildDocumentFilename } from '@/database/models/agentDocuments';import { DOCUMENT_FOLDER_TYPE } from '@/database/schemas';@@ -27,6 +29,7 @@ export async function writeOrdinaryDocument(ctx: AgentDocumentVfsContext,createMode: NonNullable<AgentDocumentWriteOptions['createMode']>,contentFormat: NonNullable<AgentDocumentWriteOptions['contentFormat']>,+ source: DocumentWriteSource = 'user',): Promise<AgentDocumentStats> {if (path === './' || path === LOBE_PATH || path.startsWith(`${LOBE_PATH}/`)) {throw new AgentDocumentVfsError(`Cannot write reserved path: ${path}`, 'BAD_REQUEST');@@ -46,6 +49,11 @@ export async function writeOrdinaryDocument(}if (contentFormat === 'raw') {+ await deps.assertWithinCharLimit({+ charCount: content.length,+ previousCharCount: existing.content?.length ?? 0,+ source,+ });await deps.agentDocumentModel.update(existing.id, {content,editorData: null,@@ -53,11 +61,19 @@ export async function writeOrdinaryDocument(});} else {const snapshot = await createAgentMarkdownSnapshot(content);- const inRoom = await deps.writeThroughRoom(existing.documentId, {- editorData: snapshot.editorData,- markdown: snapshot.content,- });+ // A live room checks the limit against its own body, which may be ahead of+ // the row; the row's length is the baseline only without a room.+ const inRoom = await deps.writeThroughRoom(+ existing.documentId,+ { editorData: snapshot.editorData, markdown: snapshot.content },+ source,+ );if (!inRoom) {+ await deps.assertWithinCharLimit({+ charCount: snapshot.content.length,+ previousCharCount: existing.content?.length ?? 0,+ source,+ });await deps.agentDocumentModel.update(existing.id, {content: snapshot.content,editorData: snapshot.editorData,@@ -102,6 +118,7 @@ export async function writeOrdinaryDocument(const normalizedFilename = buildDocumentFilename(filename);if (contentFormat === 'raw') {+ await deps.assertWithinCharLimit({ charCount: content.length, source });const created = await deps.agentDocumentModel.create(ctx.agentId, normalizedFilename, content, {fileType: RAW_TEXT_DOCUMENT_FILE_TYPE,parentId: parentNode?.documentId ?? null,@@ -112,6 +129,7 @@ export async function writeOrdinaryDocument(}const snapshot = await createAgentMarkdownSnapshot(content);+ await deps.assertWithinCharLimit({ charCount: snapshot.content.length, source });const created = await deps.agentDocumentModel.create(ctx.agentId,normalizedFilename,diff --git a/apps/server/src/services/agentDocumentVfs/types.ts b/apps/server/src/services/agentDocumentVfs/types.tsindex 05cefa85371..ff9500d0e5b 100644--- a/apps/server/src/services/agentDocumentVfs/types.ts+++ b/apps/server/src/services/agentDocumentVfs/types.ts@@ -1,3 +1,5 @@+import type { DocumentWriteSource } from '@lobechat/types';+import type { AgentAccess } from '@/database/models/agentDocuments';/**@@ -206,6 +208,11 @@ export interface AgentDocumentWriteOptions {*/contentFormat?: 'markdown' | 'raw';createMode?: 'always-new' | 'if-missing' | 'must-exist';+ /**+ * Who asked for the write, for the per-document character limit. Defaults to+ * `user` (the CLI and API); copies and the tool-result archive pass `system`.+ */+ source?: DocumentWriteSource;}export interface AgentDocumentMkdirOptions {diff --git a/apps/server/src/services/agentDocuments/archivedToolResults.ts b/apps/server/src/services/agentDocuments/archivedToolResults.tsnew file mode 100644index 00000000000..8fc330ea546--- /dev/null+++ b/apps/server/src/services/agentDocuments/archivedToolResults.ts@@ -0,0 +1,46 @@+import { DOCUMENT_FOLDER_TYPE } from '@lobechat/database/schemas';++import type { AgentDocument } from '@/database/models/agentDocuments';++import { TOOL_RESULTS_DIR_NAME } from '../toolExecution/constants';++/** Collect ids of root `.tool-results` archive folders present in a doc list. */+export const collectArchiveFolderIds = <+ T extends Pick<AgentDocument, 'documentId' | 'parentId' | 'filename' | 'fileType'>,+>(+ docs: T[],+): Set<string> =>+ new Set(+ docs+ .filter(+ (d) =>+ d.filename === TOOL_RESULTS_DIR_NAME &&+ !d.parentId &&+ d.fileType === DOCUMENT_FOLDER_TYPE,+ )+ .map((d) => d.documentId),+ );++/**+ * Hide the auto-created `.tool-results/` archive (root folder + its children)+ * from user-facing document lists. Applied by default everywhere, including+ * `listDocuments` / `listDocumentsForTopic`. The tool runtime that lets agents+ * discover archived entries opts back in via `includeArchivedToolResults`.+ *+ * `archiveFolderIds` lets callers whose list may not contain the folder row+ * supply the ids explicitly — the topic path only sees the archived file+ * (which is topic-associated), never the folder, so it can't be derived from+ * the list alone.+ */+export const excludeArchivedToolResults = <+ T extends Pick<AgentDocument, 'documentId' | 'parentId' | 'filename' | 'fileType'>,+>(+ docs: T[],+ archiveFolderIds: Set<string> = collectArchiveFolderIds(docs),+): T[] => {+ if (archiveFolderIds.size === 0) return docs;+ return docs.filter(+ (d) =>+ !archiveFolderIds.has(d.documentId) && (!d.parentId || !archiveFolderIds.has(d.parentId)),+ );+};diff --git a/apps/server/src/services/agentDocuments/bodyWrite.ts b/apps/server/src/services/agentDocuments/bodyWrite.tsindex 2fdfa618d30..49278c08b21 100644--- a/apps/server/src/services/agentDocuments/bodyWrite.ts+++ b/apps/server/src/services/agentDocuments/bodyWrite.ts@@ -1,3 +1,5 @@+import type { DocumentWriteSource } from '@lobechat/types';+import type { AgentDocumentModel } from '@/database/models/agentDocuments';import type { LobeChatDatabase } from '@/database/type';@@ -26,12 +28,13 @@ export const writeSnapshotThroughRoom = (writer: AgentDocumentBodyWriter,documentId: string,snapshot: BodySnapshot,+ writeSource: DocumentWriteSource = 'agent',) =>writePageBodyThroughRoom(writer.db,documentId,{ editorData: snapshot.editorData, markdown: snapshot.content },- { saveSource: 'llm_call', userId: writer.userId, workspaceId: writer.workspaceId },+ { saveSource: 'llm_call', userId: writer.userId, workspaceId: writer.workspaceId, writeSource },);/**@@ -47,9 +50,18 @@ export const writeAgentDocumentBody = async (/** The pre-edit state, when the stored one is stale (it forced a Markdown recovery). */previousEditorData?: Record<string, any>;recordHistory?: boolean;+ /**+ * Runs before the row write, only when there is no live room: a room checks+ * the character limit against its own body, which may be ahead of the row.+ */+ beforeRowWrite?: () => Promise<void>;+ /** Who asked for the write, for the room's character-limit check; defaults to `agent`. */+ writeSource?: DocumentWriteSource;} = {},) => {- if (await writeSnapshotThroughRoom(writer, target.documentId, snapshot)) return;+ if (await writeSnapshotThroughRoom(writer, target.documentId, snapshot, options.writeSource))+ return;+ await options.beforeRowWrite?.();if (options.recordHistory !== false) {const { documentService } = writer;diff --git a/apps/server/src/services/agentDocuments/contextPayload.ts b/apps/server/src/services/agentDocuments/contextPayload.tsnew file mode 100644index 00000000000..d8702833fff--- /dev/null+++ b/apps/server/src/services/agentDocuments/contextPayload.ts@@ -0,0 +1,29 @@+import type {+ AgentDocumentContextPayload,+ AgentDocumentContextRow,+} from '@/database/models/agentDocuments';++/** The fields of a context row the agent runtime injects. */+export const toAgentDocumentContextPayload = (+ doc: AgentDocumentContextRow,+): AgentDocumentContextPayload => ({+ content: doc.content,+ contentCharCount: doc.contentCharCount,+ createdAt: doc.createdAt,+ description: doc.description,+ documentId: doc.documentId,+ filename: doc.filename,+ fileType: doc.fileType,+ id: doc.id,+ isFolder: doc.isFolder,+ loadRules: doc.loadRules,+ parentId: doc.parentId,+ policy: doc.policy,+ policyLoad: doc.policyLoad,+ policyLoadFormat: doc.policyLoadFormat,+ policyLoadPosition: doc.policyLoadPosition,+ sourceType: doc.sourceType,+ templateId: doc.templateId,+ title: doc.title,+ updatedAt: doc.updatedAt,+});diff --git a/apps/server/src/services/agentDocuments/filenames.ts b/apps/server/src/services/agentDocuments/filenames.tsnew file mode 100644index 00000000000..00c86d4e3c2--- /dev/null+++ b/apps/server/src/services/agentDocuments/filenames.ts@@ -0,0 +1,19 @@+export const MAX_UNIQUE_FILENAME_ATTEMPTS = 1000;++/** `notes.md` + 2 → `notes-2.md`. */+export const appendFilenameSuffix = (filename: string, suffix: number): string => {+ const dotIndex = filename.lastIndexOf('.');++ if (dotIndex <= 0) return `${filename}-${suffix}`;++ return `${filename.slice(0, dotIndex)}-${suffix}${filename.slice(dotIndex)}`;+};++/** `notes.md` + 2 → `notes 2.md`. */+export const appendSpacedFilenameSuffix = (filename: string, suffix: number): string => {+ const dotIndex = filename.lastIndexOf('.');++ if (dotIndex <= 0) return `${filename} ${suffix}`;++ return `${filename.slice(0, dotIndex)} ${suffix}${filename.slice(dotIndex)}`;+};diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.tsindex 7e8179154d8..1e12f14214c 100644--- a/apps/server/src/services/agentDocuments/index.ts+++ b/apps/server/src/services/agentDocuments/index.ts@@ -8,13 +8,12 @@ import { DocumentLoadPosition, getDocumentTemplate, PolicyLoad } from '@lobechatimport { buildAgentSkillIdentifier, WEB_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';import type { LobeChatDatabase } from '@lobechat/database';import { DOCUMENT_FOLDER_TYPE } from '@lobechat/database/schemas';-import type { DocumentAccessScope } from '@lobechat/types';+import type { DocumentAccessScope, DocumentWriteSource } from '@lobechat/types';import { FileSource, ordinaryDocumentAccessScope } from '@lobechat/types';import type {AgentDocument,AgentDocumentContextPayload,- AgentDocumentContextRow,AgentDocumentListItem,AgentDocumentListSourceType,AgentDocumentWithRules,@@ -33,19 +32,27 @@ import { isUuid } from '@/database/utils/uuid';import { AgentDocumentVfsError } from '../agentDocumentVfs/errors';import { isManagedSkillDocument } from '../agentDocumentVfs/mounts/skills/providers/providerSkillsAgentDocumentUtils';import { DocumentService } from '../document';+import { assertDocumentWriteWithinLimit } from '../document/writeLimit';import { FileService } from '../file';import { TOOL_RESULTS_DIR_NAME } from '../toolExecution/constants';+import { excludeArchivedToolResults } from './archivedToolResults';import {type AgentDocumentBodyWriter,writeAgentDocumentBody,writeSnapshotThroughRoom,} from './bodyWrite';import { isRawTextAgentDocument } from './contentFormat';+import { toAgentDocumentContextPayload } from './contextPayload';import {attachEmptyParseShellLiteXML,isEmptyParseShellDocument,projectEmptyParseShell,} from './emptyParseShell';+import {+ appendFilenameSuffix,+ appendSpacedFilenameSuffix,+ MAX_UNIQUE_FILENAME_ATTEMPTS,+} from './filenames';import {type AgentDocumentLiteXMLOperation,applyLiteXMLOperations,@@ -54,7 +61,6 @@ import {exportEditorDataSnapshot,} from './headlessEditor';-const MAX_UNIQUE_FILENAME_ATTEMPTS = 1000;/** Guards the ancestor walk against a corrupt parent cycle. */const MAX_TREE_DEPTH = 64;@@ -84,21 +90,6 @@ export interface CreateAgentFolderResult {created: boolean;folder: AgentDocument;}-const appendFilenameSuffix = (filename: string, suffix: number): string => {- const dotIndex = filename.lastIndexOf('.');-- if (dotIndex <= 0) return `${filename}-${suffix}`;-- return `${filename.slice(0, dotIndex)}-${suffix}${filename.slice(dotIndex)}`;-};--const appendSpacedFilenameSuffix = (filename: string, suffix: number): string => {- const dotIndex = filename.lastIndexOf('.');-- if (dotIndex <= 0) return `${filename} ${suffix}`;-- return `${filename.slice(0, dotIndex)} ${suffix}${filename.slice(dotIndex)}`;-};interface UpsertDocumentParams {agentId: string;@@ -110,6 +101,11 @@ interface UpsertDocumentParams {metadata?: Record<string, any>;policy?: AgentDocumentPolicy;policyLoad?: PolicyLoad;+ /**+ * Who asked for the write. Defaults to `user` (the upsert API); templates,+ * onboarding and clones pass `system` to skip the per-document character limit.+ */+ source?: DocumentWriteSource;templateId?: string;updatedAt?: Date;}@@ -117,6 +113,8 @@ interface UpsertDocumentParams {interface CreateAgentDocumentOptions {hintIsSkill?: boolean;parentId?: string;+ /** Defaults to `agent`: these entry points are the agent document tools. */+ source?: DocumentWriteSource;}type AgentDocumentWithLiteXML = AgentDocument & { litexml?: string };@@ -125,71 +123,6 @@ type ProjectableAgentDocument = Pick<'content' | 'editorData' | 'fileType' | 'templateId'>;-/** Collect ids of root `.tool-results` archive folders present in a doc list. */-const collectArchiveFolderIds = <- T extends Pick<AgentDocument, 'documentId' | 'parentId' | 'filename' | 'fileType'>,->(- docs: T[],-): Set<string> =>- new Set(- docs- .filter(- (d) =>- d.filename === TOOL_RESULTS_DIR_NAME &&- !d.parentId &&- d.fileType === DOCUMENT_FOLDER_TYPE,- )- .map((d) => d.documentId),- );--/**- * Hide the auto-created `.tool-results/` archive (root folder + its children)- * from user-facing document lists. Applied by default everywhere, including- * `listDocuments` / `listDocumentsForTopic`. The tool runtime that lets agents- * discover archived entries opts back in via `includeArchivedToolResults`.- *- * `archiveFolderIds` lets callers whose list may not contain the folder row- * supply the ids explicitly — the topic path only sees the archived file- * (which is topic-associated), never the folder, so it can't be derived from- * the list alone.- */-const excludeArchivedToolResults = <- T extends Pick<AgentDocument, 'documentId' | 'parentId' | 'filename' | 'fileType'>,->(- docs: T[],- archiveFolderIds: Set<string> = collectArchiveFolderIds(docs),-): T[] => {- if (archiveFolderIds.size === 0) return docs;- return docs.filter(- (d) =>- !archiveFolderIds.has(d.documentId) && (!d.parentId || !archiveFolderIds.has(d.parentId)),- );-};--const toAgentDocumentContextPayload = (- doc: AgentDocumentContextRow,-): AgentDocumentContextPayload => ({- content: doc.content,- contentCharCount: doc.contentCharCount,- createdAt: doc.createdAt,- description: doc.description,- documentId: doc.documentId,- filename: doc.filename,- fileType: doc.fileType,- id: doc.id,- isFolder: doc.isFolder,- loadRules: doc.loadRules,- parentId: doc.parentId,- policy: doc.policy,- policyLoad: doc.policyLoad,- policyLoadFormat: doc.policyLoadFormat,- policyLoadPosition: doc.policyLoadPosition,- sourceType: doc.sourceType,- templateId: doc.templateId,- title: doc.title,- updatedAt: doc.updatedAt,-});-/*** Service for managing agent documents with reusable template sets.* Document-level policy controls runtime behavior (context rendering/retrieval).@@ -337,9 +270,11 @@ export class AgentDocumentsService {metadata?: Record<string, unknown>;parentId?: string;policy?: AgentDocumentPolicy;+ source?: DocumentWriteSource;templateId?: string;},) {+ const { source, ...createParams } = params ?? {};const baseFilename = buildDocumentFilename(title);let filename = baseFilename;@@ -363,14 +298,33 @@ export class AgentDocumentsService {}const snapshot = await createAgentMarkdownSnapshot(content);+ await this.assertWithinCharLimit(snapshot.content.length, 0, source ?? 'agent');return this.agentDocumentModel.create(agentId, filename, snapshot.content, {- ...params,+ ...createParams,editorData: snapshot.editorData,title,});}+ /**+ * Refuses a write that would leave a document over the plan's character limit,+ * before anything is persisted. A write that does not grow the document passes.+ */+ private assertWithinCharLimit(+ charCount: number,+ previousCharCount: number,+ source: DocumentWriteSource,+ ) {+ return assertDocumentWriteWithinLimit({+ charCount,+ previousCharCount,+ source,+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+ }+/*** Initialize documents from a specific template set.*/@@ -392,6 +346,7 @@ export class AgentDocumentsService {? { context: { policyLoadFormat: template.policyLoadFormat } }: undefined,policyLoad: template.policyLoad,+ source: 'system',templateId,});}@@ -413,6 +368,7 @@ export class AgentDocumentsService {? { context: { policyLoadFormat: template.policyLoadFormat } }: undefined,policyLoad: template.policyLoad,+ source: 'system',templateId: templateSet.id,});}@@ -596,9 +552,19 @@ export class AgentDocumentsService {policyLoad,createdAt,updatedAt,+ source = 'user',}: UpsertDocumentParams) {const snapshot = await createMarkdownEditorSnapshot(content);+ if (source !== 'system') {+ const existing = await this.agentDocumentModel.findByFilename(agentId, filename);+ await this.assertWithinCharLimit(+ snapshot.content.length,+ existing?.content?.length ?? 0,+ source,+ );+ }+return this.agentDocumentModel.upsert(agentId, filename, snapshot.content, {createdAt,editorData: snapshot.editorData,@@ -714,6 +680,7 @@ export class AgentDocumentsService {return this.createWithUniqueFilename(agentId, finalTitle, finalContent, {...(metadata ? { metadata } : {}),...(parentId ? { parentId } : {}),+ source: options.source ?? 'agent',});}@@ -1010,6 +977,8 @@ export class AgentDocumentsService {loadRules: doc.loadRules,metadata: doc.metadata || undefined,policy: doc.policy || undefined,+ // A clone copies content the user already stored; it must not be refused.+ source: 'system',templateId: doc.templateId || undefined,});}@@ -1072,6 +1041,9 @@ export class AgentDocumentsService {return this.projectDocumentContent(doc);}+ /**+ * System write (onboarding documents), exempt from the per-document character limit.+ */async upsertDocumentByFilename({agentId,filename,@@ -1086,7 +1058,7 @@ export class AgentDocumentsService {const snapshot = await createAgentMarkdownSnapshot(content);if (existing && projectedExisting?.content !== snapshot.content) {- if (await writeSnapshotThroughRoom(this.bodyWriter, existing.documentId, snapshot))+ if (await writeSnapshotThroughRoom(this.bodyWriter, existing.documentId, snapshot, 'system'))return (await this.agentDocumentModel.findById(existing.id)) ?? existing;await this.documentService.trySaveCurrentDocumentHistory(existing.documentId, 'llm_call');}@@ -1096,7 +1068,12 @@ export class AgentDocumentsService {});}- async replaceDocumentContentById(documentId: string, content: string, expectedAgentId?: string) {+ async replaceDocumentContentById(+ documentId: string,+ content: string,+ expectedAgentId?: string,+ source: DocumentWriteSource = 'agent',+ ) {const doc = await this.getDocumentByIdInAgent(documentId, expectedAgentId);if (!doc) return undefined;@@ -1107,7 +1084,12 @@ export class AgentDocumentsService {const target = { agentDocumentId: documentId, documentId: doc.documentId };const recordHistory = doc.content !== snapshot.content;- await writeAgentDocumentBody(this.bodyWriter, target, snapshot, { recordHistory });+ await writeAgentDocumentBody(this.bodyWriter, target, snapshot, {+ beforeRowWrite: () =>+ this.assertWithinCharLimit(snapshot.content.length, doc.content?.length ?? 0, source),+ recordHistory,+ writeSource: source,+ });return this.getDocumentByIdInAgent(documentId, expectedAgentId);}@@ -1115,6 +1097,7 @@ export class AgentDocumentsService {documentId: string,operations: AgentDocumentLiteXMLOperation[],expectedAgentId?: string,+ source: DocumentWriteSource = 'agent',) {const doc = await this.getDocumentByIdInAgent(documentId, expectedAgentId);if (!doc) return undefined;@@ -1124,12 +1107,16 @@ export class AgentDocumentsService {fallbackContent: doc.content,operations,});-// History must capture the successfully hydrated pre-edit state. Persisted// editorData may be the stale payload that forced Markdown recovery.const target = { agentDocumentId: documentId, documentId: doc.documentId };const { previousEditorData } = snapshot;- await writeAgentDocumentBody(this.bodyWriter, target, snapshot, { previousEditorData });+ await writeAgentDocumentBody(this.bodyWriter, target, snapshot, {+ beforeRowWrite: () =>+ this.assertWithinCharLimit(snapshot.content.length, doc.content?.length ?? 0, source),+ previousEditorData,+ writeSource: source,+ });return this.getDocumentByIdInAgent(documentId, expectedAgentId);}@@ -1171,6 +1158,7 @@ export class AgentDocumentsService {);}+ // A copy has the length of its source, so it is exempt from the character limit.return this.agentDocumentModel.copy(documentId, newTitle);}diff --git a/apps/server/src/services/agentDocuments/index.writeLimit.test.ts b/apps/server/src/services/agentDocuments/index.writeLimit.test.tsnew file mode 100644index 00000000000..ba0c3b8518f--- /dev/null+++ b/apps/server/src/services/agentDocuments/index.writeLimit.test.ts@@ -0,0 +1,147 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { checkDocumentCharLimit } from '@/business/server/document/writeLimit';+import { AgentDocumentModel } from '@/database/models/agentDocuments';+import type { LobeChatDatabase } from '@/database/type';++import { DocumentService } from '../document';+import { AgentDocumentsService } from './index';++const { writePageBodyThroughRoom } = vi.hoisted(() => ({ writePageBodyThroughRoom: vi.fn() }));++vi.mock('@/business/server/document/writeLimit', () => ({ checkDocumentCharLimit: vi.fn() }));+vi.mock('../pageCollab/bodyWriter', () => ({ writePageBodyThroughRoom }));++vi.mock('@/database/models/agentDocuments', () => ({+ AgentDocumentModel: vi.fn(),+ DocumentLoadPosition: { BEFORE_FIRST_USER: 'before_first_user' },+ buildDocumentFilename: vi.fn((title: string) => title),+ deriveAgentDocumentFields: vi.fn(() => ({})),+ extractMarkdownH1Title: vi.fn((content: string) => ({ content })),+}));+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));+vi.mock('@/database/models/agentSkill', () => ({ AgentSkillModel: vi.fn() }));+vi.mock('@/database/models/topicDocument', () => ({ TopicDocumentModel: vi.fn() }));+vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));+vi.mock('../document', () => ({ DocumentService: vi.fn() }));+vi.mock('../file', () => ({ FileService: vi.fn() }));+vi.mock('../skill/resource', () => ({ SkillResourceService: vi.fn() }));++vi.mock('@lobehub/editor/headless', () => ({+ DEFAULT_HEADLESS_EDITOR_PLUGINS: [],+ createHeadlessEditor: vi.fn(() => {+ let markdown = '';+ return {+ destroy: vi.fn(),+ export: vi.fn(() => ({ editorData: { root: { children: [] } }, markdown })),+ hydrateEditorData: vi.fn(),+ hydrateMarkdown: vi.fn((content: string) => {+ markdown = content;+ }),+ };+ }),+}));++const check = vi.mocked(checkDocumentCharLimit);++describe('AgentDocumentsService per-document character limit', () => {+ const doc = {+ agentId: 'agent-1',+ content: 'x'.repeat(20),+ documentId: 'documents-1',+ id: 'agent-doc-1',+ title: 'Doc',+ };+ const model = {+ copy: vi.fn(),+ create: vi.fn(),+ findByFilename: vi.fn(),+ findByParentAndFilename: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ upsert: vi.fn(),+ };+ const documentService = { trySaveCurrentDocumentHistory: vi.fn() };+ const service = () => new AgentDocumentsService({} as LobeChatDatabase, 'user-1');++ beforeEach(() => {+ vi.clearAllMocks();+ (AgentDocumentModel as any).mockImplementation(function () {+ return model;+ });+ (DocumentService as any).mockImplementation(function () {+ return documentService;+ });+ check.mockResolvedValue({ allowed: false, limit: 10, plan: 'free' });+ writePageBodyThroughRoom.mockResolvedValue(false);+ model.findById.mockResolvedValue(doc);+ model.findByFilename.mockResolvedValue(doc);+ model.findByParentAndFilename.mockResolvedValue(undefined);+ });++ it('refuses an agent createDocument over the limit before persisting', async () => {+ await expect(service().createDocument('agent-1', 'Doc', 'x'.repeat(50))).rejects.toMatchObject({+ cause: { data: { code: 'DocumentCharLimitExceeded', limit: 10 } },+ });++ expect(check).toHaveBeenCalledWith(+ expect.objectContaining({ charCount: 50, source: 'agent', userId: 'user-1' }),+ );+ expect(model.create).not.toHaveBeenCalled();+ });++ it('refuses an agent full rewrite of a page without a live room, leaving no row write', async () => {+ await expect(+ service().replaceDocumentContentById('agent-doc-1', 'x'.repeat(50), 'agent-1'),+ ).rejects.toMatchObject({ cause: { data: { code: 'DocumentCharLimitExceeded' } } });++ expect(writePageBodyThroughRoom).toHaveBeenCalledWith(+ expect.anything(),+ 'documents-1',+ expect.anything(),+ expect.objectContaining({ writeSource: 'agent' }),+ );+ expect(documentService.trySaveCurrentDocumentHistory).not.toHaveBeenCalled();+ expect(model.update).not.toHaveBeenCalled();+ });++ it('allows an agent rewrite that shrinks an over-limit document', async () => {+ await service().replaceDocumentContentById('agent-doc-1', 'x'.repeat(15), 'agent-1');++ expect(model.update).toHaveBeenCalled();+ });++ it('checks a user upsert against the stored length and refuses growth', async () => {+ await expect(+ service().upsertDocument({ agentId: 'agent-1', content: 'x'.repeat(50), filename: 'a.md' }),+ ).rejects.toMatchObject({ cause: { data: { code: 'DocumentCharLimitExceeded' } } });++ expect(check).toHaveBeenCalledWith(expect.objectContaining({ source: 'user' }));+ expect(model.upsert).not.toHaveBeenCalled();+ });++ it('exempts system upserts (templates, clones) and onboarding upserts by filename', async () => {+ await service().upsertDocument({+ agentId: 'agent-1',+ content: 'x'.repeat(50),+ filename: 'a.md',+ source: 'system',+ });+ await service().upsertDocumentByFilename({+ agentId: 'agent-1',+ content: 'x'.repeat(50),+ filename: 'a.md',+ });++ expect(check).not.toHaveBeenCalled();+ expect(model.upsert).toHaveBeenCalledTimes(2);+ });++ it('exempts copyDocumentById', async () => {+ await service().copyDocumentById('agent-doc-1', undefined, 'agent-1');++ expect(check).not.toHaveBeenCalled();+ expect(model.copy).toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.tsindex 29924f6e3ee..a277421748a 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/index.ts@@ -31,6 +31,7 @@ import {} from './guards';import { dispatchAfterStepHooks, dispatchBeforeStepHooks, persistStepTracking } from './hooks';import { prepareStepInput } from './prepare';+import { startRunSlotLease } from './runSlotLease';import { runAndReconcileStep, saveAndPublishStep } from './runStep';const log = debug('lobe-server:agent-runtime-service');@@ -112,6 +113,7 @@ export async function executeStep(// Hoisted so the shared `finally` can stop it on every exit path — an// orphaned poll would keep reading Redis for a step that is long gone.let abortPoll: StepAbortPoll | undefined;+ let stopRunSlotLease: (() => void) | undefined;// Hoisted so the error-path snapshot finalize can record an// approximate startedAt for the failing step. The inner `startAt` at the@@ -148,6 +150,7 @@ export async function executeStep(if (!agentState) {throw new Error(`Agent state not found for operation ${operationId}`);}+ stopRunSlotLease = startRunSlotLease(deps.userId, agentState);// A run created without its init still carries the turn's request: run// that init here, after the step claim and before anything is published.@@ -368,6 +371,7 @@ export async function executeStep(} finally {invokeAgentSpan.end();abortPoll?.stop();+ stopRunSlotLease?.();stopStepLockHeartbeat();// Parked runs (human input, async tools) and finished ones are read back// by a different invocation, so the partial cannot stay in memory only.diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runSlotLease.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runSlotLease.tsnew file mode 100644index 00000000000..3eeded51481--- /dev/null+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/executeStep/runSlotLease.ts@@ -0,0 +1,26 @@+import type { AgentState } from '@lobechat/agent-runtime';++import { renewAgentRunSlot } from '@/business/server/agent-run/runConcurrency';++/** Renewal cadence, well inside the lease lifetime so one missed tick does not drop it. */+export const RUN_SLOT_RENEW_MS = 60_000;++/**+ * Keeps the run tree's concurrency slot alive while this step executes. A+ * child run renews its parent's slot: one tree holds one slot, so a parent+ * parked on its children keeps it for as long as they work. Renewing never+ * recreates a lapsed lease, so runs that took no slot stay slot-free.+ *+ * @returns stops the periodic renewal+ */+export const startRunSlotLease = (userId: string, state: AgentState): (() => void) => {+ const holderId = state.origin?.lineage?.parentOperationId ?? state.operationId;++ const renew = () => {+ renewAgentRunSlot(userId, holderId).catch(() => undefined);+ };+ renew();+ const timer = setInterval(renew, RUN_SLOT_RENEW_MS);+ (timer as { unref?: () => void }).unref?.();+ return () => clearInterval(timer);+};diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.runSlot.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.runSlot.test.tsnew file mode 100644index 00000000000..9cd18a2611f--- /dev/null+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.runSlot.test.ts@@ -0,0 +1,77 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import { hookDispatcher } from '../hooks';+import { CompletionLifecycle } from '.';++const { releaseAgentRunSlot } = vi.hoisted(() => ({ releaseAgentRunSlot: vi.fn() }));++vi.mock('@/business/server/agent-run/runConcurrency', () => ({ releaseAgentRunSlot }));+vi.mock('@/database/models/work', () => import('./testUtils').then((m) => m.workModelModule()));+vi.mock('@/database/models/topic', () => import('./testUtils').then((m) => m.topicModelModule()));+vi.mock('@/business/server/agent-run/agentInterventionReview', () =>+ import('./testUtils').then((m) => m.agentInterventionReviewModule()),+);+vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () =>+ import('./testUtils').then((m) => m.notifyAgentRunCompletedModule()),+);+vi.mock('../agentInterventionNotification', () =>+ import('./testUtils').then((m) => m.agentInterventionNotificationModule()),+);+vi.mock('@/server/services/workRegistration', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ registerWorksForOperation: vi.fn(),+}));++const buildLifecycle = () => {+ const lifecycle = new CompletionLifecycle({} as any, 'user-1');+ (lifecycle as any).agentOperationModel = {+ findById: vi.fn(async () => null),+ recordCompletion: vi.fn(async () => true),+ sumChildUsage: vi.fn(async () => undefined),+ };+ (lifecycle as any).messageModel = { update: vi.fn(async () => ({ success: true })) };+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});+ return lifecycle;+};++const state = (status: string) => ({+ host: { hooks: [] },+ messages: [{ content: 'reply', role: 'assistant' }],+ origin: { agentId: 'agt_1', userId: 'user-1' },+ status,+});++describe('CompletionLifecycle.dispatchHooks — concurrency slot', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ releaseAgentRunSlot.mockReset();+ });++ it.each(['done', 'error', 'interrupted'])(+ 'frees the slot when the run ends in %s',+ async (reason) => {+ await buildLifecycle().dispatchHooks('op-1', state(reason), reason, {+ skipErrorMessageWrite: true,+ });++ expect(releaseAgentRunSlot).toHaveBeenCalledWith('user-1', 'op-1');+ },+ );++ it('frees the slot while the run waits on a human decision', async () => {+ await buildLifecycle().dispatchHooks('op-1', state('waiting_for_human'), 'waiting_for_human');++ expect(releaseAgentRunSlot).toHaveBeenCalledWith('user-1', 'op-1');+ });++ it.each(['waiting_for_async_tool', 'waiting_for_client'])(+ 'keeps the slot while the same run is parked in %s',+ async (reason) => {+ await buildLifecycle().dispatchHooks('op-1', state(reason), reason);++ expect(releaseAgentRunSlot).not.toHaveBeenCalled();+ },+ );+});diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.tsindex bac36b017b0..7a6d0732464 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts@@ -1,5 +1,6 @@import debug from 'debug';+import { releaseAgentRunSlot } from '@/business/server/agent-run/runConcurrency';import {AgentOperationModel,type RecordOperationStartParams,@@ -362,6 +363,11 @@ export class CompletionLifecycle {if (isAsyncToolPark) return;+ // The run tree no longer works, so its concurrency slot frees now rather+ // than when the lease lapses. A run parked on a human decision frees it+ // too; its continuation takes a slot of its own.+ await releaseAgentRunSlot(runOrigin.userId || this.userId, operationId);+// `lastAssistantContent` comes off the Redis-backed `state.messages`,// while the assistant message row is persisted through a separate// `messageModel.update` path. When the two diverge (state entry emptydiff --git a/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts b/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.tsindex ed9820d10c6..6dfda8cd17b 100644--- a/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts+++ b/apps/server/src/services/agentSignal/services/__tests__/receiptRollbackService.test.ts@@ -149,6 +149,7 @@ describe('rollbackAgentSignalReceipt', () => {lockOwnerId: 'server:lock-owner',restoreFromHistoryId: 'history-1',saveSource: 'restore',+ writeSource: 'system',});expect(mocks.receiptService.updateAgentSignalReceiptMetadata).toHaveBeenCalledWith('receipt-1',diff --git a/apps/server/src/services/agentSignal/services/receiptRollbackService.ts b/apps/server/src/services/agentSignal/services/receiptRollbackService.tsindex 631e3478195..fd9d4a2f695 100644--- a/apps/server/src/services/agentSignal/services/receiptRollbackService.ts+++ b/apps/server/src/services/agentSignal/services/receiptRollbackService.ts@@ -296,6 +296,7 @@ export const rollbackAgentSignalReceipt = async (...(lockOwnerId ? { lockOwnerId } : {}),restoreFromHistoryId: history.id,saveSource: 'restore',+ writeSource: 'system',},{ userId: context.userId, workspaceId: context.workspaceId },);diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex a0716db3691..0d19129a650 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -75,6 +75,7 @@ import {} from './pipeline/groupMemberApproval';import { resolveNewThread } from './pipeline/newThread';import { createGroupAgentTopic, type PrecreatedTopicDeps } from './pipeline/precreatedTopic';+import { releaseUnstartedRunSlot, type RunSlotClaim } from './pipeline/runSlot';import { scheduleAgentRun } from './pipeline/scheduleAgentRun';import { runWithTopicStart, type TopicStartDeps } from './pipeline/topicStart';import { bindTopicWorkingDirectory } from './pipeline/topicWorkingDirectory';@@ -527,9 +528,12 @@ export class AiAgentService {rollbackSnapshot: [],};+ const runSlot: RunSlotClaim = {};+try {- return await execAgentTurn(this.execAgentTurnDeps, params, approvalClaim);+ return await execAgentTurn(this.execAgentTurnDeps, params, approvalClaim, runSlot);} finally {+ await releaseUnstartedRunSlot(runSlot, this.userId);if (!approvalClaim.continuationPrepared &&!approvalClaim.continuationStarted &&diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.onScheduled.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.onScheduled.test.tsnew file mode 100644index 00000000000..7cc7d884760--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.onScheduled.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it, vi } from 'vitest';++import { startOperation } from '../startOperation';++vi.mock('@/libs/trpc/utils/internalJwt', () => ({+ signUserJWT: vi.fn().mockResolvedValue('jwt'),+}));++const setup = (autoStarted: boolean) => {+ const deps = {+ agentRuntimeService: {+ acceptsFileWorks: vi.fn(async () => false),+ acceptsMemberRuntimeEnd: vi.fn(async () => false),+ createOperation: vi.fn(async () => ({ autoStarted, messageId: 'msg-assistant' })),+ getLlmExecutor: vi.fn(async () => undefined),+ getOperationEditingGroupId: vi.fn(async () => undefined),+ },+ messageModel: { update: vi.fn(async () => undefined) },+ retirePendingApprovalOperation: vi.fn(),+ topicModel: {+ updateMetadata: vi.fn(async () => {+ throw new Error('metadata write failed');+ }),+ },+ userId: 'user-1',+ withholdGatewayToken: true,+ } as any;+ const ctx = {+ agentConfig: {},+ assistantMessageId: 'msg-assistant',+ model: 'gpt',+ provider: 'openai',+ resolvedAgentId: 'agt-1',+ topicId: 'tpc-1',+ userMessageId: 'msg-user',+ } as any;+ const onScheduled = vi.fn();+ const input = {+ approvalClaim: {},+ approvalSourceToolMessageIds: [],+ autoStart: true,+ discovery: {+ credentialFactsPromise: Promise.resolve(undefined),+ modelMediaCapabilities: {},+ toolsResult: { enabledToolIds: [] },+ },+ initialContext: {},+ onScheduled,+ operationId: 'op-new',+ prep: { allMessages: [], deviceSystemInfo: {} },+ updateAbortedAssistantMessage: vi.fn(),+ userInterventionConfig: { approvalMode: 'manual' },+ } as any;+ return { ctx, deps, input, onScheduled };+};++describe('startOperation › onScheduled', () => {+ // A marker write failing after the first step is queued still returns+ // `success: false`, but the run executes; its concurrency slot must follow+ // the run instead of being released by the caller.+ it('reports a queued run even when a later startup write fails', async () => {+ const { ctx, deps, input, onScheduled } = setup(true);++ const result = await startOperation(deps, ctx, input);++ expect(result.success).toBe(false);+ expect(onScheduled).toHaveBeenCalledOnce();+ });++ it('does not report a run created without auto-start', async () => {+ const { ctx, deps, input, onScheduled } = setup(false);++ await startOperation(deps, ctx, input);++ expect(onScheduled).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.tsindex ee13b5b2261..d82b01d093d 100644--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts@@ -36,6 +36,7 @@ import { createHistoryMessagesLoader } from './operationPrep';import { resolveRunAgentConfig } from './resolveRunAgentConfig';import { loadResumeParentMessage } from './resumeParent';import { resolveRunSettings } from './runSettings';+import { bindRunSlot, claimRunSlot, resolveRunSlotPolicy, type RunSlotClaim } from './runSlot';import { traceSendStage } from './sendTracing';import { startOperation } from './startOperation';import { bindTopicWorkingDirectory } from './topicWorkingDirectory';@@ -87,6 +88,7 @@ export const execAgentTurn = async (deps: ExecAgentTurnDeps,params: InternalExecAgentParams,approvalClaim: ApprovalClaimState,+ runSlot: RunSlotClaim = {},): Promise<ExecAgentResult> => {const {additionalPluginIds,@@ -284,6 +286,12 @@ export const execAgentTurn = async (// flags, tools engine, context snapshot) reads it.if (shareGate) applyShareGateToAgentConfig(agentConfig);+ // Before the turn writes any row: a refused send leaves nothing behind.+ await claimRunSlot(runSlot, {+ policy: resolveRunSlotPolicy(params, { agentConfig, workspaceId: deps.workspaceId }),+ userId: deps.userId,+ });+let resumeParentMessage: Awaited<ReturnType<MessageModel['findById']>>;// `resumeApproval` implies the same "load parent message + skip user@@ -590,6 +598,7 @@ export const execAgentTurn = async (params.reservedOperationId ??continuationOperationId ??`op_${Date.now()}_${resolvedAgentId}_${topicId}_${nanoid(8)}`;+ await bindRunSlot(runSlot, deps.userId, operationId);// Stages 5–18 — the run's init: the tool surface, the message/context// assembly, and the human decision a resumed approval turns into the first@@ -719,7 +728,7 @@ export const execAgentTurn = async (// 19. Create the operation via AgentRuntimeService, persist the reconnect// marker, and mint the gateway token (see `pipeline/startOperation`).- return traceSendStage('start_operation', () =>+ const started = await traceSendStage('start_operation', () =>startOperation({agentRuntimeService: deps.agentRuntimeService,@@ -739,6 +748,11 @@ export const execAgentTurn = async (approvalSourceToolMessageIds,autoStart,onOperationCreated: params.onOperationCreated,+ // From here the run's completion releases the slot; a run that never+ // started (failed, or created without auto-start) gives it back.+ onScheduled: () => {+ runSlot.handedOff = true;+ },botContext,botPlatformContext,clientIp,@@ -774,4 +788,5 @@ export const execAgentTurn = async (},),);+ return started;};diff --git a/apps/server/src/services/aiAgent/pipeline/runSlot.test.ts b/apps/server/src/services/aiAgent/pipeline/runSlot.test.tsnew file mode 100644index 00000000000..c39699cb3cd--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/runSlot.test.ts@@ -0,0 +1,129 @@+// @vitest-environment node+import { ChatErrorType } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { AgentConfigWithId } from '@/server/services/agent';++import type { InternalExecAgentParams } from '../types';+import {+ bindRunSlot,+ claimRunSlot,+ releaseUnstartedRunSlot,+ resolveRunSlotPolicy,+ type RunSlotClaim,+} from './runSlot';++const slots = vi.hoisted(() => ({+ acquireAgentRunSlot: vi.fn(),+ rebindAgentRunSlot: vi.fn(),+ releaseAgentRunSlot: vi.fn(),+}));++vi.mock('@/business/server/agent-run/runConcurrency', () => slots);++const agentConfig = { id: 'agt_1', model: 'gpt-4o' } as AgentConfigWithId;+const composerSend = {+ agentId: 'agt_1',+ interactiveStart: true,+ prompt: 'hi',+} as InternalExecAgentParams;++const policyOf = (params: Partial<InternalExecAgentParams>, workspaceId?: string) =>+ resolveRunSlotPolicy({ ...composerSend, ...params } as InternalExecAgentParams, {+ agentConfig,+ workspaceId,+ });++describe('resolveRunSlotPolicy', () => {+ it('refuses a fresh composer send past the cap', () => {+ expect(policyOf({})).toBe('enforced');+ });++ it('counts but never refuses a run that continues one already started', () => {+ expect(policyOf({ resumeApproval: { decision: 'approved' } as any })).toBe('counted');+ expect(policyOf({ steer: true } as any)).toBe('counted');+ expect(policyOf({ parentMessageId: 'msg_1' })).toBe('counted');+ expect(policyOf({ interactiveStart: false })).toBe('counted');+ });++ it('exempts sub-agent, group member, Workspace and background runs', () => {+ expect(policyOf({ parentOperationId: 'op_parent' })).toBe('exempt');+ expect(policyOf({ appContext: { isSubAgent: true } as any })).toBe('exempt');+ expect(policyOf({ appContext: { orchestrationRole: 'member' } as any })).toBe('exempt');+ expect(policyOf({}, 'ws_1')).toBe('exempt');+ expect(policyOf({ trigger: 'cron' } as any)).toBe('exempt');+ });++ it('exempts external agents', () => {+ expect(+ resolveRunSlotPolicy(composerSend, {+ agentConfig: {+ ...agentConfig,+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },+ } as AgentConfigWithId,+ }),+ ).toBe('exempt');+ });+});++describe('run slot claim', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('rejects the send past the cap with TOO_MANY_REQUESTS and the cap', async () => {+ slots.acquireAgentRunSlot.mockResolvedValue({ acquired: false });+ const claim: RunSlotClaim = {};++ const error = await claimRunSlot(claim, { policy: 'enforced', userId: 'u1' }).catch(+ (e: unknown) => e,+ );++ expect(error).toBeInstanceOf(TRPCError);+ expect((error as TRPCError).code).toBe('TOO_MANY_REQUESTS');+ expect((error as TRPCError).message).toBe(ChatErrorType.AgentConcurrencyLimitExceeded);+ expect(claim.holderId).toBeUndefined();+ });++ it('takes no slot for an exempt run', async () => {+ const claim: RunSlotClaim = {};+ await claimRunSlot(claim, { policy: 'exempt', userId: 'u1' });++ expect(slots.acquireAgentRunSlot).not.toHaveBeenCalled();+ await releaseUnstartedRunSlot(claim, 'u1');+ expect(slots.releaseAgentRunSlot).not.toHaveBeenCalled();+ });++ it('asks a continuation to be counted without enforcement', async () => {+ slots.acquireAgentRunSlot.mockResolvedValue({ acquired: true });+ await claimRunSlot({}, { policy: 'counted', userId: 'u1' });++ expect(slots.acquireAgentRunSlot).toHaveBeenCalledWith(+ expect.objectContaining({ enforce: false, userId: 'u1' }),+ );+ });++ it('moves the slot to the operation and frees it when the operation never starts', async () => {+ slots.acquireAgentRunSlot.mockResolvedValue({ acquired: true });+ const claim: RunSlotClaim = {};+ await claimRunSlot(claim, { policy: 'enforced', userId: 'u1' });+ const provisional = claim.holderId!;++ await bindRunSlot(claim, 'u1', 'op_1');+ expect(slots.rebindAgentRunSlot).toHaveBeenCalledWith('u1', provisional, 'op_1');++ await releaseUnstartedRunSlot(claim, 'u1');+ expect(slots.releaseAgentRunSlot).toHaveBeenCalledWith('u1', 'op_1');+ });++ it('leaves the slot to the started operation once handed off', async () => {+ slots.acquireAgentRunSlot.mockResolvedValue({ acquired: true });+ const claim: RunSlotClaim = {};+ await claimRunSlot(claim, { policy: 'enforced', userId: 'u1' });+ claim.handedOff = true;++ await releaseUnstartedRunSlot(claim, 'u1');+ expect(slots.releaseAgentRunSlot).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/runSlot.ts b/apps/server/src/services/aiAgent/pipeline/runSlot.tsnew file mode 100644index 00000000000..80c7ffe9653--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/runSlot.ts@@ -0,0 +1,108 @@+import { isHeterogeneousAgentModelId } from '@lobechat/const';+import { ChatErrorType } from '@lobechat/types';+import { nanoid } from '@lobechat/utils';+import { TRPCError } from '@trpc/server';++import {+ acquireAgentRunSlot,+ rebindAgentRunSlot,+ releaseAgentRunSlot,+} from '@/business/server/agent-run/runConcurrency';+import type { AgentConfigWithId } from '@/server/services/agent';+import { isForegroundOperationTrigger } from '@/server/services/agentRuntime/foregroundOperation';++import type { InternalExecAgentParams } from '../types';++/**+ * How a run counts toward its user's concurrent-run cap.+ *+ * - `exempt`: takes no slot. A sub-agent or group member rides its root's+ * slot; Workspace, shared-visitor and background runs are capped elsewhere+ * or must not fail; an external agent (Claude Code, Codex, …) runs on a+ * device that never renews a lease.+ * - `counted`: takes a slot without being refused — it continues a run the+ * user already started (an approval or tool-result resume, a queued+ * follow-up, a regeneration), or no composer is there to tell.+ * - `enforced`: a fresh composer send, refused once the cap is reached.+ */+export type RunSlotPolicy = 'counted' | 'enforced' | 'exempt';++export const resolveRunSlotPolicy = (+ params: InternalExecAgentParams,+ { agentConfig, workspaceId }: { agentConfig: AgentConfigWithId; workspaceId?: string },+): RunSlotPolicy => {+ const { appContext } = params;+ if (workspaceId || params.shareGate) return 'exempt';+ if (+ params.parentOperationId ||+ appContext?.isSubAgent ||+ appContext?.orchestrationRole === 'member'+ )+ return 'exempt';+ if (!isForegroundOperationTrigger(params.trigger)) return 'exempt';+ if (+ agentConfig.agencyConfig?.heterogeneousProvider?.type ||+ isHeterogeneousAgentModelId(agentConfig.model)+ )+ return 'exempt';++ const continuesRun =+ !!params.resume ||+ !!params.resumeApproval ||+ !!params.resumeApprovals?.length ||+ !!params.resumeToolResult ||+ !!params.parentMessageId ||+ !!params.approvalResolutionRequestId ||+ !!params.steer;+ return params.interactiveStart && !continuesRun ? 'enforced' : 'counted';+};++/**+ * The slot one `execAgentTurn` call holds. It is taken before the turn writes+ * any row, under a provisional id because the operation id is minted later,+ * and moved to that id once it exists. Until the operation starts, the caller+ * releases it on every exit; afterwards the run's completion releases it.+ */+export interface RunSlotClaim {+ /** Set once the started operation owns the slot. */+ handedOff?: boolean;+ holderId?: string;+}++/**+ * Takes the run's slot, or throws `TOO_MANY_REQUESTS` before the turn writes+ * anything, so the refused message stays in the composer.+ */+export const claimRunSlot = async (+ claim: RunSlotClaim,+ { policy, userId }: { policy: RunSlotPolicy; userId: string },+): Promise<void> => {+ if (policy === 'exempt') return;++ const holderId = `pending_${nanoid()}`;+ const result = await acquireAgentRunSlot({+ enforce: policy === 'enforced',+ holderId,+ userId,+ });+ if (!result.acquired) {+ throw new TRPCError({+ code: 'TOO_MANY_REQUESTS',+ message: ChatErrorType.AgentConcurrencyLimitExceeded,+ });+ }+ claim.holderId = holderId;+};++/** Moves the claimed slot to the operation that will hold it for the rest of the run. */+export const bindRunSlot = async (claim: RunSlotClaim, userId: string, operationId: string) => {+ if (!claim.holderId || claim.holderId === operationId) return;+ await rebindAgentRunSlot(userId, claim.holderId, operationId);+ claim.holderId = operationId;+};++/** Frees a slot whose operation never started. */+export const releaseUnstartedRunSlot = async (claim: RunSlotClaim, userId: string) => {+ if (!claim.holderId || claim.handedOff) return;+ await releaseAgentRunSlot(userId, claim.holderId);+};diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.tsindex 49b17373e2b..784006a1de0 100644--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts@@ -57,6 +57,12 @@ export interface StartOperationInput {llmExecutor?: InternalExecAgentParams['llmExecutor'];maxSteps?: number;onOperationCreated?: InternalExecAgentParams['onOperationCreated'];+ /**+ * Called once the first step is queued. A later startup failure (a marker+ * write) still returns `success: false` while the run executes, so ownership+ * that follows the run (its concurrency slot) must transfer here.+ */+ onScheduled?: () => void;operationId: string;operationTaskId?: string;parentOperationId?: string;@@ -349,6 +355,7 @@ export const startOperation = async (workspaceId: deps.workspaceId,});approvalClaim.continuationStarted = true;+ if (result.autoStarted) input.onScheduled?.();// The approval continuation is a fresh operation. Legacy direct callers// retire the old parked runtime here, only after createOperation hasdiff --git a/apps/server/src/services/aiAgent/pipeline/topicStart.ts b/apps/server/src/services/aiAgent/pipeline/topicStart.tsindex f2bf318fa12..4e1f6761c3f 100644--- a/apps/server/src/services/aiAgent/pipeline/topicStart.ts+++ b/apps/server/src/services/aiAgent/pipeline/topicStart.ts@@ -3,6 +3,7 @@ import { nanoid } from '@lobechat/utils';import debug from 'debug';import { deriveAgentInterventionContinuationOperationId } from '@/business/server/agent-run/agentInterventionIdentity';+import { releaseAgentRunSlot } from '@/business/server/agent-run/runConcurrency';import type { AgentOperationModel } from '@/database/models/agentOperation';import type { TopicModel } from '@/database/models/topic';import type { AgentRuntimeService } from '@/server/services/agentRuntime';@@ -152,6 +153,9 @@ export const supersedeRunningForegroundOperation = async (if (!interrupted.success) {console.warn('[execAgent] supersede of %s was not confirmed', holderId, { topicId });}+ // The interrupted run settles at its next step boundary; free its slot now+ // so the send that replaces it is not refused for the run it just stopped.+ await releaseAgentRunSlot(deps.userId, holderId);return { holderId, kind };};@@ -298,6 +302,7 @@ export const runWithTopicStart = async (if (interruption.deviceCancellationConfirmed === false) {throw new Error('Replaced heterogeneous agent process did not confirm termination');}+ await releaseAgentRunSlot(deps.userId, replacesOperationId);}const reserved = await acquireTopicStartReservation({allowSameReservationReentry: !params.approvalResolutionRequestId,diff --git a/apps/server/src/services/document/__tests__/writeLimit.service.test.ts b/apps/server/src/services/document/__tests__/writeLimit.service.test.tsnew file mode 100644index 00000000000..f0a886d9f61--- /dev/null+++ b/apps/server/src/services/document/__tests__/writeLimit.service.test.ts@@ -0,0 +1,194 @@+import { type LobeChatDatabase } from '@lobechat/database';+import { TRPCError } from '@trpc/server';+import { 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 { DocumentHistoryService } from '../history';+import { DocumentService } from '../index';++const { checkDocumentCharLimit } = vi.hoisted(() => ({ checkDocumentCharLimit: vi.fn() }));++vi.mock('@/business/server/document/writeLimit', () => ({ checkDocumentCharLimit }));+vi.mock('@/server/modules/AgentRuntime/redis', () => ({ getAgentRuntimeRedisClient: () => null }));+vi.mock('@/server/services/resourceEvents', () => ({ publishResourceEvent: vi.fn() }));+vi.mock('@/database/models/document');+vi.mock('@/database/models/file');+vi.mock('@/database/models/knowledgeBase');+vi.mock('../../file');+vi.mock('../history');++const longEditorData = (length: number) => ({+ root: {+ children: [{ children: [{ text: 'x'.repeat(length), type: 'text' }], type: 'paragraph' }],+ type: 'root',+ },+});++const refuse = () => checkDocumentCharLimit.mockResolvedValue({ allowed: false, limit: 10 });++describe('DocumentService per-document character limit', () => {+ const documentModel = {+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ };+ const db = {+ transaction: async (fn: (tx: unknown) => unknown) => fn({}),+ } as unknown as LobeChatDatabase;+ const service = () => new DocumentService(db, 'user-1', 'ws-1');++ beforeEach(() => {+ vi.clearAllMocks();+ checkDocumentCharLimit.mockResolvedValue({ allowed: true });+ documentModel.create.mockResolvedValue({ id: 'doc-1' });+ documentModel.findById.mockResolvedValue({+ content: '12345678901234',+ fileType: 'custom/document',+ id: 'doc-1',+ updatedAt: new Date(),+ });+ documentModel.update.mockResolvedValue(new Date());+ vi.mocked(DocumentModel).mockImplementation(function () {+ return documentModel as any;+ });+ vi.mocked(DocumentHistoryService).mockImplementation(function () {+ return { createHistory: vi.fn() } as any;+ });+ vi.mocked(FileModel).mockImplementation(function () {+ return {} as any;+ });+ vi.mocked(KnowledgeBaseModel).mockImplementation(function () {+ return {} as any;+ });+ });++ describe('createDocument', () => {+ it('refuses over-limit content before inserting a row', async () => {+ refuse();++ await expect(+ service().createDocument({ content: 'x'.repeat(11), title: 'T' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });++ expect(checkDocumentCharLimit).toHaveBeenCalledWith(+ expect.objectContaining({ charCount: 11, userId: 'user-1', workspaceId: 'ws-1' }),+ );+ expect(documentModel.create).not.toHaveBeenCalled();+ });++ it('skips the check for a system write', async () => {+ refuse();++ await service().createDocument({+ content: 'x'.repeat(11),+ title: 'T',+ writeSource: 'system',+ });++ expect(checkDocumentCharLimit).not.toHaveBeenCalled();+ expect(documentModel.create).toHaveBeenCalled();+ });++ it('passes the agent source to the limit check', async () => {+ await service().createDocument({ content: 'abc', title: 'T', writeSource: 'agent' });++ expect(checkDocumentCharLimit).toHaveBeenCalledWith(+ expect.objectContaining({ source: 'agent' }),+ );+ });++ it('measures editor data sent without matching content', async () => {+ refuse();++ await expect(+ service().createDocument({ content: '', editorData: longEditorData(11), title: 'T' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });++ expect(checkDocumentCharLimit).toHaveBeenCalledWith(+ expect.objectContaining({ charCount: 11 }),+ );+ expect(documentModel.create).not.toHaveBeenCalled();+ });++ it('does not check a document without content', async () => {+ refuse();++ await service().createDocument({ editorData: {}, title: 'T' });++ expect(documentModel.create).toHaveBeenCalled();+ });+ });++ describe('updateDocument', () => {+ it('refuses a write that makes the document longer than the limit', async () => {+ refuse();++ await expect(+ service().updateDocument('doc-1', { content: 'x'.repeat(20) }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });++ expect(documentModel.update).not.toHaveBeenCalled();+ });++ it('allows a write that shrinks an already over-limit document', async () => {+ refuse();++ await service().updateDocument('doc-1', { content: 'x'.repeat(12) });++ expect(documentModel.update).toHaveBeenCalled();+ });++ it('exempts a system write', async () => {+ refuse();++ await service().updateDocument('doc-1', { content: 'x'.repeat(20), writeSource: 'system' });++ expect(documentModel.update).toHaveBeenCalled();+ });++ it('skips room projections', async () => {+ refuse();++ await service().updateDocument('doc-1', {+ content: 'x'.repeat(20),+ origin: 'room-projection',+ });++ expect(checkDocumentCharLimit).not.toHaveBeenCalled();+ expect(documentModel.update).toHaveBeenCalled();+ });++ it('checks a client restore: its history id is not proof of the body', async () => {+ refuse();++ await expect(+ service().updateDocument('doc-1', {+ content: 'x'.repeat(20),+ restoreFromHistoryId: 'h1',+ }),+ ).rejects.toThrow(TRPCError);+ expect(documentModel.update).not.toHaveBeenCalled();+ });++ it('refuses over-limit editor data sent without content', async () => {+ refuse();++ await expect(+ service().updateDocument('doc-1', { editorData: longEditorData(20) }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });++ expect(documentModel.update).not.toHaveBeenCalled();+ });++ it('allows editor data that carries no more text than the stored body', async () => {+ refuse();++ await service().updateDocument('doc-1', { editorData: { root: {} } });++ expect(checkDocumentCharLimit).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/services/document/editorData.test.ts b/apps/server/src/services/document/editorData.test.tsindex 3c789529bc7..c836cf2d82a 100644--- a/apps/server/src/services/document/editorData.test.ts+++ b/apps/server/src/services/document/editorData.test.ts@@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest';import { isValidEditorData } from '@/libs/editor/isValidEditorData';import { applyLiteXMLOperations, exportEditorDataSnapshot } from '../agentDocuments/headlessEditor';-import { resolveDocumentWrite, stripTitleHeading } from './editorData';+import { countEditorDataText, resolveDocumentWrite, stripTitleHeading } from './editorData';describe('resolveDocumentWrite', () => {it('keeps valid Lexical editorData untouched', async () => {@@ -120,3 +120,36 @@ describe('stripTitleHeading', () => {expect(stripTitleHeading('# Report\n\nbody', undefined)).toBe('# Report\n\nbody');});});++describe('countEditorDataText', () => {+ it('counts the body of code blocks and math, which is not in text children', async () => {+ const code = 'x'.repeat(500);+ const { editorData } = await resolveDocumentWrite({+ content: `\`\`\`ts\n${code}\n\`\`\`\n\n$$\n${'y'.repeat(40)}\n$$\n`,+ });++ expect(countEditorDataText(editorData)).toBeGreaterThanOrEqual(540);+ });++ it('sums text across nested nodes', () => {+ const editorData = {+ root: {+ children: [+ { children: [{ text: 'abc', type: 'text' }], type: 'paragraph' },+ {+ children: [{ children: [{ text: 'de', type: 'text' }], type: 'listitem' }],+ type: 'list',+ },+ ],+ type: 'root',+ },+ };++ expect(countEditorDataText(editorData)).toBe(5);+ });++ it('returns 0 for invalid editor data', () => {+ expect(countEditorDataText(undefined)).toBe(0);+ expect(countEditorDataText({ root: {} })).toBe(0);+ });+});diff --git a/apps/server/src/services/document/editorData.ts b/apps/server/src/services/document/editorData.tsindex 12eb50ba2f8..a80b98e5c0b 100644--- a/apps/server/src/services/document/editorData.ts+++ b/apps/server/src/services/document/editorData.ts@@ -88,3 +88,34 @@ export const resolveDocumentWrite = async ({const snapshot = await createMarkdownEditorSnapshot(body);return { content: body, editorData: snapshot.editorData };};++/**+ * Node fields that carry body text: `text` on text nodes, `code` on code blocks+ * and math nodes, which keep their body there instead of in text children.+ */+const BODY_TEXT_FIELDS = ['text', 'code'] as const;++/**+ * Counts the visible text carried by Lexical editor data. Callers may send editor+ * data without a matching Markdown `content`, so length limits measure both and+ * keep the larger one instead of trusting the client-supplied Markdown alone.+ */+export const countEditorDataText = (editorData: unknown): number => {+ if (!isValidEditorData(editorData)) return 0;++ let count = 0;+ const stack: unknown[] = [editorData.root];+ while (stack.length > 0) {+ const node = stack.pop();+ if (typeof node !== 'object' || node === null) continue;++ const record = node as Record<string, unknown>;+ for (const field of BODY_TEXT_FIELDS) {+ const value = record[field];+ if (typeof value === 'string') count += value.length;+ }+ if (Array.isArray(record.children)) stack.push(...record.children);+ }++ return count;+};diff --git a/apps/server/src/services/document/index.ts b/apps/server/src/services/document/index.tsindex b930f76eefd..b6d8a0c15f1 100644--- a/apps/server/src/services/document/index.ts+++ b/apps/server/src/services/document/index.ts@@ -10,7 +10,7 @@ import { type DocumentItem } from '@lobechat/database/schemas';import { documents, files } from '@lobechat/database/schemas';import { loadFile, UnsupportedFileTypeError } from '@lobechat/file-loaders';import { sliceHead } from '@lobechat/prompts/textWindow';-import type { DocumentAccessScope, FileAccessScope } from '@lobechat/types';+import type { DocumentAccessScope, DocumentWriteSource, FileAccessScope } from '@lobechat/types';import {ordinaryDocumentAccessScope,ordinaryFileAccessScope,@@ -33,6 +33,7 @@ import { type LobeDocument } from '@/types/document';import { EditLockService } from '../editLock';import { FileService } from '../file';import { publishResourceEvent } from '../resourceEvents';+import { countEditorDataText } from './editorData';import { DocumentHistoryService } from './history';import type {CompareDocumentHistoryItemsParams,@@ -47,6 +48,7 @@ import type {UpdateDocumentParams,UpdateDocumentResult,} from './types';+import { assertDocumentWriteWithinLimit } from './writeLimit';const log = debug('lobe-chat:service:document');@@ -207,6 +209,8 @@ export class DocumentService {slug?: string;title: string;visibility?: 'private' | 'public';+ /** Who asked for the write; `system` skips the per-document character limit. Defaults to `user`. */+ writeSource?: DocumentWriteSource;}): Promise<DocumentItem> {const {content,@@ -217,6 +221,14 @@ export class DocumentService {slug,visibility,} = params;+ // Refuse before any row (including the KB mirror file) is written.+ await assertDocumentWriteWithinLimit({+ charCount: Math.max(content?.length ?? 0, countEditorDataText(editorData)),+ source: params.writeSource,+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+// Agent tool calls often fill optional ids with "" — that means "unset".// Passed through, it reaches the `parent_id` / `knowledge_base_id` FKs and// fails the insert with an opaque `Failed query` error.@@ -348,6 +360,7 @@ export class DocumentService {slug?: string;title: string;visibility?: 'private' | 'public';+ writeSource?: DocumentWriteSource;}>,): Promise<DocumentItem[]> {// Create all documents in parallel for better performance@@ -810,6 +823,27 @@ export class DocumentService {const updates: Record<string, unknown> = {};+ // Room projections persist what the room already accepted. Checked before+ // anything is persisted. `restoreFromHistoryId` is not an exemption: the+ // client sends it with a body the server does not match against the+ // version, so only server-side restores opt out via `writeSource`.+ // Editor data is measured too because it can arrive without `content`.+ if (+ (params.content !== undefined || editorDataParam !== undefined) &&+ params.origin !== 'room-projection'+ ) {+ await assertDocumentWriteWithinLimit({+ charCount: Math.max(params.content?.length ?? 0, countEditorDataText(editorDataParam)),+ previousCharCount: Math.max(+ currentDocument.content?.length ?? 0,+ countEditorDataText(currentDocument.editorData),+ ),+ source: params.writeSource,+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+ }+if (params.content !== undefined) {updates.content = params.content;updates.totalCharCount = params.content.length;diff --git a/apps/server/src/services/document/types.ts b/apps/server/src/services/document/types.tsindex ace16a892f5..9a1efb5fc58 100644--- a/apps/server/src/services/document/types.ts+++ b/apps/server/src/services/document/types.ts@@ -1,3 +1,5 @@+import type { DocumentWriteSource } from '@lobechat/types';+import type { LobeChatDatabase, Transaction } from '@/database/type';export type DocumentHistorySaveSource = 'autosave' | 'manual' | 'restore' | 'system' | 'llm_call';@@ -87,6 +89,12 @@ export interface UpdateDocumentParams {restoreFromHistoryId?: string;saveSource?: DocumentHistorySaveSource;title?: string;+ /**+ * Who asked for the write; decides whether the per-document character limit+ * applies. Defaults to `user`. Restores, rollbacks and other writes the user+ * did not type pass `system`.+ */+ writeSource?: DocumentWriteSource;}export interface UpdateDocumentResult {diff --git a/apps/server/src/services/document/writeLimit.test.ts b/apps/server/src/services/document/writeLimit.test.tsnew file mode 100644index 00000000000..7c2d97f0c4c--- /dev/null+++ b/apps/server/src/services/document/writeLimit.test.ts@@ -0,0 +1,73 @@+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { checkDocumentCharLimit } from '@/business/server/document/writeLimit';++import { assertDocumentWriteWithinLimit, formatDocumentCharLimitMessage } from './writeLimit';++vi.mock('@/business/server/document/writeLimit', () => ({+ checkDocumentCharLimit: vi.fn(),+}));++const check = vi.mocked(checkDocumentCharLimit);++describe('assertDocumentWriteWithinLimit', () => {+ beforeEach(() => {+ check.mockReset();+ check.mockResolvedValue({ allowed: false, limit: 100, plan: 'free' });+ });++ it('refuses a write past the limit with structured error data', async () => {+ const error = await assertDocumentWriteWithinLimit({ charCount: 150, userId: 'u1' }).catch(+ (e) => e,+ );++ expect(error).toBeInstanceOf(TRPCError);+ expect(error.code).toBe('BAD_REQUEST');+ expect(error.cause).toMatchObject({+ data: { actual: 150, code: 'DocumentCharLimitExceeded', limit: 100, plan: 'free' },+ });+ expect(error.message).toContain('150 characters');+ expect(error.message).toContain('100-character limit');+ expect(check).toHaveBeenCalledWith({+ charCount: 150,+ source: 'user',+ userId: 'u1',+ workspaceId: undefined,+ });+ });++ it('passes when the slot allows the write', async () => {+ check.mockResolvedValue({ allowed: true });+ await expect(+ assertDocumentWriteWithinLimit({ charCount: 150, userId: 'u1' }),+ ).resolves.toBeUndefined();+ });++ it('skips system writes without asking the slot', async () => {+ await assertDocumentWriteWithinLimit({ charCount: 150, source: 'system', userId: 'u1' });+ expect(check).not.toHaveBeenCalled();+ });++ it('lets a write that does not make the document longer through', async () => {+ await assertDocumentWriteWithinLimit({ charCount: 150, previousCharCount: 200, userId: 'u1' });+ await assertDocumentWriteWithinLimit({ charCount: 200, previousCharCount: 200, userId: 'u1' });+ expect(check).not.toHaveBeenCalled();+ });++ it('checks a write that grows a document already over the limit', async () => {+ await expect(+ assertDocumentWriteWithinLimit({ charCount: 201, previousCharCount: 200, userId: 'u1' }),+ ).rejects.toThrow(TRPCError);+ });+});++describe('formatDocumentCharLimitMessage', () => {+ it('omits the plan when there is none and never groups digits', () => {+ const message = formatDocumentCharLimitMessage({ actual: 1_234_567, limit: 500_000 });+ expect(message).toBe(+ 'Document is too long: 1234567 characters, over the 500000-character limit per document. ' ++ 'Split the content into several documents or shorten it.',+ );+ });+});diff --git a/apps/server/src/services/document/writeLimit.ts b/apps/server/src/services/document/writeLimit.tsnew file mode 100644index 00000000000..574e64cb752--- /dev/null+++ b/apps/server/src/services/document/writeLimit.ts@@ -0,0 +1,64 @@+import {+ DOCUMENT_CHAR_LIMIT_EXCEEDED,+ type DocumentCharLimitErrorData,+ type DocumentWriteSource,+} from '@lobechat/types';+import { TRPCError } from '@trpc/server';++import { checkDocumentCharLimit } from '@/business/server/document/writeLimit';++export interface AssertDocumentWriteWithinLimitParams {+ /** Length of the document after the write, in UTF-16 code units. */+ charCount: number;+ /** Length before the write; `0` for a new document. */+ previousCharCount?: number;+ /** Defaults to `user`; pass `system` for writes the user did not ask for. */+ source?: DocumentWriteSource;+ userId: string;+ workspaceId?: string | null;+}++/**+ * Message for a refused write. The agent runtime passes only the message to the+ * model, so it carries the numbers and what to do instead. Numbers stay plain+ * digits: tool error classification treats a 3-digit 4xx/5xx token as an HTTP+ * status.+ */+export const formatDocumentCharLimitMessage = ({+ actual,+ limit,+ plan,+}: Omit<DocumentCharLimitErrorData, 'code'>) =>+ `Document is too long: ${actual} characters, over the ${limit}-character limit per document` ++ `${plan ? ` on the current plan (${plan})` : ''}. ` ++ 'Split the content into several documents or shorten it.';++/**+ * Refuses a write that would leave a document longer than the caller's+ * per-document character limit. A write that does not make the document longer+ * always passes, so a document already over the limit stays editable.+ */+export const assertDocumentWriteWithinLimit = async ({+ charCount,+ previousCharCount = 0,+ source = 'user',+ userId,+ workspaceId,+}: AssertDocumentWriteWithinLimitParams): Promise<void> => {+ if (source === 'system' || charCount <= previousCharCount) return;++ const result = await checkDocumentCharLimit({ charCount, source, userId, workspaceId });+ if (result.allowed) return;++ const data: DocumentCharLimitErrorData = {+ actual: charCount,+ code: DOCUMENT_CHAR_LIMIT_EXCEEDED,+ limit: result.limit,+ plan: result.plan,+ };+ throw new TRPCError({+ cause: { data },+ code: 'BAD_REQUEST',+ message: formatDocumentCharLimitMessage(data),+ });+};diff --git a/apps/server/src/services/goal/reportPage.ts b/apps/server/src/services/goal/reportPage.tsindex 4abfea495c4..dffe58a3498 100644--- a/apps/server/src/services/goal/reportPage.ts+++ b/apps/server/src/services/goal/reportPage.ts@@ -37,7 +37,12 @@ export const writeGoalReportPage = async (const previous = await new DocumentModel(db, userId, workspaceId).findById(previousPageId);if (previous?.fileType === HTML_DOCUMENT_FILE_TYPE) {const updated = await documentService- .updateDocument(previousPageId, { content: html, saveSource: 'llm_call', title })+ .updateDocument(previousPageId, {+ content: html,+ saveSource: 'llm_call',+ title,+ writeSource: 'system',+ }).then(() => true).catch((error) => {console.warn('[GoalReportPage] could not rewrite the previous page:', error);@@ -51,6 +56,7 @@ export const writeGoalReportPage = async (content: html,fileType: HTML_DOCUMENT_FILE_TYPE,title,+ writeSource: 'system',...(workspaceId ? { visibility: 'public' as const } : {}),});if (workspaceId && page.visibility !== 'private') {diff --git a/apps/server/src/services/notebook/__tests__/index.test.ts b/apps/server/src/services/notebook/__tests__/index.test.tsindex 96c3c8174eb..d5643cbde39 100644--- a/apps/server/src/services/notebook/__tests__/index.test.ts+++ b/apps/server/src/services/notebook/__tests__/index.test.ts@@ -3,12 +3,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { DocumentModel } from '@/database/models/document';import { TopicDocumentModel } from '@/database/models/topicDocument';import { DocumentService } from '@/server/services/document';+import { assertDocumentWriteWithinLimit } from '@/server/services/document/writeLimit';import { NotebookRuntimeService } from '../index';vi.mock('@/database/models/document');vi.mock('@/database/models/topicDocument');vi.mock('@/server/services/document');+vi.mock('@/server/services/document/writeLimit', () => ({+ assertDocumentWriteWithinLimit: vi.fn(),+}));describe('NotebookRuntimeService', () => {let service: NotebookRuntimeService;@@ -96,6 +100,52 @@ describe('NotebookRuntimeService', () => {});});+ it('checks an agent write and stores the character count, not the word count', async () => {+ mockDocumentModel.create.mockResolvedValue(mockDocument);+ const wordy = new NotebookRuntimeService({+ serverDB: mockDb,+ userId: mockUserId,+ workspaceId: 'ws-1',+ });++ await wordy.createDocument({+ content: 'two words',+ fileType: 'markdown',+ source: 's',+ sourceType: 'api',+ title: 't',+ totalCharCount: 2,+ totalLineCount: 1,+ });++ expect(assertDocumentWriteWithinLimit).toHaveBeenCalledWith({+ charCount: 9,+ source: 'agent',+ userId: mockUserId,+ workspaceId: 'ws-1',+ });+ expect(mockDocumentModel.create).toHaveBeenCalledWith(+ expect.objectContaining({ totalCharCount: 9 }),+ );+ });++ it('creates nothing when the limit refuses the write', async () => {+ vi.mocked(assertDocumentWriteWithinLimit).mockRejectedValueOnce(new Error('too long'));++ await expect(+ service.createDocument({+ content: 'x',+ fileType: 'markdown',+ source: 's',+ sourceType: 'api',+ title: 't',+ totalCharCount: 1,+ totalLineCount: 1,+ }),+ ).rejects.toThrow('too long');+ expect(mockDocumentModel.create).not.toHaveBeenCalled();+ });+it('should convert topic sourceType to api', async () => {mockDocumentModel.create.mockResolvedValue({...mockDocument,@@ -157,6 +207,31 @@ describe('NotebookRuntimeService', () => {expect(result.content).toBe(newContent);});+ it('checks an agent update against the previous length before writing', async () => {+ mockDocumentModel.findById.mockResolvedValue({ ...mockDocument, content: 'abc' });+ mockDocumentModel.update.mockResolvedValue(undefined);++ await service.updateDocument('doc-1', { content: 'abcdef' });++ expect(assertDocumentWriteWithinLimit).toHaveBeenCalledWith({+ charCount: 6,+ previousCharCount: 3,+ source: 'agent',+ userId: mockUserId,+ workspaceId: undefined,+ });+ });++ it('does not update when the limit refuses the write', async () => {+ mockDocumentModel.findById.mockResolvedValue({ ...mockDocument, content: 'abc' });+ vi.mocked(assertDocumentWriteWithinLimit).mockRejectedValueOnce(new Error('too long'));++ await expect(service.updateDocument('doc-1', { content: 'abcdef' })).rejects.toThrow(+ 'too long',+ );+ expect(mockDocumentModel.update).not.toHaveBeenCalled();+ });+it('should update title only', async () => {mockDocumentModel.update.mockResolvedValue(undefined);mockDocumentModel.findById.mockResolvedValue({diff --git a/apps/server/src/services/notebook/index.ts b/apps/server/src/services/notebook/index.tsindex 6e1b42835e4..e7bb4145b09 100644--- a/apps/server/src/services/notebook/index.ts+++ b/apps/server/src/services/notebook/index.ts@@ -4,6 +4,7 @@ import type { AgentDocumentSourceType } from '@/database/models/agentDocuments/timport { DocumentModel } from '@/database/models/document';import { TopicDocumentModel } from '@/database/models/topicDocument';import { DocumentService } from '@/server/services/document';+import { assertDocumentWriteWithinLimit } from '@/server/services/document/writeLimit';interface DocumentServiceResult {content: string | null;@@ -59,8 +60,12 @@ export class NotebookRuntimeService {private documentModel: DocumentModel;private topicDocumentModel: TopicDocumentModel;private callerAgentVisibility?: 'private' | 'public' | null;+ private userId: string;+ private workspaceId?: string;constructor(options: NotebookRuntimeServiceOptions) {+ this.userId = options.userId;+ this.workspaceId = options.workspaceId;this.callerAgentVisibility = options.callerAgentVisibility;this.documentService = new DocumentService(options.serverDB,@@ -94,8 +99,17 @@ export class NotebookRuntimeService {totalCharCount: number;totalLineCount: number;}): Promise<DocumentServiceResult> => {+ await assertDocumentWriteWithinLimit({+ charCount: params.content.length,+ source: 'agent',+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+const doc = await this.documentModel.create({...params,+ // Characters, not words: callers have passed a word count here.+ totalCharCount: params.content.length,...(this.callerAgentVisibility === 'private' || this.callerAgentVisibility === 'public'? { visibility: this.callerAgentVisibility }: {}),@@ -126,6 +140,17 @@ export class NotebookRuntimeService {id: string,params: { content?: string; title?: string },): Promise<DocumentServiceResult> => {+ if (params.content !== undefined) {+ const existing = await this.documentModel.findById(id);+ await assertDocumentWriteWithinLimit({+ charCount: params.content.length,+ previousCharCount: existing?.content?.length ?? 0,+ source: 'agent',+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+ }+await this.documentModel.update(id, {...(params.content !== undefined && {content: params.content,diff --git a/apps/server/src/services/onboarding/index.ts b/apps/server/src/services/onboarding/index.tsindex 452f4392849..cdce3899051 100644--- a/apps/server/src/services/onboarding/index.ts+++ b/apps/server/src/services/onboarding/index.ts@@ -179,6 +179,8 @@ export class OnboardingService {content: template.content,filename: template.filename,loadPosition: template.loadPosition,+ // Seeded templates are not user writes; the character limit does not apply.+ source: 'system',loadRules: template.loadRules,policy: template.policyLoadFormat? {diff --git a/apps/server/src/services/pageCollab/__tests__/bodyWriter.test.ts b/apps/server/src/services/pageCollab/__tests__/bodyWriter.test.tsindex 5efada56f64..04587fcb1bf 100644--- a/apps/server/src/services/pageCollab/__tests__/bodyWriter.test.ts+++ b/apps/server/src/services/pageCollab/__tests__/bodyWriter.test.ts@@ -44,7 +44,7 @@ vi.mock('@/server/services/document', () => ({},}));-const writer = { saveSource: 'system' as const, userId: 'u1' };+const writer = { saveSource: 'system' as const, userId: 'u1', writeSource: 'system' as const };const editorDataOf = (markdown: string) => {const editor = createHeadlessEditor();diff --git a/apps/server/src/services/pageCollab/__tests__/dbSession.test.ts b/apps/server/src/services/pageCollab/__tests__/dbSession.test.tsindex 79f12dedfb9..2507432c46c 100644--- a/apps/server/src/services/pageCollab/__tests__/dbSession.test.ts+++ b/apps/server/src/services/pageCollab/__tests__/dbSession.test.ts@@ -127,6 +127,7 @@ describe('DbPageSessions through withPageSync', () => {operationId: 'op_1',saveSource: 'llm_call',userId: 'u1',+ writeSource: 'agent',});const sandbox = withPageSync(shellSandbox, { documentId: 'doc_1', pageDir, sessions });exec = async (command) => {@@ -146,6 +147,7 @@ describe('DbPageSessions through withPageSync', () => {expect(store.updates[0]).toMatchObject({history: { agentId: 'agt_1', editorIds: ['u1'], operationId: 'op_1' },saveSource: 'llm_call',+ writeSource: 'agent',});});diff --git a/apps/server/src/services/pageCollab/__tests__/roomSession.writeLimit.test.ts b/apps/server/src/services/pageCollab/__tests__/roomSession.writeLimit.test.tsnew file mode 100644index 00000000000..013af85dcfc--- /dev/null+++ b/apps/server/src/services/pageCollab/__tests__/roomSession.writeLimit.test.ts@@ -0,0 +1,90 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { RoomPageSessions } from '../roomSession';+import type { PageWriter } from '../session';++const { fork, pushUpdate, state } = vi.hoisted(() => ({+ fork: {+ destroy: vi.fn(),+ diff: vi.fn(() => new Uint8Array([1])),+ doc: { getMap: () => ({ set: vi.fn() }) },+ editor: { export: vi.fn() },+ hasChanges: vi.fn(() => true),+ },+ pushUpdate: vi.fn(),+ state: { update: new Uint8Array() },+}));++vi.mock('@/business/server/document/writeLimit', () => ({+ checkDocumentCharLimit: async ({ charCount }: { charCount: number }) =>+ charCount > 10 ? { allowed: false, limit: 10, plan: 'free' } : { allowed: true },+}));++vi.mock('@/server/services/document', () => ({ DocumentService: class {} }));++vi.mock('../fork', () => ({+ openPageFork: async () => fork,+ PAGE_META_KEY: 'meta',+ readPageTitle: () => 'Title',+}));++vi.mock('../persist', () => ({ persistPageState: vi.fn() }));++vi.mock('../roomClient', () => ({+ createPageRoomClient: () => ({+ getState: async () => ({ bootstrapped: true, update: state.update }),+ pushUpdate,+ }),+ PageRoomConflictError: class extends Error {},+}));++vi.mock('yjs', () => ({ encodeStateAsUpdate: () => new Uint8Array() }));++const writerOf = (writeSource: PageWriter['writeSource']): PageWriter => ({+ saveSource: 'llm_call',+ userId: 'u1',+ workspaceId: 'ws_1',+ writeSource,+});++/** Opens a session whose page is `before` long, then edits it to `after`. */+const commitWith = async (+ writeSource: PageWriter['writeSource'],+ before: number,+ after: number,+) => {+ fork.editor.export.mockReturnValueOnce({ markdown: 'x'.repeat(before) });+ const session = await new RoomPageSessions({} as any, writerOf(writeSource)).openLiveSession(+ 'doc_1',+ );+ fork.editor.export.mockReturnValue({ markdown: 'x'.repeat(after) });+ return session!.commit();+};++describe('RoomPageSessions character limit', () => {+ beforeEach(() => {+ pushUpdate.mockReset();+ fork.editor.export.mockReset();+ });++ it('refuses a commit that grows the page over the limit and pushes nothing', async () => {+ await expect(commitWith('agent', 5, 20)).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(pushUpdate).not.toHaveBeenCalled();+ });++ it('allows a commit that shrinks a page already over the limit', async () => {+ await expect(commitWith('agent', 30, 20)).resolves.toBe(true);+ expect(pushUpdate).toHaveBeenCalledTimes(1);+ });++ it('allows a commit under the limit', async () => {+ await expect(commitWith('user', 2, 8)).resolves.toBe(true);+ expect(pushUpdate).toHaveBeenCalledTimes(1);+ });++ it('exempts a system writer', async () => {+ await expect(commitWith('system', 5, 500)).resolves.toBe(true);+ expect(pushUpdate).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/services/pageCollab/__tests__/sessions.test.ts b/apps/server/src/services/pageCollab/__tests__/sessions.test.tsindex cf7074eeb5c..76a214db402 100644--- a/apps/server/src/services/pageCollab/__tests__/sessions.test.ts+++ b/apps/server/src/services/pageCollab/__tests__/sessions.test.ts@@ -36,7 +36,12 @@ vi.mock('../dbSession', () => ({},}));-const writer = { saveSource: 'llm_call' as const, userId: 'u2', workspaceId: 'ws_1' };+const writer = {+ saveSource: 'llm_call' as const,+ userId: 'u2',+ workspaceId: 'ws_1',+ writeSource: 'agent' as const,+};describe('createPageSessions', () => {beforeEach(() => {diff --git a/apps/server/src/services/pageCollab/bodyWriter.ts b/apps/server/src/services/pageCollab/bodyWriter.tsindex 1fc657b5ddc..7e2f24ab96f 100644--- a/apps/server/src/services/pageCollab/bodyWriter.ts+++ b/apps/server/src/services/pageCollab/bodyWriter.ts@@ -109,7 +109,7 @@ export const updateDocumentThroughRoom = async (service: Pick<DocumentService, 'updateDocument'>,documentId: string,params: UpdateDocumentParams,- writer: Omit<PageWriter, 'saveSource'>,+ writer: Omit<PageWriter, 'saveSource' | 'writeSource'>,): Promise<UpdateDocumentResult> => {const writesRoom =params.content !== undefined || params.editorData !== undefined || params.title !== undefined;@@ -121,7 +121,11 @@ export const updateDocumentThroughRoom = async (db,documentId,{ editorData: params.editorData, markdown: params.content, title: params.title },- { ...writer, saveSource: params.saveSource ?? 'system' },+ {+ ...writer,+ saveSource: params.saveSource ?? 'system',+ writeSource: params.writeSource ?? 'user',+ },);if (!routed) return service.updateDocument(documentId, params);diff --git a/apps/server/src/services/pageCollab/dbSession.ts b/apps/server/src/services/pageCollab/dbSession.tsindex ffd6f1d2652..c74f027862f 100644--- a/apps/server/src/services/pageCollab/dbSession.ts+++ b/apps/server/src/services/pageCollab/dbSession.ts@@ -69,6 +69,7 @@ export class DbPageSessions implements PageSessions {expectedUpdatedAt: row.updatedAt,history: historyAttributionOf(this.writer),saveSource: this.writer.saveSource,+ writeSource: this.writer.writeSource,});} catch (error) {throw toPageChangedError(error) ?? error;diff --git a/apps/server/src/services/pageCollab/roomSession.ts b/apps/server/src/services/pageCollab/roomSession.tsindex 143e4c33c0c..89637ad2786 100644--- a/apps/server/src/services/pageCollab/roomSession.ts+++ b/apps/server/src/services/pageCollab/roomSession.ts@@ -4,6 +4,7 @@ import * as Y from 'yjs';import type { LobeChatDatabase } from '@/database/type';import { DocumentService } from '@/server/services/document';import type { DocumentHistorySaveSource } from '@/server/services/document/types';+import { assertDocumentWriteWithinLimit } from '@/server/services/document/writeLimit';import { editorDataFromRow } from './editorData';import { openPageFork, PAGE_META_KEY, type PageFork, readPageTitle } from './fork';@@ -78,11 +79,22 @@ export class RoomPageSessions implements PageSessions {): Promise<RoomPageSession> {const fork = await openPageFork(state.update);const title = readPageTitle(fork.doc) ?? (await this.getStoredTitle(documentId));+ // Length when the session opened, so a commit that does not grow the page passes.+ const initialCharCount =+ this.writer.writeSource === 'system' ? 0 : fork.editor.export().markdown.length;const actor = `${this.writer.saveSource === 'llm_call' ? 'agent' : 'external'}:${this.writer.userId}`;return {commit: async () => {if (!fork.hasChanges()) return false;+ // Refuse before anything reaches the room, so a refused write leaves no partial state.+ await assertDocumentWriteWithinLimit({+ charCount: fork.editor.export().markdown.length,+ previousCharCount: initialCharCount,+ source: this.writer.writeSource,+ userId: this.writer.userId,+ workspaceId: this.writer.workspaceId,+ });await room.pushUpdate(documentId, fork.diff(), { actor });await this.persist(documentId, fork);return true;diff --git a/apps/server/src/services/pageCollab/session.ts b/apps/server/src/services/pageCollab/session.tsindex f4ded551a45..aef3bd022f3 100644--- a/apps/server/src/services/pageCollab/session.ts+++ b/apps/server/src/services/pageCollab/session.ts@@ -1,3 +1,4 @@+import type { DocumentWriteSource } from '@lobechat/types';import type { HeadlessEditor } from '@lobehub/editor/headless';import { TRPCError } from '@trpc/server';@@ -51,6 +52,11 @@ export interface PageWriter {saveSource: DocumentHistorySaveSource;userId: string;workspaceId?: string;+ /**+ * Who asked for the write; decides whether the per-document character limit+ * applies. `saveSource` cannot: writers default it to `system` for agent edits.+ */+ writeSource: DocumentWriteSource;}export const historyAttributionOf = (writer: PageWriter) => ({diff --git a/apps/server/src/services/redis/agentRunSlots.realRedis.test.ts b/apps/server/src/services/redis/agentRunSlots.realRedis.test.tsnew file mode 100644index 00000000000..b64ebb112a9--- /dev/null+++ b/apps/server/src/services/redis/agentRunSlots.realRedis.test.ts@@ -0,0 +1,108 @@+// @vitest-environment node+import type IORedisClient from 'ioredis';+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';++import type { agentRunSlots } from './agentRunSlots';++/**+ * Runs the run-slot Lua scripts against a real Redis. Skipped unless+ * `AGENT_RUN_SLOTS_REAL_REDIS_URL` points at a disposable instance:+ *+ * docker run -d -p 127.0.0.1:6391:6379 redis:7-alpine+ * AGENT_RUN_SLOTS_REAL_REDIS_URL=redis://127.0.0.1:6391 vitest run apps/server/src/services/redis/agentRunSlots.realRedis.test.ts+ */+const url = process.env.AGENT_RUN_SLOTS_REAL_REDIS_URL;++describe.skipIf(!url)('agentRunSlots redis domain (real Redis)', () => {+ const prefix = `agent-run-slots-test-${Date.now()}`;+ const ttlMs = 60_000;+ let domain: typeof agentRunSlots;+ let raw: IORedisClient;+ let cleanup: () => Promise<void>;++ beforeAll(async () => {+ vi.resetModules();+ process.env.REDIS_URL = url;+ process.env.REDIS_PREFIX = prefix;+ domain = (await import('./agentRunSlots')).agentRunSlots;+ const { default: IORedis } = await import('ioredis');+ raw = new IORedis(url!);+ cleanup = async () => {+ const keys = await raw.keys(`${prefix}:*`);+ if (keys.length > 0) await raw.del(...keys);+ raw.disconnect();+ };+ });++ afterAll(async () => {+ await cleanup?.();+ });++ const slotsKey = (userId: string) => `${prefix}:agentRun:run_slots:v1:${userId}`;++ it('refuses the run past the limit and admits it again once a slot is released', async () => {+ expect(await domain.acquire('u1', 'op-a', { limit: 2, ttlMs })).toEqual({+ inFlight: 1,+ status: 'acquired',+ });+ expect(await domain.acquire('u1', 'op-b', { limit: 2, ttlMs })).toEqual({+ inFlight: 2,+ status: 'acquired',+ });+ expect(await domain.acquire('u1', 'op-c', { limit: 2, ttlMs })).toEqual({+ inFlight: 2,+ status: 'full',+ });++ await domain.release('u1', 'op-a');+ expect(await domain.acquire('u1', 'op-c', { limit: 2, ttlMs })).toEqual({+ inFlight: 2,+ status: 'acquired',+ });+ });++ it('treats a repeated acquire by the same holder as one slot', async () => {+ await domain.acquire('u2', 'op-a', { limit: 1, ttlMs });+ expect(await domain.acquire('u2', 'op-a', { limit: 1, ttlMs })).toEqual({+ inFlight: 1,+ status: 'acquired',+ });+ expect(await raw.hlen(slotsKey('u2'))).toBe(1);+ });++ it('drops a lapsed lease before counting', async () => {+ await raw.hset(slotsKey('u3'), 'op-stale', String(Date.now() - 1));+ expect(await domain.acquire('u3', 'op-new', { limit: 1, ttlMs })).toEqual({+ inFlight: 1,+ status: 'acquired',+ });+ expect(await raw.hexists(slotsKey('u3'), 'op-stale')).toBe(0);+ });++ it('counts an unchecked lease without refusing it', async () => {+ await domain.acquire('u4', 'op-a', { limit: 1, ttlMs });+ expect(await domain.acquire('u4', 'op-resume', { limit: null, ttlMs })).toEqual({+ inFlight: 2,+ status: 'acquired',+ });+ expect(await domain.acquire('u4', 'op-c', { limit: 2, ttlMs })).toEqual({+ inFlight: 2,+ status: 'full',+ });+ });++ it('renews only a live lease and moves a provisional lease to the real id', async () => {+ await domain.renew('u5', 'op-missing', ttlMs);+ expect(await raw.exists(slotsKey('u5'))).toBe(0);++ await domain.acquire('u5', 'pending-1', { limit: 1, ttlMs });+ await domain.rebind('u5', 'pending-1', 'op-real', ttlMs);+ expect(await raw.hkeys(slotsKey('u5'))).toEqual(['op-real']);++ const before = Number(await raw.hget(slotsKey('u5'), 'op-real'));+ await new Promise((resolve) => setTimeout(resolve, 5));+ await domain.renew('u5', 'op-real', ttlMs);+ expect(Number(await raw.hget(slotsKey('u5'), 'op-real'))).toBeGreaterThan(before);+ expect(await raw.pttl(slotsKey('u5'))).toBeGreaterThan(ttlMs - 5000);+ });+});diff --git a/apps/server/src/services/redis/agentRunSlots.ts b/apps/server/src/services/redis/agentRunSlots.tsnew file mode 100644index 00000000000..1f6bf7fbb49--- /dev/null+++ b/apps/server/src/services/redis/agentRunSlots.ts@@ -0,0 +1,135 @@+import { RedisKeys } from '@/server/modules/Redis';++import { getRedisServiceClient } from './client';++const getClient = () => getRedisServiceClient('agentRun');++/**+ * KEYS[1] = slots hash; ARGV = holder, now, expiresAt, limit (-1 = no limit).+ * Drops lapsed leases, then takes or refreshes the holder's lease unless the+ * other live leases already reach the limit. Returns { taken, live leases }.+ */+const ACQUIRE_SCRIPT = `+local now = tonumber(ARGV[2])+local entries = redis.call('HGETALL', KEYS[1])+local others = 0+for i = 1, #entries, 2 do+ if tonumber(entries[i + 1]) <= now then+ redis.call('HDEL', KEYS[1], entries[i])+ elseif entries[i] ~= ARGV[1] then+ others = others + 1+ end+end+local limit = tonumber(ARGV[4])+if limit >= 0 and others >= limit and redis.call('HEXISTS', KEYS[1], ARGV[1]) == 0 then+ return { 0, others }+end+redis.call('HSET', KEYS[1], ARGV[1], ARGV[3])+redis.call('PEXPIREAT', KEYS[1], ARGV[3])+return { 1, others + 1 }+`;++/** KEYS[1] = slots hash; ARGV = holder, expiresAt. Extends only a lease that still exists. */+const RENEW_SCRIPT = `+if redis.call('HEXISTS', KEYS[1], ARGV[1]) == 0 then return 0 end+redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])+redis.call('PEXPIREAT', KEYS[1], ARGV[2])+return 1+`;++/** KEYS[1] = slots hash; ARGV = from holder, to holder, expiresAt. Moves a lease to a new holder id. */+const REBIND_SCRIPT = `+if redis.call('HDEL', KEYS[1], ARGV[1]) == 0 then return 0 end+redis.call('HSET', KEYS[1], ARGV[2], ARGV[3])+redis.call('PEXPIREAT', KEYS[1], ARGV[3])+return 1+`;++export type AgentRunSlotAcquireResult =+ | { inFlight: number; status: 'acquired' }+ | { inFlight: number; status: 'full' }+ | { status: 'unavailable' };++/**+ * Per-user leases on in-flight agent runs, one hash field per holder. A lease+ * lapses unless renewed, so a run that stops without releasing frees its slot+ * on its own. Every write sets the whole key to expire with its newest lease:+ * leases share one TTL, so no live lease outlives the key.+ *+ * Callers decide the limit; this domain only counts.+ */+export const agentRunSlots = {+ /**+ * Takes a lease for `holderId`, or refreshes the one it already holds.+ *+ * @param limit maximum live leases, counting this one; `null` takes the+ * lease without checking (a run that must be counted but not refused)+ * @returns `unavailable` without Redis or on a Redis error, so callers can fail open+ */+ async acquire(+ userId: string,+ holderId: string,+ { limit, ttlMs }: { limit: number | null; ttlMs: number },+ ): Promise<AgentRunSlotAcquireResult> {+ const redis = await getClient();+ if (!redis) return { status: 'unavailable' };++ const now = Date.now();+ try {+ const [taken, inFlight] = await redis.eval<[number, number]>(+ ACQUIRE_SCRIPT,+ 1,+ RedisKeys.agentRun.runSlots(userId),+ holderId,+ String(now),+ String(now + ttlMs),+ String(limit ?? -1),+ );+ return { inFlight: Number(inFlight), status: taken === 1 ? 'acquired' : 'full' };+ } catch (error) {+ console.warn('[agentRunSlots] acquire failed:', error);+ return { status: 'unavailable' };+ }+ },++ /** Best effort: moves the lease taken under a provisional id to the run's real id. */+ async rebind(userId: string, fromHolderId: string, toHolderId: string, ttlMs: number) {+ const redis = await getClient();+ if (!redis) return;++ await redis+ .eval(+ REBIND_SCRIPT,+ 1,+ RedisKeys.agentRun.runSlots(userId),+ fromHolderId,+ toHolderId,+ String(Date.now() + ttlMs),+ )+ .catch(() => undefined);+ },++ /** Best effort: frees the holder's slot; a lease that cannot be released lapses on its own. */+ async release(userId: string, holderId: string) {+ const redis = await getClient();+ if (!redis) return;++ await redis.hdel(RedisKeys.agentRun.runSlots(userId), holderId).catch(() => undefined);+ },++ /** Best effort: extends the holder's lease; never recreates one that already lapsed. */+ async renew(userId: string, holderId: string, ttlMs: number) {+ const redis = await getClient();+ if (!redis) return;++ await redis+ .eval(+ RENEW_SCRIPT,+ 1,+ RedisKeys.agentRun.runSlots(userId),+ holderId,+ String(Date.now() + ttlMs),+ )+ .catch(() => undefined);+ },+};diff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.tsindex 2641b49d314..60c90202d97 100644--- a/apps/server/src/services/redis/index.ts+++ b/apps/server/src/services/redis/index.ts@@ -1,4 +1,5 @@import { agentIdentity } from './agentIdentity';+import { agentRunSlots } from './agentRunSlots';import { agentSignal } from './agentSignal';import { botWake } from './botWake';import { deviceSystemInfo } from './deviceSystemInfo';@@ -12,6 +13,7 @@ import { workspaceRescan } from './workspaceRescan';/** Business Redis API. Providers, keys and expiry policy stay inside each domain. */export const redisService = {agentIdentity,+ agentRunSlots,agentSignal,botWake,deviceSystemInfo,diff --git a/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts b/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.tsindex 2a01364a2e3..40392ddbda8 100644--- a/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts@@ -93,7 +93,7 @@ describe('archiveToolResultIfNeeded', () => {ARCHIVE_PATH,CONTENT,{ agentId: 'agent-1', topicId: 'topic-1' },- { contentFormat: 'raw' },+ { contentFormat: 'raw', source: 'system' },);expect(mockVfsService.read).toHaveBeenCalledWith(ARCHIVE_PATH, {agentId: 'agent-1',@@ -165,7 +165,7 @@ describe('archiveToolResultIfNeeded', () => {collisionPath,CONTENT,{ agentId: 'agent-1', topicId: 'topic-1' },- { contentFormat: 'raw' },+ { contentFormat: 'raw', source: 'system' },);expect(mockTopicDocumentModel.associate).toHaveBeenCalledWith({documentId: 'document-1',diff --git a/apps/server/src/services/toolExecution/__tests__/errorClassification.test.ts b/apps/server/src/services/toolExecution/__tests__/errorClassification.test.tsindex 69390f509e6..da7aebd8ebd 100644--- a/apps/server/src/services/toolExecution/__tests__/errorClassification.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/errorClassification.test.ts@@ -1,5 +1,8 @@+import { TRPCError } from '@trpc/server';import { describe, expect, it } from 'vitest';+import { formatDocumentCharLimitMessage } from '@/server/services/document/writeLimit';+import { classifyToolError, getToolAccessDeniedError } from '../errorClassification';describe('classifyToolError', () => {@@ -21,6 +24,32 @@ describe('classifyToolError', () => {expect(result.kind).toBe('replan');});+ it('classifies a refused document write as replan and keeps the numbers', () => {+ const error = new TRPCError({+ cause: { data: { actual: 123456, code: 'DocumentCharLimitExceeded', limit: 100000 } },+ code: 'BAD_REQUEST',+ message: formatDocumentCharLimitMessage({ actual: 123456, limit: 100000, plan: 'free' }),+ });++ const result = classifyToolError(error);++ expect(result.kind).toBe('replan');+ expect(result.message).toContain('123456');+ expect(result.message).toContain('100000');+ expect(result.message).toContain('split the content');+ });++ it('reads the code of an error a builtin runtime wrapped as its body', () => {+ const body = new TRPCError({+ code: 'BAD_REQUEST',+ message: formatDocumentCharLimitMessage({ actual: 123456, limit: 100000 }),+ });++ const result = classifyToolError({ body, message: body.message, type: 'PluginServerError' });++ expect(result.kind).toBe('replan');+ });+it('should default unknown errors to stop', () => {const result = classifyToolError(new Error('unexpected issue'));diff --git a/apps/server/src/services/toolExecution/archiveToolResult.ts b/apps/server/src/services/toolExecution/archiveToolResult.tsindex 4e556501fdc..09c47404bc4 100644--- a/apps/server/src/services/toolExecution/archiveToolResult.ts+++ b/apps/server/src/services/toolExecution/archiveToolResult.ts@@ -172,7 +172,11 @@ export const archiveToolResultIfNeeded = async ({path: string,outcome: ArchiveHandle['outcome'],): Promise<ArchiveHandle> => {- const stats = await vfsService.write(path, content, ctx, { contentFormat: 'raw' });+ const stats = await vfsService.write(path, content, ctx, {+ contentFormat: 'raw',+ // Archiving a tool result is not a user or agent authored write.+ source: 'system',+ });const persisted = await vfsService.read(path, ctx);// Never tell the model that a full result exists unless the VFS can return it losslessly.diff --git a/apps/server/src/services/toolExecution/errorClassification.ts b/apps/server/src/services/toolExecution/errorClassification.tsindex 9497afe00a0..d93f6e51a1f 100644--- a/apps/server/src/services/toolExecution/errorClassification.ts+++ b/apps/server/src/services/toolExecution/errorClassification.ts@@ -107,6 +107,8 @@ const normalizeSignal = (error: unknown): ToolErrorSignal => {if (error && typeof error === 'object') {const raw = error as {+ /** Builtin runtimes wrap the thrown error as `{ body, message, type }`. */+ body?: { code?: unknown };code?: string;error?: { code?: string; message?: string; status?: number; statusCode?: number };message?: string;@@ -119,7 +121,7 @@ const normalizeSignal = (error: unknown): ToolErrorSignal => {const message = (raw.message || nestedMessage || 'unknown error').toLowerCase();return {- code: normalizeCode(raw.code || nestedCode),+ code: normalizeCode(raw.code || nestedCode || toRecord(raw.body)?.code),message,status:typeof raw.status === 'number'diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgentPlan.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgentPlan.test.tsindex 0ab0ac63b55..38f29dc6f1e 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgentPlan.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgentPlan.test.ts@@ -1,14 +1,27 @@-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { DocumentModel } from '@/database/models/document';import { TopicDocumentModel } from '@/database/models/topicDocument';import { createServerPlanRuntimeService } from '../lobeAgentPlan';+const mocks = vi.hoisted(() => ({+ assertWrite: vi.fn(),+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+}));++vi.mock('@/server/services/document/writeLimit', () => ({+ assertDocumentWriteWithinLimit: mocks.assertWrite,+}));+vi.mock('@/database/models/document', () => ({DocumentModel: vi.fn(function () {return {- findById: vi.fn(),+ create: mocks.create,+ findById: mocks.findById,+ update: mocks.update,};}),}));@@ -16,6 +29,7 @@ vi.mock('@/database/models/document', () => ({vi.mock('@/database/models/topicDocument', () => ({TopicDocumentModel: vi.fn(function () {return {+ associate: vi.fn(),findByTopicId: vi.fn(),};}),@@ -44,4 +58,67 @@ describe('createServerPlanRuntimeService', () => {expect(DocumentModel).toHaveBeenCalledWith(serverDB, 'user-1', 'workspace-1', 'private');});++ describe('document character limit', () => {+ const doc = { id: 'plan-1', content: 'old', title: 'g', description: 'd', metadata: null };++ beforeEach(() => {+ for (const mock of Object.values(mocks)) mock.mockReset();+ mocks.create.mockResolvedValue(doc);+ mocks.findById.mockResolvedValue(doc);+ });++ it('checks a new plan as an agent write before creating it', async () => {+ const service = createServerPlanRuntimeService({} as never, 'user-1', 'ws-1');++ await service.createPlan({ content: 'abcd', description: 'd', goal: 'g', topicId: 't' });++ expect(mocks.assertWrite).toHaveBeenCalledWith({+ charCount: 4,+ source: 'agent',+ userId: 'user-1',+ workspaceId: 'ws-1',+ });+ });++ it('creates nothing when the limit refuses a new plan', async () => {+ mocks.assertWrite.mockRejectedValue(new Error('too long'));+ const service = createServerPlanRuntimeService({} as never, 'user-1');++ await expect(+ service.createPlan({ content: 'abcd', description: 'd', goal: 'g', topicId: 't' }),+ ).rejects.toThrow('too long');+ expect(mocks.create).not.toHaveBeenCalled();+ });++ it('checks a plan update against the previous length', async () => {+ const service = createServerPlanRuntimeService({} as never, 'user-1');++ await service.updatePlan('plan-1', { content: 'abcdef' });++ expect(mocks.assertWrite).toHaveBeenCalledWith({+ charCount: 6,+ previousCharCount: 3,+ source: 'agent',+ userId: 'user-1',+ workspaceId: undefined,+ });+ });++ it('does not update when the limit refuses the write', async () => {+ mocks.assertWrite.mockRejectedValue(new Error('too long'));+ const service = createServerPlanRuntimeService({} as never, 'user-1');++ await expect(service.updatePlan('plan-1', { content: 'abcdef' })).rejects.toThrow('too long');+ expect(mocks.update).not.toHaveBeenCalled();+ });++ it('skips the check for a goal-only update', async () => {+ const service = createServerPlanRuntimeService({} as never, 'user-1');++ await service.updatePlan('plan-1', { goal: 'new goal' });++ expect(mocks.assertWrite).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.tsindex a72db22742c..c47dc006345 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts@@ -166,6 +166,7 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {knowledgeBaseId,parentId,title,+ writeSource: 'agent',// Inherit caller-agent visibility: private-agent output stays in// the owner's private bucket; public-agent output is visible to// the workspace. When null (no agent / cannot resolve), falldiff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgentPlan.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgentPlan.tsindex 13dd7ebdc5f..6fa82ed387a 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgentPlan.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgentPlan.ts@@ -4,6 +4,7 @@ import { type LobeChatDatabase } from '@lobechat/database';import { DocumentModel } from '@/database/models/document';import { TopicDocumentModel } from '@/database/models/topicDocument';+import { assertDocumentWriteWithinLimit } from '@/server/services/document/writeLimit';/*** Build a server-side `PlanRuntimeService` backed by the application database.@@ -47,6 +48,13 @@ export const createServerPlanRuntimeService = (return {createPlan: async ({ topicId, goal, description, content }) => {+ await assertDocumentWriteWithinLimit({+ charCount: content.length,+ source: 'agent',+ userId,+ workspaceId,+ });+const doc = await documentModel.create({content,description,@@ -92,6 +100,14 @@ export const createServerPlanRuntimeService = (if (goal !== undefined) updateData.title = goal;if (description !== undefined) updateData.description = description;if (content !== undefined) {+ const existing = await documentModel.findById(id);+ await assertDocumentWriteWithinLimit({+ charCount: content.length,+ previousCharCount: existing?.content?.length ?? 0,+ source: 'agent',+ userId,+ workspaceId,+ });updateData.content = content;updateData.totalCharCount = content.length;updateData.totalLineCount = content.split('\n').length;diff --git a/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.tsindex 44da02a28f5..9c26144d43c 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/pageAgent.ts@@ -55,6 +55,7 @@ export const pageAgentRuntime: ServerRuntimeRegistration = {saveSource: 'llm_call',userId: context.userId,workspaceId: context.workspaceId,+ writeSource: 'agent',};return new PageAgentExecutionRuntime(buildService(createPageSessions(context.serverDB, writer)),diff --git a/apps/server/src/services/toolExecution/serverRuntimes/pageSandboxSync.ts b/apps/server/src/services/toolExecution/serverRuntimes/pageSandboxSync.tsindex 8e82be3df21..5297f7e7634 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/pageSandboxSync.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/pageSandboxSync.ts@@ -27,6 +27,7 @@ export const pageSandboxWrapper = (saveSource: 'llm_call',userId,workspaceId,+ writeSource: 'agent',}),});};diff --git a/apps/server/src/services/webBrowsing/__tests__/index.test.ts b/apps/server/src/services/webBrowsing/__tests__/index.test.tsindex c53ac64ad82..ac650654d62 100644--- a/apps/server/src/services/webBrowsing/__tests__/index.test.ts+++ b/apps/server/src/services/webBrowsing/__tests__/index.test.ts@@ -129,6 +129,7 @@ describe('WebBrowsingDocumentService.upsertCrawledDocument ()', () => {editorData: { root: { fakeNodeFor: 'new body' } },saveSource: 'llm_call',title: 'Updated title',+ writeSource: 'system',});expect(result).toEqual({ id: 'doc-existing', status: 'updated' });});diff --git a/apps/server/src/services/webBrowsing/index.ts b/apps/server/src/services/webBrowsing/index.tsindex 841ebd7c95b..b9a7e9baf7c 100644--- a/apps/server/src/services/webBrowsing/index.ts+++ b/apps/server/src/services/webBrowsing/index.ts@@ -132,6 +132,7 @@ export class WebBrowsingDocumentService {editorData: snapshot.editorData,saveSource: 'llm_call',title,+ writeSource: 'system',},{ userId: this.userId, workspaceId: this.workspaceId },);diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 5a8ce8de38b..9f5c5dc7e89 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1616,6 +1616,8 @@"input.agentModeUnsupportedModel": "The current model doesn’t support agentic tool calling. Switch to a model with agent capability for the best experience.","input.agentSlugMoved": "This link now opens a different agent. Switching to it — try again once it opens. Your draft is kept.","input.agentSlugUnconfirmed": "Couldn’t confirm which agent this link opens. Check your connection, then try again.",+ "input.concurrencyLimit": "You have too many agent tasks running at once. Send again when one finishes.",+ "input.concurrencyLimitWithCount": "Your plan runs up to {{count}} agent tasks at once. Send again when one finishes.","input.costEstimate.creditsPerMillionTokens": "{{credits}} credits/M tokens","input.costEstimate.hint": "Estimated cost: ~{{credits}} credits","input.costEstimate.inputLabel": "Input",diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex b391c74dc47..20e2daf6ffc 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -283,6 +283,10 @@"pageEditor.agentUnavailable.viewDocs": "View docs","pageEditor.artifactTag": "Artifact","pageEditor.autoSaveMessage": "Your page is saved automatically. No need to save manually.",+ "pageEditor.charLimit.blockedDescription": "Changes are not saved. Shorten the page or upgrade your plan to keep editing.",+ "pageEditor.charLimit.blockedTitle": "This page has {{actual}} characters, over the {{limit}}-character limit per page on your plan.",+ "pageEditor.charLimit.nearDescription": "Saving will be refused once the page goes over the limit.",+ "pageEditor.charLimit.nearTitle": "This page has {{actual}} of {{limit}} characters allowed per page on your plan.","pageEditor.chooseIcon": "Choose Icon","pageEditor.collab.notSynced": "Your latest page edits are still syncing, so the Agent may not see them yet.","pageEditor.collab.offlineRestore.content": "The page was reloaded from the server while you were offline, and your unsynced edits are not in it. Put your version back?",diff --git a/locales/en-US/subscription.json b/locales/en-US/subscription.jsonindex c56107677c0..704f067f484 100644--- a/locales/en-US/subscription.json+++ b/locales/en-US/subscription.json@@ -269,6 +269,7 @@"crossPlatform.title": "Cross-Platform Subscription","currentPlan.cancelAlert": "Subscription will be cancelled after {{canceledAt}}. You can still restore it before then","currentPlan.downgradeAlert": "Will be downgraded to {{plan}} after {{downgradedAt}}.",+ "currentPlan.legacyCancelAlert": "Subscription will end after {{canceledAt}}. A canceled legacy plan cannot be restored, but you can upgrade to a new plan anytime.","currentPlan.management": "Manage Subscription","currentPlan.notIncluded": "Not included in current plan","currentPlan.paymentExpired": "This subscription will expire on {{expiredAt}}, please plan your usage accordingly",@@ -318,23 +319,46 @@"limitation.insufficientBudget.exactDesc": "This request needs more credits. Top up credits or upgrade your plan.","limitation.insufficientBudget.required": "Required Credits","limitation.insufficientBudget.rescue.desc": "This request needs {{shortfall}} more credits to continue",+ "limitation.insufficientBudget.rescue.overflow.badge": "Enough for this",+ "limitation.insufficientBudget.rescue.overflow.benefit": "Spend your {{credits}} credits once plan limits run out. No extra cost.",+ "limitation.insufficientBudget.rescue.overflow.cta": "Use credit packs and continue",+ "limitation.insufficientBudget.rescue.overflow.title": "Use your credit packs","limitation.insufficientBudget.rescue.referral.badge": "Free","limitation.insufficientBudget.rescue.referral.benefit": "Invite a friend — you both get {{reward}}M credits","limitation.insufficientBudget.rescue.referral.cta": "Invite friends","limitation.insufficientBudget.rescue.referral.title": "Invite friends","limitation.insufficientBudget.rescue.title": "Out of credits","limitation.insufficientBudget.rescue.topup.benefit": "Pay as you go, credited instantly",+ "limitation.insufficientBudget.rescue.topup.benefitOverflow": "Purchased credits are used after your plan limits run out. We'll turn that on for you.","limitation.insufficientBudget.rescue.topup.cta": "Top up & continue","limitation.insufficientBudget.rescue.topup.title": "Top up {{quantity}}M credits","limitation.insufficientBudget.rescue.upgrade.badge": "Best value","limitation.insufficientBudget.rescue.upgrade.benefit": "{{credits}} credits per month, cancel anytime",+ "limitation.insufficientBudget.rescue.upgrade.benefitMultiple": "{{multiple}}× the usage of your current plan",+ "limitation.insufficientBudget.rescue.upgrade.benefitRolling": "Higher weekly usage limits","limitation.insufficientBudget.rescue.upgrade.benefitWithRuns": "{{credits}} credits per month ≈ {{runs}}+ requests like this","limitation.insufficientBudget.rescue.upgrade.cta": "Upgrade & continue","limitation.insufficientBudget.rescue.upgrade.price": "from ${{price}}/mo","limitation.insufficientBudget.rescue.upgrade.title": "Upgrade to {{plan}}",+ "limitation.insufficientBudget.rescue.wait.hint": "Or wait for the reset and retry, it's free.","limitation.insufficientBudget.retry": "Retry","limitation.insufficientBudget.shortfall": "Credit Shortfall","limitation.insufficientBudget.title": "Insufficient Credits",+ "limitation.insufficientBudget.window.desc": "You've reached your {{rules}}.",+ "limitation.insufficientBudget.window.duration.days": "{{count}} d",+ "limitation.insufficientBudget.window.duration.hours": "{{count}} h",+ "limitation.insufficientBudget.window.duration.minutes": "{{count}} min",+ "limitation.insufficientBudget.window.listSeparator": ", ",+ "limitation.insufficientBudget.window.requestTooLarge": "This request needs more than the limit allows, so waiting won't help.",+ "limitation.insufficientBudget.window.resetNow": "It has just reset, so you can retry now.",+ "limitation.insufficientBudget.window.resetsIn": "Resets in {{duration}} ({{time}}).",+ "limitation.insufficientBudget.window.rule.overflowMonth": "monthly credit-pack cap",+ "limitation.insufficientBudget.window.rule.plan5h": "5-hour limit",+ "limitation.insufficientBudget.window.rule.plan7d": "weekly limit",+ "limitation.insufficientBudget.window.rule.planMonth": "monthly limit",+ "limitation.insufficientBudget.window.rule.planUltraMonth": "monthly Ultra-model limit",+ "limitation.insufficientBudget.window.sentenceSeparator": " ",+ "limitation.insufficientBudget.window.title": "Usage limit reached","limitation.limited.action": "Upgrade Now","limitation.limited.advanceFeature": "Upgrade to enjoy premium features:","limitation.limited.desc": "Your {{plan}} credits have been exhausted. Upgrade now to get more credits.",@@ -424,6 +448,20 @@"plans.cloud.history": "Unlimited conversation history","plans.cloud.sync": "Global cloud sync","plans.cloud.title": "Cloud Service",+ "plans.compare.agentMemory": "Agent memory",+ "plans.compare.artifactSiteSize": "Max size per site",+ "plans.compare.artifactSites": "Active Artifact sites",+ "plans.compare.concurrentAgentRuns": "Concurrent agent tasks",+ "plans.compare.documentCharacters": "Characters per document",+ "plans.compare.earlyAccess": "Early access to new features",+ "plans.compare.none": "None",+ "plans.compare.rolling5hSpend": "5-hour usage limit",+ "plans.compare.rolling7dSpend": "Weekly usage",+ "plans.compare.sandboxStorage": "Cloud sandbox storage",+ "plans.compare.ultraMonthlySpend": "Ultra models per month",+ "plans.compare.unlimited": "Unlimited",+ "plans.compare.usageBase": "Standard",+ "plans.compare.usageMultiple": "{{multiple}}×","plans.credit.api": "Custom API","plans.credit.apiDesc": "Requires your own model API configuration","plans.credit.apiProvider": "Supports 20+ mainstream model providers including OpenAI / Anthropic / OpenRouter",@@ -465,6 +503,35 @@"plans.knowledgeBase.filetype": "Supports PDF / MD / DOC / XLS / PPT and other formats","plans.knowledgeBase.title": "Files & Knowledge Base","plans.knowledgeBase.tooltip": "Supports file upload and knowledge base features. Upload files, images, audio, video and more. Create knowledge bases for easy file management. Use files and knowledge base in conversations for richer experiences.",+ "plans.legacy.banner.desc": "It keeps its current price. You can upgrade to a higher-tier plan anytime, and what you have used this billing period is on us.",+ "plans.legacy.banner.downgrade": "Switches to {{plan}} when this billing period ends",+ "plans.legacy.banner.title": "You are on {{plan}}, a legacy plan",+ "plans.legacy.upgradeOnly": "A legacy plan can only be upgraded to a higher-tier plan",+ "plans.limits.agentMemory.unavailable": "Agent memory",+ "plans.limits.agentMemory.unlimited": "Agent memory",+ "plans.limits.artifactSiteSize": "Up to {{value}} per published site",+ "plans.limits.artifactSites": "Up to {{value}} active Artifact sites",+ "plans.limits.concurrentAgentRuns": "{{value}} agent tasks at once",+ "plans.limits.concurrentAgentRuns.unlimited": "Unlimited concurrent agent tasks",+ "plans.limits.documentCharacters": "Up to {{value}} characters per document",+ "plans.limits.documentCharacters.unlimited": "No document length limit",+ "plans.limits.earlyAccess.unavailable": "Early access to new features",+ "plans.limits.earlyAccess.unlimited": "Early access to new features",+ "plans.limits.embeddingVectors": "{{value}} vector entries",+ "plans.limits.fileStorage": "{{value}} file storage",+ "plans.limits.rolling5hSpend": "5-hour usage limit",+ "plans.limits.rolling5hSpend.multiple": "5-hour usage limit: {{multiple}}× that of {{plan}}",+ "plans.limits.rolling5hSpend.tooltip": "Usage within any 5 hours is capped too. The window starts with your first request and resets 5 hours later.",+ "plans.limits.rolling5hSpend.unavailable": "No 5-hour limit",+ "plans.limits.rolling7dSpend": "Weekly usage allowance",+ "plans.limits.rolling7dSpend.multiple": "{{multiple}}× the usage of {{plan}}",+ "plans.limits.rolling7dSpend.tooltip": "Model usage your plan covers in any 7 days. The week starts with your first request and resets 7 days later.",+ "plans.limits.sandboxStorage": "{{value}} cloud sandbox storage",+ "plans.limits.support": "{{value}}",+ "plans.limits.ultraMonthlySpend": "Ultra models, with a separate monthly limit",+ "plans.limits.ultraMonthlySpend.multiple": "Ultra models: {{multiple}}× the usage of {{plan}}",+ "plans.limits.ultraMonthlySpend.tooltip": "Ultra models are the most capable and most expensive ones. They use your weekly credits and are also capped each month.",+ "plans.limits.ultraMonthlySpend.unavailable": "Ultra models","plans.llm.customAPI": "Global mainstream model custom API service","plans.llm.messageRequest": "Unlimited message requests","plans.llm.title": "Model Service",@@ -495,10 +562,13 @@"plans.plan.free.title": "Free","plans.plan.hobby.desc": "For users with their own API who pay as they go","plans.plan.hobby.title": "Hobby",+ "plans.plan.max.desc": "For power users running agents at scale","plans.plan.max.title": "Max",+ "plans.plan.plus.desc": "For everyday AI use","plans.plan.plus.title": "Plus","plans.plan.premium.desc": "For professional users who frequently use AI","plans.plan.premium.title": "Premium",+ "plans.plan.pro.desc": "For professionals who rely on AI every day","plans.plan.pro.title": "Pro","plans.plan.starter.desc": "For occasional AI users","plans.plan.starter.title": "Starter",@@ -507,6 +577,9 @@"plans.restoreSubscription": "Restore Subscription","plans.restoreSubscriptionError": "Could not restore your subscription","plans.restoreSubscriptionSuccess": "Subscription has been restored",+ "plans.soldOut": "Sold Out",+ "plans.soldOutError": "This plan just sold out. Choose another plan or try again later.",+ "plans.soldOutTooltip": "All spots for this plan are taken. Check back later.","plans.storage.title": "Data Storage","plans.subscribe": "Subscribe","plans.support.free": "Community Forum",@@ -517,6 +590,7 @@"plans.support.ultimate": "Priority Chat and Email Support","plans.target": "Target Plan","plans.unlimited": "Unlimited",+ "plans.usageHero.comparedTo": "more usage than {{plan}}","plans.workspace.features.adminControls": "Centralized billing and role management","plans.workspace.features.apiKey": "Workspace API Keys","plans.workspace.features.auditLog": "Audit Logs",@@ -542,6 +616,8 @@"plansModal.modelAccess.title": "Unlock all models","plansModal.persistentSandbox.desc": "Files your agent writes in the cloud sandbox are discarded when the session ends. Upgrade to keep a persistent working directory that survives sessions and is shared across your topics.","plansModal.persistentSandbox.title": "Keep your sandbox files",+ "plansModal.ultraModelAccess.desc": "Ultra models are the most capable and most expensive ones, available on Pro and above. Upgrade to use them.",+ "plansModal.ultraModelAccess.title": "Ultra models need Pro or above","qa.desc": "If your question is not answered, check <1>Product Documentation</1> for more FAQs, or contact us.","qa.detail": "View Details","qa.list.credit.a": "Credits are how {{cloud}} measures AI model usage. Different AI models consume different amounts of credits.",@@ -549,10 +625,12 @@"qa.list.embeddings.a": "Vector storage is not equal to the original size of your uploaded or imported dataset, but is calculated based on the vectorization of pure text content in your files. For example, a 1-page PDF file (1000-1500 characters) may only take up about 1 vector storage entry when extracted and vectorized into pure text. You can view your usage under \"{{usage}}\".","qa.list.embeddings.q": "How is vector storage calculated?","qa.list.free.a": "{{name}} has always adhered to open source principles. For professional developers, you can use all open source capabilities through self-deployment of the community version. In {{cloud}}, we provide all registered users with {{credit}} free credits per month, ready to use without complex configuration. If you need more usage, you can subscribe to {{starter}}, {{premium}} or {{ultimate}}.",+ "qa.list.free.newA": "{{name}} has always adhered to open source principles. For professional developers, you can use all open source capabilities through self-deployment of the community version. In {{cloud}}, every registered user gets {{credit}} free credits per month, ready to use without complex configuration. For more usage, subscribe to {{plus}}, {{pro}} or {{max}}.","qa.list.free.q": "Can {{name}} be used for free?","qa.list.highUsage.a": "Credit consumption depends heavily on conversation length. As a conversation grows, each new message sends the entire history as input tokens, which increases cost significantly. We recommend starting a new conversation when topics change. Also, if there is a long gap between messages, the prompt cache may expire, causing a spike in cost. Some models like the Gemini Pro series use tiered pricing — input beyond 200K tokens is charged at double the rate.","qa.list.highUsage.q": "Why are my credits being consumed faster than expected?","qa.list.limit.a": "{{cloud}} subscription plans are divided into {{starter}}, {{premium}} and {{ultimate}}, each providing different credit amounts. If your current plan credits are insufficient, we recommend upgrading. You can also purchase credit packages on the <fundsLink>\"{{funds}}\"</fundsLink> page for pay-as-you-go usage. Alternatively, you can set up a custom model API key to use API credits purchased from other sources.",+ "qa.list.limit.newA": "{{cloud}} offers {{plus}}, {{pro}} and {{max}}. Each caps usage within 5 hours and within a week; each window resets 5 hours or 7 days after it starts. When you reach a limit, you can wait for it to reset or upgrade your plan. Credit packs bought on the <fundsLink>\"{{funds}}\"</fundsLink> page keep you going once your plan limits run out. You can also set up a custom model API key to use API credits purchased from other sources.","qa.list.limit.q": "What if I run out of credits?","qa.list.management.a": "On the {{subscribe}} page, you can \"Upgrade / Downgrade\" your current subscription plan, or switch between yearly and monthly billing. Through \"{{usage}}-{{management}}\" you can go to Stripe for subscription management, and you can cancel your subscription at any time. After cancellation, you will be automatically downgraded to the free version when your current plan expires.","qa.list.management.q": "How do I change or cancel my subscription?",@@ -580,6 +658,7 @@"recurring.perMonth": "Per Month","recurring.perYear": "Per Year","recurring.sixMonth": "6 Months",+ "recurring.slashMonth": "/mo","recurring.threeMonth": "3 Months","recurring.title": "Billing Cycle","recurring.yearly": "Yearly Billing",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 9ca4a1f3b60..773553c7e2c 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1616,6 +1616,8 @@"input.agentModeUnsupportedModel": "当前模型不支持 Agentic 工具调用,建议切换为具备 Agent 能力的模型以获得最佳体验。","input.agentSlugMoved": "该链接现在指向另一个助理,正在切换,打开后请重试。输入框中的草稿会保留。","input.agentSlugUnconfirmed": "暂时无法确认该链接对应的助理,请检查网络后重试。",+ "input.concurrencyLimit": "同时运行的助理任务太多了,等其中一个结束后再发送",+ "input.concurrencyLimitWithCount": "当前套餐最多同时运行 {{count}} 个助理任务,等其中一个结束后再发送","input.costEstimate.creditsPerMillionTokens": "{{credits}} 积分/百万标记","input.costEstimate.hint": "预计费用:约{{credits}}积分","input.costEstimate.inputLabel": "输入",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex a52800c2e82..92264a99ed1 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -283,6 +283,10 @@"pageEditor.agentUnavailable.viewDocs": "查看文档","pageEditor.artifactTag": "Artifact","pageEditor.autoSaveMessage": "文稿会自动保存,无需手动保存",+ "pageEditor.charLimit.blockedDescription": "改动未保存。请缩短页面内容,或升级套餐后继续编辑。",+ "pageEditor.charLimit.blockedTitle": "此页面有 {{actual}} 个字符,超过了当前套餐每页 {{limit}} 个字符的上限。",+ "pageEditor.charLimit.nearDescription": "超过上限后,改动将无法保存。",+ "pageEditor.charLimit.nearTitle": "此页面已有 {{actual}} 个字符,当前套餐每页上限为 {{limit}} 个字符。","pageEditor.chooseIcon": "选择图标","pageEditor.collab.notSynced": "你最近的页面修改还在同步,Agent 可能暂时看不到。","pageEditor.collab.offlineRestore.content": "离线期间页面已从服务器重新加载,你未同步的修改不在其中。要恢复你的版本吗?",diff --git a/locales/zh-CN/subscription.json b/locales/zh-CN/subscription.jsonindex 6c54fe51894..35b89725e21 100644--- a/locales/zh-CN/subscription.json+++ b/locales/zh-CN/subscription.json@@ -269,6 +269,7 @@"crossPlatform.title": "跨平台订阅","currentPlan.cancelAlert": "订阅将于 {{canceledAt}} 后取消。您仍可在此之前恢复。","currentPlan.downgradeAlert": "将于 {{downgradedAt}} 降级为 {{plan}}。",+ "currentPlan.legacyCancelAlert": "订阅将于 {{canceledAt}} 后结束。旧版套餐取消后无法恢复,你可以随时升级到新套餐。","currentPlan.management": "管理订阅","currentPlan.notIncluded": "当前套餐不包含","currentPlan.paymentExpired": "当前订阅将于 {{expiredAt}} 到期,请合理安排使用",@@ -318,23 +319,46 @@"limitation.insufficientBudget.exactDesc": "本次请求需要更多积分,请充值积分或升级套餐。","limitation.insufficientBudget.required": "所需积分","limitation.insufficientBudget.rescue.desc": "本次请求还差 {{shortfall}} 积分,续上就能继续",+ "limitation.insufficientBudget.rescue.overflow.badge": "足够本次使用",+ "limitation.insufficientBudget.rescue.overflow.benefit": "套餐额度用完后,改用你已有的 {{credits}} 积分,无需额外付费。",+ "limitation.insufficientBudget.rescue.overflow.cta": "使用积分包并继续",+ "limitation.insufficientBudget.rescue.overflow.title": "使用你的积分包","limitation.insufficientBudget.rescue.referral.badge": "免费","limitation.insufficientBudget.rescue.referral.benefit": "邀 1 位好友注册,双方各得 {{reward}}M 积分","limitation.insufficientBudget.rescue.referral.cta": "去邀请好友","limitation.insufficientBudget.rescue.referral.title": "邀请好友","limitation.insufficientBudget.rescue.title": "积分不够啦","limitation.insufficientBudget.rescue.topup.benefit": "按需补充,即时到账",+ "limitation.insufficientBudget.rescue.topup.benefitOverflow": "购买的积分会在套餐额度用完后使用,我们会为你自动开启。","limitation.insufficientBudget.rescue.topup.cta": "充值并继续","limitation.insufficientBudget.rescue.topup.title": "充值 {{quantity}}M 积分","limitation.insufficientBudget.rescue.upgrade.badge": "最划算","limitation.insufficientBudget.rescue.upgrade.benefit": "每月 {{credits}} 积分,随时可取消",+ "limitation.insufficientBudget.rescue.upgrade.benefitMultiple": "当前套餐的 {{multiple}} 倍用量",+ "limitation.insufficientBudget.rescue.upgrade.benefitRolling": "更高的每周用量上限","limitation.insufficientBudget.rescue.upgrade.benefitWithRuns": "每月 {{credits}} 积分 ≈ {{runs}}+ 次这样的请求","limitation.insufficientBudget.rescue.upgrade.cta": "升级并继续","limitation.insufficientBudget.rescue.upgrade.price": "${{price}}/月起","limitation.insufficientBudget.rescue.upgrade.title": "升级至 {{plan}}",+ "limitation.insufficientBudget.rescue.wait.hint": "也可以等额度重置后重试,无需付费。","limitation.insufficientBudget.retry": "重试","limitation.insufficientBudget.shortfall": "缺口积分","limitation.insufficientBudget.title": "积分不足",+ "limitation.insufficientBudget.window.desc": "{{rules}}已用完。",+ "limitation.insufficientBudget.window.duration.days": "{{count}} 天",+ "limitation.insufficientBudget.window.duration.hours": "{{count}} 小时",+ "limitation.insufficientBudget.window.duration.minutes": "{{count}} 分钟",+ "limitation.insufficientBudget.window.listSeparator": "、",+ "limitation.insufficientBudget.window.requestTooLarge": "这次请求所需额度超过了上限,等待重置也无法解决。",+ "limitation.insufficientBudget.window.resetNow": "额度刚刚已重置,现在可以重试。",+ "limitation.insufficientBudget.window.resetsIn": "{{duration}}后重置({{time}})。",+ "limitation.insufficientBudget.window.rule.overflowMonth": "每月积分包消耗上限",+ "limitation.insufficientBudget.window.rule.plan5h": "5 小时额度",+ "limitation.insufficientBudget.window.rule.plan7d": "每周额度",+ "limitation.insufficientBudget.window.rule.planMonth": "每月额度",+ "limitation.insufficientBudget.window.rule.planUltraMonth": "每月 Ultra 模型额度",+ "limitation.insufficientBudget.window.sentenceSeparator": "",+ "limitation.insufficientBudget.window.title": "额度已用完","limitation.limited.action": "立即升级","limitation.limited.advanceFeature": "升级以解锁高级功能:","limitation.limited.desc": "您的 {{plan}} 计算积分已用尽。请立即升级以获取更多积分。",@@ -424,6 +448,20 @@"plans.cloud.history": "无限对话历史","plans.cloud.sync": "全球云端同步","plans.cloud.title": "云服务",+ "plans.compare.agentMemory": "智能体记忆",+ "plans.compare.artifactSiteSize": "单站点大小上限",+ "plans.compare.artifactSites": "在线 Artifact 站点数",+ "plans.compare.concurrentAgentRuns": "并发智能体任务数",+ "plans.compare.documentCharacters": "单文档字符数上限",+ "plans.compare.earlyAccess": "新功能抢先体验",+ "plans.compare.none": "无",+ "plans.compare.rolling5hSpend": "5 小时用量限制",+ "plans.compare.rolling7dSpend": "每周用量",+ "plans.compare.sandboxStorage": "云端沙箱存储",+ "plans.compare.ultraMonthlySpend": "Ultra 模型每月用量",+ "plans.compare.unlimited": "不限",+ "plans.compare.usageBase": "标准",+ "plans.compare.usageMultiple": "{{multiple}} 倍","plans.credit.api": "自定义 API","plans.credit.apiDesc": "需配置您自己的模型 API","plans.credit.apiProvider": "支持 OpenAI / Anthropic / OpenRouter 等 20+ 主流模型提供商",@@ -465,6 +503,35 @@"plans.knowledgeBase.filetype": "支持 PDF / MD / DOC / XLS / PPT 等格式","plans.knowledgeBase.title": "文件与知识库","plans.knowledgeBase.tooltip": "支持上传文件、图片、音频、视频等,创建知识库便于管理。在对话中使用文件和知识库,提升交互体验。",+ "plans.legacy.banner.desc": "旧版套餐保持原价不变。你可以随时升级到更高级的新套餐,本期已用的额度不会扣除。",+ "plans.legacy.banner.downgrade": "本期结束后降级为 {{plan}}",+ "plans.legacy.banner.title": "你当前是 {{plan}}(旧版套餐)",+ "plans.legacy.upgradeOnly": "旧版套餐只能升级到更高级的套餐",+ "plans.limits.agentMemory.unavailable": "智能体记忆",+ "plans.limits.agentMemory.unlimited": "智能体记忆",+ "plans.limits.artifactSiteSize": "单个站点最大 {{value}}",+ "plans.limits.artifactSites": "最多 {{value}} 个在线 Artifact 站点",+ "plans.limits.concurrentAgentRuns": "同时运行 {{value}} 个智能体任务",+ "plans.limits.concurrentAgentRuns.unlimited": "智能体任务并发不限",+ "plans.limits.documentCharacters": "单个文档最多 {{value}} 字",+ "plans.limits.documentCharacters.unlimited": "文档字数不限",+ "plans.limits.earlyAccess.unavailable": "新功能抢先体验",+ "plans.limits.earlyAccess.unlimited": "新功能抢先体验",+ "plans.limits.embeddingVectors": "{{value}} 条向量存储",+ "plans.limits.fileStorage": "{{value}} 文件存储",+ "plans.limits.rolling5hSpend": "每 5 小时用量限制",+ "plans.limits.rolling5hSpend.multiple": "每 5 小时用量:{{plan}} 的 {{multiple}} 倍",+ "plans.limits.rolling5hSpend.tooltip": "每 5 小时的用量也有上限。从你的第一次请求开始计算,5 小时后重置。",+ "plans.limits.rolling5hSpend.unavailable": "无 5 小时用量限制",+ "plans.limits.rolling7dSpend": "每周用量额度",+ "plans.limits.rolling7dSpend.multiple": "{{plan}} 的 {{multiple}} 倍用量",+ "plans.limits.rolling7dSpend.tooltip": "套餐每 7 天可用的模型额度。从你的第一次请求开始计算,7 天后重置。",+ "plans.limits.sandboxStorage": "{{value}} 云端沙箱存储",+ "plans.limits.support": "{{value}}",+ "plans.limits.ultraMonthlySpend": "可使用 Ultra 模型,每月单独限额",+ "plans.limits.ultraMonthlySpend.multiple": "Ultra 模型:{{plan}} 的 {{multiple}} 倍用量",+ "plans.limits.ultraMonthlySpend.tooltip": "Ultra 模型是能力最强、成本最高的模型。它们消耗每周额度,同时每月另有上限。",+ "plans.limits.ultraMonthlySpend.unavailable": "Ultra 模型","plans.llm.customAPI": "全球主流模型自定义 API 服务","plans.llm.messageRequest": "无限消息请求","plans.llm.title": "模型服务",@@ -495,10 +562,13 @@"plans.plan.free.title": "免费版","plans.plan.hobby.desc": "适合拥有自定义 API、按量付费的用户","plans.plan.hobby.title": "自助版",+ "plans.plan.max.desc": "适合大规模运行智能体的重度用户","plans.plan.max.title": "Max",+ "plans.plan.plus.desc": "适合日常使用 AI","plans.plan.plus.title": "Plus","plans.plan.premium.desc": "适合频繁使用 AI 的专业用户","plans.plan.premium.title": "进阶版",+ "plans.plan.pro.desc": "适合每天深度依赖 AI 的专业用户","plans.plan.pro.title": "Pro","plans.plan.starter.desc": "适合偶尔使用 AI 的用户","plans.plan.starter.title": "基础版",@@ -507,6 +577,9 @@"plans.restoreSubscription": "恢复订阅","plans.restoreSubscriptionError": "订阅恢复失败","plans.restoreSubscriptionSuccess": "订阅已恢复",+ "plans.soldOut": "已售罄",+ "plans.soldOutError": "该套餐刚刚售罄,请选择其他套餐或稍后再试",+ "plans.soldOutTooltip": "该套餐名额已满,请稍后再来看看","plans.storage.title": "数据存储","plans.subscribe": "订阅","plans.support.free": "社区论坛",@@ -517,6 +590,7 @@"plans.support.ultimate": "优先聊天与邮件支持","plans.target": "目标计划","plans.unlimited": "无限制",+ "plans.usageHero.comparedTo": "倍于 {{plan}} 的用量","plans.workspace.features.adminControls": "集中计费和角色权限管理","plans.workspace.features.apiKey": "工作区 API 密钥","plans.workspace.features.auditLog": "审计日志",@@ -542,6 +616,8 @@"plansModal.modelAccess.title": "解锁全部模型","plansModal.persistentSandbox.desc": "云端沙箱里写下的文件会在会话结束后丢弃。升级后可获得持久化工作目录,跨会话保留、并在各个话题间共享。","plansModal.persistentSandbox.title": "保留沙箱中的文件",+ "plansModal.ultraModelAccess.desc": "Ultra 模型能力最强、成本最高,Pro 及以上套餐可用。升级后即可使用。",+ "plansModal.ultraModelAccess.title": "Ultra 模型需要 Pro 及以上套餐","qa.desc": "如果您的问题未被解答,请查看 <1>产品文档</1> 获取更多常见问题,或联系我们。","qa.detail": "查看详情","qa.list.credit.a": "积分是 {{cloud}} 用于衡量 AI 模型调用用量的指标。不同模型消耗的积分不同。",@@ -549,10 +625,12 @@"qa.list.embeddings.a": "向量存储并不等于您上传或导入数据集的原始大小,而是根据文件中纯文本内容向量化后的结果计算。例如,一页 PDF 文件(1000-1500 字符)提取为纯文本后,可能只占用约 1 个向量存储条目。您可在“{{usage}}”中查看使用情况。","qa.list.embeddings.q": "向量存储是如何计算的?","qa.list.free.a": "{{name}} 始终坚持开源原则。专业开发者可通过部署社区版使用全部开源功能。在 {{cloud}} 中,我们为所有注册用户每月提供 {{credit}} 免费积分,无需复杂配置即可使用。如需更多使用量,可订阅 {{starter}}、{{premium}} 或 {{ultimate}}。",+ "qa.list.free.newA": "{{name}} 始终坚持开源原则。专业开发者可通过部署社区版使用全部开源功能。在 {{cloud}} 中,我们为所有注册用户每月提供 {{credit}} 免费积分,无需复杂配置即可使用。如需更多用量,可订阅 {{plus}}、{{pro}} 或 {{max}}。","qa.list.free.q": "{{name}} 可以免费使用吗?","qa.list.highUsage.a": "积分消耗与对话长度密切相关。随着对话变长,每条新消息都会将完整历史作为输入 token 发送,导致费用显著增加。建议在切换话题时开启新对话。此外,如果两次发送间隔较长,提示词缓存可能失效,也会导致费用骤增。部分模型(如 Gemini Pro 系列)采用分梯度定价,输入超过 200K token 后费率翻倍。","qa.list.highUsage.q": "为什么我的积分消耗比预期快?","qa.list.limit.a": "{{cloud}} 的订阅计划分为 {{starter}}、{{premium}} 和 {{ultimate}},每个计划提供不同的积分额度。如当前计划积分不足,建议升级计划。您也可以在<fundsLink>「{{funds}}」</fundsLink>页面购买积分包进行按量付费充值。此外,您也可以配置自定义模型 API 密钥,使用其他来源购买的 API 积分。",+ "qa.list.limit.newA": "{{cloud}} 提供 {{plus}}、{{pro}} 和 {{max}} 三档订阅,每档都有 5 小时用量额度和每周用量额度,分别从开始使用起 5 小时、7 天后重置。额度用完后,可以等待重置或升级套餐;在<fundsLink>「{{funds}}」</fundsLink>页面购买的积分包,会在套餐额度用完后继续为你提供用量。此外,你也可以配置自定义模型 API 密钥,使用其他来源购买的 API 积分。","qa.list.limit.q": "积分用完怎么办?","qa.list.management.a": "在 {{subscribe}} 页面,您可以“升级 / 降级”当前订阅计划,或切换年付与月付。在“{{usage}}-{{management}}”中可跳转至 Stripe 进行订阅管理,您可随时取消订阅。取消后,当前计划到期时将自动降级为免费版。","qa.list.management.q": "如何更改或取消订阅?",@@ -580,6 +658,7 @@"recurring.perMonth": "每月","recurring.perYear": "每年","recurring.sixMonth": "六个月",+ "recurring.slashMonth": "/月","recurring.threeMonth": "三个月","recurring.title": "计费周期","recurring.yearly": "按年计费",diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.tsindex 4e5443cfb81..9366d9e581f 100644--- a/packages/app-config/src/featureFlags/schema.test.ts+++ b/packages/app-config/src/featureFlags/schema.test.ts@@ -257,6 +257,19 @@ describe('mapFeatureFlagsEnvToState', () => {expect(mapFeatureFlagsEnvToState(config).enableAgentShare).toBe(false);});+ it('should keep the new subscription tiers off by default and enable them for listed users', () => {+ expect(DEFAULT_FEATURE_FLAGS.new_tier_plans).toBe(false);+ expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableNewTierPlans).toBe(+ false,+ );++ const config = { new_tier_plans: ['tester-123'] };++ expect(mapFeatureFlagsEnvToState(config, 'tester-123').enableNewTierPlans).toBe(true);+ expect(mapFeatureFlagsEnvToState(config, 'user-456').enableNewTierPlans).toBe(false);+ expect(mapFeatureFlagsEnvToState(config).enableNewTierPlans).toBe(false);+ });+it('should keep topic previews off by default and enable them for listed users', () => {expect(DEFAULT_FEATURE_FLAGS.topic_preview).toBe(false);expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableTopicPreview).toBe(diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex 7dc8c35e933..19433d8c57b 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -90,6 +90,7 @@ export const FeatureFlagsSchema = z.object({auth_captcha: FeatureFlagValue.optional(),cloud_promotion: FeatureFlagValue.optional(),onboarding_v2: FeatureFlagValue.optional(),+ new_tier_plans: FeatureFlagValue.optional(),storage_overage: FeatureFlagValue.optional(),workspace: FeatureFlagValue.optional(),@@ -198,6 +199,9 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {auth_captcha: true,cloud_promotion: false,onboarding_v2: isDev,+ // Cloud-only grayscale for the new subscription tiers: off until an admin+ // publishes a whitelist (array of user IDs) or flips it to true.+ new_tier_plans: false,storage_overage: true,workspace: isDev,@@ -253,6 +257,7 @@ export const mapFeatureFlagsEnvToState = (enableDevDock: evaluateFeatureFlag(config.dev_dock, userId, 'dev_dock'),enableAuthCaptcha: evaluateFeatureFlag(config.auth_captcha, userId, 'auth_captcha'),enableOnboardingV2: evaluateFeatureFlag(config.onboarding_v2, userId, 'onboarding_v2'),+ enableNewTierPlans: evaluateFeatureFlag(config.new_tier_plans, userId, 'new_tier_plans'),enableStorageOverage: evaluateFeatureFlag(config.storage_overage, userId, 'storage_overage'),showCloudPromotion: evaluateFeatureFlag(config.cloud_promotion, userId, 'cloud_promotion'),diff --git a/packages/business-server/src/agent-run/runConcurrency.ts b/packages/business-server/src/agent-run/runConcurrency.tsnew file mode 100644index 00000000000..8422fd292e3--- /dev/null+++ b/packages/business-server/src/agent-run/runConcurrency.ts@@ -0,0 +1,36 @@+export interface AcquireAgentRunSlotParams {+ /**+ * `false` counts the run without refusing it: a continuation of a run the+ * user already started (approval resume, queued follow-up) must not fail.+ */+ enforce: boolean;+ /** The run's operation id, or a provisional id later moved with {@link rebindAgentRunSlot}. */+ holderId: string;+ userId: string;+}++export interface AcquireAgentRunSlotResult {+ /** `false` once the user's cap on concurrent runs is reached. */+ acquired: boolean;+}++/**+ * Caps how many agent runs one user has in flight. The default never limits;+ * a deployment that enforces a cap overrides these four functions.+ */+export const acquireAgentRunSlot = async (+ _params: AcquireAgentRunSlotParams,+): Promise<AcquireAgentRunSlotResult> => ({ acquired: true });++/** Moves a slot taken under a provisional id to the operation id that owns it. */+export const rebindAgentRunSlot = async (+ _userId: string,+ _fromHolderId: string,+ _toHolderId: string,+): Promise<void> => {};++/** Keeps a running holder's slot from lapsing. */+export const renewAgentRunSlot = async (_userId: string, _holderId: string): Promise<void> => {};++/** Frees the holder's slot once its run ends. */+export const releaseAgentRunSlot = async (_userId: string, _holderId: string): Promise<void> => {};diff --git a/packages/business-server/src/document/writeLimit.ts b/packages/business-server/src/document/writeLimit.tsnew file mode 100644index 00000000000..2abacdd5271--- /dev/null+++ b/packages/business-server/src/document/writeLimit.ts@@ -0,0 +1,26 @@+import type { DocumentWriteSource } from '@lobechat/types';++export interface CheckDocumentCharLimitParams {+ /** Length the document would have after the write, in UTF-16 code units. */+ charCount: number;+ source: DocumentWriteSource;+ userId: string;+ workspaceId?: string | null;+}++export type CheckDocumentCharLimitResult =+ | { allowed: true }+ | {+ allowed: false;+ limit: number;+ /** Plan the limit comes from, shown to the user and the model. */+ plan?: string;+ };++/**+ * Decides whether a document may grow to `charCount` characters. The default+ * never limits; a deployment with per-document size limits overrides it.+ */+export const checkDocumentCharLimit = async (+ _params: CheckDocumentCharLimitParams,+): Promise<CheckDocumentCharLimitResult> => ({ allowed: true });diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 4e44c47f503..9ca55f48bea 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -970,6 +970,10 @@ export default {'This link now opens a different agent. Switching to it — try again once it opens. Your draft is kept.','input.agentSlugUnconfirmed':'Couldn’t confirm which agent this link opens. Check your connection, then try again.',+ 'input.concurrencyLimit':+ 'You have too many agent tasks running at once. Send again when one finishes.',+ 'input.concurrencyLimitWithCount':+ 'Your plan runs up to {{count}} agent tasks at once. Send again when one finishes.','input.costEstimate.creditsPerMillionTokens': '{{credits}} credits/M tokens','input.costEstimate.hint': 'Estimated cost: ~{{credits}} credits','input.costEstimate.inputLabel': 'Input',diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.tsindex 9086c9d908a..8d258eaafa6 100644--- a/packages/locales/src/default/file.ts+++ b/packages/locales/src/default/file.ts@@ -319,6 +319,14 @@ export default {'pageEditor.agentUnavailable.viewDocs': 'View docs','pageEditor.artifactTag': 'Artifact','pageEditor.autoSaveMessage': 'Your page is saved automatically. No need to save manually.',+ 'pageEditor.charLimit.blockedDescription':+ 'Changes are not saved. Shorten the page or upgrade your plan to keep editing.',+ 'pageEditor.charLimit.blockedTitle':+ 'This page has {{actual}} characters, over the {{limit}}-character limit per page on your plan.',+ 'pageEditor.charLimit.nearDescription':+ 'Saving will be refused once the page goes over the limit.',+ 'pageEditor.charLimit.nearTitle':+ 'This page has {{actual}} of {{limit}} characters allowed per page on your plan.','pageEditor.chooseIcon': 'Choose Icon','pageEditor.collab.notSynced':'Your latest page edits are still syncing, so the Agent may not see them yet.',diff --git a/packages/locales/src/default/subscription.ts b/packages/locales/src/default/subscription.tsindex e3a686d4df0..b8bef970528 100644--- a/packages/locales/src/default/subscription.ts+++ b/packages/locales/src/default/subscription.ts@@ -95,6 +95,8 @@ export default {'currentPlan.cancelAlert':'Subscription will be cancelled after {{canceledAt}}. You can still restore it before then','currentPlan.downgradeAlert': 'Will be downgraded to {{plan}} after {{downgradedAt}}.',+ 'currentPlan.legacyCancelAlert':+ 'Subscription will end after {{canceledAt}}. A canceled legacy plan cannot be restored, but you can upgrade to a new plan anytime.','currentPlan.management': 'Manage Subscription','currentPlan.notIncluded': 'Not included in current plan','currentPlan.paymentExpired':@@ -106,6 +108,33 @@ export default {'discount.maxOff': 'Up to {{percent}}% off','discount.off': '{{percent}}% off','discount.save': 'Save',+ 'limitation.insufficientBudget.rescue.overflow.badge': 'Enough for this',+ 'limitation.insufficientBudget.rescue.overflow.benefit':+ 'Spend your {{credits}} credits once plan limits run out. No extra cost.',+ 'limitation.insufficientBudget.rescue.overflow.cta': 'Use credit packs and continue',+ 'limitation.insufficientBudget.rescue.overflow.title': 'Use your credit packs',+ 'limitation.insufficientBudget.rescue.topup.benefitOverflow':+ "Purchased credits are used after your plan limits run out. We'll turn that on for you.",+ 'limitation.insufficientBudget.rescue.upgrade.benefitMultiple':+ '{{multiple}}× the usage of your current plan',+ 'limitation.insufficientBudget.rescue.upgrade.benefitRolling': 'Higher weekly usage limits',+ 'limitation.insufficientBudget.rescue.wait.hint': "Or wait for the reset and retry, it's free.",+ 'limitation.insufficientBudget.window.desc': "You've reached your {{rules}}.",+ 'limitation.insufficientBudget.window.duration.days': '{{count}} d',+ 'limitation.insufficientBudget.window.duration.hours': '{{count}} h',+ 'limitation.insufficientBudget.window.duration.minutes': '{{count}} min',+ 'limitation.insufficientBudget.window.listSeparator': ', ',+ 'limitation.insufficientBudget.window.requestTooLarge':+ "This request needs more than the limit allows, so waiting won't help.",+ 'limitation.insufficientBudget.window.resetNow': 'It has just reset, so you can retry now.',+ 'limitation.insufficientBudget.window.resetsIn': 'Resets in {{duration}} ({{time}}).',+ 'limitation.insufficientBudget.window.rule.overflowMonth': 'monthly credit-pack cap',+ 'limitation.insufficientBudget.window.rule.plan5h': '5-hour limit',+ 'limitation.insufficientBudget.window.rule.plan7d': 'weekly limit',+ 'limitation.insufficientBudget.window.rule.planMonth': 'monthly limit',+ 'limitation.insufficientBudget.window.rule.planUltraMonth': 'monthly Ultra-model limit',+ 'limitation.insufficientBudget.window.sentenceSeparator': ' ',+ 'limitation.insufficientBudget.window.title': 'Usage limit reached','modelSelection.confirm.continue': 'Continue using','modelSelection.confirm.description':'{{model}} can incur higher usage costs. Review its current rates before continuing.',@@ -489,6 +518,20 @@ export default {'plans.cloud.history': 'Unlimited conversation history','plans.cloud.sync': 'Global cloud sync','plans.cloud.title': 'Cloud Service',+ 'plans.compare.agentMemory': 'Agent memory',+ 'plans.compare.artifactSiteSize': 'Max size per site',+ 'plans.compare.artifactSites': 'Active Artifact sites',+ 'plans.compare.concurrentAgentRuns': 'Concurrent agent tasks',+ 'plans.compare.documentCharacters': 'Characters per document',+ 'plans.compare.earlyAccess': 'Early access to new features',+ 'plans.compare.none': 'None',+ 'plans.compare.rolling5hSpend': '5-hour usage limit',+ 'plans.compare.rolling7dSpend': 'Weekly usage',+ 'plans.compare.sandboxStorage': 'Cloud sandbox storage',+ 'plans.compare.ultraMonthlySpend': 'Ultra models per month',+ 'plans.compare.unlimited': 'Unlimited',+ 'plans.compare.usageBase': 'Standard',+ 'plans.compare.usageMultiple': '{{multiple}}×','plans.credit.api': 'Custom API','plans.credit.apiDesc': 'Requires your own model API configuration','plans.credit.apiProvider':@@ -507,6 +550,42 @@ export default {'plans.downgradeWillCancel': 'This action will cancel your scheduled plan downgrade','plans.cancelDowngrade': 'Cancel Scheduled Downgrade','plans.cancelDowngradeSuccess': 'Scheduled downgrade has been cancelled',+ 'plans.legacy.banner.desc':+ 'It keeps its current price. You can upgrade to a higher-tier plan anytime, and what you have used this billing period is on us.',+ 'plans.legacy.banner.downgrade': 'Switches to {{plan}} when this billing period ends',+ 'plans.legacy.banner.title': 'You are on {{plan}}, a legacy plan',+ 'plans.legacy.upgradeOnly': 'A legacy plan can only be upgraded to a higher-tier plan',+ 'plans.limits.agentMemory.unavailable': 'Agent memory',+ 'plans.limits.agentMemory.unlimited': 'Agent memory',+ 'plans.limits.artifactSiteSize': 'Up to {{value}} per published site',+ 'plans.limits.artifactSites': 'Up to {{value}} active Artifact sites',+ 'plans.limits.concurrentAgentRuns': '{{value}} agent tasks at once',+ 'plans.limits.concurrentAgentRuns.unlimited': 'Unlimited concurrent agent tasks',+ 'plans.limits.documentCharacters': 'Up to {{value}} characters per document',+ 'plans.limits.documentCharacters.unlimited': 'No document length limit',+ 'plans.limits.earlyAccess.unavailable': 'Early access to new features',+ 'plans.limits.earlyAccess.unlimited': 'Early access to new features',+ 'plans.limits.embeddingVectors': '{{value}} vector entries',+ 'plans.limits.fileStorage': '{{value}} file storage',+ 'plans.limits.rolling5hSpend': '5-hour usage limit',+ 'plans.limits.rolling5hSpend.multiple': '5-hour usage limit: {{multiple}}× that of {{plan}}',+ 'plans.limits.rolling5hSpend.tooltip':+ 'Usage within any 5 hours is capped too. The window starts with your first request and resets 5 hours later.',+ 'plans.limits.rolling5hSpend.unavailable': 'No 5-hour limit',+ 'plans.limits.rolling7dSpend': 'Weekly usage allowance',+ 'plans.limits.rolling7dSpend.multiple': '{{multiple}}× the usage of {{plan}}',+ 'plans.limits.rolling7dSpend.tooltip':+ 'Model usage your plan covers in any 7 days. The week starts with your first request and resets 7 days later.',+ 'plans.limits.sandboxStorage': '{{value}} cloud sandbox storage',+ 'plans.limits.support': '{{value}}',+ 'plans.limits.ultraMonthlySpend': 'Ultra models, with a separate monthly limit',+ 'plans.limits.ultraMonthlySpend.multiple': 'Ultra models: {{multiple}}× the usage of {{plan}}',+ 'plans.limits.ultraMonthlySpend.tooltip':+ 'Ultra models are the most capable and most expensive ones. They use your weekly credits and are also capped each month.',+ 'plans.limits.ultraMonthlySpend.unavailable': 'Ultra models',+ 'plans.plan.max.desc': 'For power users running agents at scale',+ 'plans.plan.plus.desc': 'For everyday AI use',+ 'plans.plan.pro.desc': 'For professionals who rely on AI every day','plans.restoreSubscription': 'Restore Subscription','plans.restoreSubscriptionError': 'Could not restore your subscription','plans.restoreSubscriptionSuccess': 'Subscription has been restored',@@ -586,6 +665,9 @@ export default {'plans.plan.starter.title': 'Starter','plans.plan.ultimate.desc': 'For heavy users who need complex AI conversations','plans.plan.ultimate.title': 'Ultimate',+ 'plans.soldOut': 'Sold Out',+ 'plans.soldOutError': 'This plan just sold out. Choose another plan or try again later.',+ 'plans.soldOutTooltip': 'All spots for this plan are taken. Check back later.','plans.storage.title': 'Data Storage','plans.subscribe': 'Subscribe','plans.support.free': 'Community Forum',@@ -594,6 +676,7 @@ export default {'plans.support.starter': 'Email and Community Forum','plans.support.title': 'Support','plans.support.ultimate': 'Priority Chat and Email Support',+ 'plans.usageHero.comparedTo': 'more usage than {{plan}}','plans.workspace.features.adminControls': 'Centralized billing and role management','plans.workspace.features.apiKey': 'Workspace API Keys','plans.workspace.features.auditLog': 'Audit Logs',@@ -627,6 +710,9 @@ export default {'plansModal.modelAccess.desc':'This model is available on paid plans. Upgrade to use the full model lineup.','plansModal.modelAccess.title': 'Unlock all models',+ 'plansModal.ultraModelAccess.desc':+ 'Ultra models are the most capable and most expensive ones, available on Pro and above. Upgrade to use them.',+ 'plansModal.ultraModelAccess.title': 'Ultra models need Pro or above','qa.desc':'If your question is not answered, check <1>Product Documentation</1> for more FAQs, or contact us.','qa.detail': 'View Details',@@ -638,9 +724,13 @@ export default {'qa.list.embeddings.q': 'How is vector storage calculated?','qa.list.free.a':'{{name}} has always adhered to open source principles. For professional developers, you can use all open source capabilities through self-deployment of the community version. In {{cloud}}, we provide all registered users with {{credit}} free credits per month, ready to use without complex configuration. If you need more usage, you can subscribe to {{starter}}, {{premium}} or {{ultimate}}.',+ 'qa.list.free.newA':+ '{{name}} has always adhered to open source principles. For professional developers, you can use all open source capabilities through self-deployment of the community version. In {{cloud}}, every registered user gets {{credit}} free credits per month, ready to use without complex configuration. For more usage, subscribe to {{plus}}, {{pro}} or {{max}}.','qa.list.free.q': 'Can {{name}} be used for free?','qa.list.limit.a':'{{cloud}} subscription plans are divided into {{starter}}, {{premium}} and {{ultimate}}, each providing different credit amounts. If your current plan credits are insufficient, we recommend upgrading. You can also purchase credit packages on the <fundsLink>"{{funds}}"</fundsLink> page for pay-as-you-go usage. Alternatively, you can set up a custom model API key to use API credits purchased from other sources.',+ 'qa.list.limit.newA':+ '{{cloud}} offers {{plus}}, {{pro}} and {{max}}. Each caps usage within 5 hours and within a week; each window resets 5 hours or 7 days after it starts. When you reach a limit, you can wait for it to reset or upgrade your plan. Credit packs bought on the <fundsLink>"{{funds}}"</fundsLink> page keep you going once your plan limits run out. You can also set up a custom model API key to use API credits purchased from other sources.','qa.list.limit.q': 'What if I run out of credits?','qa.list.highUsage.a':'Credit consumption depends heavily on conversation length. As a conversation grows, each new message sends the entire history as input tokens, which increases cost significantly. We recommend starting a new conversation when topics change. Also, if there is a long gap between messages, the prompt cache may expire, causing a spike in cost. Some models like the Gemini Pro series use tiered pricing — input beyond 200K tokens is charged at double the rate.',@@ -679,6 +769,7 @@ export default {'recurring.perMonth': 'Per Month','recurring.perYear': 'Per Year','recurring.sixMonth': '6 Months',+ 'recurring.slashMonth': '/mo','recurring.threeMonth': '3 Months','recurring.title': 'Billing Cycle','recurring.yearly': 'Yearly Billing',diff --git a/packages/types/src/document/index.ts b/packages/types/src/document/index.tsindex 27ff0e0db3f..a847c691570 100644--- a/packages/types/src/document/index.ts+++ b/packages/types/src/document/index.ts@@ -1,5 +1,6 @@export * from './access';export * from './share';+export * from './writeLimit';/*** Document object in LobeChatdiff --git a/packages/types/src/document/writeLimit.ts b/packages/types/src/document/writeLimit.tsnew file mode 100644index 00000000000..427f9d0fc2a--- /dev/null+++ b/packages/types/src/document/writeLimit.ts@@ -0,0 +1,22 @@+/**+ * Error code a document write carries when it would leave the document longer+ * than the per-document character limit. Sent as `errorData.code` on the TRPC+ * error so the editor, CLI and agent tools can recognize it.+ */+export const DOCUMENT_CHAR_LIMIT_EXCEEDED = 'DocumentCharLimitExceeded';++/**+ * Who asked for a document write. `system` writes (tool-result archives, copies,+ * migrations, generated reports) are never limited.+ */+export type DocumentWriteSource = 'agent' | 'system' | 'user';++/** `errorData` of a write refused by the per-document character limit. */+export interface DocumentCharLimitErrorData {+ /** Length the document would have after the write, in UTF-16 code units. */+ actual: number;+ code: typeof DOCUMENT_CHAR_LIMIT_EXCEEDED;+ limit: number;+ /** Plan the limit comes from, when the deployment has plans. */+ plan?: string;+}diff --git a/packages/types/src/fetch.ts b/packages/types/src/fetch.tsindex 600923f99a8..1a7522c80bb 100644--- a/packages/types/src/fetch.ts+++ b/packages/types/src/fetch.ts@@ -16,6 +16,7 @@ export const ChatErrorType = {ShareHeterogeneousAgentUnsupported: 'ShareHeterogeneousAgentUnsupported', // This agent configuration is not supported for shared visitorsAgentShareProviderNotSupported: 'AgentShareProviderNotSupported', // This shared agent uses a provider that is not supported for shared visitorsSupervisorDecisionFailed: 'SupervisorDecisionFailed', // Supervisor decision failed+ AgentConcurrencyLimitExceeded: 'AgentConcurrencyLimitExceeded', // The user already has as many agent runs in flight as allowed — recovers when one finishesInvalidUserKey: 'InvalidUserKey', // is not valid User keyCreateMessageError: 'CreateMessageError',diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex 22c63796d11..502c30fc515 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -44,6 +44,11 @@ export type IFeatureFlagsState = {* current sidebar layout.*/enableImLayout: boolean | undefined;+ /**+ * New subscription tiers (`new_tier_plans`). Off by default: the plans page keeps+ * selling the current tiers; listed users see and can buy the new tiers instead.+ */+ enableNewTierPlans: boolean | undefined;/*** LobeHub Mobile rollout gate for the multiplexed gateway socket and* protocol-v2 payloads. Web follows `GlobalServerConfig.agentGatewayProtocol`.diff --git a/src/business/client/hooks/useBusinessDocumentCharLimit.ts b/src/business/client/hooks/useBusinessDocumentCharLimit.tsnew file mode 100644index 00000000000..46e8f8241fa--- /dev/null+++ b/src/business/client/hooks/useBusinessDocumentCharLimit.ts@@ -0,0 +1,17 @@+import type { ReactNode } from 'react';++export interface BusinessDocumentCharLimit {+ /** Button shown beside the page-limit notice, such as an upgrade entry. */+ action?: ReactNode;+ /** Per-page character limit known before a save is refused. Undefined means unknown or unlimited. */+ limit?: number;+}++/**+ * Lets a deployment tell the page editor the character limit that applies to+ * the current user, so it can warn before a save is refused.+ */+export const useBusinessDocumentCharLimit = (): BusinessDocumentCharLimit => ({+ action: undefined,+ limit: undefined,+});diff --git a/src/business/client/hooks/useBusinessSendErrorAlert.ts b/src/business/client/hooks/useBusinessSendErrorAlert.tsnew file mode 100644index 00000000000..b653a49a63e--- /dev/null+++ b/src/business/client/hooks/useBusinessSendErrorAlert.ts@@ -0,0 +1,14 @@+import type { ReactNode } from 'react';++export interface BusinessSendErrorAlert {+ /** Button shown beside the notice, such as an upgrade entry. */+ action?: ReactNode;+ /** Replaces the default notice text. */+ title?: string;+}++/**+ * Lets a deployment enrich the composer notice for a refused send, keyed by the+ * error type the server returned as the message.+ */+export const useBusinessSendErrorAlert = (_errorMessage?: string): BusinessSendErrorAlert => ({});diff --git a/src/features/Conversation/ChatInput/SendErrorAlert.tsx b/src/features/Conversation/ChatInput/SendErrorAlert.tsxnew file mode 100644index 00000000000..0b2ef193de8--- /dev/null+++ b/src/features/Conversation/ChatInput/SendErrorAlert.tsx@@ -0,0 +1,46 @@+import { ChatErrorType } from '@lobechat/types';+import { Alert, Flexbox } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useBusinessSendErrorAlert } from '@/business/client/hooks/useBusinessSendErrorAlert';++import { toDisplayableSendErrorMessage } from './utils';++interface SendErrorAlertProps {+ /** The failed send's `error.message`. */+ errorMessage: string;+ onClose: () => void;+}++/**+ * Notice above the composer for a send the server refused. The typed message+ * is back in the composer, so the notice only says why and what to do next.+ */+const SendErrorAlert = memo<SendErrorAlertProps>(({ errorMessage, onClose }) => {+ const { t } = useTranslation(['chat', 'common']);+ const business = useBusinessSendErrorAlert(errorMessage);++ // `errorMessage` can still be a raw database dump on servers predating the+ // databaseError middleware. That text is SQL plus every bound parameter —+ // including the user's own input — so it is never echoed; generic copy+ // stands in for it.+ const title =+ business.title ??+ (errorMessage === ChatErrorType.AgentConcurrencyLimitExceeded+ ? t('input.concurrencyLimit')+ : t('input.errorMsg', {+ errorMsg:+ toDisplayableSendErrorMessage(errorMessage) ?? t('unknownError', { ns: 'common' }),+ }));++ return (+ <Flexbox paddingBlock={'0 6px'} paddingInline={12}>+ <Alert closable action={business.action} title={title} type={'secondary'} onClose={onClose} />+ </Flexbox>+ );+});++SendErrorAlert.displayName = 'SendErrorAlert';++export default SendErrorAlert;diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex a864435aeb6..5329b567f6d 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -6,10 +6,9 @@ import {type ChatInputActionsProps,type ChatInputProps as EditorChatInputProps,} from '@lobehub/editor/react';-import { Alert, type DropdownItem, Flexbox, toast } from '@lobehub/ui';+import { type DropdownItem, Flexbox, toast } from '@lobehub/ui';import { type ReactNode } from 'react';import { memo, useCallback, useEffect, useMemo, useRef } from 'react';-import { useTranslation } from 'react-i18next';import {getBusinessChatInputSendAreaPrefix,@@ -45,6 +44,7 @@ import InputCompletionErrorAlert from './InputCompletionErrorAlert';import LinkedGoalTray from './LinkedGoalTray';import OpStatusTray from './OpStatusTray';import QueueTray from './QueueTray';+import SendErrorAlert from './SendErrorAlert';import { sendVoiceMessage } from './sendVoiceMessage';import { transcribeVoiceMessage } from './transcribeVoiceMessage';import { useConversationChatInputUiState } from './useConversationChatInputUiState';@@ -53,7 +53,6 @@ import {getContextWindowMessages,getConversationSendButtonProps,toChatInputMessages,- toDisplayableSendErrorMessage,} from './utils';import {canSendVoiceMessage,@@ -207,8 +206,6 @@ const ChatInput = memo<ChatInputProps>(onEditorReady,skipScrollMarginWithList,}) => {- const { t } = useTranslation('chat');-// ConversationStore stateconst storeApi = useConversationStoreApi();const dbMessages = useConversationStore(dataSelectors.dbMessages);@@ -280,22 +277,6 @@ const ChatInput = memo<ChatInputProps>(const sendMessageErrorMsg = useConversationStore(messageStateSelectors.sendMessageError);const clearSendMessageError = useChatStore((s) => s.clearSendMessageError);- // `inputSendErrorMsg` is the failed call's `error.message` verbatim, so it- // can still be a raw database dump on servers predating the databaseError- // middleware. That text is SQL plus every bound parameter — including the- // user's own input — so it is never echoed; generic copy stands in for it.- const sendMessageErrorTitle = useMemo(- () =>- sendMessageErrorMsg- ? t('input.errorMsg', {- errorMsg:- toDisplayableSendErrorMessage(sendMessageErrorMsg) ??- t('unknownError', { ns: 'common' }),- })- : undefined,- [sendMessageErrorMsg, t],- );-// File store - for UI state only (disabled button, etc.)const fileList = useFileStore(fileChatSelectors.chatUploadFileList);const contextList = useFileStore(fileChatSelectors.chatContextSelections(contextKey));@@ -494,15 +475,8 @@ const ChatInput = memo<ChatInputProps>({/* Keep the chat input mounted while an intervention panel is showing —unmounting would wipe the Lexical editor's in-memory document. */}<div style={{ display: hasPendingInterventions ? 'none' : 'contents' }}>- {sendMessageErrorTitle && (- <Flexbox paddingBlock={'0 6px'} paddingInline={12}>- <Alert- closable- title={sendMessageErrorTitle}- type={'secondary'}- onClose={clearSendMessageError}- />- </Flexbox>+ {sendMessageErrorMsg && (+ <SendErrorAlert errorMessage={sendMessageErrorMsg} onClose={clearSendMessageError} />)}{businessAlerts}<Flexboxdiff --git a/src/features/EditorCanvas/CharLimitBanner.tsx b/src/features/EditorCanvas/CharLimitBanner.tsxnew file mode 100644index 00000000000..70a539af1a5--- /dev/null+++ b/src/features/EditorCanvas/CharLimitBanner.tsx@@ -0,0 +1,79 @@+'use client';++import { Alert } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useBusinessDocumentCharLimit } from '@/business/client/hooks/useBusinessDocumentCharLimit';+import { useDocumentStore } from '@/store/document';+import { editorSelectors } from '@/store/document/slices/editor';++import { resolveCharLimitNotice } from './charLimitNotice';++export interface CharLimitBannerProps {+ documentId?: string;+ /**+ * Keeps the refused-save notice pinned to the top of the scrolling body, so+ * it stays visible when the banner sits inside the scroll host. A host that+ * renders the banner above its scroll area leaves this off.+ */+ sticky?: boolean;+}++/**+ * Persistent notice for the plan's per-page character limit:+ *+ * - blocked: the last save was refused and the page is still over the limit.+ * The edits are not saved, so this stays until the page is shortened (the next+ * successful save clears the stored refusal).+ * - near: the page reached 90% of the known limit. The limit comes from the last+ * refusal, else from the business hook (Cloud: the current personal plan).+ */+const CharLimitBanner = memo<CharLimitBannerProps>(({ documentId, sticky }) => {+ const { t, i18n } = useTranslation('file');+ const refusal = useDocumentStore((s) =>+ documentId ? editorSelectors.charLimitError(documentId)(s) : undefined,+ );+ const length = useDocumentStore((s) =>+ documentId ? editorSelectors.content(documentId)(s).length : 0,+ );+ const { action, limit: planLimit } = useBusinessDocumentCharLimit();++ const notice = resolveCharLimitNotice({ length, planLimit, refusal });+ if (!notice) return null;++ const format = new Intl.NumberFormat(i18n.language);+ const values = { actual: format.format(length), limit: format.format(notice.limit) };++ if (notice.kind === 'blocked') {+ return (+ <Alert+ showIcon+ action={action}+ description={t('pageEditor.charLimit.blockedDescription')}+ title={t('pageEditor.charLimit.blockedTitle', values)}+ type="warning"+ style={+ sticky+ ? { insetBlockStart: 0, marginBlock: 8, position: 'sticky', zIndex: 2 }+ : { marginBlock: 8 }+ }+ />+ );+ }++ return (+ <Alert+ showIcon+ action={action}+ description={t('pageEditor.charLimit.nearDescription')}+ style={{ marginBlock: 8 }}+ title={t('pageEditor.charLimit.nearTitle', values)}+ type="info"+ />+ );+});++CharLimitBanner.displayName = 'CharLimitBanner';++export default CharLimitBanner;diff --git a/src/features/EditorCanvas/charLimitNotice.test.ts b/src/features/EditorCanvas/charLimitNotice.test.tsnew file mode 100644index 00000000000..000390957f5--- /dev/null+++ b/src/features/EditorCanvas/charLimitNotice.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { resolveCharLimitNotice } from './charLimitNotice';++describe('resolveCharLimitNotice', () => {+ it('shows nothing without a known limit', () => {+ expect(resolveCharLimitNotice({ length: 500 })).toBeUndefined();+ });++ it('is blocked while the page is over the refused limit', () => {+ expect(resolveCharLimitNotice({ length: 120, refusal: { limit: 100 } })).toEqual({+ kind: 'blocked',+ limit: 100,+ });+ });++ it('prefers the refused limit over the plan limit', () => {+ expect(+ resolveCharLimitNotice({ length: 120, planLimit: 1000, refusal: { limit: 100 } }),+ ).toEqual({ kind: 'blocked', limit: 100 });+ });++ it('warns softly from 90% of the plan limit', () => {+ expect(resolveCharLimitNotice({ length: 90, planLimit: 100 })).toEqual({+ kind: 'near',+ limit: 100,+ });+ expect(resolveCharLimitNotice({ length: 89, planLimit: 100 })).toBeUndefined();+ });++ it('downgrades to the soft warning once the page is shortened under the refused limit', () => {+ expect(resolveCharLimitNotice({ length: 95, refusal: { limit: 100 } })?.kind).toBe('near');+ expect(resolveCharLimitNotice({ length: 50, refusal: { limit: 100 } })).toBeUndefined();+ });+});diff --git a/src/features/EditorCanvas/charLimitNotice.ts b/src/features/EditorCanvas/charLimitNotice.tsnew file mode 100644index 00000000000..1150991a296--- /dev/null+++ b/src/features/EditorCanvas/charLimitNotice.ts@@ -0,0 +1,29 @@+/** Share of the limit at which the softer "near the limit" warning appears. */+export const CHAR_LIMIT_WARN_RATIO = 0.9;++export interface CharLimitNotice {+ kind: 'blocked' | 'near';+ limit: number;+}++/**+ * Decides which page-size notice to show.+ *+ * - `blocked`: the last save was refused and the page is still over the refused+ * limit, so the edits are not saved.+ * - `near`: the page reached 90% of the known limit (the last refusal's, else the+ * plan's).+ */+export const resolveCharLimitNotice = ({+ length,+ planLimit,+ refusal,+}: {+ length: number;+ planLimit?: number;+ refusal?: { limit: number };+}): CharLimitNotice | undefined => {+ const limit = refusal?.limit ?? planLimit;+ if (!limit || length < limit * CHAR_LIMIT_WARN_RATIO) return undefined;+ return { kind: refusal && length > refusal.limit ? 'blocked' : 'near', limit };+};diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsxindex 6d5db8165be..2377ca1cfcd 100644--- a/src/features/PageEditor/PageEditor.tsx+++ b/src/features/PageEditor/PageEditor.tsx@@ -6,6 +6,7 @@ import type { FC, ReactNode, UIEvent } from 'react';import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';import type { ComposerTarget } from '@/features/Conversation/types';+import CharLimitBanner from '@/features/EditorCanvas/CharLimitBanner';import DiffAllToolbar from '@/features/EditorCanvas/DiffAllToolbar';import PageMetaBar from '@/features/PageEditor/PageMetaBar';import WideScreenContainer from '@/features/WideScreenContainer';@@ -388,6 +389,8 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {{/* Prominent in-body notice when another member holds the lock; thecompact status badge lives in the Header (EditingIndicator). */}<LockedAlert />+ {/* Plan page-size limit: refused-save notice and near-limit warning. */}+ <CharLimitBanner sticky documentId={documentId} /><EditorCanvas askCopilotTarget={askCopilotTarget} /><BlockCommentMarker hostRef={editorContentRef} />{documentId && <DocumentLikes documentId={documentId} key={documentId} />}diff --git a/src/features/Portal/Document/Body.test.tsx b/src/features/Portal/Document/Body.test.tsxindex 4b4a7d9ecaa..83405756425 100644--- a/src/features/Portal/Document/Body.test.tsx+++ b/src/features/Portal/Document/Body.test.tsx@@ -78,6 +78,12 @@ vi.mock('./EditorCanvas', () => ({default: () => <div data-testid="editor-canvas" />,}));+vi.mock('@/features/EditorCanvas/CharLimitBanner', () => ({+ default: ({ documentId }: { documentId?: string }) => (+ <div data-document-id={documentId} data-testid="char-limit-banner" />+ ),+}));+vi.mock('./TodoList', () => ({default: () => <div data-testid="todo-list" />,}));@@ -165,6 +171,7 @@ describe('DocumentBody', () => {/** @example Neither editor mounts. */expect(screen.queryByTestId('highlight-editor')).toBeNull();expect(screen.queryByTestId('editor-canvas')).toBeNull();+ expect(screen.queryByTestId('char-limit-banner')).toBeNull();});beforeEach(() => {@@ -196,6 +203,7 @@ describe('DocumentBody', () => {expect(screen.getByTestId('highlight-editor')).toHaveValue('raw log content');expect(screen.queryByTestId('editor-canvas')).toBeNull();+ expect(screen.getByTestId('char-limit-banner')).toBeDefined();});it('renders EditorCanvas for markdown files', () => {@@ -205,6 +213,7 @@ describe('DocumentBody', () => {expect(screen.getByTestId('editor-canvas')).toBeDefined();expect(screen.queryByTestId('highlight-editor')).toBeNull();+ expect(screen.getByTestId('char-limit-banner').dataset.documentId).toBe('document-1');});it('renders an HTML page in a sandboxed frame without mounting either editor', () => {@@ -221,6 +230,7 @@ describe('DocumentBody', () => {expect(frame.getAttribute('srcdoc')).toContain('<h1>Goal report</h1>');expect(frame.getAttribute('sandbox')).not.toContain('allow-same-origin');expect(screen.queryByTestId('editor-canvas')).toBeNull();+ expect(screen.queryByTestId('char-limit-banner')).toBeNull();expect(screen.queryByTestId('highlight-editor')).toBeNull();});diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsxindex de4920908b3..e9ca337eeb0 100644--- a/src/features/Portal/Document/Body.tsx+++ b/src/features/Portal/Document/Body.tsx@@ -18,6 +18,7 @@ import AsyncError from '@/components/AsyncError';import CodeEditorPane from '@/components/CodeEditorPane';import { HtmlDocumentFrame } from '@/components/HtmlPreview';import Loading from '@/components/Loading/CircleLoading';+import CharLimitBanner from '@/features/EditorCanvas/CharLimitBanner';import FileNotFound from '@/features/FileNotFound';import { FileDocumentPreview } from '@/features/FileViewer/FileDocumentPreview';import WideScreenContainer from '@/features/WideScreenContainer';@@ -110,7 +111,9 @@ const SkillFrontmatterBlock = memo<SkillFrontmatterBlockProps>(({ documentId, frawait performSave(documentId, undefined, { saveSource: 'manual' });const latestDocument = useDocumentStore.getState().documents[documentId];if (latestDocument?.isDirty) {- setError(t('skillFrontmatter.saveFailed'));+ // A length refusal already has its toast and banner; a second, vaguer+ // "save failed" line would only repeat it.+ setError(latestDocument.charLimitError ? undefined : t('skillFrontmatter.saveFailed'));return;}@@ -298,6 +301,12 @@ const DocumentBody = memo(() => {return (<Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}>+ {/* Above the scroll host, so the plan page-size notice stays in view. */}+ {(renderMode.mode === 'editor' || renderMode.mode === 'highlight') && (+ <Flexbox paddingInline={16}>+ <CharLimitBanner documentId={documentId} />+ </Flexbox>+ )}<div className={fullPage ? styles.contentFull : styles.content}>{fullPage && renderMode.mode !== 'file' ? (<WideScreenContainer>{editorContent}</WideScreenContainer>diff --git a/src/features/Portal/Document/useHighlightSave.test.ts b/src/features/Portal/Document/useHighlightSave.test.tsindex 48d3e3d4720..6c59cbb2ae2 100644--- a/src/features/Portal/Document/useHighlightSave.test.ts+++ b/src/features/Portal/Document/useHighlightSave.test.ts@@ -2,7 +2,9 @@ import { toast } from '@lobehub/ui';import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';-import { useHighlightSave } from './useHighlightSave';+import { useDocumentStore } from '@/store/document';++import { resetRefusedDraftsForTests, useHighlightSave } from './useHighlightSave';vi.mock('@lobehub/ui', async (importOriginal) => ({...(await importOriginal<object>()),@@ -329,4 +331,191 @@ describe('useHighlightSave', () => {expect(result.current.editingValue).toBe('new remote draft');expect(toast.error).not.toHaveBeenCalled();});++ describe('plan character limit', () => {+ const limitError = () =>+ Object.assign(new Error('Over the limit'), {+ data: {+ code: 'BAD_REQUEST',+ errorData: { actual: 120, code: 'DocumentCharLimitExceeded', limit: 100, plan: 'free' },+ },+ });++ const seedStoreDocument = () =>+ act(() => {+ useDocumentStore.getState().internal_dispatchDocument({+ id: 'doc-1',+ type: 'addDocument',+ value: { content: 'before', lastSavedContent: 'before', sourceType: 'notebook' },+ });+ });++ beforeEach(() => {+ resetRefusedDraftsForTests();+ act(() => useDocumentStore.getState().closeDocument('doc-1'));+ });++ const updatedAt = new Date('2024-01-01T00:00:00.000Z');++ const refuseDraft = async () => {+ mockUpdateDocument.mockRejectedValueOnce(limitError());+ const editor = renderHook(() =>+ useHighlightSave({+ content: 'before',+ documentId: 'doc-1',+ onSaveStart: () => vi.fn(),+ updatedAt,+ }),+ );+ act(() => editor.result.current.handleChange('after'));+ await act(() => editor.result.current.handleSave());+ // The unmount flush retries the same refused draft.+ mockUpdateDocument.mockRejectedValueOnce(limitError());+ editor.unmount();+ await act(async () => {});+ // Closing the portal drops the document's store entry.+ act(() => useDocumentStore.getState().closeDocument('doc-1'));+ };++ it('reopens a refused draft and its banner after the editor unmounts', async () => {+ await refuseDraft();+ seedStoreDocument();++ const { result } = renderHook(() =>+ useHighlightSave({+ content: 'before',+ documentId: 'doc-1',+ onSaveStart: () => vi.fn(),+ updatedAt,+ }),+ );++ expect(result.current.editingValue).toBe('after');+ expect(useDocumentStore.getState().documents['doc-1'].charLimitError).toMatchObject({+ limit: 100,+ });+ });++ it('keeps warning before the page unloads after the editor unmounts', async () => {+ await refuseDraft();++ const event = new Event('beforeunload', { cancelable: true });+ window.dispatchEvent(event);++ expect(event.defaultPrevented).toBe(true);+ });++ it('stops warning before unload once no refused draft is kept', async () => {+ await refuseDraft();+ resetRefusedDraftsForTests();++ const event = new Event('beforeunload', { cancelable: true });+ window.dispatchEvent(event);++ expect(event.defaultPrevented).toBe(false);+ });++ it('drops a refused draft once the document has a newer version', async () => {+ await refuseDraft();+ seedStoreDocument();++ const { result } = renderHook(() =>+ useHighlightSave({+ content: 'remote',+ documentId: 'doc-1',+ onSaveStart: () => vi.fn(),+ updatedAt: new Date('2024-01-03T00:00:00.000Z'),+ }),+ );++ expect(result.current.editingValue).toBe('remote');+ expect(useDocumentStore.getState().documents['doc-1'].charLimitError).toBeUndefined();+ });++ it('forgets a refused draft edited back to the saved body', async () => {+ seedStoreDocument();+ mockUpdateDocument.mockRejectedValueOnce(limitError());+ const first = renderHook(() =>+ useHighlightSave({+ content: 'before',+ documentId: 'doc-1',+ onSaveStart: () => vi.fn(),+ updatedAt,+ }),+ );+ act(() => first.result.current.handleChange('after'));+ await act(() => first.result.current.handleSave());+ act(() => first.result.current.handleChange('before'));+ expect(useDocumentStore.getState().documents['doc-1'].charLimitError).toBeUndefined();+ first.unmount();+ await act(async () => {});++ const { result } = renderHook(() =>+ useHighlightSave({+ content: 'before',+ documentId: 'doc-1',+ onSaveStart: () => vi.fn(),+ updatedAt,+ }),+ );+ expect(result.current.editingValue).toBe('before');+ });++ it('records the refusal, keeps the buffer and toasts on a manual save', async () => {+ seedStoreDocument();+ mockUpdateDocument.mockRejectedValueOnce(limitError());+ const { result } = renderHook(() =>+ useHighlightSave({ content: 'before', documentId: 'doc-1', onSaveStart: () => vi.fn() }),+ );++ act(() => result.current.handleChange('after'));+ await act(() => result.current.handleSave());++ expect(result.current.editingValue).toBe('after');+ expect(useDocumentStore.getState().documents['doc-1'].charLimitError).toEqual({+ actual: 120,+ limit: 100,+ plan: 'free',+ });+ expect(toast.error).toHaveBeenCalledTimes(1);+ });++ it('stays quiet when an autosave is refused', async () => {+ vi.useFakeTimers();+ seedStoreDocument();+ mockUpdateDocument.mockRejectedValueOnce(limitError());+ const { result } = renderHook(() =>+ useHighlightSave({ content: 'before', documentId: 'doc-1', onSaveStart: () => vi.fn() }),+ );++ act(() => result.current.handleChange('after'));+ await act(async () => {+ await vi.runAllTimersAsync();+ });+ vi.useRealTimers();++ expect(mockUpdateDocument).toHaveBeenCalledWith(+ expect.objectContaining({ saveSource: 'autosave' }),+ );+ expect(useDocumentStore.getState().documents['doc-1'].charLimitError).toBeDefined();+ expect(toast.error).not.toHaveBeenCalled();+ });++ it('clears the refusal once a later save succeeds', async () => {+ seedStoreDocument();+ mockUpdateDocument+ .mockRejectedValueOnce(limitError())+ .mockResolvedValueOnce({ updatedAt: '2024-01-02T00:00:00.000Z' });+ const { result } = renderHook(() =>+ useHighlightSave({ content: 'before', documentId: 'doc-1', onSaveStart: () => vi.fn() }),+ );++ act(() => result.current.handleChange('after'));+ await act(() => result.current.handleSave());+ act(() => result.current.handleChange('short'));+ await act(() => result.current.handleSave());++ expect(useDocumentStore.getState().documents['doc-1'].charLimitError).toBeUndefined();+ });+ });});diff --git a/src/features/Portal/Document/useHighlightSave.ts b/src/features/Portal/Document/useHighlightSave.tsindex 1df1267fa8c..9178ad83adf 100644--- a/src/features/Portal/Document/useHighlightSave.ts+++ b/src/features/Portal/Document/useHighlightSave.ts@@ -8,10 +8,73 @@ import { useTranslation } from 'react-i18next';import { documentService } from '@/services/document';import { invalidateDocumentMutation } from '@/services/document/invalidation';+import { useDocumentStore } from '@/store/document';+import {+ type DocumentCharLimitRefusal,+ getCharLimitRefusal,+ notifyCharLimitRefused,+} from '@/store/document/slices/editor/charLimit';const isConflictError = (error: unknown) =>(error as { data?: { code?: string } })?.data?.code === 'CONFLICT';+/**+ * Records (or clears) a save refused by the plan's per-document character limit+ * on the document's store entry, which the portal's limit banner reads.+ */+const setCharLimitError = (id: string, charLimitError: DocumentCharLimitRefusal | undefined) => {+ const { documents, internal_dispatchDocument } = useDocumentStore.getState();+ if (!documents[id] || documents[id].charLimitError === charLimitError) return;+ internal_dispatchDocument({ id, type: 'updateDocument', value: { charLimitError } });+};++/**+ * Drafts the server refused for exceeding the plan's character limit, by+ * document. The editor unmounts when the user opens another document or closes+ * the portal, and would reopen on the persisted body, so the refused text lives+ * here until it is saved, replaced by a newer remote body, or the page unloads.+ * The unload is guarded by {@link guardRefusedDraftsOnExit}, not by the editor's own+ * `beforeunload` listener, which goes away when the editor unmounts.+ */+const refusedDrafts = new Map<+ string,+ { baseUpdatedAt?: number; content: string; refusal: DocumentCharLimitRefusal }+>();++let exitGuardInstalled = false;++/**+ * Warns before the page unloads while any refused draft is still kept. It lives at+ * module level because the drafts outlive the editor: once the portal closes, the+ * editor's listener is gone and a reload would drop the refused text silently.+ */+const guardRefusedDraftsOnExit = () => {+ if (exitGuardInstalled || typeof window === 'undefined') return;+ exitGuardInstalled = true;+ window.addEventListener('beforeunload', (event) => {+ if (refusedDrafts.size === 0) return;+ event.preventDefault();+ event.returnValue = '';+ });+};++/** Test-only: forgets every kept refused draft. */+export const resetRefusedDraftsForTests = () => refusedDrafts.clear();++/**+ * The refused draft to reopen with, if it was written against the version the+ * editor now shows. A draft over an older version is dropped: the remote body+ * replaced it, the same as when the editor is mounted (see the `updatedAt` effect),+ * and `null` is returned so its banner is cleared too.+ */+const takeRefusedDraft = (documentId: string, updatedAt?: Date) => {+ const draft = refusedDrafts.get(documentId);+ if (!draft) return;+ if (draft.baseUpdatedAt === updatedAt?.getTime()) return draft;+ refusedDrafts.delete(documentId);+ return null;+};+export interface UseHighlightSaveParams {content: string;documentId: string;@@ -37,7 +100,8 @@ export const useHighlightSave = ({updatedAt,}: UseHighlightSaveParams): UseHighlightSaveResult => {const { t } = useTranslation('portal');- const [buffer, setBuffer] = useState<string | undefined>(undefined);+ const [restored] = useState(() => takeRefusedDraft(documentId, updatedAt));+ const [buffer, setBuffer] = useState<string | undefined>(restored?.content ?? undefined);const editingValue = buffer ?? content;const bufferRef = useRef(buffer);@@ -52,6 +116,15 @@ export const useHighlightSave = ({onSaveStartRef.current = onSaveStart;tRef.current = t;+ // Reopening a refused draft shows its banner again (closing the portal drops+ // the document's store entry), or clears it when the draft was dropped.+ // Runs once: `restored` never changes, and the caller keys the editor by document.+ // `undefined` means there was no draft, so the banner is left alone.+ useEffect(() => {+ if (restored === undefined) return;+ setCharLimitError(documentId, restored?.refusal);+ }, [documentId, restored]);+const saveBuffer = useCallback(async (source: 'manual' | 'autosave') => {const toWrite = bufferRef.current;if (toWrite === undefined) return;@@ -70,6 +143,8 @@ export const useHighlightSave = ({expectedUpdatedAtRef.current = savedAt;}baseContentRef.current = toWrite;+ refusedDrafts.delete(documentIdRef.current);+ setCharLimitError(documentIdRef.current, undefined);commitSaved(toWrite, result?.updatedAt);if (bufferRef.current === toWrite) {bufferRef.current = undefined;@@ -81,6 +156,8 @@ export const useHighlightSave = ({if (expectedUpdatedAtRef.current?.getTime() !== expectedUpdatedAt?.getTime()) return;bufferRef.current = undefined;setBuffer(undefined);+ refusedDrafts.delete(documentIdRef.current);+ setCharLimitError(documentIdRef.current, undefined);// Refreshes the document's replica entry, which the portal body reads.await Promise.allSettled([invalidateDocumentMutation({ documentId: documentIdRef.current }),@@ -88,6 +165,20 @@ export const useHighlightSave = ({toast.error(tRef.current('document.saveConflict'));return;}+ // Keep the buffer: the banner explains why it is unsaved, and the next+ // edit schedules the next attempt.+ const charLimitError = getCharLimitRefusal(error, toWrite.length);+ if (charLimitError) {+ refusedDrafts.set(documentIdRef.current, {+ baseUpdatedAt: expectedUpdatedAt?.getTime(),+ content: toWrite,+ refusal: charLimitError,+ });+ guardRefusedDraftsOnExit();+ setCharLimitError(documentIdRef.current, charLimitError);+ if (source === 'manual') notifyCharLimitRefused(charLimitError);+ return;+ }console.error('[HighlightEditor] save failed:', error);}}, []);@@ -118,6 +209,9 @@ export const useHighlightSave = ({debouncedAutoSave.cancel();bufferRef.current = undefined;setBuffer(undefined);+ // The refused buffer is gone, so its refusal no longer applies.+ refusedDrafts.delete(documentIdRef.current);+ setCharLimitError(documentIdRef.current, undefined);}baseContentRef.current = content;expectedUpdatedAtRef.current = updatedAt;@@ -128,8 +222,14 @@ export const useHighlightSave = ({const isDirty = next !== baseContentRef.current;bufferRef.current = isDirty ? next : undefined;setBuffer(bufferRef.current);- if (isDirty) debouncedAutoSave();- else debouncedAutoSave.cancel();+ if (isDirty) {+ debouncedAutoSave();+ return;+ }+ debouncedAutoSave.cancel();+ // Back to the saved body: nothing refused is left to keep or explain.+ refusedDrafts.delete(documentIdRef.current);+ setCharLimitError(documentIdRef.current, undefined);},[debouncedAutoSave],);diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.refusedFirstSend.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.refusedFirstSend.test.tsnew file mode 100644index 00000000000..f97783f9812--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.refusedFirstSend.test.ts@@ -0,0 +1,88 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getDraft } from '@/features/ChatInput/draftStorage';+import { agentService } from '@/services/agent';+import { agentRunSelectors } from '@/store/chat/selectors';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { getSessionStoreState } from '@/store/session';+import { useUserStore } from '@/store/user';++import { useChatStore } from '../../../../store';+import { createMockAgentConfig, TEST_IDS } from './fixtures';+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';++vi.mock('../transports/hetero/heterogeneousAgentExecutor', () => ({+ executeHeterogeneousAgent: vi.fn(),+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ session: { updateSession: { mutate: vi.fn().mockResolvedValue(undefined) } },+ },+}));++const typedDraft = { root: { children: [], type: 'root' } };++beforeEach(() => {+ resetTestEnvironment();+ setupMockSelectors();+ spyOnMessageService();+ localStorage.clear();+ vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);+ useUserStore.setState({ workspaceUserPreference: {} });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('sendMessage refused by the server on a new topic', () => {+ // ROOT CAUSE:+ //+ // A first send mints a topic, and its operation, error notice and restored+ // draft are all keyed by that topic. When the server refuses to start the run+ // (for example, too many runs already in flight), the minted topic rolls back+ // and the composer returns to the blank conversation, whose key holds neither.+ //+ // Before the fix, the user saw no notice and lost the typed message.+ it('keeps the notice and the typed message in the blank conversation', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const editor = {+ clearContent: vi.fn(),+ getJSONState: vi.fn(() => typedDraft),+ getMarkdownContent: vi.fn(() => 'hello'),+ setDocument: vi.fn(),+ setJSONState: vi.fn(),+ };++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: null,+ executeClientAgent: vi.fn(),+ executeGatewayAgent: vi.fn().mockRejectedValue(new Error('AgentConcurrencyLimitExceeded')),+ isGatewayModeEnabled: () => true,+ mainInputEditor: editor as any,+ refreshMessages: vi.fn(),+ refreshTopic: vi.fn(),+ });+ });++ await act(async () => {+ await result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: 'hello',+ });+ });++ const state = useChatStore.getState();+ expect(state.activeTopicId).toBeNull();+ expect(agentRunSelectors.isCurrentSendMessageError(state)).toBe(+ 'AgentConcurrencyLimitExceeded',+ );+ expect(getDraft(messageMapKey({ agentId, threadId: null, topicId: null }))).toEqual(typedDraft);+ });+});diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.tsindex 87ff7d594e1..71314617889 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts@@ -138,6 +138,7 @@ import { mergePartialPersistedMessages, resolveSendResponseMessages } from '../pimport { resolveExistingTopicForRun } from '../resolveExistingTopic';import { resolveProjectDirectoryRun } from '../resolveProjectDirectoryRun';import { type ContextCompressionOptions, executeContextCompression } from './compression';+import { showSendErrorInContext } from './sendErrorNotice';/*** Extended params for sendMessage with context@@ -1356,18 +1357,15 @@ export class ConversationLifecycleActionImpl {messageMapKey({ ...operationContext, topicId: null }),);if (this.#get().activeTopicId === optimisticTopic.id) {- // Cancelling restores the editor before the optimistic topic rolls back.- // Read the live editor: the user may have edited or cleared the restored draft- // while the cancelled request was unwinding. Preserve it across the topic switch.- if (- !hasNotifiedMessageAccepted &&- this.#get().operations[operationId]?.status === 'cancelled' &&- jsonState- ) {- saveDraft(- messageMapKey({ ...operationContext, topicId: null }),- targetInputEditor?.getJSONState() ?? jsonState,- );+ const op = this.#get().operations[operationId];+ // A cancel or a refused send restores the editor before the topic rolls back. Read the+ // live editor (the user may have edited it meanwhile) and carry it, plus the refusal+ // notice, to the blank conversation: both are keyed by the topic being discarded.+ const sendError = op?.status === 'failed' ? op.metadata.inputSendErrorMsg : undefined;+ if (!hasNotifiedMessageAccepted && (op?.status === 'cancelled' || sendError) && jsonState) {+ const blankContext = { ...operationContext, topicId: null };+ saveDraft(messageMapKey(blankContext), targetInputEditor?.getJSONState() ?? jsonState);+ if (sendError) showSendErrorInContext(this.#get(), blankContext, sendError);}void this.#get().switchTopic(null, { skipRefreshMessage: true });// Adopting the minted topic consumed the staging; the topic never camediff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/sendErrorNotice.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/sendErrorNotice.tsnew file mode 100644index 00000000000..6a9d64d84e3--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/sendErrorNotice.ts@@ -0,0 +1,19 @@+import type { OperationContext } from '@/store/chat/slices/operation/types';+import type { ChatStore } from '@/store/chat/store';++/**+ * Shows a refused send's notice above the composer of `context`. The composer+ * reads the notice from the latest failed `sendMessage` operation of its own+ * context, so a refusal whose operation belongs to a discarded topic (a first+ * send that minted a topic and rolled it back) needs a record in the+ * conversation the user lands on.+ */+export const showSendErrorInContext = (+ store: ChatStore,+ context: OperationContext,+ message: string,+): void => {+ const { operationId } = store.startOperation({ context, type: 'sendMessage' });+ store.failOperation(operationId, { message, type: 'GatewayError' });+ store.updateOperationMetadata(operationId, { inputSendErrorMsg: message });+};diff --git a/src/store/document/slices/editor/action.charLimit.test.ts b/src/store/document/slices/editor/action.charLimit.test.tsnew file mode 100644index 00000000000..259c9409754--- /dev/null+++ b/src/store/document/slices/editor/action.charLimit.test.ts@@ -0,0 +1,175 @@+import { toast } from '@lobehub/ui';+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { documentService } from '@/services/document';++import { useDocumentStore } from '../../store';++// Mock services+vi.mock('@/services/document', () => ({+ documentService: {+ acquireDocumentLock: vi.fn().mockResolvedValue({ holderId: null, lockedByOther: false }),+ releaseDocumentLock: vi.fn().mockResolvedValue(undefined),+ getDocumentById: vi.fn().mockResolvedValue({+ content: '# Test',+ id: 'doc-1',+ updatedAt: new Date('2026-01-01T00:00:00.000Z'),+ }),+ updateDocument: vi.fn().mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-01T00:00:00.000Z',+ }),+ },+}));++vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ toast: { error: vi.fn(), success: vi.fn() },+}));++vi.mock('@/services/notebook', () => ({+ notebookService: {+ updateDocument: vi.fn().mockResolvedValue({}),+ },+}));++// Create mock editor+const createValidMockEditor = () => ({+ getDocument: vi.fn((type: string) => {+ if (type === 'markdown') return '# Test';+ if (type === 'json') {+ return { root: { children: [{ children: [], type: 'paragraph' }], type: 'root' } };+ }+ return null;+ }),+ setDocument: vi.fn(),+});++describe('DocumentStore - Editor Actions (plan character limit)', () => {+ const limitError = () =>+ Object.assign(new Error('Over the limit'), {+ data: {+ code: 'BAD_REQUEST',+ errorData: { actual: 120, code: 'DocumentCharLimitExceeded', limit: 100, plan: 'free' },+ },+ });++ const initDirtyDoc = (result: { current: ReturnType<typeof useDocumentStore.getState> }) => {+ act(() => {+ result.current.initDocumentWithEditor({+ content: '# Test',+ documentId: 'doc-1',+ editor: createValidMockEditor() as any,+ sourceType: 'page',+ });+ result.current.markDirty('doc-1');+ });+ };++ beforeEach(() => {+ vi.mocked(toast.error).mockClear();+ vi.mocked(documentService.updateDocument).mockReset().mockResolvedValue({+ historyAppended: false,+ id: 'doc-1',+ updatedAt: '2026-01-01T00:00:00.000Z',+ });+ const { result } = renderHook(() => useDocumentStore());+ act(() => {+ Object.keys(result.current.documents).forEach((id) => result.current.closeDocument(id));+ });+ });++ it('fails the save, keeps the page dirty, stores the refusal and does not retry', async () => {+ const { result } = renderHook(() => useDocumentStore());+ initDirtyDoc(result);+ const debounced = vi.fn();+ useDocumentStore.setState({ triggerDebouncedSave: debounced });+ vi.mocked(documentService.updateDocument).mockRejectedValueOnce(limitError());++ await act(async () => {+ await result.current.performSave('doc-1');+ });++ const doc = result.current.documents['doc-1'];+ expect(documentService.updateDocument).toHaveBeenCalledTimes(1);+ expect(debounced).not.toHaveBeenCalled();+ expect(doc.saveStatus).toBe('failed');+ expect(doc.isDirty).toBe(true);+ expect(doc.charLimitError).toEqual({ actual: 120, limit: 100, plan: 'free' });+ });++ it('clears the refusal once a later save succeeds', async () => {+ const { result } = renderHook(() => useDocumentStore());+ initDirtyDoc(result);+ vi.mocked(documentService.updateDocument).mockRejectedValueOnce(limitError());+ await act(async () => {+ await result.current.performSave('doc-1');+ });+ expect(result.current.documents['doc-1'].charLimitError).toBeDefined();++ vi.mocked(documentService.updateDocument).mockResolvedValueOnce({+ id: 'doc-1',+ updatedAt: '2030-01-01T00:00:00.000Z',+ } as any);+ await act(async () => {+ await result.current.performSave('doc-1');+ });++ const doc = result.current.documents['doc-1'];+ expect(doc.saveStatus).toBe('saved');+ expect(doc.charLimitError).toBeUndefined();+ expect(doc.isDirty).toBe(false);+ });++ it('keeps the refusal when only the title is saved', async () => {+ const { result } = renderHook(() => useDocumentStore());+ initDirtyDoc(result);+ vi.mocked(documentService.updateDocument).mockRejectedValueOnce(limitError());+ await act(async () => {+ await result.current.performSave('doc-1');+ });++ vi.mocked(documentService.updateDocument).mockResolvedValueOnce({+ id: 'doc-1',+ updatedAt: '2030-01-01T00:00:00.000Z',+ } as any);+ await act(async () => {+ await result.current.performSave('doc-1', { title: 'Renamed' }, { metadataOnly: true });+ });++ const doc = result.current.documents['doc-1'];+ expect(doc.saveStatus).toBe('failed');+ expect(doc.charLimitError).toEqual({ actual: 120, limit: 100, plan: 'free' });+ });++ it('stays quiet on a refused autosave', async () => {+ const { result } = renderHook(() => useDocumentStore());+ initDirtyDoc(result);+ vi.mocked(documentService.updateDocument).mockRejectedValueOnce(limitError());++ await act(async () => {+ await result.current.performSave('doc-1', undefined, { saveSource: 'autosave' });+ });++ expect(toast.error).not.toHaveBeenCalled();+ });++ it('tells the user why a manual save did nothing', async () => {+ const { result } = renderHook(() => useDocumentStore());+ initDirtyDoc(result);+ vi.mocked(documentService.updateDocument).mockRejectedValueOnce(limitError());++ await act(async () => {+ await result.current.saveVersion('doc-1');+ });++ expect(toast.error).toHaveBeenCalledTimes(1);+ expect(result.current.documents['doc-1'].charLimitError).toEqual({+ actual: 120,+ limit: 100,+ plan: 'free',+ });+ });+});diff --git a/src/store/document/slices/editor/action.ts b/src/store/document/slices/editor/action.tsindex 03013072945..5ccbd006e19 100644--- a/src/store/document/slices/editor/action.ts+++ b/src/store/document/slices/editor/action.ts@@ -16,6 +16,7 @@ import { setNamespace } from '@/utils/storeDebug';import { PAGE_SYNC_WAIT_MS, waitForPageSynced } from '../../collabRegistry';import type { DocumentStore } from '../../store';import { documentDetailResource } from '../document/projection';+import { getCharLimitRefusal, notifyCharLimitRefused } from './charLimit';import type { DocumentFormatFields } from './contentFormat';import { hasDocumentFormatFields, resolveDocumentContentFormat } from './contentFormat';import type { EditorContentState } from './initialState';@@ -385,6 +386,7 @@ export class EditorActionImpl {lastUpdatedTime: updatedAt,// The editor reloads the adopted body and records it again.loadedBody: undefined,+ charLimitError: undefined,saveBlockedByLock: false,saveStatus: 'saved',},@@ -634,11 +636,14 @@ export class EditorActionImpl {lastSavedEditorData: structuredClone(currentEditorData),// The saved body is now the editor's own serialization.loadedBody: undefined,+ // Only a saved body clears a body refused for its length.+ charLimitError: undefined,}: {}),...(savedAt ? { lastUpdatedTime: savedAt } : {}),saveBlockedByLock: false,- saveStatus: 'saved',+ // A title save does not save a body still refused for its length.+ saveStatus: metadataOnly && current?.charLimitError ? 'failed' : 'saved',},});@@ -677,6 +682,22 @@ export class EditorActionImpl {this.#get().triggerDebouncedSave(id);}} catch (error) {+ // The plan's per-document character limit refused this body. Keep it dirty+ // and surface a persistent banner instead of a toast on every autosave; no+ // debounced retry, since the same body would be refused again until the+ // user shortens it (the next edit schedules the next attempt).+ const charLimitError = getCharLimitRefusal(error, (doc.content ?? '').length);+ if (charLimitError) {+ internal_dispatchDocument({+ id,+ type: 'updateDocument',+ value: { charLimitError, saveStatus: 'failed' },+ });+ if (options?.saveSource === 'manual') notifyCharLimitRefused(charLimitError);+ if (hasMetadataChanges) throw error;+ return;+ }+const errorCode = (error as { data?: { code?: string } })?.data?.code;const conflicted = errorCode === 'CONFLICT';// A view-level workspace member has no edit right on this documentdiff --git a/src/store/document/slices/editor/charLimit.ts b/src/store/document/slices/editor/charLimit.tsnew file mode 100644index 00000000000..8d06ba75258--- /dev/null+++ b/src/store/document/slices/editor/charLimit.ts@@ -0,0 +1,42 @@+import { DOCUMENT_CHAR_LIMIT_EXCEEDED, type DocumentCharLimitErrorData } from '@lobechat/types';+import { toast } from '@lobehub/ui';+import i18next, { t } from 'i18next';++/** A save refused by the plan's per-document character limit. */+export interface DocumentCharLimitRefusal {+ actual: number;+ limit: number;+ plan?: string;+}++/**+ * Reads a per-document character limit refusal from a save error.+ *+ * @param fallbackActual - Length of the refused body, used when the server omits it.+ */+export const getCharLimitRefusal = (+ error: unknown,+ fallbackActual: number,+): DocumentCharLimitRefusal | undefined => {+ const data = (error as { data?: { errorData?: Partial<DocumentCharLimitErrorData> } })?.data+ ?.errorData;+ if (data?.code !== DOCUMENT_CHAR_LIMIT_EXCEEDED || typeof data.limit !== 'number') return;++ return { actual: data.actual ?? fallbackActual, limit: data.limit, plan: data.plan };+};++/**+ * Tells the user why a save they asked for (Cmd+S, a save button) did nothing.+ * Autosaves stay quiet and rely on the editor's banner, which may be scrolled+ * out of view when the user saves by hand.+ */+export const notifyCharLimitRefused = ({ actual, limit }: DocumentCharLimitRefusal) => {+ const format = new Intl.NumberFormat(i18next.language);+ toast.error(+ t('pageEditor.charLimit.blockedTitle', {+ actual: format.format(actual),+ limit: format.format(limit),+ ns: 'file',+ }),+ );+};diff --git a/src/store/document/slices/editor/initialState.ts b/src/store/document/slices/editor/initialState.tsindex 386955912e7..f58172d1042 100644--- a/src/store/document/slices/editor/initialState.ts+++ b/src/store/document/slices/editor/initialState.ts@@ -3,6 +3,10 @@import type { IEditor } from '@lobehub/editor';import type { EditorState as LobehubEditorState } from '@lobehub/editor/react';+import type { SaveStatus } from '@/types/saveState';++import type { DocumentCharLimitRefusal } from './charLimit';+/*** Document source type - determines which service to use for persistence*/@@ -29,6 +33,12 @@ export interface EditorContentState {* Defaults to true. Set to false if the consumer handles saving themselves.*/autoSave?: boolean;+ /**+ * Set when the last save was refused for exceeding the plan's per-document+ * character limit. The body stays dirty and unsaved; cleared by the next+ * successful save.+ */+ charLimitError?: DocumentCharLimitRefusal;/*** The body syncs through a live collaboration room, which persists it; local* saves only carry metadata.@@ -85,7 +95,7 @@ export interface EditorContentState {/*** Current save status*/- saveStatus: 'idle' | 'saving' | 'saved';+ saveStatus: SaveStatus;/*** YAML frontmatter for SKILL.md documents. It is kept outside the rich Markdown editor because* the editor parses the closing `---` as a Setext heading underline and renders metadata as a giant heading.diff --git a/src/store/document/slices/editor/selectors.ts b/src/store/document/slices/editor/selectors.tsindex ab2aa986e41..ab5a66191b7 100644--- a/src/store/document/slices/editor/selectors.ts+++ b/src/store/document/slices/editor/selectors.ts@@ -24,6 +24,8 @@ const saveStatus = (id: string) => (s: DocumentStore) => s.documents[id]?.saveStconst saveBlockedByLock = (id: string) => (s: DocumentStore) =>s.documents[id]?.saveBlockedByLock ?? false;+const charLimitError = (id: string) => (s: DocumentStore) => s.documents[id]?.charLimitError;+const content = (id: string) => (s: DocumentStore) => s.documents[id]?.content ?? '';const editorData = (id: string) => (s: DocumentStore) => s.documents[id]?.editorData;@@ -109,6 +111,7 @@ export const editorSelectors = {isDocumentLoading,isDirty,lastUpdatedTime,+ charLimitError,saveBlockedByLock,saveStatus,sourceType,