π€― 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: extract project directory environment database support (#19693)
Arvin Xu5428efc10327
diff --git a/alint.config.toml b/alint.config.tomlindex cb067c6b0b1..a8c4801e094 100644--- a/alint.config.toml+++ b/alint.config.toml@@ -31,6 +31,17 @@ lobehub = "./packages/alint/rules""lobehub/pmap-over-promise-all" = "warn""lobehub/no-dynamic-import-in-server" = "warn"+# Database models layer: cross-table write transactions belong in repositories.+[[config.group]]+files = [ "packages/database/src/models/**/*.ts" ]+ignores = [ "**/*.test.ts", "**/__tests__/**" ]++[config.group.plugins]+lobehub = "./packages/alint/rules"++[config.group.rules]+"lobehub/no-transactions-in-models" = "warn"+# Web client components.[[config.group]]files = [ "src/**/*.tsx" ]@@ -88,6 +99,13 @@ lobehub = "./packages/alint/rules"[config.group.rules]"lobehub/no-mode-flags" = "warn"+[[config.group]]+files = [ "packages/alint/fixtures/no-transactions-in-models/**" ]+[config.group.plugins]+lobehub = "./packages/alint/rules"+[config.group.rules]+"lobehub/no-transactions-in-models" = "warn"+[[config.group]]files = [ "packages/alint/fixtures/test-the-exit-not-the-entry/**" ][config.group.plugins]diff --git a/packages/alint/README.md b/packages/alint/README.mdindex 2af0decce7b..b6ccf49e2d7 100644--- a/packages/alint/README.md+++ b/packages/alint/README.md@@ -12,6 +12,7 @@ This is Phase 0: the rule set is a private workspace package (`@lobechat/alint`)| `no-dynamic-import-in-server` | same | backend code uses static top-level imports || `no-effect-fetching` | `src/**/*.tsx` | `data-fetching-architecture` skill || `no-mode-flags` | `src/**/*.tsx` | `compose-atoms` skill |+| `no-transactions-in-models` | `packages/database/src/models` | cross-table write transactions use repositories || `test-the-exit-not-the-entry` | Vitest files | tests assert outcomes, not only that a mock ran |Scopes are declared as `[[config.group]]` entries in the root `alint.config.toml`. Never scope a rule with `includeFiles` inside `rule.alint.toml`: it only filters reports, so every file still runs (double the jobs), and it marks the rule uncacheable.diff --git a/packages/alint/fixtures/no-transactions-in-models/bad-cross-table-transaction.ts b/packages/alint/fixtures/no-transactions-in-models/bad-cross-table-transaction.tsnew file mode 100644index 00000000000..9b8f9429c39--- /dev/null+++ b/packages/alint/fixtures/no-transactions-in-models/bad-cross-table-transaction.ts@@ -0,0 +1,23 @@+// Fixture: a Model whose bind() writes four tables inside one transaction.+import { and, eq } from 'drizzle-orm';++import { devices, directories, links, topics } from '../../schemas';+import type { LobeChatDatabase } from '../../type';++export class DirectoryModel {+ constructor(private readonly db: LobeChatDatabase) {}++ async bind(deviceId: string, path: string) {+ // alint-expect+ return this.db.transaction(async (tx) => {+ const [device] = await tx.select().from(devices).where(eq(devices.id, deviceId));+ await tx.insert(links).values({ deviceId: device.id });+ const [directory] = await tx.insert(directories).values({ path }).returning();+ await tx+ .update(topics)+ .set({ directoryId: directory.id })+ .where(and(eq(topics.deviceId, device.id)));+ return directory;+ });+ }+}diff --git a/packages/alint/fixtures/no-transactions-in-models/good-single-table-lock.ts b/packages/alint/fixtures/no-transactions-in-models/good-single-table-lock.tsnew file mode 100644index 00000000000..11959d7db91--- /dev/null+++ b/packages/alint/fixtures/no-transactions-in-models/good-single-table-lock.ts@@ -0,0 +1,17 @@+// Fixture: a same-table lock + update is a legitimate model-level guard.+import { eq } from 'drizzle-orm';++import { jobs } from '../../schemas';+import type { LobeChatDatabase } from '../../type';++export class JobModel {+ constructor(private readonly db: LobeChatDatabase) {}++ async claim(id: string) {+ return this.db.transaction(async (tx) => {+ const [row] = await tx.select().from(jobs).where(eq(jobs.id, id)).for('update');+ await tx.update(jobs).set({ claimed: true }).where(eq(jobs.id, id));+ return row;+ });+ }+}diff --git a/packages/alint/fixtures/no-transactions-in-models/good-wide-read.ts b/packages/alint/fixtures/no-transactions-in-models/good-wide-read.tsnew file mode 100644index 00000000000..8a825ccd1d6--- /dev/null+++ b/packages/alint/fixtures/no-transactions-in-models/good-wide-read.ts@@ -0,0 +1,18 @@+// Fixture: a join-heavy read stays in the model; only transactional writes move.+import { desc, eq } from 'drizzle-orm';++import { agents, topics } from '../../schemas';+import type { LobeChatDatabase } from '../../type';++export class TopicListModel {+ constructor(private readonly db: LobeChatDatabase) {}++ async listWithAgent(userId: string) {+ return this.db+ .select({ id: topics.id, agentTitle: agents.title, title: topics.title })+ .from(topics)+ .innerJoin(agents, eq(topics.agentId, agents.id))+ .where(eq(topics.userId, userId))+ .orderBy(desc(topics.updatedAt));+ }+}diff --git a/packages/alint/rules/no-transactions-in-models/rule.alint.toml b/packages/alint/rules/no-transactions-in-models/rule.alint.tomlnew file mode 100644index 00000000000..1bb8fec44d5--- /dev/null+++ b/packages/alint/rules/no-transactions-in-models/rule.alint.toml@@ -0,0 +1,17 @@+name = "no-transactions-in-models"+builtInAgent = "basic-structured"+instruction = """+You are reviewing one file from the LobeHub database package's models layer (packages/database/src/models).++Team rule: the models layer holds one Model class per aggregate (table). When a write path needs a transaction spanning MORE THAN ONE table β a cross-aggregate unit of work such as upserting an environment, its instance, a project link and a directory row inside one `db.transaction` β that flow belongs in a Repository under packages/database/src/repositories, not in a Model. Models stay limited to single-aggregate access; repositories own composite, transactional persistence and compose the models.++Report a Model method whose `this.db.transaction(...)` (or a `tx` / `trx` handle it receives) writes β insert, update, delete β to two or more different tables. Anchor the finding on the line where the transaction starts (the `.transaction(` call). In the message, name the method and the tables it writes. In the suggestion, name the Repository to extract the flow into, and which single-aggregate pieces can remain Model methods that the repository composes.++Do not report:+- read-only queries, including joins across many tables β reading widely is what models do;+- a transaction that writes only one table, such as a `.for('update')` lock followed by an update of that same table, or a batch update / reorder of one table;+- single-table upserts (`onConflictDoNothing`, `onConflictDoUpdate`) without an explicit transaction;+- files outside the models layer (repositories, services, routers) β transactions are expected there.++If uncertain whether a write hits a second table, use low confidence rather than forcing a finding.+"""diff --git a/packages/database/src/models/__tests__/environment.test.ts b/packages/database/src/models/__tests__/environment.test.tsnew file mode 100644index 00000000000..8b837260a11--- /dev/null+++ b/packages/database/src/models/__tests__/environment.test.ts@@ -0,0 +1,52 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { environments, users } from '../../schemas';+import { EnvironmentModel, normalizeProjectRepository } from '../environment';++const db = await getTestDB();+const userId = 'environment-user';+const otherUserId = 'other-environment-user';+const model = new EnvironmentModel(db, userId);+const other = new EnvironmentModel(db, otherUserId);++beforeEach(async () => {+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);+});+afterEach(async () => {+ await db.delete(environments);+ await db.delete(users);+});++describe('EnvironmentModel', () => {+ it('creates, lists and updates environments in the owner scope', async () => {+ const env = await model.save({+ name: 'Shared GitHub',+ repositoryUrl: '[email protected]:lobehub/lobehub.git',+ });+ expect(env.configuration).toEqual({+ sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobehub' }],+ });+ expect(await model.list()).toEqual([expect.objectContaining({ id: env.id })]);+ expect(await other.list()).toEqual([]);+ await expect(other.findEnabledById(env.id)).resolves.toBeUndefined();+ await model.save({+ id: env.id,+ name: 'Updated resource',+ repositoryUrl: 'https://github.com/lobehub/new-repo',+ });+ expect((await model.list())[0].name).toBe('Updated resource');+ await expect(other.save({ id: env.id, name: 'Denied' })).rejects.toThrow('access denied');+ });+});++it('rejects credentials, clone options and non-repository URLs', () => {+ for (const value of [+ 'https://[email protected]/a/b',+ 'https://github.com/a/b?token=x',+ 'https://example.com/a/b',+ 'https://github.com/a/b/tree/main',+ '--upload-pack=x',+ ])+ expect(() => normalizeProjectRepository(value)).toThrow();+});diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.tsindex b55a9ad0a73..9efe5cb2cb0 100644--- a/packages/database/src/models/__tests__/project.test.ts+++ b/packages/database/src/models/__tests__/project.test.ts@@ -1,11 +1,15 @@+import { randomUUID } from 'node:crypto';+import { and, eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';import {agents,+ environments,knowledgeBases,projectCompletionReviews,+ projectEnvironments,projects,projectWorks,tasks,@@ -15,9 +19,11 @@ import {} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AgentModel } from '../agent';+import { EnvironmentModel } from '../environment';import type { CreateProjectInput } from '../project';import { ProjectModel } from '../project';import { TaskModel } from '../task';+import { TopicModel } from '../topic';const serverDB: LobeChatDatabase = await getTestDB();const userId = 'project-model-user';@@ -41,6 +47,8 @@ describe('ProjectModel', () => {afterEach(async () => {vi.restoreAllMocks();+ await serverDB.delete(projectEnvironments);+ await serverDB.delete(environments);await serverDB.delete(users);});@@ -481,4 +489,66 @@ describe('ProjectModel', () => {});expect(await model.getEnabledKnowledgeBaseIdsForTask(standaloneTask.id)).toEqual([]);});++ it('attaches environments and lists them per project in the owner scope', async () => {+ const project = await createProject(model, { name: 'Env host' });+ const environmentModel = new EnvironmentModel(serverDB, userId);+ const env = await environmentModel.save({+ name: 'Shared GitHub',+ repositoryUrl: 'https://github.com/lobehub/lobehub',+ });+ expect(await model.listEnvironments(project.id)).toEqual([]);+ await model.attachEnvironment(project.id, env.id);+ await model.attachEnvironment(project.id, env.id);+ expect(await model.listEnvironments(project.id)).toEqual([+ expect.objectContaining({ id: env.id }),+ ]);+ await expect(otherModel.attachEnvironment(project.id, env.id)).rejects.toThrow('access denied');+ await expect(otherModel.listEnvironments(project.id)).rejects.toThrow('access denied');+ await expect(model.attachEnvironment(project.id, randomUUID())).rejects.toThrow(+ 'access denied',+ );+ });++ it('lists project conversations with or without directories, retaining each agent', async () => {+ const project = await createProject(model, { name: 'Topics host' });+ const topicModel = new TopicModel(serverDB, userId);+ const plain = await topicModel.create({+ agentId: project.coordinatorAgentId,+ projectId: project.id,+ title: 'Planning',+ });+ const work = await topicModel.create({+ agentId: project.coordinatorAgentId,+ favorite: true,+ metadata: { workingDirectory: '/work/repo' },+ projectId: project.id,+ title: 'Implementation',+ });+ const list = await model.listTopics(project.id);+ expect(list).toHaveLength(2);+ expect(list.find((t) => t.id === plain.id)).toMatchObject({+ agentId: project.coordinatorAgentId,+ projectWorkingDirectoryId: null,+ });+ expect(list.find((t) => t.id === work.id)).toMatchObject({+ agentId: project.coordinatorAgentId,+ createdAt: expect.any(Date),+ favorite: true,+ metadata: expect.objectContaining({ workingDirectory: '/work/repo' }),+ userId,+ });+ await expect(otherModel.listTopics(project.id)).rejects.toThrow('access denied');+ });++ it('keeps agentless conversations visible in project listings', async () => {+ const project = await createProject(model, { name: 'Agentless host' });+ const topic = await new TopicModel(serverDB, userId).create({+ projectId: project.id,+ title: 'Agentless',+ });+ expect(await model.listTopics(project.id)).toEqual([+ expect.objectContaining({ agentId: null, agentTitle: null, id: topic.id }),+ ]);+ });});diff --git a/packages/database/src/models/__tests__/projectWorkingDirectory.test.ts b/packages/database/src/models/__tests__/projectWorkingDirectory.test.tsnew file mode 100644index 00000000000..2d3997bacb4--- /dev/null+++ b/packages/database/src/models/__tests__/projectWorkingDirectory.test.ts@@ -0,0 +1,266 @@+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { ProjectDirectoryRepository } from '../../repositories/projectDirectory';+import {+ agents,+ devices,+ environmentInstances,+ environments,+ projectEnvironments,+ projects,+ projectWorkingDirectories,+ topics,+ users,+} from '../../schemas';+import {+ normalizeProjectDirectory,+ ProjectWorkingDirectoryModel,+} from '../projectWorkingDirectory';+import { TopicModel } from '../topic';++const db = await getTestDB();+const userId = 'directory-user';+const otherUserId = 'other-directory-user';+const model = new ProjectWorkingDirectoryModel(db, userId);+const other = new ProjectWorkingDirectoryModel(db, otherUserId);+const repo = new ProjectDirectoryRepository(db, userId);+const base = {+ deviceId: 'directory-device',+ name: 'Repo',+ path: '/work/repo',+ projectId: 'directory-project',+};++beforeEach(async () => {+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await db.insert(agents).values([+ { id: 'directory-agent', userId },+ { id: 'directory-coordinator', userId },+ ]);+ await db.insert(projects).values({+ coordinatorAgentId: 'directory-coordinator',+ id: base.projectId,+ identifier: 'DIR',+ name: 'Directory project',+ userId,+ });+ await db+ .insert(devices)+ .values({ deviceId: base.deviceId, identitySource: 'fallback', platform: 'linux', userId });+});+afterEach(async () => {+ await db.delete(topics);+ await db.delete(projectWorkingDirectories);+ await db.delete(projectEnvironments);+ await db.delete(environmentInstances);+ await db.delete(environments);+ await db.delete(users);+});++/** A conversation pinned to a directory the way the start-topic flow pins it. */+const createPinnedTopic = (directory: { id: string }) =>+ new TopicModel(db, userId).create({+ agentId: 'directory-agent',+ metadata: {+ boundDeviceId: base.deviceId,+ workingDirectory: base.path,+ workingDirectoryConfig: { path: base.path },+ },+ projectId: base.projectId,+ projectWorkingDirectoryId: directory.id,+ title: 'Work',+ });++describe('project directory queries', () => {+ it('keeps legacy directories visible but refuses to resolve them', async () => {+ const [device] = await db.select().from(devices);+ const [legacy] = await db+ .insert(projectWorkingDirectories)+ .values({+ projectId: base.projectId,+ deviceId: device.id,+ path: base.path,+ name: base.name,+ addedByUserId: userId,+ })+ .returning();+ expect((await model.list())[0]).toMatchObject({+ id: legacy.id,+ instanceId: null,+ path: base.path,+ });+ await expect(model.resolve(legacy.id)).rejects.toThrow('Link this directory');+ expect(await model.listTopics(legacy.id)).toEqual([]);+ });++ it('allows reading conversations in a read-only directory but blocks execution', async () => {+ const directory = await repo.bind(base);+ await createPinnedTopic(directory);+ await db+ .update(projectWorkingDirectories)+ .set({ permission: 'readOnly' })+ .where(eq(projectWorkingDirectories.id, directory.id));+ expect(await model.listTopics(directory.id)).toHaveLength(1);+ await expect(model.resolve(directory.id)).rejects.toThrow('read-only');+ });++ it('does not expose another userβs directories', async () => {+ const directory = await repo.bind(base);+ expect(await other.list()).toEqual([]);+ await expect(other.resolve(directory.id)).rejects.toThrow();+ await expect(other.listTopics(directory.id)).rejects.toThrow();+ });++ it('keeps agentless conversations visible in directory listings', async () => {+ const directory = await repo.bind(base);+ const topic = await new TopicModel(db, userId).create({+ projectId: base.projectId,+ projectWorkingDirectoryId: directory.id,+ title: 'Agentless',+ });+ expect(await model.listTopics(directory.id)).toEqual([+ expect.objectContaining({ agentId: null, agentTitle: null, id: topic.id }),+ ]);+ });++ it('keeps a colliding legacy directory visible when another project upgrades first', async () => {+ await db.insert(agents).values({ id: 'directory-coordinator-2', userId });+ await db.insert(projects).values({+ coordinatorAgentId: 'directory-coordinator-2',+ id: 'second-project',+ identifier: 'SEC',+ name: 'Second project',+ userId,+ });+ const [device] = await db.select().from(devices);+ await db.insert(projectWorkingDirectories).values([+ {+ addedByUserId: userId,+ deviceId: device.id,+ name: 'First',+ path: base.path,+ projectId: base.projectId,+ },+ {+ addedByUserId: userId,+ deviceId: device.id,+ name: 'Second',+ path: base.path,+ projectId: 'second-project',+ },+ ]);+ await repo.bind(base);+ const rows = await model.list();+ expect(rows).toHaveLength(2);+ const legacy = rows.find((row) => row.projectId === 'second-project')!;+ expect(legacy).toMatchObject({+ configuration: null,+ environmentId: null,+ instanceId: null,+ path: base.path,+ });+ await expect(model.resolve(legacy.id)).rejects.toThrow('Link this directory');+ });++ it('returns the project icon and leading agent metadata with directory topics', async () => {+ await db.update(projects).set({ avatar: 'π¦' }).where(eq(projects.id, base.projectId));+ await db+ .update(agents)+ .set({ title: 'Design Agent', avatar: 'π¨' })+ .where(eq(agents.id, 'directory-agent'));+ const directory = await repo.bind(base);+ const topic = await createPinnedTopic(directory);+ expect((await model.list())[0].projectAvatar).toBe('π¦');+ expect(await model.listTopics(directory.id)).toEqual([+ expect.objectContaining({+ id: topic.id,+ agentId: 'directory-agent',+ agentTitle: 'Design Agent',+ agentAvatar: 'π¨',+ }),+ ]);+ });+});++describe('resolveForTopic', () => {+ it('follows the pinned directory even after the agent default device changes', async () => {+ const directory = await repo.bind(base);+ const topic = await createPinnedTopic(directory);+ expect(topic).toMatchObject({+ projectId: base.projectId,+ projectWorkingDirectoryId: directory.id,+ metadata: { boundDeviceId: base.deviceId, workingDirectory: base.path },+ });+ await db+ .update(agents)+ .set({ agencyConfig: { boundDeviceId: 'some-other-device', executionTarget: 'device' } })+ .where(eq(agents.id, 'directory-agent'));+ expect(await model.resolveForTopic(topic.id)).toMatchObject({+ deviceId: base.deviceId,+ path: base.path,+ });+ });++ it('blocks disabled environments and a removed directory instead of falling back', async () => {+ const directory = await repo.bind(base);+ const topic = await createPinnedTopic(directory);+ const row = await model.resolve(directory.id);+ await db+ .update(environments)+ .set({ enabled: false })+ .where(eq(environments.id, row.environmentId));+ await expect(model.resolveForTopic(topic.id)).rejects.toThrow('disabled');+ await db+ .delete(projectWorkingDirectories)+ .where(eq(projectWorkingDirectories.id, directory.id));+ await expect(model.resolveForTopic(topic.id)).rejects.toThrow('no longer exists');+ });++ it('returns nothing for conversations without a project pin', async () => {+ const topic = await new TopicModel(db, userId).create({+ agentId: 'directory-agent',+ title: 'Plain',+ });+ expect(await model.resolveForTopic(topic.id)).toBeUndefined();+ });++ it('leaves plain device-bound conversations to the device-resolution path', async () => {+ const topic = await new TopicModel(db, userId).create({+ agentId: 'directory-agent',+ metadata: { boundDeviceId: base.deviceId, workingDirectory: base.path },+ title: 'Device chat',+ });+ expect(await model.resolveForTopic(topic.id)).toBeUndefined();+ });++ it('resolves legacy topics whose metadata path is not canonical', async () => {+ const directory = await repo.bind(base);+ const topic = await new TopicModel(db, userId).create({+ agentId: 'directory-agent',+ metadata: { workingDirectory: '/work/./repo' },+ projectId: base.projectId,+ projectWorkingDirectoryId: directory.id,+ title: 'Legacy',+ });+ expect(await model.resolveForTopic(topic.id)).toMatchObject({ id: directory.id });+ });+});++describe('topic projections', () => {+ it('includes project bindings in the slim sidebar topic projection', async () => {+ const directory = await repo.bind(base);+ const topic = await createPinnedTopic(directory);+ const page = await new TopicModel(db, userId).query({ agentId: 'directory-agent' });+ expect(page.items.find((item) => item.id === topic.id)).toMatchObject({+ projectId: base.projectId,+ projectWorkingDirectoryId: directory.id,+ });+ });+});++it('normalizes directory paths per platform', () => {+ expect(normalizeProjectDirectory('C:\\work\\repo\\', 'win32')).toBe('C:\\work\\repo');+ expect(() => normalizeProjectDirectory('relative/path', 'linux')).toThrow();+});diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsindex a324b56b0b9..6e06a332b3c 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -8,6 +8,7 @@ import {agents,chatGroups,messages,+ projects,sessions,topics,users,@@ -634,6 +635,36 @@ describe('TopicModel', () => {expect(item.runningOperation).toBeNull();});++ it('never leaks the creator project binding ids when the topic joins a project', async () => {+ await serverDB.insert(agents).values([+ { id: 'agent-share-project', userId },+ { id: 'agent-coordinator', userId },+ ]);+ await serverDB.insert(projects).values({+ coordinatorAgentId: 'agent-coordinator',+ id: 'project-creator-only',+ identifier: 'CRE',+ name: 'Creator project',+ userId,+ });+ await serverDB.insert(topics).values({+ agentId: 'agent-share-project',+ id: 't-visitor-project',+ projectId: 'project-creator-only',+ senderId: 'visitor-user-project',+ title: 'project',+ userId,+ });++ const [item] = await topicModel.queryBySender({+ agentId: 'agent-share-project',+ senderId: 'visitor-user-project',+ });++ expect(item).not.toHaveProperty('projectId');+ expect(item).not.toHaveProperty('projectWorkingDirectoryId');+ });});describe('queryTopics', () => {diff --git a/packages/database/src/models/environment.ts b/packages/database/src/models/environment.tsnew file mode 100644index 00000000000..bce92a62481--- /dev/null+++ b/packages/database/src/models/environment.ts@@ -0,0 +1,138 @@+import type { EnvironmentConfiguration } from '@lobechat/types';+import { and, eq } from 'drizzle-orm';++import { environmentInstances, environments } from '../schemas';+import type { LobeChatDatabase } from '../type';+import { buildWorkspaceWhere } from '../utils/workspace';++/** Canonical GitHub source only; credentials and arbitrary clone transports are never persisted. */+export const normalizeProjectRepository = (value: string): string => {+ const ssh = /^git@github\.com:([^/]+\/[^/]+?)(?:\.git)?$/.exec(value.trim());+ const url = new URL(ssh ? `https://github.com/${ssh[1]}` : value.trim());+ if (+ url.protocol !== 'https:' ||+ url.hostname !== 'github.com' ||+ url.port ||+ url.username ||+ url.password ||+ url.search ||+ url.hash+ )+ throw new Error('Use a GitHub repository URL without credentials');+ const path = url.pathname.replace(/\/$/, '').replace(/\.git$/, '');+ if (!/^\/[\w.-]+\/[\w.-]+$/.test(path)) throw new Error('Use a GitHub repository URL');+ return `https://github.com${path}`;+};++/**+ * Single-aggregate access to abstract environments and their materialized+ * instances. Cross-table flows (e.g. binding a project directory, which+ * upserts environment + instance + project link in one transaction) live in+ * `repositories/projectDirectory` and compose this model with a tx handle.+ */+export class EnvironmentModel {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ private scope() {+ return { userId: this.userId, workspaceId: this.workspaceId };+ }++ /** Enabled environments visible in the current workspace scope. */+ async list() {+ return this.db+ .select({+ id: environments.id,+ name: environments.name,+ configuration: environments.configuration,+ })+ .from(environments)+ .where(and(buildWorkspaceWhere(this.scope(), environments), eq(environments.enabled, true)));+ }++ /** Enabled, workspace-visible lookup used when linking projects or binding directories. */+ async findEnabledById(id: string) {+ const [row] = await this.db+ .select()+ .from(environments)+ .where(+ and(+ eq(environments.id, id),+ buildWorkspaceWhere(this.scope(), environments),+ eq(environments.enabled, true),+ ),+ );+ return row;+ }++ async save(input: { id?: string; name: string; repositoryUrl?: string }) {+ const source = input.repositoryUrl?.trim();+ const configuration: EnvironmentConfiguration = source+ ? { sources: [{ kind: 'git', url: normalizeProjectRepository(source) }] }+ : {};+ if (input.id) {+ const [existing] = await this.db+ .select()+ .from(environments)+ .where(+ and(+ eq(environments.id, input.id),+ buildWorkspaceWhere(this.scope(), environments),+ eq(environments.userId, this.userId),+ ),+ );+ if (!existing) throw new Error('Environment not found or access denied');+ const [row] = await this.db+ .update(environments)+ .set({+ name: input.name.trim(),+ configuration: { ...existing.configuration, sources: configuration.sources ?? [] },+ updatedAt: new Date(),+ })+ .where(eq(environments.id, existing.id))+ .returning();+ return row;+ }+ const [row] = await this.db+ .insert(environments)+ .values({+ name: input.name.trim(),+ configuration,+ userId: this.userId,+ workspaceId: this.workspaceId,+ })+ .returning();+ return row;+ }++ /** Device instances are unique per (device, workingDirectory) β see the schema constraint. */+ async findDeviceInstance(deviceId: string, workingDirectory: string) {+ const [row] = await this.db+ .select()+ .from(environmentInstances)+ .where(+ and(+ eq(environmentInstances.deviceId, deviceId),+ eq(environmentInstances.workingDirectory, workingDirectory),+ ),+ );+ return row;+ }++ async createDeviceInstance(input: {+ configurationSnapshot: EnvironmentConfiguration;+ deviceId: string;+ environmentId: string;+ name: string;+ workingDirectory: string;+ }) {+ const [row] = await this.db+ .insert(environmentInstances)+ .values({ ...input, kind: 'device' })+ .returning();+ return row;+ }+}diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.tsindex d74c477b063..ed55be8175b 100644--- a/packages/database/src/models/project.ts+++ b/packages/database/src/models/project.ts@@ -3,6 +3,7 @@ import type { ProjectStatus, ProjectVisibility } from '@lobechat/types';import { and, asc, desc, eq, inArray, isNull, max, or, sql } from 'drizzle-orm';import { agents } from '../schemas/agent';+import { environments } from '../schemas/environment';import { knowledgeBases } from '../schemas/file';import {projectAgents,@@ -10,12 +11,15 @@ import {projectKnowledgeBases,projects,} from '../schemas/project';+import { projectEnvironments } from '../schemas/projectEnvironment';import { projectWorks } from '../schemas/projectWork';import { tasks } from '../schemas/task';+import { topics } from '../schemas/topic';import { works } from '../schemas/work';import type { LobeChatDatabase } from '../type';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { AgentModel } from './agent';+import { EnvironmentModel } from './environment';export interface CreateProjectInput {avatar?: string;@@ -617,4 +621,85 @@ export class ProjectModel {.limit(1);return project ?? null;}++ /** Link an existing environment to a project; re-attaching is a no-op. */+ async attachEnvironment(projectId: string, environmentId: string) {+ if (!(await this.findManageableById(projectId)))+ throw new Error('Project not found or access denied');+ const environment = await new EnvironmentModel(+ this.db,+ this.userId,+ this.workspaceId,+ ).findEnabledById(environmentId);+ if (!environment) throw new Error('Environment not found or access denied');+ await this.db+ .insert(projectEnvironments)+ .values({+ projectId,+ environmentId,+ workspaceId: this.workspaceId,+ addedByUserId: this.userId,+ })+ .onConflictDoNothing();+ return { projectId, environmentId };+ }++ /** Enabled environments linked to this project. */+ async listEnvironments(projectId: string) {+ if (!(await this.findById(projectId))) throw new Error('Project not found or access denied');+ return this.db+ .select({+ id: environments.id,+ name: environments.name,+ configuration: environments.configuration,+ })+ .from(environments)+ .innerJoin(+ projectEnvironments,+ and(+ eq(projectEnvironments.environmentId, environments.id),+ eq(projectEnvironments.projectId, projectId),+ eq(projectEnvironments.enabled, true),+ ),+ )+ .where(+ and(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, environments),+ eq(environments.enabled, true),+ ),+ );+ }++ /** All conversations belonging to the project, with or without a working directory. */+ async listTopics(projectId: string) {+ if (!(await this.findById(projectId))) throw new Error('Project not found or access denied');+ const scope = { userId: this.userId, workspaceId: this.workspaceId };+ return this.db+ .select({+ id: topics.id,+ createdAt: topics.createdAt,+ favorite: topics.favorite,+ metadata: topics.metadata,+ trigger: topics.trigger,+ userId: topics.userId,+ title: topics.title,+ status: topics.status,+ agentId: topics.agentId,+ agentTitle: agents.title,+ agentName: agents.name,+ agentAvatar: agents.avatar,+ updatedAt: topics.updatedAt,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,+ })+ .from(topics)+ .leftJoin(agents, and(eq(agents.id, topics.agentId), buildWorkspaceWhere(scope, agents)))+ .where(+ and(+ eq(topics.projectId, projectId),+ buildWorkspaceWhere(scope, topics),+ isNull(topics.deletedAt),+ ),+ )+ .orderBy(desc(topics.updatedAt));+ }}diff --git a/packages/database/src/models/projectWorkingDirectory.ts b/packages/database/src/models/projectWorkingDirectory.tsnew file mode 100644index 00000000000..181f5b19267--- /dev/null+++ b/packages/database/src/models/projectWorkingDirectory.ts@@ -0,0 +1,235 @@+import nodePath from 'node:path';++import type { EnvironmentConfiguration } from '@lobechat/types';+import { getWorkingDirSourcePath } from '@lobechat/types';+import { and, asc, eq, isNull, sql } from 'drizzle-orm';++import {+ agents,+ devices,+ environmentInstances,+ environments,+ projectEnvironments,+ projects,+ projectWorkingDirectories,+ topics,+} from '../schemas';+import type { LobeChatDatabase } from '../type';+import { buildWorkspaceWhere } from '../utils/workspace';++export const normalizeProjectDirectory = (value: string, platform: string | null) => {+ const paths = platform === 'win32' ? nodePath.win32 : nodePath.posix;+ if (!value.trim() || value.includes('\0') || !paths.isAbsolute(value))+ throw new Error('An absolute directory path is required');+ const normalized = paths.normalize(value);+ return normalized.length > paths.parse(normalized).root.length+ ? normalized.replace(/[\\/]+$/, '')+ : normalized;+};++/**+ * Single-aggregate access to project working directories: directory queries,+ * the environment/instance state resolution behind them, and directory-scoped+ * topic reads. Cross-table write flows (bind, associateTopic) live in+ * `repositories/projectDirectory`; environment and project-link access live on+ * `EnvironmentModel` and `ProjectModel`.+ */+export class ProjectWorkingDirectoryModel {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ private scope() {+ return { userId: this.userId, workspaceId: this.workspaceId };+ }++ private async project(id: string, write = false) {+ const [row] = await this.db+ .select()+ .from(projects)+ .where(+ and(+ eq(projects.id, id),+ buildWorkspaceWhere(this.scope(), projects),+ isNull(projects.deletedAt),+ write ? eq(projects.userId, this.userId) : undefined,+ ),+ );+ if (!row) throw new Error('Project not found or access denied');+ return row;+ }++ async findByLocation(projectId: string, deviceId: string, path: string) {+ const [row] = await this.db+ .select()+ .from(projectWorkingDirectories)+ .where(+ and(+ eq(projectWorkingDirectories.projectId, projectId),+ eq(projectWorkingDirectories.deviceId, deviceId),+ eq(projectWorkingDirectories.path, path),+ ),+ );+ return row;+ }++ async create(input: {+ addedByUserId: string;+ deviceId: string;+ name: string;+ path: string;+ projectId: string;+ workspaceId?: string;+ }) {+ const [row] = await this.db.insert(projectWorkingDirectories).values(input).returning();+ return row;+ }++ async list(projectId?: string) {+ if (projectId) await this.project(projectId);+ return this.db+ .select({+ id: projectWorkingDirectories.id,+ name: projectWorkingDirectories.name,+ projectId: projects.id,+ projectName: projects.name,+ projectAvatar: projects.avatar,+ projectSlug: projects.slug,+ // The instance join keys on the global natural key (device, path), so a+ // row can meet an instance another project linked first. Project the+ // instance and its configuration snapshot only when the environment is+ // linked to THIS project β otherwise the row stays a legacy directory+ // with null environment fields, discoverable for upgrade.+ instanceId: sql<+ string | null+ >`case when ${environments.id} is not null then ${environmentInstances.id} else null end`,+ environmentId: environments.id,+ environmentName: environments.name,+ // The materialized instance's snapshot, not the live environment+ // definition β the snapshot is never implicitly refreshed, so it is+ // the configuration the instance actually represents.+ configuration: sql<EnvironmentConfiguration | null>`case when ${environments.id} is not null then ${environmentInstances.configurationSnapshot} else null end`,+ deviceId: devices.deviceId,+ deviceName: devices.friendlyName,+ platform: devices.platform,+ path: sql<string>`coalesce(${environmentInstances.workingDirectory}, ${projectWorkingDirectories.path})`,+ permission: projectWorkingDirectories.permission,+ })+ .from(projectWorkingDirectories)+ .innerJoin(projects, eq(projects.id, projectWorkingDirectories.projectId))+ .leftJoin(+ environmentInstances,+ and(+ eq(environmentInstances.deviceId, projectWorkingDirectories.deviceId),+ eq(environmentInstances.workingDirectory, projectWorkingDirectories.path),+ ),+ )+ .leftJoin(+ projectEnvironments,+ and(+ eq(projectEnvironments.environmentId, environmentInstances.environmentId),+ eq(projectEnvironments.projectId, projects.id),+ ),+ )+ .leftJoin(+ environments,+ and(+ eq(environments.id, projectEnvironments.environmentId),+ buildWorkspaceWhere(this.scope(), environments),+ ),+ )+ .innerJoin(devices, eq(devices.id, projectWorkingDirectories.deviceId))+ .where(+ and(+ buildWorkspaceWhere(this.scope(), projects),+ isNull(projects.deletedAt),+ buildWorkspaceWhere(this.scope(), devices),+ projectId ? eq(projects.id, projectId) : undefined,+ ),+ )+ .orderBy(asc(projectWorkingDirectories.sortOrder), asc(projectWorkingDirectories.createdAt));+ }++ async resolve(id: string, projectId?: string) {+ const row = (await this.list(projectId)).find((item) => item.id === id);+ if (!row) throw new Error('Project directory not found or access denied');+ if (!row.instanceId || !row.environmentId)+ throw new Error('Link this directory to an environment before starting work');+ const [state] = await this.db+ .select({+ instanceEnabled: environmentInstances.enabled,+ environmentEnabled: environments.enabled,+ linked: projectEnvironments.enabled,+ })+ .from(environmentInstances)+ .innerJoin(environments, eq(environments.id, environmentInstances.environmentId))+ .innerJoin(+ projectEnvironments,+ and(+ eq(projectEnvironments.environmentId, environments.id),+ eq(projectEnvironments.projectId, row.projectId),+ ),+ )+ .where(eq(environmentInstances.id, row.instanceId));+ if (!state?.instanceEnabled || !state.environmentEnabled || !state.linked)+ throw new Error('Project environment is disabled');+ if (row.permission !== 'readWrite') throw new Error('This directory is read-only');+ return { ...row, instanceId: row.instanceId, environmentId: row.environmentId };+ }++ async listTopics(directoryId: string) {+ if (!(await this.list()).some((row) => row.id === directoryId))+ throw new Error('Project directory not found or access denied');+ return this.db+ .select({+ id: topics.id,+ title: topics.title,+ agentId: topics.agentId,+ agentTitle: agents.title,+ agentName: agents.name,+ agentAvatar: agents.avatar,+ updatedAt: topics.updatedAt,+ })+ .from(topics)+ .leftJoin(+ agents,+ and(eq(agents.id, topics.agentId), buildWorkspaceWhere(this.scope(), agents)),+ )+ .where(+ and(+ eq(topics.projectWorkingDirectoryId, directoryId),+ buildWorkspaceWhere(this.scope(), topics),+ isNull(topics.deletedAt),+ ),+ )+ .orderBy(asc(topics.updatedAt));+ }++ async resolveForTopic(topicId: string) {+ const [topic] = await this.db+ .select()+ .from(topics)+ .where(and(eq(topics.id, topicId), buildWorkspaceWhere(this.scope(), topics)));+ if (!topic?.projectWorkingDirectoryId) {+ // The binding row is gone (directory deletion sets the FK null) but the+ // topic still carries its project pin. Plain device-bound topics have no+ // projectId and simply follow the normal device-resolution path.+ if (topic?.projectId && topic?.metadata?.boundDeviceId)+ throw new Error('Project directory binding no longer exists');+ return;+ }+ if (!topic.projectId) throw new Error('Project directory has no owning project');+ const directory = await this.resolve(topic.projectWorkingDirectoryId, topic.projectId);+ const source = getWorkingDirSourcePath(+ topic.metadata?.workingDirectoryConfig ?? topic.metadata?.workingDirectory,+ );+ // Compare with the same platform-aware normalization used when binding β+ // legacy metadata may carry non-canonical segments (`./`, `..`, duplicate+ // separators) that a plain trailing-separator trim would reject forever.+ if (source && normalizeProjectDirectory(source, directory.platform) !== directory.path)+ throw new Error('Conversation directory differs from its project binding');+ return directory;+ }+}diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 57a9e78aa73..e21d6a0a328 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -194,6 +194,10 @@ export interface CreateTopicParams {metadata?: ChatTopicMetadata;/** Pinned model snapshot, persisted to the top-level `topics.model` column. */model?: string | null;+ /** Owning business project, independent of the execution directory. */+ projectId?: string | null;+ /** Project directory this conversation is pinned to as its execution context. */+ projectWorkingDirectoryId?: string | null;provider?: string | null;/*** Agent-share visitor topics carry the CREATOR's `userId` (billing/data@@ -629,6 +633,8 @@ export class TopicModel {historySummary: topics.historySummary,id: topics.id,metadata: topics.metadata,+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,model: topics.model,provider: topics.provider,runStartedAt: runStartedAtColumn,@@ -708,6 +714,8 @@ export class TopicModel {historySummary: topics.historySummary,id: topics.id,metadata: topics.metadata,+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,model: topics.model,provider: topics.provider,runStartedAt: runStartedAtColumn,@@ -781,6 +789,8 @@ export class TopicModel {historySummary: topics.historySummary,id: topics.id,metadata: topics.metadata,+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,model: topics.model,provider: topics.provider,runStartedAt: runStartedAtColumn,@@ -1846,7 +1856,12 @@ export class TopicModel {) => {return this.db.transaction(async (tx) => {const [existing] = await tx- .select({ metadata: topics.metadata, status: topics.status })+ .select({+ metadata: topics.metadata,+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,+ status: topics.status,+ }).from(topics).where(and(eq(topics.id, id), this.ownership())).for('update');@@ -2833,7 +2848,12 @@ export class TopicModel {): Promise<boolean> {return db.transaction(async (tx) => {const [row] = await tx- .select({ metadata: topics.metadata, status: topics.status })+ .select({+ metadata: topics.metadata,+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,+ status: topics.status,+ }).from(topics).where(eq(topics.id, id)).for('update');@@ -2873,7 +2893,12 @@ export class TopicModel {): Promise<void> {await db.transaction(async (tx) => {const [row] = await tx- .select({ metadata: topics.metadata, status: topics.status })+ .select({+ metadata: topics.metadata,+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,+ status: topics.status,+ }).from(topics).where(eq(topics.id, id)).for('update');@@ -2911,7 +2936,12 @@ export class TopicModel {): Promise<void> {await db.transaction(async (tx) => {const [row] = await tx- .select({ metadata: topics.metadata, status: topics.status })+ .select({+ metadata: topics.metadata,+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,+ status: topics.status,+ }).from(topics).where(eq(topics.id, id)).for('update');diff --git a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts b/packages/database/src/repositories/projectDirectory/__tests__/index.test.tsnew file mode 100644index 00000000000..9be196aa303--- /dev/null+++ b/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts@@ -0,0 +1,295 @@+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { EnvironmentModel } from '../../../models/environment';+import { ProjectModel } from '../../../models/project';+import { ProjectWorkingDirectoryModel } from '../../../models/projectWorkingDirectory';+import {+ agents,+ devices,+ environmentInstances,+ environments,+ projectEnvironments,+ projects,+ projectWorkingDirectories,+ topics,+ users,+} from '../../../schemas';+import { ProjectDirectoryRepository } from '../index';++const db = await getTestDB();+const userId = 'directory-repo-user';+const otherUserId = 'other-directory-repo-user';+const repo = new ProjectDirectoryRepository(db, userId);+const otherRepo = new ProjectDirectoryRepository(db, otherUserId);+const directoryModel = new ProjectWorkingDirectoryModel(db, userId);+const base = {+ deviceId: 'repo-device',+ name: 'Repo',+ path: '/work/repo',+ projectId: 'repo-project',+};++beforeEach(async () => {+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await db.insert(agents).values([+ { id: 'repo-agent', userId },+ { id: 'repo-coordinator', userId },+ ]);+ await db.insert(projects).values({+ coordinatorAgentId: 'repo-coordinator',+ id: base.projectId,+ identifier: 'REP',+ name: 'Repository project',+ userId,+ });+ await db+ .insert(devices)+ .values({ deviceId: base.deviceId, identitySource: 'fallback', platform: 'linux', userId });+});+afterEach(async () => {+ await db.delete(topics);+ await db.delete(projectWorkingDirectories);+ await db.delete(projectEnvironments);+ await db.delete(environmentInstances);+ await db.delete(environments);+ await db.delete(users);+});++describe('ProjectDirectoryRepository.bind', () => {+ it('links an ordinary folder and reuses the instance and project binding', async () => {+ const first = await repo.bind(base);+ const second = await repo.bind({ ...base, path: '/work/repo/' });+ expect(second.id).toBe(first.id);+ expect(await db.select().from(environmentInstances)).toHaveLength(1);+ expect(await db.select().from(environments)).toHaveLength(1);+ expect((await directoryModel.list())[0]).toMatchObject({+ configuration: {},+ path: '/work/repo',+ projectId: base.projectId,+ });+ });++ it('upgrades a legacy directory binding in place', async () => {+ const [device] = await db.select().from(devices);+ const [legacy] = await db+ .insert(projectWorkingDirectories)+ .values({+ projectId: base.projectId,+ deviceId: device.id,+ path: base.path,+ name: base.name,+ addedByUserId: userId,+ })+ .returning();+ const upgraded = await repo.bind(base);+ expect(upgraded.id).toBe(legacy.id);+ expect((await directoryModel.resolve(legacy.id)).instanceId).toBeTruthy();+ });++ it('records GitHub configuration and keeps the instance snapshot stable', async () => {+ const directory = await repo.bind({+ ...base,+ repositoryUrl: '[email protected]:lobehub/lobehub.git',+ });+ const row = await directoryModel.resolve(directory.id);+ expect(row.configuration).toEqual({+ sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobehub' }],+ });+ await db+ .update(environments)+ .set({ configuration: {} })+ .where(eq(environments.id, row.environmentId));+ const [instance] = await db.select().from(environmentInstances);+ expect(instance.configurationSnapshot).toEqual(row.configuration);+ await expect(+ repo.bind({ ...base, repositoryUrl: 'https://github.com/other/repo' }),+ ).rejects.toThrow('Repository differs');+ });++ it('isolates devices even when their path matches', async () => {+ await db+ .insert(devices)+ .values({ deviceId: 'second-device', identitySource: 'fallback', userId });+ await repo.bind(base);+ await repo.bind({ ...base, deviceId: 'second-device' });+ expect(await directoryModel.list()).toHaveLength(2);+ });++ it('resolves the instance configuration snapshot, not later environment edits', async () => {+ const directory = await repo.bind({+ ...base,+ repositoryUrl: 'https://github.com/lobehub/lobehub',+ });+ const row = await directoryModel.resolve(directory.id);+ await db+ .update(environments)+ .set({ configuration: { sources: [{ kind: 'git', url: 'https://github.com/other/repo' }] } })+ .where(eq(environments.id, row.environmentId));+ expect((await directoryModel.resolve(directory.id)).configuration).toEqual({+ sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobehub' }],+ });+ });++ it('does not expose or change another userβs project or device', async () => {+ await repo.bind(base);+ await expect(otherRepo.bind(base)).rejects.toThrow('access denied');+ await db.insert(devices).values({+ deviceId: 'private-device',+ identitySource: 'fallback',+ userId: otherUserId,+ });+ await expect(repo.bind({ ...base, deviceId: 'private-device' })).rejects.toThrow();+ });++ it('reuses an attached environment and keeps its instance snapshot across updates', async () => {+ const projectModel = new ProjectModel(db, userId);+ const env = await new EnvironmentModel(db, userId).save({+ name: 'Shared GitHub',+ repositoryUrl: '[email protected]:lobehub/lobehub.git',+ });+ await projectModel.attachEnvironment(base.projectId, env.id);+ const binding = await repo.bind({ ...base, environmentId: env.id });+ const bound = await directoryModel.resolve(binding.id);+ const [before] = await db+ .select()+ .from(environmentInstances)+ .where(eq(environmentInstances.id, bound.instanceId!));+ await new EnvironmentModel(db, userId).save({+ id: env.id,+ name: 'Updated resource',+ repositoryUrl: 'https://github.com/lobehub/new-repo',+ });+ const [after] = await db+ .select()+ .from(environmentInstances)+ .where(eq(environmentInstances.id, bound.instanceId!));+ expect(after.configurationSnapshot).toEqual(before.configurationSnapshot);+ });++ it('rejects filing conversations for an agent fixed to another execution target', async () => {+ await db+ .update(agents)+ .set({+ agencyConfig: {+ boundDeviceId: 'other-device',+ executionTarget: 'device',+ executionTargetSelectionPolicy: 'fixed',+ },+ })+ .where(eq(agents.id, 'repo-agent'));+ await db.insert(topics).values({+ id: 'fixed-agent-topic',+ agentId: 'repo-agent',+ userId,+ metadata: { workingDirectory: base.path },+ });+ await expect(+ repo.bind({ ...base, agentId: 'repo-agent', topicIds: ['fixed-agent-topic'] }),+ ).rejects.toThrow('execution target');+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'fixed-agent-topic'));+ expect(topic.projectId).toBeNull();+ });++ it('files explicit conversations and rolls back mismatched selections', async () => {+ await db.insert(topics).values([+ {+ id: 'matching',+ agentId: 'repo-agent',+ userId,+ metadata: { workingDirectory: base.path },+ },+ {+ id: 'other-path',+ agentId: 'repo-agent',+ userId,+ metadata: { workingDirectory: '/other' },+ },+ ]);+ await expect(+ repo.bind({ ...base, agentId: 'repo-agent', topicIds: ['matching', 'other-path'] }),+ ).rejects.toThrow('different directory');+ expect(await directoryModel.list()).toEqual([]);+ const directory = await repo.bind({ ...base, agentId: 'repo-agent', topicIds: ['matching'] });+ expect(await directoryModel.listTopics(directory.id)).toHaveLength(1);+ });+});++describe('ProjectDirectoryRepository.associateTopic', () => {+ it('associates an existing conversation without changing its agent or metadata', async () => {+ await db.insert(topics).values({+ id: 'existing',+ agentId: 'repo-agent',+ userId,+ metadata: { workingDirectory: undefined },+ });+ await repo.associateTopic(base.projectId, 'existing');+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'existing'));+ expect(topic).toMatchObject({+ projectId: base.projectId,+ agentId: 'repo-agent',+ metadata: {},+ projectWorkingDirectoryId: null,+ });+ await expect(otherRepo.associateTopic(base.projectId, 'existing')).rejects.toThrow(+ 'access denied',+ );+ });++ it('refuses running topics and mismatched execution locations without partially changing ownership', async () => {+ const directory = await repo.bind(base);+ await db.insert(topics).values([+ { id: 'running', agentId: 'repo-agent', userId, status: 'running' },+ {+ id: 'different-path',+ agentId: 'repo-agent',+ userId,+ metadata: { workingDirectory: '/elsewhere' },+ },+ ]);+ await expect(repo.associateTopic(base.projectId, 'running')).rejects.toThrow('running');+ await expect(+ repo.associateTopic(base.projectId, 'different-path', directory.id),+ ).rejects.toThrow('existing device');+ expect((await db.select().from(topics)).every((t) => t.projectId === null)).toBe(true);+ });++ it('pins the topic to the directory device and path when associating with a directory', async () => {+ const directory = await repo.bind(base);+ await db.insert(topics).values({+ id: 'to-pin',+ agentId: 'repo-agent',+ userId,+ metadata: { workingDirectory: base.path },+ });+ await repo.associateTopic(base.projectId, 'to-pin', directory.id);+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'to-pin'));+ expect(topic).toMatchObject({+ projectId: base.projectId,+ projectWorkingDirectoryId: directory.id,+ metadata: {+ boundDeviceId: base.deviceId,+ workingDirectory: base.path,+ workingDirectoryConfig: { path: base.path },+ },+ });+ });++ it('accepts a non-canonical but equivalent topic path when associating', async () => {+ const directory = await repo.bind(base);+ await db.insert(topics).values({+ id: 'legacy-path',+ agentId: 'repo-agent',+ userId,+ metadata: { workingDirectory: '/work//repo/' },+ });+ await repo.associateTopic(base.projectId, 'legacy-path', directory.id);+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'legacy-path'));+ expect(topic.metadata).toMatchObject({+ boundDeviceId: base.deviceId,+ workingDirectory: base.path,+ workingDirectoryConfig: { path: base.path },+ });+ });+});diff --git a/packages/database/src/repositories/projectDirectory/index.ts b/packages/database/src/repositories/projectDirectory/index.tsnew file mode 100644index 00000000000..6ed90dc71ad--- /dev/null+++ b/packages/database/src/repositories/projectDirectory/index.ts@@ -0,0 +1,255 @@+import { getWorkingDirSourcePath } from '@lobechat/types';+import { and, eq, inArray, isNull } from 'drizzle-orm';++import { EnvironmentModel, normalizeProjectRepository } from '../../models/environment';+import { ProjectModel } from '../../models/project';+import {+ normalizeProjectDirectory,+ ProjectWorkingDirectoryModel,+} from '../../models/projectWorkingDirectory';+import { agents, devices, projectEnvironments, topics } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { buildWorkspaceWhere } from '../../utils/workspace';++export interface BindProjectDirectoryInput {+ agentId?: string;+ deviceId: string;+ environmentId?: string;+ name: string;+ path: string;+ projectId: string;+ repositoryUrl?: string;+ topicIds?: string[];+}++/**+ * Cross-aggregate write flows for project working directories. Binding a+ * directory upserts the environment, its device instance, the project link and+ * the directory row β and optionally files existing conversations β as one+ * transaction, so it lives here rather than on any single-aggregate model.+ * Read paths stay on {@link ProjectWorkingDirectoryModel}.+ */+export class ProjectDirectoryRepository {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ private scope() {+ return { userId: this.userId, workspaceId: this.workspaceId };+ }++ private async assertManageableProject(projectId: string) {+ const project = await new ProjectModel(+ this.db,+ this.userId,+ this.workspaceId,+ ).findManageableById(projectId);+ if (!project) throw new Error('Project not found or access denied');+ return project;+ }++ async bind(input: BindProjectDirectoryInput) {+ await this.assertManageableProject(input.projectId);+ return this.db.transaction(async (tx) => {+ const db = tx as LobeChatDatabase;+ const environmentModel = new EnvironmentModel(db, this.userId, this.workspaceId);+ const projectModel = new ProjectModel(db, this.userId, this.workspaceId);+ const directoryModel = new ProjectWorkingDirectoryModel(db, this.userId, this.workspaceId);+ // Serialize bindings of the same device, including bindings from different projects.+ const [device] = await db+ .select()+ .from(devices)+ .where(+ and(eq(devices.deviceId, input.deviceId), buildWorkspaceWhere(this.scope(), devices)),+ )+ .for('update');+ if (!device) throw new Error('Device not found or access denied');+ const path = normalizeProjectDirectory(input.path, device.platform);+ const repositoryUrl = input.repositoryUrl+ ? normalizeProjectRepository(input.repositoryUrl)+ : undefined;+ const existing = await environmentModel.findDeviceInstance(device.id, path);+ let instance = existing;+ let environment;+ const environmentId = existing?.environmentId ?? input.environmentId;+ if (environmentId) {+ environment = await environmentModel.findEnabledById(environmentId);+ if (!environment || (input.environmentId && input.environmentId !== environment.id))+ throw new Error('This directory belongs to another environment');+ if (+ repositoryUrl &&+ !environment.configuration.sources?.some(+ (source) => source.kind === 'git' && source.url === repositoryUrl,+ )+ )+ throw new Error('Repository differs from the existing environment');+ } else {+ environment = await environmentModel.save({+ name: input.name,+ repositoryUrl: input.repositoryUrl,+ });+ }+ if (!instance) {+ instance = await environmentModel.createDeviceInstance({+ configurationSnapshot: environment.configuration,+ deviceId: device.id,+ environmentId: environment.id,+ name: input.name.trim(),+ workingDirectory: path,+ });+ }+ if (!instance.enabled) throw new Error('Environment instance is disabled');+ await projectModel.attachEnvironment(input.projectId, environment.id);+ const [link] = await db+ .select()+ .from(projectEnvironments)+ .where(+ and(+ eq(projectEnvironments.projectId, input.projectId),+ eq(projectEnvironments.environmentId, environment.id),+ ),+ );+ if (!link.enabled) throw new Error('Environment is disabled in this project');+ const prior = await directoryModel.findByLocation(input.projectId, device.id, path);+ const directory =+ prior ??+ (await directoryModel.create({+ addedByUserId: this.userId,+ deviceId: device.id,+ name: input.name.trim(),+ path,+ projectId: input.projectId,+ workspaceId: this.workspaceId,+ }));+ if (input.topicIds?.length) {+ if (!input.agentId) throw new Error('Agent is required when filing conversations');+ const [filingAgent] = await db+ .select()+ .from(agents)+ .where(and(eq(agents.id, input.agentId), buildWorkspaceWhere(this.scope(), agents)));+ if (+ !filingAgent ||+ (filingAgent.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&+ filingAgent.agencyConfig.boundDeviceId !== device.deviceId)+ )+ throw new Error('Agent cannot use this execution target');+ const selected = await db+ .select()+ .from(topics)+ .where(+ and(+ inArray(topics.id, input.topicIds),+ eq(topics.agentId, input.agentId),+ eq(topics.userId, this.userId),+ buildWorkspaceWhere(this.scope(), topics),+ ),+ )+ .for('update');+ if (selected.length !== new Set(input.topicIds).size)+ throw new Error('Conversation not found or access denied');+ for (const topic of selected) {+ const metadata = topic.metadata ?? {};+ const source = getWorkingDirSourcePath(+ metadata.workingDirectoryConfig ?? metadata.workingDirectory,+ );+ const pinnedDevice = metadata.boundDeviceId ?? metadata.runningOperation?.deviceId;+ if (+ !source ||+ normalizeProjectDirectory(source, device.platform) !== path ||+ (pinnedDevice && pinnedDevice !== device.deviceId)+ )+ throw new Error('Conversation uses a different directory or device');+ if (topic.projectId && topic.projectId !== input.projectId)+ throw new Error('Conversation already belongs to another project');+ if (metadata.runningOperation || topic.status === 'running')+ throw new Error('Wait for the conversation to finish before binding it');+ await db+ .update(topics)+ .set({+ projectId: input.projectId,+ projectWorkingDirectoryId: directory.id,+ metadata: { ...metadata, boundDeviceId: device.deviceId },+ })+ .where(eq(topics.id, topic.id));+ }+ }+ return directory;+ });+ }++ async associateTopic(projectId: string, topicId: string, directoryId?: string) {+ await this.assertManageableProject(projectId);+ return this.db.transaction(async (tx) => {+ const db = tx as LobeChatDatabase;+ const directory = directoryId+ ? await new ProjectWorkingDirectoryModel(db, this.userId, this.workspaceId).resolve(+ directoryId,+ projectId,+ )+ : undefined;+ const [topic] = await db+ .select()+ .from(topics)+ .where(+ and(+ eq(topics.id, topicId),+ eq(topics.userId, this.userId),+ buildWorkspaceWhere(this.scope(), topics),+ isNull(topics.deletedAt),+ ),+ )+ .for('update');+ if (!topic) throw new Error('Topic not found or access denied');+ if (topic.projectId && topic.projectId !== projectId)+ throw new Error('Topic already belongs to another project');+ if (topic.status === 'running' || topic.metadata?.runningOperation)+ throw new Error('Wait for the running topic to finish before associating it');+ const source = getWorkingDirSourcePath(+ topic.metadata?.workingDirectoryConfig ?? topic.metadata?.workingDirectory,+ );+ if (source && !directory) throw new Error('Select the existing working directory');+ const pinned = topic.metadata?.boundDeviceId;+ if (+ directory &&+ ((source && normalizeProjectDirectory(source, directory.platform) !== directory.path) ||+ (pinned && pinned !== directory.deviceId))+ )+ throw new Error('Keep the existing device and working directory');+ if (topic.projectWorkingDirectoryId && topic.projectWorkingDirectoryId !== directoryId)+ throw new Error('Keep the existing project directory binding');+ if (directory && topic.agentId) {+ const [agent] = await db+ .select()+ .from(agents)+ .where(and(eq(agents.id, topic.agentId), buildWorkspaceWhere(this.scope(), agents)));+ if (+ !agent ||+ (agent.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&+ agent.agencyConfig.boundDeviceId !== directory.deviceId)+ )+ throw new Error('Agent cannot use this execution target');+ }+ const [updated] = await db+ .update(topics)+ .set({+ projectId,+ ...(directory+ ? {+ projectWorkingDirectoryId: directory.id,+ metadata: {+ ...topic.metadata,+ boundDeviceId: directory.deviceId,+ workingDirectory: directory.path,+ workingDirectoryConfig: { path: directory.path },+ },+ }+ : {}),+ })+ .where(eq(topics.id, topicId))+ .returning();+ return updated;+ });+ }+}diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex b454e533604..c88095cfc7f 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -121,6 +121,7 @@ export interface ChatTopicMetadata {summarizedAt: string;version: number;};+bot?: ChatTopicBotContext;boundDeviceId?: string;cronJobId?: string;@@ -657,6 +658,8 @@ export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {* `metadata.model` (measured dominant model from the usage roll-up).*/model?: string | null;+ projectId?: string | null;+ projectWorkingDirectoryId?: string | null;provider?: string | null;/*** Start time of the topic's current run β the latest top-level running