🤯 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(integrations): connect Linear via OAuth (#21036)
Rdmclin2013dcba32e4e
diff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.tsindex 6e284e13c8d..cf64351f1f2 100644--- a/apps/server/src/modules/Redis/keys.ts+++ b/apps/server/src/modules/Redis/keys.ts@@ -29,6 +29,10 @@ export const RedisKeyNamespace = {* AI generation related keys (agent welcome, placeholders, etc.)*/AI_GENERATION: 'aiGeneration',+ /**+ * Third-party integrations (Linear, …): OAuth hand-off state.+ */+ INTEGRATIONS: 'integrations',/*** Core LOBEHUB application keys (sessions, cache, etc.)*/@@ -133,6 +137,16 @@ export const RedisKeys = {*/homeBrief: (userId: string): string => `home_brief:${userId}`,},+ /**+ * Integrations scope — see {@link RedisKeyNamespace.INTEGRATIONS}.+ */+ integrations: {+ /**+ * Single-use state of one "Connect Linear" OAuth hand-off.+ * Full key: integrations:linear_oauth_state:v1:{state}+ */+ linearOAuthState: (state: string): string => `linear_oauth_state:v1:${state}`,+ },/*** Lobechat core scope - for application-level caching*/@@ -175,6 +189,7 @@ export const RedisKeyScopeNamespace = {agentSignal: RedisKeyNamespace.AGENT_SIGNAL,agentSteer: RedisKeyNamespace.AGENT_STEER,aiGeneration: RedisKeyNamespace.AI_GENERATION,+ integrations: RedisKeyNamespace.INTEGRATIONS,lobechat: RedisKeyNamespace.LOBEHUB,sendPathCache: RedisKeyNamespace.SEND_PATH_CACHE,} as const satisfies Record<diff --git a/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts b/apps/server/src/router-hono/webhooks/__tests__/routes.test.tsindex 7ff6e15241d..3f60ba9a079 100644--- a/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts+++ b/apps/server/src/router-hono/webhooks/__tests__/routes.test.ts@@ -15,6 +15,8 @@ vi.mock('../handlers/casdoor', () => ({ casdoorWebhook: vi.fn() }));vi.mock('../handlers/github', () => ({ githubWebhook: vi.fn() }));vi.mock('../handlers/githubInstall', () => ({ githubInstall: vi.fn() }));vi.mock('../handlers/githubSetup', () => ({ githubSetup: vi.fn() }));+vi.mock('../handlers/linearCallback', () => ({ linearCallback: vi.fn() }));+vi.mock('../handlers/linearInstall', () => ({ linearInstall: vi.fn() }));vi.mock('../handlers/logto', () => ({ logtoWebhook: vi.fn() }));vi.mock('../handlers/memoryExtraction', () => ({ memoryExtractionWebhook: vi.fn() }));vi.mock('../handlers/memoryExtractionBenchmarkLocomo', () => ({@@ -44,13 +46,15 @@ describe('webhooks hono routes', () => {]);});- it('serves the GitHub App install and setup redirects as GET', () => {+ it('serves the GitHub App and Linear install and OAuth redirects as GET', () => {const paths = app.routes.filter((route) => route.method === 'GET').map((route) => route.path);expect([...new Set(paths)].sort()).toEqual(['/api/webhooks/github/install','/api/webhooks/github/oauth/callback','/api/webhooks/github/setup',+ '/api/webhooks/linear/install',+ '/api/webhooks/linear/oauth/callback',]);});});diff --git a/apps/server/src/router-hono/webhooks/handlers/__tests__/linearOAuth.test.ts b/apps/server/src/router-hono/webhooks/handlers/__tests__/linearOAuth.test.tsnew file mode 100644index 00000000000..7b38c8cffcc--- /dev/null+++ b/apps/server/src/router-hono/webhooks/handlers/__tests__/linearOAuth.test.ts@@ -0,0 +1,223 @@+// @vitest-environment node+import { getTestDB } from '@lobechat/database/test-utils';+import { Hono } from 'hono';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { LinearConnectionModel } from '@/database/models/linear';+import { linearConnections, users, workspaceMembers, workspaces } from '@/database/schemas';++import { linearCallback } from '../linearCallback';+import { linearInstall } from '../linearInstall';++const serverDB = await getTestDB();+const userId = 'linear-oauth-user';++const mocks = vi.hoisted(() => ({+ consumeOAuthState: vi.fn(),+ exchangeLinearCode: vi.fn(),+ fetchLinearViewer: vi.fn(),+ getSession: vi.fn(),+ issueOAuthState: vi.fn(),+ revokeLinearToken: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => serverDB) }));+vi.mock('@/envs/linear', () => ({ linearEnv: { ENABLED_LINEAR: true } }));+vi.mock('@/auth', () => ({ auth: { api: { getSession: mocks.getSession } } }));+vi.mock('@/server/services/redis', () => ({+ redisService: {+ linear: {+ consumeOAuthState: mocks.consumeOAuthState,+ issueOAuthState: mocks.issueOAuthState,+ },+ },+}));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: {+ initWithEnvKey: async () => ({+ decrypt: async (ciphertext: string) => ({ plaintext: ciphertext }),+ encrypt: async (plaintext: string) => plaintext,+ }),+ },+}));+vi.mock('@/server/services/linear/client', () => ({+ buildLinearAuthorizeUrl: (state: string) => `https://linear.app/oauth/authorize?state=${state}`,+ exchangeLinearCode: mocks.exchangeLinearCode,+ fetchLinearViewer: mocks.fetchLinearViewer,+ LINEAR_INSTALL_PATH: '/api/webhooks/linear/install',+ revokeLinearToken: mocks.revokeLinearToken,+}));++const app = new Hono().get('/install', linearInstall).get('/callback', linearCallback);+const request = (path: string, query: Record<string, string>) =>+ app.request(`http://localhost${path}?${new URLSearchParams(query)}`);++const location = (res: Response) => new URL(res.headers.get('location')!);++beforeEach(async () => {+ await serverDB.insert(users).values({ id: userId });+ mocks.getSession.mockResolvedValue({ user: { id: userId } });+ mocks.issueOAuthState.mockResolvedValue('state-1');+ mocks.exchangeLinearCode.mockResolvedValue({+ accessToken: 'token',+ expiresAt: new Date('2030-01-01T00:00:00.000Z'),+ refreshToken: 'refresh',+ scopes: ['read'],+ });+ mocks.fetchLinearViewer.mockResolvedValue({+ avatarUrl: 'https://avatar',+ id: 'linear-user',+ name: 'Ada',+ organization: { id: 'org-1', logoUrl: 'https://logo', name: 'Acme', urlKey: 'acme' },+ });+});++afterEach(async () => {+ await serverDB.delete(linearConnections);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);+ vi.clearAllMocks();+});++describe('linearInstall', () => {+ it('issues a state for the session user and sends them to Linear', async () => {+ const res = await request('/install', { returnTo: '/settings/integrations/linear' });++ expect(res.status).toBe(302);+ expect(res.headers.get('location')).toBe('https://linear.app/oauth/authorize?state=state-1');+ expect(mocks.issueOAuthState).toHaveBeenCalledWith({+ lobeUserId: userId,+ returnTo: '/settings/integrations/linear',+ workspaceId: null,+ });+ });++ it('bounces a signed-out visitor through sign-in', async () => {+ mocks.getSession.mockResolvedValue(null);++ const res = await request('/install', {});++ expect(location(res).pathname).toBe('/signin');+ expect(mocks.issueOAuthState).not.toHaveBeenCalled();+ });++ it('refuses a workspace the user may only view', async () => {+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'ws', primaryOwnerId: userId, slug: 'linear-oauth-ws' })+ .returning();+ await serverDB+ .insert(workspaceMembers)+ .values({ role: 'viewer', userId, workspaceId: workspace.id });++ const res = await request('/install', { workspaceId: workspace.id });++ expect(res.status).toBe(403);+ });++ it('answers 503 when no state can be stored', async () => {+ mocks.issueOAuthState.mockResolvedValue(null);++ const res = await request('/install', {});++ expect(res.status).toBe(503);+ });+});++describe('linearCallback', () => {+ it('stores the connection for the user named by the state and returns to settings', async () => {+ mocks.consumeOAuthState.mockResolvedValue({+ lobeUserId: userId,+ returnTo: '/settings/integrations/linear',+ ts: Date.now(),+ });++ const res = await request('/callback', { code: 'code-1', state: 'state-1' });++ expect(location(res).pathname).toBe('/settings/integrations/linear');+ expect(location(res).searchParams.get('installed')).toBe('ok');+ expect(mocks.exchangeLinearCode).toHaveBeenCalledWith('code-1');++ const [connection] = await LinearConnectionModel.listByScope(serverDB, { userId });+ expect(connection).toMatchObject({+ actorName: 'Ada',+ organizationId: 'org-1',+ organizationUrlKey: 'acme',+ workspaceId: null,+ });+ const decrypted = await LinearConnectionModel.findDecryptedById(serverDB, connection.id);+ expect(decrypted?.credentials).toEqual({ accessToken: 'token', refreshToken: 'refresh' });+ });++ it('never exchanges a code that arrives without our state', async () => {+ mocks.consumeOAuthState.mockResolvedValue(null);++ const res = await request('/callback', { code: 'forwarded', state: 'unknown' });++ expect(location(res).searchParams.get('error')).toBe('invalid_state');+ expect(mocks.exchangeLinearCode).not.toHaveBeenCalled();+ });++ it('reports a declined consent and a failed exchange', async () => {+ mocks.consumeOAuthState.mockResolvedValue({ lobeUserId: userId, ts: Date.now() });+ const declined = await request('/callback', { error: 'access_denied', state: 's' });+ expect(location(declined).searchParams.get('error')).toBe('access_denied');++ mocks.exchangeLinearCode.mockRejectedValue(new Error('bad code'));+ const failed = await request('/callback', { code: 'c', state: 's' });+ expect(location(failed).searchParams.get('error')).toBe('exchange_failed');+ expect(await LinearConnectionModel.listByScope(serverDB, { userId })).toEqual([]);+ });++ it('refuses a state finished by a different signed-in user', async () => {+ mocks.consumeOAuthState.mockResolvedValue({ lobeUserId: userId, ts: Date.now() });+ mocks.getSession.mockResolvedValue({ user: { id: 'someone-else' } });++ const res = await request('/callback', { code: 'victim-code', state: 'forwarded' });++ expect(location(res).searchParams.get('error')).toBe('invalid_state');+ expect(mocks.exchangeLinearCode).not.toHaveBeenCalled();+ expect(await LinearConnectionModel.listByScope(serverDB, { userId })).toEqual([]);+ });++ it('refuses a state finished without a session', async () => {+ mocks.consumeOAuthState.mockResolvedValue({ lobeUserId: userId, ts: Date.now() });+ mocks.getSession.mockResolvedValue(null);++ const res = await request('/callback', { code: 'code', state: 'state' });++ expect(location(res).searchParams.get('error')).toBe('invalid_state');+ expect(mocks.exchangeLinearCode).not.toHaveBeenCalled();+ });++ it('hands the token back when the viewer cannot be read', async () => {+ mocks.consumeOAuthState.mockResolvedValue({ lobeUserId: userId, ts: Date.now() });+ mocks.fetchLinearViewer.mockRejectedValue(new Error('graphql down'));++ const res = await request('/callback', { code: 'code', state: 'state' });++ expect(location(res).searchParams.get('error')).toBe('exchange_failed');+ expect(mocks.revokeLinearToken).toHaveBeenCalledWith(+ expect.objectContaining({ accessToken: 'token', refreshToken: 'refresh' }),+ new Date('2030-01-01T00:00:00.000Z'),+ );+ });++ it('returns to settings and hands the token back when the connection cannot be saved', async () => {+ mocks.consumeOAuthState.mockResolvedValue({+ lobeUserId: userId,+ returnTo: '/settings/integrations/linear',+ ts: Date.now(),+ });+ const upsert = vi+ .spyOn(LinearConnectionModel, 'upsert')+ .mockRejectedValueOnce(new Error('unique violation'));++ const res = await request('/callback', { code: 'code', state: 'state' });++ expect(location(res).pathname).toBe('/settings/integrations/linear');+ expect(location(res).searchParams.get('error')).toBe('save_failed');+ expect(mocks.revokeLinearToken).toHaveBeenCalledTimes(1);+ upsert.mockRestore();+ });+});diff --git a/apps/server/src/router-hono/webhooks/handlers/linearCallback.ts b/apps/server/src/router-hono/webhooks/handlers/linearCallback.tsnew file mode 100644index 00000000000..286722710ab--- /dev/null+++ b/apps/server/src/router-hono/webhooks/handlers/linearCallback.ts@@ -0,0 +1,126 @@+import debug from 'debug';+import type { Context } from 'hono';++import { auth } from '@/auth';+import { getServerDB } from '@/database/core/db-adaptor';+import { LinearConnectionModel } from '@/database/models/linear';+import { linearEnv } from '@/envs/linear';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import {+ exchangeLinearCode,+ fetchLinearViewer,+ revokeLinearToken,+} from '@/server/services/linear/client';+import { redisService } from '@/server/services/redis';+import { canWriteScmScope, sanitizeReturnTo } from '@/server/services/scm/scope';++const log = debug('lobe-server:linear:callback');++/** Where the user lands after connecting; the page reads `installed=…` or `error=…`. */+export const LINEAR_SETTINGS_PATH = '/settings/integrations/linear';++const redirectToSettings = (origin: string, params: Record<string, string>, returnTo?: string) => {+ const target = new URL(sanitizeReturnTo(returnTo) ?? LINEAR_SETTINGS_PATH, origin);+ for (const [key, value] of Object.entries(params)) target.searchParams.set(key, value);+ return Response.redirect(target, 302);+};++/**+ * Linear sends the user here after the consent screen. Only a callback that+ * carries our state is honored: the state names the user and scope, so the+ * code is never exchanged for a session we did not start. The browser must+ * also be signed in as that user — otherwise an authorization URL started by+ * one account and forwarded to another would file the clicker's Linear+ * workspace under the sender.+ */+export const linearCallback = async (c: Context): Promise<Response> => {+ const url = new URL(c.req.url);+ const code = url.searchParams.get('code');+ const state = url.searchParams.get('state');+ const providerError = url.searchParams.get('error');++ if (!linearEnv.ENABLED_LINEAR) {+ return new Response('Linear is not configured on this LobeHub deployment.', { status: 503 });+ }++ const statePayload = state ? await redisService.linear.consumeOAuthState(state) : null;+ if (!statePayload) return redirectToSettings(url.origin, { error: 'invalid_state' });++ const { lobeUserId: userId, returnTo } = statePayload;+ const workspaceId = statePayload.workspaceId ?? null;++ const session = await auth.api.getSession({ headers: c.req.raw.headers }).catch((error) => {+ log('getSession failed: %O', error);+ return null;+ });+ if (session?.user?.id !== userId) {+ log('state for user=%s finished by another session', userId);+ return redirectToSettings(url.origin, { error: 'invalid_state' });+ }++ // The user declined on Linear's consent screen.+ if (providerError) return redirectToSettings(url.origin, { error: 'access_denied' }, returnTo);+ if (!code) return redirectToSettings(url.origin, { error: 'missing_code' }, returnTo);++ const db = await getServerDB();+ // Membership can change between the click and the callback; recheck.+ if (!(await canWriteScmScope(db, userId, workspaceId))) {+ return redirectToSettings(url.origin, { error: 'workspace_forbidden' }, returnTo);+ }++ let tokens: Awaited<ReturnType<typeof exchangeLinearCode>>;+ try {+ tokens = await exchangeLinearCode(code);+ } catch (error) {+ log('code exchange failed: %O', error);+ return redirectToSettings(url.origin, { error: 'exchange_failed' }, returnTo);+ }++ // From here on Linear has issued a token; any failure hands it back.+ const abandon = async (error: string) => {+ await revokeLinearToken(tokens, tokens.expiresAt);+ return redirectToSettings(url.origin, { error }, returnTo);+ };++ let viewer: Awaited<ReturnType<typeof fetchLinearViewer>>;+ try {+ viewer = await fetchLinearViewer(tokens.accessToken);+ } catch (error) {+ log('viewer lookup failed: %O', error);+ return abandon('exchange_failed');+ }++ try {+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();+ await LinearConnectionModel.upsert(+ db,+ {+ actorExternalId: viewer.id,+ actorName: viewer.name,+ credentials: { accessToken: tokens.accessToken, refreshToken: tokens.refreshToken },+ metadata: {+ actorAvatarUrl: viewer.avatarUrl ?? undefined,+ organizationLogoUrl: viewer.organization.logoUrl ?? undefined,+ scopes: tokens.scopes,+ },+ organizationId: viewer.organization.id,+ organizationName: viewer.organization.name,+ organizationUrlKey: viewer.organization.urlKey,+ tokenExpiresAt: tokens.expiresAt ?? null,+ userId,+ workspaceId,+ },+ gateKeeper,+ );+ } catch (error) {+ log('cannot store connection: %O', error);+ return abandon('save_failed');+ }++ log('connected organization %s for user=%s', viewer.organization.urlKey, userId);+ return redirectToSettings(+ url.origin,+ { account: viewer.organization.name, installed: 'ok' },+ returnTo,+ );+};diff --git a/apps/server/src/router-hono/webhooks/handlers/linearInstall.ts b/apps/server/src/router-hono/webhooks/handlers/linearInstall.tsnew file mode 100644index 00000000000..5665c45d63b--- /dev/null+++ b/apps/server/src/router-hono/webhooks/handlers/linearInstall.ts@@ -0,0 +1,64 @@+import debug from 'debug';+import type { Context } from 'hono';++import { auth } from '@/auth';+import { getServerDB } from '@/database/core/db-adaptor';+import { linearEnv } from '@/envs/linear';+import { buildLinearAuthorizeUrl, LINEAR_INSTALL_PATH } from '@/server/services/linear/client';+import { redisService } from '@/server/services/redis';+import { canWriteScmScope, sanitizeReturnTo } from '@/server/services/scm/scope';++const log = debug('lobe-server:linear:install');++/**+ * Entry point for "Connect Linear". Reached from a signed-in LobeHub page,+ * so the session says which user (and optionally which workspace) the+ * connection belongs to; that binding travels through Linear in the+ * single-use `state` and is consumed by the callback.+ */+export const linearInstall = async (c: Context): Promise<Response> => {+ if (!linearEnv.ENABLED_LINEAR) {+ return new Response('Linear is not configured on this LobeHub deployment.', { status: 503 });+ }++ const req = c.req.raw;+ const url = new URL(req.url);+ const workspaceId = url.searchParams.get('workspaceId');+ const returnTo = sanitizeReturnTo(url.searchParams.get('returnTo'));++ let session: Awaited<ReturnType<typeof auth.api.getSession>>;+ try {+ session = await auth.api.getSession({ headers: req.headers });+ } catch (error) {+ log('getSession failed: %O', error);+ session = null;+ }+ if (!session?.user?.id) {+ const callbackUrl = encodeURIComponent(`${LINEAR_INSTALL_PATH}${url.search}`);+ return Response.redirect(new URL(`/signin?callbackUrl=${callbackUrl}`, url.origin), 302);+ }+ const userId = session.user.id;++ // Viewers read a workspace; a connection writes tasks into it.+ if (workspaceId && !(await canWriteScmScope(await getServerDB(), userId, workspaceId))) {+ return c.json({ error: 'connecting Linear to this workspace needs the member role' }, 403);+ }++ const state = await redisService.linear+ .issueOAuthState({ lobeUserId: userId, returnTo, workspaceId })+ .catch((error) => {+ log('cannot issue OAuth state: %O', error);+ return null;+ });+ if (!state) {+ return new Response('Connecting Linear needs Redis (REDIS_URL) on this LobeHub deployment.', {+ status: 503,+ });+ }++ const authorizeUrl = buildLinearAuthorizeUrl(state);+ if (!authorizeUrl) return new Response('Linear is not configured.', { status: 503 });++ log('redirecting user=%s workspace=%s to Linear', userId, workspaceId ?? '-');+ return Response.redirect(authorizeUrl, 302);+};diff --git a/apps/server/src/router-hono/webhooks/index.ts b/apps/server/src/router-hono/webhooks/index.tsindex 74b2d0202e0..12c9f407863 100644--- a/apps/server/src/router-hono/webhooks/index.ts+++ b/apps/server/src/router-hono/webhooks/index.ts@@ -4,6 +4,8 @@ import { casdoorWebhook } from './handlers/casdoor';import { githubWebhook } from './handlers/github';import { githubInstall } from './handlers/githubInstall';import { githubSetup } from './handlers/githubSetup';+import { linearCallback } from './handlers/linearCallback';+import { linearInstall } from './handlers/linearInstall';import { logtoWebhook } from './handlers/logto';import { memoryExtractionWebhook } from './handlers/memoryExtraction';import { memoryExtractionBenchmarkLocomo } from './handlers/memoryExtractionBenchmarkLocomo';@@ -47,4 +49,8 @@ app.get('/github/install', githubInstall);app.get('/github/setup', githubSetup);app.get('/github/oauth/callback', githubSetup);+// Linear OAuth application: the connect redirect and its OAuth callback.+app.get('/linear/install', linearInstall);+app.get('/linear/oauth/callback', linearCallback);+export default app;diff --git a/apps/server/src/routers/lambda/__tests__/linear.test.ts b/apps/server/src/routers/lambda/__tests__/linear.test.tsnew file mode 100644index 00000000000..251c8cc58db--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/linear.test.ts@@ -0,0 +1,126 @@+// @vitest-environment node+import { getTestDB } from '@lobechat/database/test-utils';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { LinearConnectionModel } from '@/database/models/linear';+import { linearConnections, users, workspaceMembers, workspaces } from '@/database/schemas';++import { linearRouter } from '../linear';++const serverDB = await getTestDB();+const userId = 'linear-router-user';+const otherUserId = 'linear-router-user-2';++vi.mock('@/envs/linear', () => ({+ linearEnv: { ENABLED_LINEAR: true },+}));++const mocks = vi.hoisted(() => ({ revoke: vi.fn() }));+vi.mock('@/server/services/linear/client', () => ({+ LINEAR_INSTALL_PATH: '/api/webhooks/linear/install',+ revokeLinearToken: mocks.revoke,+}));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: {+ initWithEnvKey: async () => ({+ decrypt: async (ciphertext: string) => ({ plaintext: ciphertext }),+ encrypt: async (plaintext: string) => plaintext,+ }),+ },+}));++vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');+ return { wsCompatProcedure: mod.trpc.procedure };+});++vi.mock('@/libs/trpc/lambda/middleware', () => ({+ serverDatabase: async (opts: any) => opts.next({ ctx: { ...opts.ctx, serverDB } }),+}));++const caller = (ctx: { userId: string; workspaceId?: string | null }) =>+ linearRouter.createCaller({ ...ctx, serverDB } as any);++const connect = (scope: { userId: string; workspaceId?: string | null }) =>+ LinearConnectionModel.upsert(serverDB, {+ actorExternalId: 'linear-user',+ actorName: 'Ada',+ credentials: { accessToken: 'token' },+ organizationId: 'org-1',+ organizationName: 'Acme',+ organizationUrlKey: 'acme',+ ...scope,+ });++beforeEach(async () => {+ vi.clearAllMocks();+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(async () => {+ await serverDB.delete(linearConnections);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);+});++describe('linearRouter', () => {+ it('reports the connect configuration', async () => {+ expect(await caller({ userId }).getConfig()).toEqual({+ enabled: true,+ installPath: '/api/webhooks/linear/install',+ });+ });++ it('lists only the caller scope, without credentials', async () => {+ await connect({ userId });+ await connect({ userId: otherUserId });++ const list = await caller({ userId }).listConnections();++ expect(list).toHaveLength(1);+ expect(list[0]).toMatchObject({ organizationName: 'Acme', userId });+ expect(list[0]).not.toHaveProperty('credentials');+ });++ it("refuses to disconnect another user's connection", async () => {+ const other = await connect({ userId: otherUserId });++ await expect(caller({ userId }).disconnect({ connectionId: other.id })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(mocks.revoke).not.toHaveBeenCalled();+ });++ it('lets workspace members disconnect a shared connection but not viewers', async () => {+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'ws', primaryOwnerId: otherUserId, slug: 'linear-router-ws' })+ .returning();+ const connection = await connect({ userId: otherUserId, workspaceId: workspace.id });+ await serverDB+ .insert(workspaceMembers)+ .values({ role: 'viewer', userId, workspaceId: workspace.id });+ const input = { connectionId: connection.id };++ await expect(+ caller({ userId, workspaceId: workspace.id }).disconnect(input),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });++ await serverDB.update(workspaceMembers).set({ role: 'member' });+ await expect(caller({ userId, workspaceId: workspace.id }).disconnect(input)).resolves.toEqual({+ ok: true,+ });+ });++ it('disconnects: revokes the token at Linear and hides the connection', async () => {+ const connection = await connect({ userId });++ await caller({ userId }).disconnect({ connectionId: connection.id });++ expect(mocks.revoke).toHaveBeenCalledWith({ accessToken: 'token' }, null);+ expect(await caller({ userId }).listConnections()).toEqual([]);+ await expect(+ caller({ userId }).disconnect({ connectionId: connection.id }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+});diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex b72fa323a9d..09f7276f5b9 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -71,6 +71,7 @@ import { importerRouter } from './importer';import { klavisRouter } from './klavis';import { knowledgeRouter } from './knowledge';import { knowledgeBaseRouter } from './knowledgeBase';+import { linearRouter } from './linear';import { llmGenerationTracingRouter } from './llmGenerationTracing';import { marketRouter } from './market';import { messageRouter } from './message';@@ -169,6 +170,7 @@ export const lambdaRouter = router({klavis: klavisRouter,knowledge: knowledgeRouter,knowledgeBase: knowledgeBaseRouter,+ linear: linearRouter,llmGenerationTracing: llmGenerationTracingRouter,market: marketRouter,message: messageRouter,diff --git a/apps/server/src/routers/lambda/linear.ts b/apps/server/src/routers/lambda/linear.tsnew file mode 100644index 00000000000..d4f959c3a3e--- /dev/null+++ b/apps/server/src/routers/lambda/linear.ts@@ -0,0 +1,86 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { LinearConnectionModel } from '@/database/models/linear';+import { linearEnv } from '@/envs/linear';+import { router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { LINEAR_INSTALL_PATH, revokeLinearToken } from '@/server/services/linear/client';+import { canWriteScmScope } from '@/server/services/scm/scope';++const linearProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ return opts.next({+ ctx: { scope: { userId: ctx.userId, workspaceId: ctx.workspaceId ?? null } },+ });+});++const connectionInput = z.object({ connectionId: z.string().uuid() });++/**+ * The Linear integration for the settings page. Connecting happens through+ * the OAuth redirect (`/api/webhooks/linear/install`); listing and+ * disconnecting comes through here, scoped to the connections visible in+ * the caller's scope.+ */+export const linearRouter = router({+ /** Remove the connection: revoke the token at Linear and hide the row. */+ disconnect: linearProcedure.input(connectionInput).mutation(async ({ ctx, input }) => {+ const connection = await requireWritableConnection(ctx, input.connectionId);++ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();+ const decrypted = await LinearConnectionModel.findDecryptedById(+ ctx.serverDB,+ connection.id,+ gateKeeper,+ );+ if (decrypted?.credentials) {+ await revokeLinearToken(decrypted.credentials, decrypted.tokenExpiresAt);+ }++ await LinearConnectionModel.revoke(ctx.serverDB, connection.id);+ return { ok: true };+ }),++ /** What the client needs to render the connect button. */+ getConfig: linearProcedure.query(async () => ({+ enabled: linearEnv.ENABLED_LINEAR,+ installPath: LINEAR_INSTALL_PATH,+ })),++ listConnections: linearProcedure.query(async ({ ctx }) => {+ const rows = await LinearConnectionModel.listByScope(ctx.serverDB, ctx.scope);+ return rows.map((row) => LinearConnectionModel.toView(row));+ }),+});++/**+ * The connection, if it is active and visible in the caller's scope and the+ * caller may write there (in a workspace that takes a member role).+ */+const requireWritableConnection = async (+ ctx: {+ scope: { userId: string; workspaceId: string | null };+ serverDB: Parameters<typeof LinearConnectionModel.findById>[0];+ userId: string;+ },+ connectionId: string,+) => {+ const connection = await LinearConnectionModel.findById(ctx.serverDB, connectionId);+ const inScope =+ !!connection &&+ !connection.revokedAt &&+ (ctx.scope.workspaceId+ ? connection.workspaceId === ctx.scope.workspaceId+ : connection.userId === ctx.userId && !connection.workspaceId);+ if (!inScope) throw new TRPCError({ code: 'NOT_FOUND', message: 'Linear connection not found' });++ if (!(await canWriteScmScope(ctx.serverDB, ctx.userId, ctx.scope.workspaceId))) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'workspace member role required' });+ }+ return connection;+};++export type LinearRouter = typeof linearRouter;diff --git a/apps/server/src/services/linear/__tests__/client.test.ts b/apps/server/src/services/linear/__tests__/client.test.tsnew file mode 100644index 00000000000..c8be3637c3c--- /dev/null+++ b/apps/server/src/services/linear/__tests__/client.test.ts@@ -0,0 +1,71 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { revokeLinearToken } from '../client';++vi.mock('@/envs/linear', () => ({+ linearEnv: { ENABLED_LINEAR: true, LINEAR_CLIENT_ID: 'client', LINEAR_CLIENT_SECRET: 'secret' },+}));+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.example.com' } }));++const fetchMock = vi.fn();++beforeEach(() => {+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ fetchMock.mockReset();+});++const authorization = (call: unknown[]) =>+ (call[1] as RequestInit).headers as Record<string, string>;++describe('revokeLinearToken', () => {+ it('revokes a live access token directly', async () => {+ fetchMock.mockResolvedValue(new Response('', { status: 200 }));++ const ok = await revokeLinearToken(+ { accessToken: 'live', refreshToken: 'refresh' },+ new Date(Date.now() + 60_000),+ );++ expect(ok).toBe(true);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetchMock.mock.calls[0][0]).toBe('https://api.linear.app/oauth/revoke');+ expect(authorization(fetchMock.mock.calls[0])).toEqual({ Authorization: 'Bearer live' });+ });++ it('refreshes an expired access token before revoking it', async () => {+ fetchMock+ .mockResolvedValueOnce(+ Response.json({ access_token: 'fresh', expires_in: 86_399, refresh_token: 'next' }),+ )+ .mockResolvedValueOnce(new Response('', { status: 200 }));++ const ok = await revokeLinearToken(+ { accessToken: 'stale', refreshToken: 'refresh' },+ new Date(Date.now() - 1000),+ );++ expect(ok).toBe(true);+ expect(fetchMock.mock.calls[0][0]).toBe('https://api.linear.app/oauth/token');+ const body = (fetchMock.mock.calls[0][1] as RequestInit).body as URLSearchParams;+ expect(body.get('grant_type')).toBe('refresh_token');+ expect(body.get('refresh_token')).toBe('refresh');+ expect(authorization(fetchMock.mock.calls[1])).toEqual({ Authorization: 'Bearer fresh' });+ });++ it('reports a revocation Linear rejected', async () => {+ fetchMock.mockResolvedValue(Response.json({ error: 'Token not found' }, { status: 401 }));++ await expect(revokeLinearToken({ accessToken: 'gone' })).resolves.toBe(false);+ });++ it('reports a network failure instead of throwing', async () => {+ fetchMock.mockRejectedValue(new Error('offline'));++ await expect(revokeLinearToken({ accessToken: 'token' })).resolves.toBe(false);+ });+});diff --git a/apps/server/src/services/linear/client.ts b/apps/server/src/services/linear/client.tsnew file mode 100644index 00000000000..0370833a36f--- /dev/null+++ b/apps/server/src/services/linear/client.ts@@ -0,0 +1,172 @@+import type { LinearConnectionCredentials } from '@lobechat/types';+import debug from 'debug';++import { appEnv } from '@/envs/app';+import { linearEnv } from '@/envs/linear';++const log = debug('lobe-server:linear:client');++const AUTHORIZE_URL = 'https://linear.app/oauth/authorize';+const TOKEN_URL = 'https://api.linear.app/oauth/token';+const REVOKE_URL = 'https://api.linear.app/oauth/revoke';+const GRAPHQL_URL = 'https://api.linear.app/graphql';++/** Read-only: connecting only needs to identify the workspace and its user. */+const SCOPES = ['read'];++export const LINEAR_INSTALL_PATH = '/api/webhooks/linear/install';+export const LINEAR_CALLBACK_PATH = '/api/webhooks/linear/oauth/callback';++/**+ * The callback URL registered on the Linear OAuth application. Built from+ * `APP_URL` rather than the request origin so the authorize and token legs+ * send byte-identical values behind any proxy.+ */+export const getLinearRedirectUri = (): string => {+ const base = appEnv.APP_URL;+ if (!base) throw new Error('APP_URL is not configured; cannot build the Linear redirect URI');+ return new URL(LINEAR_CALLBACK_PATH, base).toString();+};++export const buildLinearAuthorizeUrl = (state: string): string | undefined => {+ if (!linearEnv.ENABLED_LINEAR || !linearEnv.LINEAR_CLIENT_ID) return undefined;++ const url = new URL(AUTHORIZE_URL);+ url.searchParams.set('client_id', linearEnv.LINEAR_CLIENT_ID);+ url.searchParams.set('redirect_uri', getLinearRedirectUri());+ url.searchParams.set('response_type', 'code');+ url.searchParams.set('scope', SCOPES.join(','));+ url.searchParams.set('state', state);+ // Always show the workspace picker, so a user in several Linear workspaces+ // can choose which one to connect instead of silently reusing the last.+ url.searchParams.set('prompt', 'consent');+ return url.toString();+};++export interface LinearTokenSet {+ accessToken: string;+ /** Absent for tokens Linear issues without expiry. */+ expiresAt?: Date;+ refreshToken?: string;+ scopes: string[];+}++interface TokenResponse {+ access_token: string;+ expires_in?: number;+ refresh_token?: string;+ scope?: string | string[];+}++const requestToken = async (body: Record<string, string>): Promise<LinearTokenSet> => {+ if (!linearEnv.LINEAR_CLIENT_ID || !linearEnv.LINEAR_CLIENT_SECRET) {+ throw new Error('Linear OAuth application is not configured');+ }++ const response = await fetch(TOKEN_URL, {+ body: new URLSearchParams({+ client_id: linearEnv.LINEAR_CLIENT_ID,+ client_secret: linearEnv.LINEAR_CLIENT_SECRET,+ ...body,+ }),+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ method: 'POST',+ });+ if (!response.ok) {+ throw new Error(`Linear token request failed: ${response.status} ${await response.text()}`);+ }++ const data = (await response.json()) as TokenResponse;+ const scopes = Array.isArray(data.scope) ? data.scope : (data.scope?.split(/[ ,]/) ?? []);+ return {+ accessToken: data.access_token,+ expiresAt: data.expires_in ? new Date(Date.now() + data.expires_in * 1000) : undefined,+ refreshToken: data.refresh_token,+ scopes: scopes.filter(Boolean),+ };+};++export const exchangeLinearCode = (code: string): Promise<LinearTokenSet> =>+ requestToken({+ code,+ grant_type: 'authorization_code',+ redirect_uri: getLinearRedirectUri(),+ });++/**+ * Best effort: a token Linear already forgot is as good as revoked. An expired+ * access token cannot authorize its own revocation, so it is refreshed first.+ * Resolves whether Linear confirmed the revocation.+ */+export const revokeLinearToken = async (+ credentials: LinearConnectionCredentials,+ expiresAt?: Date | null,+): Promise<boolean> => {+ try {+ let { accessToken } = credentials;+ if (credentials.refreshToken && expiresAt && expiresAt.getTime() <= Date.now()) {+ const refreshed = await requestToken({+ grant_type: 'refresh_token',+ refresh_token: credentials.refreshToken,+ });+ accessToken = refreshed.accessToken;+ }++ const response = await fetch(REVOKE_URL, {+ headers: { Authorization: `Bearer ${accessToken}` },+ method: 'POST',+ });+ if (!response.ok) log('revoke rejected: %d %s', response.status, await response.text());+ return response.ok;+ } catch (error) {+ log('revoke failed: %O', error);+ return false;+ }+};++export class LinearApiError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ this.name = 'LinearApiError';+ }+}++export const linearGraphql = async <T>(+ accessToken: string,+ query: string,+ variables?: Record<string, unknown>,+): Promise<T> => {+ const response = await fetch(GRAPHQL_URL, {+ body: JSON.stringify({ query, variables }),+ headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' },+ method: 'POST',+ });++ const payload = (await response.json().catch(() => ({}))) as {+ data?: T;+ errors?: { message: string }[];+ };+ if (!response.ok || payload.errors?.length || !payload.data) {+ const message = payload.errors?.map((error) => error.message).join('; ') || response.statusText;+ throw new LinearApiError(`Linear API error: ${message}`, response.status);+ }+ return payload.data;+};++export interface LinearViewer {+ avatarUrl?: string;+ id: string;+ name: string;+ organization: { id: string; logoUrl?: string; name: string; urlKey: string };+}++export const fetchLinearViewer = async (accessToken: string): Promise<LinearViewer> => {+ const data = await linearGraphql<{ viewer: LinearViewer }>(+ accessToken,+ `query Viewer { viewer { id name avatarUrl organization { id name urlKey logoUrl } } }`,+ );+ return data.viewer;+};diff --git a/apps/server/src/services/redis/README.md b/apps/server/src/services/redis/README.mdindex bd1e629a094..200d91778c4 100644--- a/apps/server/src/services/redis/README.md+++ b/apps/server/src/services/redis/README.md@@ -10,6 +10,7 @@ callers do not choose a provider, prefix, key, SET options or claim lifetime.- `steerQueue`: follow-ups a user queued behind a running agent turn, per topic/thread, held fora day. Atomic append (bounded), drain and restore; the runtime drains it into the next turn.Writes return `undefined` without Redis, and the caller tells the client to send directly.+- `linear`: single-use OAuth state for "Connect Linear" (ten minutes, deleted on first read).- `agentSignal`: spend bounds for background self-iteration — classifier calls per user per UTCday, self-feedback declaration slots per topic, manual triggers per user per hour, and thedistinct topics one nightly review may cover. Its keys live in the `agent-signal` namespacediff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.tsindex 0678f13632a..26e777152aa 100644--- a/apps/server/src/services/redis/index.ts+++ b/apps/server/src/services/redis/index.ts@@ -1,5 +1,6 @@import { agentSignal } from './agentSignal';import { deviceSystemInfo } from './deviceSystemInfo';+import { linear } from './linear';import { skillTools } from './skillTools';import { steerQueue } from './steerQueue';import { threadStartFence } from './threadStartFence';@@ -9,6 +10,7 @@ import { workspaceRescan } from './workspaceRescan';export const redisService = {agentSignal,deviceSystemInfo,+ linear,skillTools,steerQueue,threadStartFence,diff --git a/apps/server/src/services/redis/linear.test.ts b/apps/server/src/services/redis/linear.test.tsnew file mode 100644index 00000000000..5e1eee69cf3--- /dev/null+++ b/apps/server/src/services/redis/linear.test.ts@@ -0,0 +1,41 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { linear } from './linear';++const store = new Map<string, string>();+const redis = vi.hoisted(() => ({ client: null as any }));+vi.mock('./client', () => ({ getRedisServiceClient: async () => redis.client }));++const memoryClient = {+ del: vi.fn(async (key: string) => (store.delete(key) ? 1 : 0)),+ get: vi.fn(async (key: string) => store.get(key) ?? null),+ set: vi.fn(async (key: string, value: string) => {+ store.set(key, value);+ return 'OK';+ }),+};++beforeEach(() => {+ store.clear();+ vi.clearAllMocks();+ redis.client = memoryClient;+});++describe('redisService.linear', () => {+ it('hands out an OAuth state that can be consumed once', async () => {+ const state = await linear.issueOAuthState({ lobeUserId: 'u1', workspaceId: null });++ expect(memoryClient.set).toHaveBeenCalledWith(+ `linear_oauth_state:v1:${state}`,+ expect.any(String),+ { ex: 600 },+ );+ expect(await linear.consumeOAuthState(state!)).toMatchObject({ lobeUserId: 'u1' });+ expect(await linear.consumeOAuthState(state!)).toBeNull();+ });++ it('cannot start the OAuth flow without Redis', async () => {+ redis.client = null;+ expect(await linear.issueOAuthState({ lobeUserId: 'u1' })).toBeNull();+ });+});diff --git a/apps/server/src/services/redis/linear.ts b/apps/server/src/services/redis/linear.tsnew file mode 100644index 00000000000..41ee22bb7dd--- /dev/null+++ b/apps/server/src/services/redis/linear.ts@@ -0,0 +1,53 @@+import { randomUUID } from 'node:crypto';++import { RedisKeys } from '@/server/modules/Redis';++import { getRedisServiceClient } from './client';++const getClient = () => getRedisServiceClient('integrations');++const OAUTH_STATE_TTL_SECONDS = 600;+export interface LinearOAuthStatePayload {+ /** LobeHub user who clicked "Connect"; the connection belongs to them. */+ lobeUserId: string;+ /** Where to send the user after the callback (relative path). */+ returnTo?: string;+ ts: number;+ /** Workspace the connection belongs to; null for a personal connection. */+ workspaceId?: string | null;+}++export const linear = {+ /**+ * Single-use OAuth state for the "Connect Linear" redirect: TTL-bound and+ * deleted on first read, so the callback cannot be replayed. `null` without+ * Redis — the flow cannot start then.+ */+ async issueOAuthState(payload: Omit<LinearOAuthStatePayload, 'ts'>) {+ const redis = await getClient();+ if (!redis) return null;++ const state = randomUUID().replaceAll('-', '');+ const value: LinearOAuthStatePayload = { ...payload, ts: Date.now() };+ await redis.set(RedisKeys.integrations.linearOAuthState(state), JSON.stringify(value), {+ ex: OAUTH_STATE_TTL_SECONDS,+ });+ return state;+ },++ async consumeOAuthState(state: string): Promise<LinearOAuthStatePayload | null> {+ const redis = await getClient();+ if (!redis) return null;++ const key = RedisKeys.integrations.linearOAuthState(state);+ const raw = await redis.get(key);+ if (!raw) return null;+ await redis.del(key);++ try {+ return JSON.parse(raw) as LinearOAuthStatePayload;+ } catch {+ return null;+ }+ },+};diff --git a/locales/ar/integration.json b/locales/ar/integration.jsonindex 715d821f513..16a2bd1a02c 100644--- a/locales/ar/integration.json+++ b/locales/ar/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "تعذر ربط التثبيت. يرجى المحاولة مرة أخرى من ربط الحساب.","github.pending.title": "ربط تثبيت GitHub","github.tagline": "مزامنة طلبات السحب، نتائج CI والمراجعات مع وكلائك",+ "linear.connections.connect": "اتصل بمساحة العمل",+ "linear.connections.connectedAs": "متصل كـ {{name}} · {{date}}",+ "linear.connections.empty": "لم يتم توصيل أي مساحة عمل Linear بعد.",+ "linear.connections.enabledBy": "تم الاتصال بواسطة {{name}} · {{date}}",+ "linear.connections.notConfigured": "هذا النشر ليس لديه تطبيق Linear مُعد، لذا فإن الاتصال غير متاح. اطلب من المسؤول إعداد متغيرات بيئة Linear.",+ "linear.connections.openInLinear": "افتح في Linear",+ "linear.connections.status.connected": "متصل",+ "linear.connections.title": "الاتصالات",+ "linear.disconnect.confirm": "قطع الاتصال",+ "linear.disconnect.content": "قطع الاتصال بـ {{account}}؟ لن يكون لدى LobeHub وصول إلى مساحة عمل Linear هذه بعد الآن.",+ "linear.disconnect.failed": "تعذر قطع الاتصال. يرجى المحاولة مرة أخرى.",+ "linear.disconnect.success": "تم قطع الاتصال بـ Linear",+ "linear.disconnect.title": "قطع الاتصال بـ Linear",+ "linear.docsLink": "اقرأ الدليل",+ "linear.installResult.error.access_denied": "تم إلغاء التفويض على Linear.",+ "linear.installResult.error.exchange_failed": "لم تقبل Linear التفويض. يرجى المحاولة مرة أخرى للاتصال.",+ "linear.installResult.error.invalid_state": "انتهت صلاحية طلب الاتصال. يرجى البدء من جديد من اتصال مساحة العمل.",+ "linear.installResult.error.missing_code": "لم تُرجع Linear رمز التفويض.",+ "linear.installResult.error.unknown": "فشل الاتصال بـ Linear ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "يمكن فقط لأعضاء مساحة العمل الاتصال بـ Linear هنا.",+ "linear.installResult.success": "تم الاتصال بـ Linear: {{account}}",+ "linear.tagline": "قم بتوصيل مساحة عمل Linear الخاصة بك بـ LobeHub","overview.all": "جميع التكاملات","overview.comingSoon": "قريبًا","overview.description": "ربط المنصات التي تستخدمها بالفعل",diff --git a/locales/bg-BG/integration.json b/locales/bg-BG/integration.jsonindex 051e9255619..4ca702a4555 100644--- a/locales/bg-BG/integration.json+++ b/locales/bg-BG/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "Не можа да се свърже инсталацията. Моля, опитайте отново от Свържете акаунт.","github.pending.title": "Свързване на GitHub инсталация","github.tagline": "Синхронизирайте заявки за изтегляне, CI резултати и рецензии с вашите агенти",+ "linear.connections.connect": "Свържете работното пространство",+ "linear.connections.connectedAs": "Свързан като {{name}} · {{date}}",+ "linear.connections.empty": "Все още няма свързано Linear работно пространство.",+ "linear.connections.enabledBy": "Свързано от {{name}} · {{date}}",+ "linear.connections.notConfigured": "Тази инсталация няма конфигурирано Linear приложение, така че свързването не е възможно. Помолете администратор да зададе променливите на средата за Linear.",+ "linear.connections.openInLinear": "Отворете в Linear",+ "linear.connections.status.connected": "Свързано",+ "linear.connections.title": "Връзки",+ "linear.disconnect.confirm": "Прекъснете връзката",+ "linear.disconnect.content": "Прекъснете връзката с {{account}}? LobeHub вече няма да има достъп до това Linear работно пространство.",+ "linear.disconnect.failed": "Неуспешно прекъсване на връзката. Моля, опитайте отново.",+ "linear.disconnect.success": "Linear връзката е прекъсната",+ "linear.disconnect.title": "Прекъснете връзката с Linear",+ "linear.docsLink": "Прочетете ръководството",+ "linear.installResult.error.access_denied": "Упълномощаването беше отменено в Linear.",+ "linear.installResult.error.exchange_failed": "Linear не прие упълномощаването. Моля, опитайте да се свържете отново.",+ "linear.installResult.error.invalid_state": "Заявката за връзка изтече. Моля, започнете отново от Свържете работното пространство.",+ "linear.installResult.error.missing_code": "Linear не върна код за упълномощаване.",+ "linear.installResult.error.unknown": "Свързването с Linear неуспешно ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "Само членове на работното пространство могат да свържат Linear тук.",+ "linear.installResult.success": "Linear свързан: {{account}}",+ "linear.tagline": "Свържете вашето Linear работно пространство с LobeHub","overview.all": "Всички интеграции","overview.comingSoon": "Очаквайте скоро","overview.description": "Свържете платформите, които вече използвате",diff --git a/locales/de-DE/integration.json b/locales/de-DE/integration.jsonindex 84b1df0be69..42b3cc5a8a3 100644--- a/locales/de-DE/integration.json+++ b/locales/de-DE/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "Die Installation konnte nicht verbunden werden. Bitte versuche es erneut über Konto verbinden.","github.pending.title": "GitHub-Installation verbinden","github.tagline": "Synchronisiere Pull-Anfragen, CI-Ergebnisse und Reviews mit deinen Agenten",+ "linear.connections.connect": "Arbeitsbereich verbinden",+ "linear.connections.connectedAs": "Verbunden als {{name}} · {{date}}",+ "linear.connections.empty": "Noch kein Linear-Arbeitsbereich verbunden.",+ "linear.connections.enabledBy": "Verbunden von {{name}} · {{date}}",+ "linear.connections.notConfigured": "Diese Bereitstellung hat keine Linear-Anwendung konfiguriert, daher ist eine Verbindung nicht möglich. Bitten Sie einen Administrator, die Linear-Umgebungsvariablen einzurichten.",+ "linear.connections.openInLinear": "In Linear öffnen",+ "linear.connections.status.connected": "Verbunden",+ "linear.connections.title": "Verbindungen",+ "linear.disconnect.confirm": "Trennen",+ "linear.disconnect.content": "{{account}} trennen? LobeHub hat dann keinen Zugriff mehr auf diesen Linear-Arbeitsbereich.",+ "linear.disconnect.failed": "Trennen war nicht möglich. Bitte versuchen Sie es erneut.",+ "linear.disconnect.success": "Linear getrennt",+ "linear.disconnect.title": "Linear trennen",+ "linear.docsLink": "Anleitung lesen",+ "linear.installResult.error.access_denied": "Die Autorisierung wurde in Linear abgebrochen.",+ "linear.installResult.error.exchange_failed": "Linear hat die Autorisierung nicht akzeptiert. Bitte versuchen Sie erneut, eine Verbindung herzustellen.",+ "linear.installResult.error.invalid_state": "Die Verbindungsanfrage ist abgelaufen. Bitte starten Sie erneut mit 'Arbeitsbereich verbinden'.",+ "linear.installResult.error.missing_code": "Linear hat keinen Autorisierungscode zurückgegeben.",+ "linear.installResult.error.unknown": "Verbindung zu Linear fehlgeschlagen ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "Nur Arbeitsbereichsmitglieder können Linear hier verbinden.",+ "linear.installResult.success": "Linear verbunden: {{account}}",+ "linear.tagline": "Verbinden Sie Ihren Linear-Arbeitsbereich mit LobeHub","overview.all": "Alle Integrationen","overview.comingSoon": "Demnächst verfügbar","overview.description": "Verbinde die Plattformen, die du bereits nutzt",diff --git a/locales/en-US/integration.json b/locales/en-US/integration.jsonindex 09c7bd81c5e..d73ea085bc8 100644--- a/locales/en-US/integration.json+++ b/locales/en-US/integration.json@@ -44,6 +44,29 @@"github.pending.failed": "Could not connect the installation. Please try again from Connect account.","github.pending.title": "Connect GitHub installation","github.tagline": "Sync pull requests, CI results and reviews with your agents",+ "linear.connections.connect": "Connect workspace",+ "linear.connections.connectedAs": "Connected as {{name}} · {{date}}",+ "linear.connections.empty": "No Linear workspace connected yet.",+ "linear.connections.enabledBy": "Connected by {{name}} · {{date}}",+ "linear.connections.notConfigured": "This deployment has no Linear application configured, so connecting is unavailable. Ask an administrator to set the Linear environment variables.",+ "linear.connections.openInLinear": "Open in Linear",+ "linear.connections.status.connected": "Connected",+ "linear.connections.title": "Connections",+ "linear.disconnect.confirm": "Disconnect",+ "linear.disconnect.content": "Disconnect {{account}}? LobeHub will no longer have access to this Linear workspace.",+ "linear.disconnect.failed": "Could not disconnect. Please try again.",+ "linear.disconnect.success": "Linear disconnected",+ "linear.disconnect.title": "Disconnect Linear",+ "linear.docsLink": "Read the guide",+ "linear.installResult.error.access_denied": "Authorization was cancelled on Linear.",+ "linear.installResult.error.exchange_failed": "Linear did not accept the authorization. Please try connecting again.",+ "linear.installResult.error.invalid_state": "The connection request expired. Please start again from Connect workspace.",+ "linear.installResult.error.missing_code": "Linear did not return an authorization code.",+ "linear.installResult.error.save_failed": "Linear authorized the connection, but LobeHub could not save it. Please try connecting again.",+ "linear.installResult.error.unknown": "Connecting Linear failed ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "Only workspace members can connect Linear here.",+ "linear.installResult.success": "Linear connected: {{account}}",+ "linear.tagline": "Connect your Linear workspace to LobeHub","overview.all": "All integrations","overview.comingSoon": "Coming soon","overview.description": "Connect the platforms you already use",diff --git a/locales/es-ES/integration.json b/locales/es-ES/integration.jsonindex 42e4d1e5230..279694c63ef 100644--- a/locales/es-ES/integration.json+++ b/locales/es-ES/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "No se pudo conectar la instalación. Intenta de nuevo desde Conectar cuenta.","github.pending.title": "Conectar instalación de GitHub","github.tagline": "Sincroniza solicitudes de extracción, resultados de CI y revisiones con tus agentes",+ "linear.connections.connect": "Conectar espacio de trabajo",+ "linear.connections.connectedAs": "Conectado como {{name}} · {{date}}",+ "linear.connections.empty": "Aún no hay ningún espacio de trabajo de Linear conectado.",+ "linear.connections.enabledBy": "Conectado por {{name}} · {{date}}",+ "linear.connections.notConfigured": "Esta implementación no tiene ninguna aplicación de Linear configurada, por lo que la conexión no está disponible. Pide a un administrador que configure las variables de entorno de Linear.",+ "linear.connections.openInLinear": "Abrir en Linear",+ "linear.connections.status.connected": "Conectado",+ "linear.connections.title": "Conexiones",+ "linear.disconnect.confirm": "Desconectar",+ "linear.disconnect.content": "¿Desconectar {{account}}? LobeHub ya no tendrá acceso a este espacio de trabajo de Linear.",+ "linear.disconnect.failed": "No se pudo desconectar. Por favor, inténtalo de nuevo.",+ "linear.disconnect.success": "Linear desconectado",+ "linear.disconnect.title": "Desconectar Linear",+ "linear.docsLink": "Leer la guía",+ "linear.installResult.error.access_denied": "La autorización fue cancelada en Linear.",+ "linear.installResult.error.exchange_failed": "Linear no aceptó la autorización. Por favor, intenta conectar de nuevo.",+ "linear.installResult.error.invalid_state": "La solicitud de conexión expiró. Por favor, comienza de nuevo desde Conectar espacio de trabajo.",+ "linear.installResult.error.missing_code": "Linear no devolvió un código de autorización.",+ "linear.installResult.error.unknown": "La conexión con Linear falló ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "Solo los miembros del espacio de trabajo pueden conectar Linear aquí.",+ "linear.installResult.success": "Linear conectado: {{account}}",+ "linear.tagline": "Conecta tu espacio de trabajo de Linear a LobeHub","overview.all": "Todas las integraciones","overview.comingSoon": "Próximamente","overview.description": "Conecta las plataformas que ya usas",diff --git a/locales/fa-IR/integration.json b/locales/fa-IR/integration.jsonindex 175c6b049d8..66230c8e0fc 100644--- a/locales/fa-IR/integration.json+++ b/locales/fa-IR/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "اتصال نصب امکانپذیر نبود. لطفاً دوباره از اتصال حساب تلاش کنید.","github.pending.title": "اتصال نصب GitHub","github.tagline": "درخواستهای کشش، نتایج CI و بازبینیها را با عوامل خود همگامسازی کنید",+ "linear.connections.connect": "اتصال فضای کاری",+ "linear.connections.connectedAs": "متصل شده به عنوان {{name}} · {{date}}",+ "linear.connections.empty": "هنوز هیچ فضای کاری Linear متصل نشده است.",+ "linear.connections.enabledBy": "متصل شده توسط {{name}} · {{date}}",+ "linear.connections.notConfigured": "این استقرار هیچ برنامه Linear پیکربندی شدهای ندارد، بنابراین اتصال امکانپذیر نیست. از یک مدیر بخواهید متغیرهای محیطی Linear را تنظیم کند.",+ "linear.connections.openInLinear": "باز کردن در Linear",+ "linear.connections.status.connected": "متصل شد",+ "linear.connections.title": "اتصالات",+ "linear.disconnect.confirm": "قطع اتصال",+ "linear.disconnect.content": "قطع اتصال {{account}}؟ LobeHub دیگر به این فضای کاری Linear دسترسی نخواهد داشت.",+ "linear.disconnect.failed": "قطع اتصال انجام نشد. لطفاً دوباره تلاش کنید.",+ "linear.disconnect.success": "Linear قطع شد",+ "linear.disconnect.title": "قطع اتصال Linear",+ "linear.docsLink": "راهنما را بخوانید",+ "linear.installResult.error.access_denied": "مجوز در Linear لغو شد.",+ "linear.installResult.error.exchange_failed": "Linear مجوز را نپذیرفت. لطفاً دوباره تلاش کنید.",+ "linear.installResult.error.invalid_state": "درخواست اتصال منقضی شد. لطفاً دوباره از اتصال فضای کاری شروع کنید.",+ "linear.installResult.error.missing_code": "Linear کد مجوزی بازنگرداند.",+ "linear.installResult.error.unknown": "اتصال به Linear ناموفق بود ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "فقط اعضای فضای کاری میتوانند Linear را اینجا متصل کنند.",+ "linear.installResult.success": "Linear متصل شد: {{account}}",+ "linear.tagline": "فضای کاری Linear خود را به LobeHub متصل کنید","overview.all": "همه یکپارچهسازیها","overview.comingSoon": "به زودی","overview.description": "پلتفرمهایی که از قبل استفاده میکنید را متصل کنید",diff --git a/locales/fr-FR/integration.json b/locales/fr-FR/integration.jsonindex 3dfe0544981..70315c2c286 100644--- a/locales/fr-FR/integration.json+++ b/locales/fr-FR/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "Impossible de connecter l'installation. Veuillez réessayer depuis Connecter le compte.","github.pending.title": "Connecter l'installation GitHub","github.tagline": "Synchronisez les pull requests, les résultats CI et les révisions avec vos agents",+ "linear.connections.connect": "Connecter l'espace de travail",+ "linear.connections.connectedAs": "Connecté en tant que {{name}} · {{date}}",+ "linear.connections.empty": "Aucun espace de travail Linear connecté pour le moment.",+ "linear.connections.enabledBy": "Connecté par {{name}} · {{date}}",+ "linear.connections.notConfigured": "Ce déploiement n'a pas d'application Linear configurée, il est donc impossible de se connecter. Demandez à un administrateur de configurer les variables d'environnement Linear.",+ "linear.connections.openInLinear": "Ouvrir dans Linear",+ "linear.connections.status.connected": "Connecté",+ "linear.connections.title": "Connexions",+ "linear.disconnect.confirm": "Déconnecter",+ "linear.disconnect.content": "Déconnecter {{account}} ? LobeHub n'aura plus accès à cet espace de travail Linear.",+ "linear.disconnect.failed": "Impossible de se déconnecter. Veuillez réessayer.",+ "linear.disconnect.success": "Linear déconnecté",+ "linear.disconnect.title": "Déconnecter Linear",+ "linear.docsLink": "Lire le guide",+ "linear.installResult.error.access_denied": "L'autorisation a été annulée sur Linear.",+ "linear.installResult.error.exchange_failed": "Linear n'a pas accepté l'autorisation. Veuillez réessayer de vous connecter.",+ "linear.installResult.error.invalid_state": "La demande de connexion a expiré. Veuillez recommencer depuis Connecter l'espace de travail.",+ "linear.installResult.error.missing_code": "Linear n'a pas renvoyé de code d'autorisation.",+ "linear.installResult.error.unknown": "La connexion à Linear a échoué ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "Seuls les membres de l'espace de travail peuvent connecter Linear ici.",+ "linear.installResult.success": "Linear connecté : {{account}}",+ "linear.tagline": "Connectez votre espace de travail Linear à LobeHub","overview.all": "Toutes les intégrations","overview.comingSoon": "Bientôt disponible","overview.description": "Connectez les plateformes que vous utilisez déjà",diff --git a/locales/it-IT/integration.json b/locales/it-IT/integration.jsonindex 90512708199..2fa72db9d8f 100644--- a/locales/it-IT/integration.json+++ b/locales/it-IT/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "Impossibile connettere l'installazione. Riprova da Collega account.","github.pending.title": "Connetti installazione GitHub","github.tagline": "Sincronizza pull request, risultati CI e revisioni con i tuoi agenti",+ "linear.connections.connect": "Connetti spazio di lavoro",+ "linear.connections.connectedAs": "Connesso come {{name}} · {{date}}",+ "linear.connections.empty": "Nessuno spazio di lavoro Linear ancora connesso.",+ "linear.connections.enabledBy": "Connesso da {{name}} · {{date}}",+ "linear.connections.notConfigured": "Questa distribuzione non ha alcuna applicazione Linear configurata, quindi la connessione non è disponibile. Chiedi a un amministratore di impostare le variabili d'ambiente di Linear.",+ "linear.connections.openInLinear": "Apri in Linear",+ "linear.connections.status.connected": "Connesso",+ "linear.connections.title": "Connessioni",+ "linear.disconnect.confirm": "Disconnetti",+ "linear.disconnect.content": "Disconnettere {{account}}? LobeHub non avrà più accesso a questo spazio di lavoro Linear.",+ "linear.disconnect.failed": "Impossibile disconnettere. Riprova.",+ "linear.disconnect.success": "Linear disconnesso",+ "linear.disconnect.title": "Disconnetti Linear",+ "linear.docsLink": "Leggi la guida",+ "linear.installResult.error.access_denied": "L'autorizzazione è stata annullata su Linear.",+ "linear.installResult.error.exchange_failed": "Linear non ha accettato l'autorizzazione. Riprova a connetterti.",+ "linear.installResult.error.invalid_state": "La richiesta di connessione è scaduta. Inizia di nuovo da Connetti spazio di lavoro.",+ "linear.installResult.error.missing_code": "Linear non ha restituito un codice di autorizzazione.",+ "linear.installResult.error.unknown": "Connessione a Linear fallita ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "Solo i membri dello spazio di lavoro possono connettere Linear qui.",+ "linear.installResult.success": "Linear connesso: {{account}}",+ "linear.tagline": "Connetti il tuo spazio di lavoro Linear a LobeHub","overview.all": "Tutte le integrazioni","overview.comingSoon": "In arrivo","overview.description": "Connetti le piattaforme che già utilizzi",diff --git a/locales/ja-JP/integration.json b/locales/ja-JP/integration.jsonindex 64200e0df47..109a4eee8ca 100644--- a/locales/ja-JP/integration.json+++ b/locales/ja-JP/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "インストールを接続できませんでした。アカウントを接続から再試行してください。","github.pending.title": "GitHubインストールを接続","github.tagline": "プルリクエスト、CI結果、レビューをエージェントと同期",+ "linear.connections.connect": "ワークスペースを接続",+ "linear.connections.connectedAs": "{{name}} · {{date}} として接続済み",+ "linear.connections.empty": "まだLinearワークスペースが接続されていません。",+ "linear.connections.enabledBy": "{{name}} · {{date}} によって接続されました",+ "linear.connections.notConfigured": "このデプロイメントにはLinearアプリケーションが構成されていないため、接続は利用できません。管理者にLinear環境変数を設定するよう依頼してください。",+ "linear.connections.openInLinear": "Linearで開く",+ "linear.connections.status.connected": "接続済み",+ "linear.connections.title": "接続",+ "linear.disconnect.confirm": "切断",+ "linear.disconnect.content": "{{account}} を切断しますか?LobeHubはこのLinearワークスペースへのアクセスを失います。",+ "linear.disconnect.failed": "切断できませんでした。もう一度お試しください。",+ "linear.disconnect.success": "Linearが切断されました",+ "linear.disconnect.title": "Linearを切断",+ "linear.docsLink": "ガイドを読む",+ "linear.installResult.error.access_denied": "Linearでの認証がキャンセルされました。",+ "linear.installResult.error.exchange_failed": "Linearが認証を受け入れませんでした。もう一度接続を試してください。",+ "linear.installResult.error.invalid_state": "接続リクエストの有効期限が切れました。ワークスペースを接続するところからやり直してください。",+ "linear.installResult.error.missing_code": "Linearが認証コードを返しませんでした。",+ "linear.installResult.error.unknown": "Linearの接続に失敗しました({{code}})。",+ "linear.installResult.error.workspace_forbidden": "ワークスペースメンバーのみがここでLinearを接続できます。",+ "linear.installResult.success": "Linearが接続されました: {{account}}",+ "linear.tagline": "LinearワークスペースをLobeHubに接続","overview.all": "すべての統合","overview.comingSoon": "近日公開","overview.description": "すでに使用しているプラットフォームを接続",diff --git a/locales/ko-KR/integration.json b/locales/ko-KR/integration.jsonindex bbc01fe3810..4327cacda56 100644--- a/locales/ko-KR/integration.json+++ b/locales/ko-KR/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "설치를 연결할 수 없습니다. 계정 연결에서 다시 시도하세요.","github.pending.title": "GitHub 설치 연결","github.tagline": "풀 리퀘스트, CI 결과 및 리뷰를 에이전트와 동기화",+ "linear.connections.connect": "작업 공간 연결",+ "linear.connections.connectedAs": "{{name}} · {{date}}로 연결됨",+ "linear.connections.empty": "아직 연결된 Linear 작업 공간이 없습니다.",+ "linear.connections.enabledBy": "{{name}} · {{date}}에 의해 연결됨",+ "linear.connections.notConfigured": "이 배포에는 Linear 애플리케이션이 구성되어 있지 않아 연결할 수 없습니다. 관리자에게 Linear 환경 변수를 설정하도록 요청하세요.",+ "linear.connections.openInLinear": "Linear에서 열기",+ "linear.connections.status.connected": "연결됨",+ "linear.connections.title": "연결",+ "linear.disconnect.confirm": "연결 해제",+ "linear.disconnect.content": "{{account}}의 연결을 해제하시겠습니까? LobeHub는 더 이상 이 Linear 작업 공간에 액세스할 수 없습니다.",+ "linear.disconnect.failed": "연결을 해제할 수 없습니다. 다시 시도하세요.",+ "linear.disconnect.success": "Linear 연결 해제됨",+ "linear.disconnect.title": "Linear 연결 해제",+ "linear.docsLink": "가이드 읽기",+ "linear.installResult.error.access_denied": "Linear에서 인증이 취소되었습니다.",+ "linear.installResult.error.exchange_failed": "Linear에서 인증을 승인하지 않았습니다. 다시 연결을 시도하세요.",+ "linear.installResult.error.invalid_state": "연결 요청이 만료되었습니다. 작업 공간 연결을 다시 시작하세요.",+ "linear.installResult.error.missing_code": "Linear에서 인증 코드를 반환하지 않았습니다.",+ "linear.installResult.error.unknown": "Linear 연결 실패 ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "작업 공간 멤버만 여기에서 Linear를 연결할 수 있습니다.",+ "linear.installResult.success": "Linear 연결됨: {{account}}",+ "linear.tagline": "Linear 작업 공간을 LobeHub에 연결하세요","overview.all": "모든 통합","overview.comingSoon": "곧 제공 예정","overview.description": "이미 사용 중인 플랫폼을 연결하세요",diff --git a/locales/nl-NL/integration.json b/locales/nl-NL/integration.jsonindex 9ea70be8be2..374f8064370 100644--- a/locales/nl-NL/integration.json+++ b/locales/nl-NL/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "Kon de installatie niet verbinden. Probeer het opnieuw via Account verbinden.","github.pending.title": "GitHub-installatie verbinden","github.tagline": "Synchroniseer pull requests, CI-resultaten en beoordelingen met je agents",+ "linear.connections.connect": "Werkruimte verbinden",+ "linear.connections.connectedAs": "Verbonden als {{name}} · {{date}}",+ "linear.connections.empty": "Nog geen Linear-werkruimte verbonden.",+ "linear.connections.enabledBy": "Verbonden door {{name}} · {{date}}",+ "linear.connections.notConfigured": "Deze implementatie heeft geen Linear-applicatie geconfigureerd, waardoor verbinden niet mogelijk is. Vraag een beheerder om de Linear-omgevingsvariabelen in te stellen.",+ "linear.connections.openInLinear": "Openen in Linear",+ "linear.connections.status.connected": "Verbonden",+ "linear.connections.title": "Verbindingen",+ "linear.disconnect.confirm": "Verbreken",+ "linear.disconnect.content": "Verbreek verbinding met {{account}}? LobeHub heeft dan geen toegang meer tot deze Linear-werkruimte.",+ "linear.disconnect.failed": "Kon de verbinding niet verbreken. Probeer het opnieuw.",+ "linear.disconnect.success": "Linear-verbinding verbroken",+ "linear.disconnect.title": "Linear-verbinding verbreken",+ "linear.docsLink": "Lees de handleiding",+ "linear.installResult.error.access_denied": "Autorisatie werd geannuleerd op Linear.",+ "linear.installResult.error.exchange_failed": "Linear accepteerde de autorisatie niet. Probeer opnieuw te verbinden.",+ "linear.installResult.error.invalid_state": "Het verbindingsverzoek is verlopen. Begin opnieuw vanaf Werkruimte verbinden.",+ "linear.installResult.error.missing_code": "Linear heeft geen autorisatiecode geretourneerd.",+ "linear.installResult.error.unknown": "Verbinding maken met Linear is mislukt ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "Alleen werkruimteleden kunnen hier Linear verbinden.",+ "linear.installResult.success": "Linear verbonden: {{account}}",+ "linear.tagline": "Verbind je Linear-werkruimte met LobeHub","overview.all": "Alle integraties","overview.comingSoon": "Binnenkort beschikbaar","overview.description": "Verbind de platforms die je al gebruikt",diff --git a/locales/pl-PL/integration.json b/locales/pl-PL/integration.jsonindex bd60a2444a4..f1bb2d98705 100644--- a/locales/pl-PL/integration.json+++ b/locales/pl-PL/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "Nie udało się połączyć instalacji. Spróbuj ponownie z opcji Połącz konto.","github.pending.title": "Połącz instalację GitHub","github.tagline": "Synchronizuj pull requesty, wyniki CI i recenzje z twoimi agentami",+ "linear.connections.connect": "Połącz przestrzeń roboczą",+ "linear.connections.connectedAs": "Połączono jako {{name}} · {{date}}",+ "linear.connections.empty": "Nie połączono jeszcze żadnej przestrzeni roboczej Linear.",+ "linear.connections.enabledBy": "Połączono przez {{name}} · {{date}}",+ "linear.connections.notConfigured": "Ta instalacja nie ma skonfigurowanej aplikacji Linear, więc połączenie jest niedostępne. Poproś administratora o ustawienie zmiennych środowiskowych Linear.",+ "linear.connections.openInLinear": "Otwórz w Linear",+ "linear.connections.status.connected": "Połączono",+ "linear.connections.title": "Połączenia",+ "linear.disconnect.confirm": "Odłącz",+ "linear.disconnect.content": "Odłączyć {{account}}? LobeHub nie będzie już miał dostępu do tej przestrzeni roboczej Linear.",+ "linear.disconnect.failed": "Nie udało się odłączyć. Spróbuj ponownie.",+ "linear.disconnect.success": "Linear odłączono",+ "linear.disconnect.title": "Odłącz Linear",+ "linear.docsLink": "Przeczytaj przewodnik",+ "linear.installResult.error.access_denied": "Autoryzacja została anulowana w Linear.",+ "linear.installResult.error.exchange_failed": "Linear nie zaakceptował autoryzacji. Spróbuj połączyć się ponownie.",+ "linear.installResult.error.invalid_state": "Żądanie połączenia wygasło. Rozpocznij ponownie od Połącz przestrzeń roboczą.",+ "linear.installResult.error.missing_code": "Linear nie zwrócił kodu autoryzacyjnego.",+ "linear.installResult.error.unknown": "Połączenie z Linear nie powiodło się ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "Tylko członkowie przestrzeni roboczej mogą połączyć Linear tutaj.",+ "linear.installResult.success": "Linear połączono: {{account}}",+ "linear.tagline": "Połącz swoją przestrzeń roboczą Linear z LobeHub","overview.all": "Wszystkie integracje","overview.comingSoon": "Wkrótce","overview.description": "Połącz platformy, których już używasz",diff --git a/locales/pt-BR/integration.json b/locales/pt-BR/integration.jsonindex 5e4f345d2eb..bae774be51c 100644--- a/locales/pt-BR/integration.json+++ b/locales/pt-BR/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "Não foi possível conectar a instalação. Tente novamente em Conectar conta.","github.pending.title": "Conectar instalação do GitHub","github.tagline": "Sincronize pull requests, resultados de CI e revisões com seus agentes",+ "linear.connections.connect": "Conectar espaço de trabalho",+ "linear.connections.connectedAs": "Conectado como {{name}} · {{date}}",+ "linear.connections.empty": "Nenhum espaço de trabalho Linear conectado ainda.",+ "linear.connections.enabledBy": "Conectado por {{name}} · {{date}}",+ "linear.connections.notConfigured": "Esta implantação não possui uma aplicação Linear configurada, portanto, a conexão não está disponível. Peça a um administrador para configurar as variáveis de ambiente do Linear.",+ "linear.connections.openInLinear": "Abrir no Linear",+ "linear.connections.status.connected": "Conectado",+ "linear.connections.title": "Conexões",+ "linear.disconnect.confirm": "Desconectar",+ "linear.disconnect.content": "Desconectar {{account}}? O LobeHub não terá mais acesso a este espaço de trabalho Linear.",+ "linear.disconnect.failed": "Não foi possível desconectar. Por favor, tente novamente.",+ "linear.disconnect.success": "Linear desconectado",+ "linear.disconnect.title": "Desconectar Linear",+ "linear.docsLink": "Leia o guia",+ "linear.installResult.error.access_denied": "A autorização foi cancelada no Linear.",+ "linear.installResult.error.exchange_failed": "O Linear não aceitou a autorização. Por favor, tente conectar novamente.",+ "linear.installResult.error.invalid_state": "A solicitação de conexão expirou. Por favor, comece novamente em Conectar espaço de trabalho.",+ "linear.installResult.error.missing_code": "O Linear não retornou um código de autorização.",+ "linear.installResult.error.unknown": "Falha ao conectar o Linear ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "Apenas membros do espaço de trabalho podem conectar o Linear aqui.",+ "linear.installResult.success": "Linear conectado: {{account}}",+ "linear.tagline": "Conecte seu espaço de trabalho Linear ao LobeHub","overview.all": "Todas as integrações","overview.comingSoon": "Em breve","overview.description": "Conecte as plataformas que você já usa",diff --git a/locales/ru-RU/integration.json b/locales/ru-RU/integration.jsonindex 357126c83b1..037ccd2ddbc 100644--- a/locales/ru-RU/integration.json+++ b/locales/ru-RU/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "Не удалось подключить установку. Попробуйте снова через Подключить аккаунт.","github.pending.title": "Подключить установку GitHub","github.tagline": "Синхронизируйте запросы на слияние, результаты CI и рецензии с вашими агентами",+ "linear.connections.connect": "Подключить рабочую область",+ "linear.connections.connectedAs": "Подключено как {{name}} · {{date}}",+ "linear.connections.empty": "Рабочая область Linear еще не подключена.",+ "linear.connections.enabledBy": "Подключено {{name}} · {{date}}",+ "linear.connections.notConfigured": "Для этого развертывания не настроено приложение Linear, поэтому подключение недоступно. Попросите администратора установить переменные среды Linear.",+ "linear.connections.openInLinear": "Открыть в Linear",+ "linear.connections.status.connected": "Подключено",+ "linear.connections.title": "Подключения",+ "linear.disconnect.confirm": "Отключить",+ "linear.disconnect.content": "Отключить {{account}}? LobeHub больше не будет иметь доступ к этой рабочей области Linear.",+ "linear.disconnect.failed": "Не удалось отключить. Пожалуйста, попробуйте снова.",+ "linear.disconnect.success": "Linear отключен",+ "linear.disconnect.title": "Отключить Linear",+ "linear.docsLink": "Прочитать руководство",+ "linear.installResult.error.access_denied": "Авторизация была отменена в Linear.",+ "linear.installResult.error.exchange_failed": "Linear не принял авторизацию. Пожалуйста, попробуйте подключиться снова.",+ "linear.installResult.error.invalid_state": "Запрос на подключение истек. Пожалуйста, начните заново с Подключить рабочую область.",+ "linear.installResult.error.missing_code": "Linear не вернул код авторизации.",+ "linear.installResult.error.unknown": "Не удалось подключить Linear ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "Только участники рабочей области могут подключить Linear здесь.",+ "linear.installResult.success": "Linear подключен: {{account}}",+ "linear.tagline": "Подключите свою рабочую область Linear к LobeHub","overview.all": "Все интеграции","overview.comingSoon": "Скоро","overview.description": "Подключите платформы, которые вы уже используете",diff --git a/locales/tr-TR/integration.json b/locales/tr-TR/integration.jsonindex 9e16291e420..8a656bd88b8 100644--- a/locales/tr-TR/integration.json+++ b/locales/tr-TR/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "Yükleme bağlanamadı. Lütfen Hesabı bağla üzerinden tekrar deneyin.","github.pending.title": "GitHub yüklemesini bağla","github.tagline": "Çekme isteklerini, CI sonuçlarını ve incelemeleri ajanlarınızla senkronize edin",+ "linear.connections.connect": "Çalışma alanını bağla",+ "linear.connections.connectedAs": "{{name}} olarak bağlandı · {{date}}",+ "linear.connections.empty": "Henüz bir Linear çalışma alanı bağlanmadı.",+ "linear.connections.enabledBy": "{{name}} tarafından bağlandı · {{date}}",+ "linear.connections.notConfigured": "Bu dağıtımda herhangi bir Linear uygulaması yapılandırılmadı, bu nedenle bağlanma mümkün değil. Bir yöneticiden Linear ortam değişkenlerini ayarlamasını isteyin.",+ "linear.connections.openInLinear": "Linear'da aç",+ "linear.connections.status.connected": "Bağlandı",+ "linear.connections.title": "Bağlantılar",+ "linear.disconnect.confirm": "Bağlantıyı kes",+ "linear.disconnect.content": "{{account}} bağlantısını kes? LobeHub artık bu Linear çalışma alanına erişemeyecek.",+ "linear.disconnect.failed": "Bağlantı kesilemedi. Lütfen tekrar deneyin.",+ "linear.disconnect.success": "Linear bağlantısı kesildi",+ "linear.disconnect.title": "Linear Bağlantısını Kes",+ "linear.docsLink": "Kılavuzu oku",+ "linear.installResult.error.access_denied": "Yetkilendirme Linear üzerinde iptal edildi.",+ "linear.installResult.error.exchange_failed": "Linear yetkilendirmeyi kabul etmedi. Lütfen tekrar bağlanmayı deneyin.",+ "linear.installResult.error.invalid_state": "Bağlantı isteğinin süresi doldu. Lütfen Çalışma alanını bağla işlemine yeniden başlayın.",+ "linear.installResult.error.missing_code": "Linear bir yetkilendirme kodu döndürmedi.",+ "linear.installResult.error.unknown": "Linear bağlanamadı ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "Sadece çalışma alanı üyeleri burada Linear'ı bağlayabilir.",+ "linear.installResult.success": "Linear bağlandı: {{account}}",+ "linear.tagline": "Linear çalışma alanınızı LobeHub'a bağlayın","overview.all": "Tüm entegrasyonlar","overview.comingSoon": "Yakında geliyor","overview.description": "Zaten kullandığınız platformları bağlayın",diff --git a/locales/vi-VN/integration.json b/locales/vi-VN/integration.jsonindex 38369dcb307..380511dea77 100644--- a/locales/vi-VN/integration.json+++ b/locales/vi-VN/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "Không thể kết nối cài đặt. Vui lòng thử lại từ Kết nối tài khoản.","github.pending.title": "Kết nối cài đặt GitHub","github.tagline": "Đồng bộ pull request, kết quả CI và đánh giá với các agent của bạn",+ "linear.connections.connect": "Kết nối không gian làm việc",+ "linear.connections.connectedAs": "Đã kết nối dưới tên {{name}} · {{date}}",+ "linear.connections.empty": "Chưa có không gian làm việc Linear nào được kết nối.",+ "linear.connections.enabledBy": "Được kết nối bởi {{name}} · {{date}}",+ "linear.connections.notConfigured": "Triển khai này chưa được cấu hình ứng dụng Linear, vì vậy việc kết nối không khả dụng. Hãy yêu cầu quản trị viên thiết lập các biến môi trường Linear.",+ "linear.connections.openInLinear": "Mở trong Linear",+ "linear.connections.status.connected": "Đã kết nối",+ "linear.connections.title": "Kết nối",+ "linear.disconnect.confirm": "Ngắt kết nối",+ "linear.disconnect.content": "Ngắt kết nối {{account}}? LobeHub sẽ không còn quyền truy cập vào không gian làm việc Linear này.",+ "linear.disconnect.failed": "Không thể ngắt kết nối. Vui lòng thử lại.",+ "linear.disconnect.success": "Đã ngắt kết nối Linear",+ "linear.disconnect.title": "Ngắt kết nối Linear",+ "linear.docsLink": "Đọc hướng dẫn",+ "linear.installResult.error.access_denied": "Quyền ủy quyền đã bị hủy trên Linear.",+ "linear.installResult.error.exchange_failed": "Linear không chấp nhận quyền ủy quyền. Vui lòng thử kết nối lại.",+ "linear.installResult.error.invalid_state": "Yêu cầu kết nối đã hết hạn. Vui lòng bắt đầu lại từ Kết nối không gian làm việc.",+ "linear.installResult.error.missing_code": "Linear không trả về mã ủy quyền.",+ "linear.installResult.error.unknown": "Kết nối Linear thất bại ({{code}}).",+ "linear.installResult.error.workspace_forbidden": "Chỉ thành viên không gian làm việc mới có thể kết nối Linear tại đây.",+ "linear.installResult.success": "Linear đã được kết nối: {{account}}",+ "linear.tagline": "Kết nối không gian làm việc Linear của bạn với LobeHub","overview.all": "Tất cả tích hợp","overview.comingSoon": "Sắp ra mắt","overview.description": "Kết nối các nền tảng bạn đã sử dụng",diff --git a/locales/zh-CN/integration.json b/locales/zh-CN/integration.jsonindex 15122c0be61..ee483e2d9ed 100644--- a/locales/zh-CN/integration.json+++ b/locales/zh-CN/integration.json@@ -44,6 +44,29 @@"github.pending.failed": "连接安装失败,请从「连接账号」重试。","github.pending.title": "连接 GitHub 安装","github.tagline": "把 Pull Request、CI 结果和评审同步给你的智能体",+ "linear.connections.connect": "连接工作区",+ "linear.connections.connectedAs": "以 {{name}} 身份连接 · {{date}}",+ "linear.connections.empty": "尚未连接 Linear 工作区。",+ "linear.connections.enabledBy": "由 {{name}} 连接 · {{date}}",+ "linear.connections.notConfigured": "当前部署未配置 Linear 应用,暂时无法连接。请联系管理员设置 Linear 相关环境变量。",+ "linear.connections.openInLinear": "在 Linear 中打开",+ "linear.connections.status.connected": "已连接",+ "linear.connections.title": "连接",+ "linear.disconnect.confirm": "断开连接",+ "linear.disconnect.content": "确定断开 {{account}} 吗?断开后 LobeHub 将不再能访问该 Linear 工作区。",+ "linear.disconnect.failed": "断开连接失败,请重试。",+ "linear.disconnect.success": "已断开 Linear",+ "linear.disconnect.title": "断开 Linear",+ "linear.docsLink": "查看指南",+ "linear.installResult.error.access_denied": "已在 Linear 上取消授权。",+ "linear.installResult.error.exchange_failed": "Linear 未接受此次授权,请重新连接。",+ "linear.installResult.error.invalid_state": "连接请求已过期,请重新点击「连接工作区」。",+ "linear.installResult.error.missing_code": "Linear 未返回授权码。",+ "linear.installResult.error.save_failed": "Linear 已授权,但 LobeHub 未能保存此次连接,请重新连接。",+ "linear.installResult.error.unknown": "连接 Linear 失败({{code}})。",+ "linear.installResult.error.workspace_forbidden": "只有工作区成员可以在此连接 Linear。",+ "linear.installResult.success": "已连接 Linear:{{account}}",+ "linear.tagline": "将你的 Linear 工作区连接到 LobeHub","overview.all": "全部集成","overview.comingSoon": "即将支持","overview.description": "连接到你正在使用的平台",diff --git a/locales/zh-TW/integration.json b/locales/zh-TW/integration.jsonindex 333c8dcc695..076d7b72065 100644--- a/locales/zh-TW/integration.json+++ b/locales/zh-TW/integration.json@@ -44,6 +44,28 @@"github.pending.failed": "無法連接安裝。請從“連接帳戶”重新嘗試。","github.pending.title": "連接 GitHub 安裝","github.tagline": "將拉取請求、CI 結果和審核與您的代理同步",+ "linear.connections.connect": "連接工作區",+ "linear.connections.connectedAs": "已連接為 {{name}} · {{date}}",+ "linear.connections.empty": "尚未連接任何 Linear 工作區。",+ "linear.connections.enabledBy": "由 {{name}} 連接 · {{date}}",+ "linear.connections.notConfigured": "此部署尚未配置 Linear 應用程式,因此無法連接。請要求管理員設置 Linear 環境變數。",+ "linear.connections.openInLinear": "在 Linear 中打開",+ "linear.connections.status.connected": "已連接",+ "linear.connections.title": "連接",+ "linear.disconnect.confirm": "斷開連接",+ "linear.disconnect.content": "斷開 {{account}} 的連接?LobeHub 將不再能訪問此 Linear 工作區。",+ "linear.disconnect.failed": "無法斷開連接。請再試一次。",+ "linear.disconnect.success": "Linear 已斷開連接",+ "linear.disconnect.title": "斷開 Linear",+ "linear.docsLink": "閱讀指南",+ "linear.installResult.error.access_denied": "在 Linear 上取消了授權。",+ "linear.installResult.error.exchange_failed": "Linear 未接受授權。請重試連接。",+ "linear.installResult.error.invalid_state": "連接請求已過期。請從“連接工作區”重新開始。",+ "linear.installResult.error.missing_code": "Linear 未返回授權碼。",+ "linear.installResult.error.unknown": "連接 Linear 失敗({{code}})。",+ "linear.installResult.error.workspace_forbidden": "只有工作區成員可以在此處連接 Linear。",+ "linear.installResult.success": "Linear 已連接:{{account}}",+ "linear.tagline": "將您的 Linear 工作區連接到 LobeHub","overview.all": "所有整合","overview.comingSoon": "即將推出","overview.description": "連接您已經使用的平台",diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 86ba335cc8a..21c47778012 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -240,6 +240,8 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRuleklavis: 'blocked',knowledge: rw('knowledge:read', 'knowledge:write'),knowledgeBase: rw('knowledge:read', 'knowledge:write'),+ // Linear OAuth connections hold workspace tokens and are managed from Settings+ linear: 'blocked',llmGenerationTracing: 'blocked',market: rw('agent:read', 'agent:write'),// tool execution inside a chat rundiff --git a/packages/database/src/models/linear/__tests__/connection.test.ts b/packages/database/src/models/linear/__tests__/connection.test.tsnew file mode 100644index 00000000000..7480a0c9b91--- /dev/null+++ b/packages/database/src/models/linear/__tests__/connection.test.ts@@ -0,0 +1,132 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { linearConnections, users, workspaces } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { LinearConnectionModel } from '../connection';++const db: LobeChatDatabase = await getTestDB();++const userId = 'linear-conn-user';+const otherUserId = 'linear-conn-other';+const workspaceId = 'linear-conn-ws';++const organization = {+ actorExternalId: 'linear-user-1',+ actorName: 'Ada',+ organizationId: 'org-1',+ organizationName: 'Acme',+ organizationUrlKey: 'acme',+};++/** Reversible stand-in for KeyVaultsGateKeeper. */+const gateKeeper = {+ decrypt: async (ciphertext: string) => ({ plaintext: ciphertext.replace(/^enc:/, '') }),+ encrypt: async (plaintext: string) => `enc:${plaintext}`,+};++beforeEach(async () => {+ await db.delete(linearConnections);+ await db.delete(users);+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await db+ .insert(workspaces)+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });+});++afterEach(async () => {+ await db.delete(linearConnections);+ await db.delete(users);+});++describe('LinearConnectionModel', () => {+ it('stores the token encrypted and decrypts it on read', async () => {+ const row = await LinearConnectionModel.upsert(+ db,+ { ...organization, credentials: { accessToken: 'tok', refreshToken: 'ref' }, userId },+ gateKeeper,+ );++ expect(row.credentials).toBe('enc:{"accessToken":"tok","refreshToken":"ref"}');+ expect(row).toMatchObject({ metadata: {}, revokedAt: null, workspaceId: null });++ const decrypted = await LinearConnectionModel.findDecryptedById(db, row.id, gateKeeper);+ expect(decrypted?.credentials).toEqual({ accessToken: 'tok', refreshToken: 'ref' });+ });++ it('re-authorizing the same organization from the same scope refreshes the row', async () => {+ const first = await LinearConnectionModel.upsert(db, {+ ...organization,+ credentials: { accessToken: 'old' },+ userId,+ });+ await LinearConnectionModel.revoke(db, first.id);++ const second = await LinearConnectionModel.upsert(db, {+ ...organization,+ credentials: { accessToken: 'new' },+ organizationName: 'Acme Inc',+ userId,+ });++ expect(second.id).toBe(first.id);+ expect(second.revokedAt).toBeNull();+ expect(second.organizationName).toBe('Acme Inc');+ expect(JSON.parse(second.credentials!)).toEqual({ accessToken: 'new' });+ });++ it('keeps personal and workspace connections to one organization apart', async () => {+ const personal = await LinearConnectionModel.upsert(db, {+ ...organization,+ credentials: { accessToken: 'a' },+ userId,+ });+ const workspace = await LinearConnectionModel.upsert(db, {+ ...organization,+ credentials: { accessToken: 'b' },+ userId,+ workspaceId,+ });++ expect(workspace.id).not.toBe(personal.id);++ const personalList = await LinearConnectionModel.listByScope(db, { userId });+ expect(personalList.map((row) => row.id)).toEqual([personal.id]);++ // Workspace scope lists every member's connection, not only the caller's.+ const workspaceList = await LinearConnectionModel.listByScope(db, {+ userId: otherUserId,+ workspaceId,+ });+ expect(workspaceList.map((row) => row.id)).toEqual([workspace.id]);+ });++ it('revoking drops the token and hides the connection', async () => {+ const row = await LinearConnectionModel.upsert(db, {+ ...organization,+ credentials: { accessToken: 'a' },+ tokenExpiresAt: new Date(),+ userId,+ });++ await LinearConnectionModel.revoke(db, row.id);++ const revoked = await LinearConnectionModel.findById(db, row.id);+ expect(revoked).toMatchObject({ credentials: null, tokenExpiresAt: null });+ expect(revoked?.revokedAt).toBeInstanceOf(Date);+ expect(await LinearConnectionModel.listByScope(db, { userId })).toEqual([]);+ });++ it('exposes a view without credentials', async () => {+ const row = await LinearConnectionModel.upsert(db, {+ ...organization,+ credentials: { accessToken: 'a' },+ userId,+ });++ const view = LinearConnectionModel.toView((await LinearConnectionModel.findById(db, row.id))!);+ expect(view).not.toHaveProperty('credentials');+ expect(view).toMatchObject({ organizationName: 'Acme', userId });+ });+});diff --git a/packages/database/src/models/linear/connection.ts b/packages/database/src/models/linear/connection.tsnew file mode 100644index 00000000000..804a5578ba8--- /dev/null+++ b/packages/database/src/models/linear/connection.ts@@ -0,0 +1,180 @@+import type {+ LinearConnectionCredentials,+ LinearConnectionMetadata,+ LinearConnectionView,+} from '@lobechat/types';+import { and, desc, eq, isNull } from 'drizzle-orm';++import type { LinearConnectionItem } from '../../schemas';+import { linearConnections } from '../../schemas';+import type { LobeChatDatabase } from '../../type';++interface GateKeeper {+ decrypt: (ciphertext: string) => Promise<{ plaintext: string }>;+ encrypt: (plaintext: string) => Promise<string>;+}++export interface LinearConnectionScope {+ userId: string;+ workspaceId?: string | null;+}++export interface LinearUpsertConnectionParams extends LinearConnectionScope {+ actorExternalId: string;+ actorName: string;+ credentials: LinearConnectionCredentials;+ metadata?: LinearConnectionMetadata;+ organizationId: string;+ organizationName: string;+ organizationUrlKey: string;+ tokenExpiresAt?: Date | null;+}++export type LinearDecryptedConnection = Omit<LinearConnectionItem, 'credentials'> & {+ credentials: LinearConnectionCredentials | null;+};++/**+ * CRUD for `linear_connections`. Callers are server-side (the OAuth callback+ * and the settings router), so like the SCM models it exposes+ * static methods taking the db; the row's scope is who the connection+ * belongs to, not the caller's identity.+ */+export class LinearConnectionModel {+ static findById = async (+ db: LobeChatDatabase,+ id: string,+ ): Promise<LinearConnectionItem | null> => {+ const [row] = await db.select().from(linearConnections).where(eq(linearConnections.id, id));+ return row ?? null;+ };++ /** The row with its token decrypted, for the server code that calls Linear. */+ static findDecryptedById = async (+ db: LobeChatDatabase,+ id: string,+ gateKeeper?: GateKeeper,+ ): Promise<LinearDecryptedConnection | null> => {+ const row = await LinearConnectionModel.findById(db, id);+ return row ? decryptRow(row, gateKeeper) : null;+ };++ /** Active connections visible to a scope: the workspace's, or the user's personal ones. */+ static listByScope = async (+ db: LobeChatDatabase,+ scope: LinearConnectionScope,+ ): Promise<LinearConnectionItem[]> =>+ db+ .select()+ .from(linearConnections)+ .where(and(scopeCondition(scope), isNull(linearConnections.revokedAt)))+ .orderBy(desc(linearConnections.createdAt));++ /**+ * Store a fresh authorization. Re-authorizing an organization from the+ * same scope refreshes that row in place and clears an earlier disconnect.+ */+ static upsert = async (+ db: LobeChatDatabase,+ params: LinearUpsertConnectionParams,+ gateKeeper?: GateKeeper,+ ): Promise<LinearConnectionItem> => {+ const workspaceId = params.workspaceId ?? null;+ const values = {+ actorExternalId: params.actorExternalId,+ actorName: params.actorName,+ credentials: await encryptCredentials(params.credentials, gateKeeper),+ metadata: params.metadata ?? {},+ organizationId: params.organizationId,+ organizationName: params.organizationName,+ organizationUrlKey: params.organizationUrlKey,+ revokedAt: null,+ tokenExpiresAt: params.tokenExpiresAt ?? null,+ userId: params.userId,+ workspaceId,+ };++ const [existing] = await db+ .select({ id: linearConnections.id })+ .from(linearConnections)+ .where(+ and(+ eq(linearConnections.organizationId, params.organizationId),+ eq(linearConnections.userId, params.userId),+ workspaceId+ ? eq(linearConnections.workspaceId, workspaceId)+ : isNull(linearConnections.workspaceId),+ ),+ )+ .limit(1);++ if (existing) {+ const [row] = await db+ .update(linearConnections)+ .set({ ...values, updatedAt: new Date() })+ .where(eq(linearConnections.id, existing.id))+ .returning();+ return row;+ }++ const [row] = await db.insert(linearConnections).values(values).returning();+ return row;+ };++ /** Disconnect: drop the token and hide the row. A reconnect reuses it. */+ static revoke = async (db: LobeChatDatabase, id: string): Promise<void> => {+ await db+ .update(linearConnections)+ .set({+ credentials: null,+ revokedAt: new Date(),+ tokenExpiresAt: null,+ updatedAt: new Date(),+ })+ .where(eq(linearConnections.id, id));+ };++ /** What the client may see: everything but the token. */+ static toView = (row: LinearConnectionItem): LinearConnectionView => ({+ actorExternalId: row.actorExternalId,+ actorName: row.actorName,+ createdAt: row.createdAt,+ id: row.id,+ metadata: row.metadata,+ organizationId: row.organizationId,+ organizationName: row.organizationName,+ organizationUrlKey: row.organizationUrlKey,+ userId: row.userId,+ workspaceId: row.workspaceId,+ });+}++const scopeCondition = (scope: LinearConnectionScope) =>+ scope.workspaceId+ ? eq(linearConnections.workspaceId, scope.workspaceId)+ : and(eq(linearConnections.userId, scope.userId), isNull(linearConnections.workspaceId));++const encryptCredentials = async (+ credentials: LinearConnectionCredentials,+ gateKeeper?: GateKeeper,+): Promise<string> => {+ const plaintext = JSON.stringify(credentials);+ return gateKeeper ? gateKeeper.encrypt(plaintext) : plaintext;+};++const decryptRow = async (+ row: LinearConnectionItem,+ gateKeeper?: GateKeeper,+): Promise<LinearDecryptedConnection> => {+ if (!row.credentials) return { ...row, credentials: null };++ const plaintext = gateKeeper+ ? (await gateKeeper.decrypt(row.credentials)).plaintext+ : row.credentials;++ try {+ return { ...row, credentials: JSON.parse(plaintext) as LinearConnectionCredentials };+ } catch {+ return { ...row, credentials: null };+ }+};diff --git a/packages/database/src/models/linear/index.ts b/packages/database/src/models/linear/index.tsnew file mode 100644index 00000000000..0fb32617504--- /dev/null+++ b/packages/database/src/models/linear/index.ts@@ -0,0 +1 @@+export * from './connection';diff --git a/packages/env/src/linear.ts b/packages/env/src/linear.tsnew file mode 100644index 00000000000..6d2def63fc5--- /dev/null+++ b/packages/env/src/linear.ts@@ -0,0 +1,30 @@+import { createEnv } from '@t3-oss/env-core';+import { z } from 'zod';++declare global {+ // eslint-disable-next-line @typescript-eslint/no-namespace+ namespace NodeJS {+ interface ProcessEnv {+ /** Client id of the LobeHub OAuth application registered on Linear. */+ LINEAR_CLIENT_ID?: string;+ LINEAR_CLIENT_SECRET?: string;+ }+ }+}++export const getLinearConfig = () =>+ createEnv({+ runtimeEnv: {+ ENABLED_LINEAR: !!process.env.LINEAR_CLIENT_ID && !!process.env.LINEAR_CLIENT_SECRET,+ LINEAR_CLIENT_ID: process.env.LINEAR_CLIENT_ID,+ LINEAR_CLIENT_SECRET: process.env.LINEAR_CLIENT_SECRET,+ },+ server: {+ /** True when the OAuth application is configured and Linear can be connected. */+ ENABLED_LINEAR: z.boolean(),+ LINEAR_CLIENT_ID: z.string().optional(),+ LINEAR_CLIENT_SECRET: z.string().optional(),+ },+ });++export const linearEnv = getLinearConfig();diff --git a/packages/locales/src/default/integration.ts b/packages/locales/src/default/integration.tsindex 7f55ffa44c0..32636745ae3 100644--- a/packages/locales/src/default/integration.ts+++ b/packages/locales/src/default/integration.ts@@ -58,6 +58,35 @@ export default {'Could not connect the installation. Please try again from Connect account.','github.pending.title': 'Connect GitHub installation','github.tagline': 'Sync pull requests, CI results and reviews with your agents',+ 'linear.connections.connect': 'Connect workspace',+ 'linear.connections.connectedAs': 'Connected as {{name}} · {{date}}',+ 'linear.connections.empty': 'No Linear workspace connected yet.',+ 'linear.connections.enabledBy': 'Connected by {{name}} · {{date}}',+ 'linear.connections.notConfigured':+ 'This deployment has no Linear application configured, so connecting is unavailable. Ask an administrator to set the Linear environment variables.',+ 'linear.connections.openInLinear': 'Open in Linear',+ 'linear.connections.status.connected': 'Connected',+ 'linear.connections.title': 'Connections',+ 'linear.disconnect.confirm': 'Disconnect',+ 'linear.disconnect.content':+ 'Disconnect {{account}}? LobeHub will no longer have access to this Linear workspace.',+ 'linear.disconnect.failed': 'Could not disconnect. Please try again.',+ 'linear.disconnect.success': 'Linear disconnected',+ 'linear.disconnect.title': 'Disconnect Linear',+ 'linear.docsLink': 'Read the guide',+ 'linear.installResult.error.access_denied': 'Authorization was cancelled on Linear.',+ 'linear.installResult.error.exchange_failed':+ 'Linear did not accept the authorization. Please try connecting again.',+ 'linear.installResult.error.invalid_state':+ 'The connection request expired. Please start again from Connect workspace.',+ 'linear.installResult.error.missing_code': 'Linear did not return an authorization code.',+ 'linear.installResult.error.save_failed':+ 'Linear authorized the connection, but LobeHub could not save it. Please try connecting again.',+ 'linear.installResult.error.unknown': 'Connecting Linear failed ({{code}}).',+ 'linear.installResult.error.workspace_forbidden':+ 'Only workspace members can connect Linear here.',+ 'linear.installResult.success': 'Linear connected: {{account}}',+ 'linear.tagline': 'Connect your Linear workspace to LobeHub','overview.all': 'All integrations','overview.comingSoon': 'Coming soon','overview.description': 'Connect the platforms you already use',diff --git a/src/features/Integrations/Linear/Connections.tsx b/src/features/Integrations/Linear/Connections.tsxnew file mode 100644index 00000000000..79f37a3456f--- /dev/null+++ b/src/features/Integrations/Linear/Connections.tsx@@ -0,0 +1,186 @@+'use client';++import type { LinearConnectionView } from '@lobechat/types';+import {+ Avatar,+ Block,+ Button,+ confirmModal,+ createStaticStyles,+ DropdownMenu,+ Flexbox,+ Icon,+ Text,+ toast,+} from '@lobehub/ui';+import { ChevronDownIcon, PlusIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { linearService } from '@/services/linear';++const styles = createStaticStyles(({ css, cssVar }) => ({+ card: css`+ padding-block: 12px;+ padding-inline: 16px;+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorFillQuaternary};+ `,+ dot: css`+ display: inline-block;+ flex: none;++ width: 6px;+ height: 6px;+ border-radius: 50%;++ background: ${cssVar.colorSuccess};+ `,+ emptyState: css`+ padding-block: 24px;+ padding-inline: 20px;+ border-radius: ${cssVar.borderRadiusLG};++ color: ${cssVar.colorTextSecondary};+ text-align: center;++ background: ${cssVar.colorFillQuaternary};+ `,+ status: css`+ cursor: pointer;+ user-select: none;++ display: inline-flex;+ gap: 8px;+ align-items: center;++ padding-block: 4px;+ padding-inline: 8px;+ border-radius: ${cssVar.borderRadiusSM};++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+}));++interface ConnectionsProps {+ /** False when the deployment has no Linear OAuth application; connecting is impossible. */+ configured: boolean;+ connections: LinearConnectionView[];+ installHref?: string;+ onChanged: () => void;+ /** Workspace rows say who connected them; personal rows belong to the viewer. */+ scope: 'personal' | 'workspace';+}++/** Every Linear workspace connected in this scope. */+const Connections = memo<ConnectionsProps>(+ ({ configured, connections, installHref, onChanged, scope }) => {+ const { t } = useTranslation('integration');++ const disconnect = (connection: LinearConnectionView) => {+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('linear.disconnect.content', { account: connection.organizationName }),+ okButtonProps: { danger: true },+ okText: t('linear.disconnect.confirm'),+ onOk: async () => {+ try {+ await linearService.disconnect(connection.id);+ toast.success(t('linear.disconnect.success'));+ onChanged();+ } catch {+ toast.error(t('linear.disconnect.failed'));+ }+ },+ title: t('linear.disconnect.title'),+ });+ };++ return (+ <Flexbox gap={10}>+ <Flexbox horizontal align="center" gap={16} justify="space-between">+ <Text strong style={{ fontSize: 16 }}>+ {t('linear.connections.title')}+ </Text>+ <Button+ disabled={!installHref}+ href={installHref}+ icon={<Icon icon={PlusIcon} />}+ size="small"+ type={connections.length > 0 ? 'default' : 'primary'}+ >+ {t('linear.connections.connect')}+ </Button>+ </Flexbox>++ {configured ? null : (+ <Text style={{ fontSize: 13 }} type="secondary">+ {t('linear.connections.notConfigured')}+ </Text>+ )}++ {connections.length === 0 ? (+ <div className={styles.emptyState}>{t('linear.connections.empty')}</div>+ ) : (+ connections.map((connection) => {+ const date = new Date(connection.createdAt).toLocaleDateString();+ const detail =+ scope === 'workspace'+ ? t('linear.connections.enabledBy', { date, name: connection.actorName })+ : t('linear.connections.connectedAs', { date, name: connection.actorName });+ return (+ <Block className={styles.card} key={connection.id} variant={'filled'}>+ <Flexbox horizontal align="center" gap={12}>+ <Avatar+ avatar={connection.metadata.organizationLogoUrl ?? undefined}+ size={36}+ title={connection.organizationName}+ />+ <Flexbox flex={1} gap={1} style={{ minWidth: 0 }}>+ <Text strong>{connection.organizationName}</Text>+ <Text style={{ fontSize: 13 }} type="secondary">+ {detail}+ </Text>+ </Flexbox>+ <DropdownMenu+ placement="bottomRight"+ items={[+ {+ key: 'open',+ label: t('linear.connections.openInLinear'),+ onClick: () =>+ window.open(+ `https://linear.app/${connection.organizationUrlKey}`,+ '_blank',+ 'noreferrer',+ ),+ },+ {+ danger: true,+ key: 'disconnect',+ label: t('linear.disconnect.confirm'),+ onClick: () => disconnect(connection),+ },+ ]}+ >+ <span className={styles.status}>+ <span className={styles.dot} />+ <Text>{t('linear.connections.status.connected')}</Text>+ <Icon icon={ChevronDownIcon} size="small" />+ </span>+ </DropdownMenu>+ </Flexbox>+ </Block>+ );+ })+ )}+ </Flexbox>+ );+ },+);++Connections.displayName = 'LinearIntegrationConnections';++export default Connections;diff --git a/src/features/Integrations/Linear/LinearIcon.tsx b/src/features/Integrations/Linear/LinearIcon.tsxnew file mode 100644index 00000000000..6636c8a885d--- /dev/null+++ b/src/features/Integrations/Linear/LinearIcon.tsx@@ -0,0 +1,26 @@+import { memo } from 'react';++interface LinearIconProps {+ size?: number;+ style?: React.CSSProperties;+}++/** Linear's logomark; `@lobehub/icons` has no Linear brand yet. */+const LinearIcon = memo<LinearIconProps>(({ size = 24, style }) => (+ <svg+ aria-label="Linear"+ fill="currentColor"+ height={size}+ role="img"+ style={{ flex: 'none', lineHeight: 1, ...style }}+ viewBox="0 0 100 100"+ width={size}+ xmlns="http://www.w3.org/2000/svg"+ >+ <path d="M1.22541 61.5228c-.2225-.9485.90748-1.5459 1.59638-.857L39.3342 97.1782c.6889.6889.0915 1.8189-.857 1.5964C20.0515 94.4522 5.54779 79.9485 1.22541 61.5228ZM.00189135 46.8891c-.01764375.2833.08887215.5599.28957165.7606L52.3503 99.7085c.2007.2007.4773.3075.7606.2896 2.3692-.1476 4.6938-.46 6.9624-.9259.7645-.157 1.0301-1.0963.4782-1.6481L2.57595 39.4485c-.55186-.5519-1.49117-.2863-1.648174.4782-.465915 2.2686-.77832 4.5932-.92588465 6.9624ZM4.21093 29.7054c-.16649.3738-.08169.8106.20765 1.1l64.77602 64.776c.2894.2894.7262.3742 1.1.2077 1.7861-.7956 3.5171-1.6927 5.1855-2.684.5521-.328.6373-1.0867.1832-1.5407L8.43566 24.3367c-.45409-.4541-1.21271-.3689-1.54074.1832-.99132 1.6684-1.88843 3.3994-2.68399 5.1855ZM12.6587 18.074c-.3701-.3701-.393-.9637-.0443-1.3541C21.7795 6.45931 35.1114 0 49.9519 0 77.5927 0 100 22.4073 100 50.0481c0 14.8405-6.4593 28.1724-16.7199 37.3375-.3903.3487-.984.3258-1.3542-.0443L12.6587 18.074Z" />+ </svg>+));++LinearIcon.displayName = 'LinearIcon';++export default LinearIcon;diff --git a/src/features/Integrations/Linear/definition.ts b/src/features/Integrations/Linear/definition.tsnew file mode 100644index 00000000000..12f60fcb23b--- /dev/null+++ b/src/features/Integrations/Linear/definition.ts@@ -0,0 +1,11 @@+import { type IntegrationDefinition, registerIntegration } from '../registry';+import LinearIcon from './LinearIcon';++export const LINEAR_INTEGRATION: IntegrationDefinition = {+ docsUrl: 'https://lobehub.com/docs/usage/integrations/linear',+ icon: LinearIcon,+ id: 'linear',+ name: 'Linear',+};++registerIntegration(LINEAR_INTEGRATION);diff --git a/src/features/Integrations/Linear/index.tsx b/src/features/Integrations/Linear/index.tsxnew file mode 100644index 00000000000..eb89d9a6219--- /dev/null+++ b/src/features/Integrations/Linear/index.tsx@@ -0,0 +1,159 @@+'use client';++import { createStaticStyles, Flexbox, Icon, Skeleton, Text, toast } from '@lobehub/ui';+import { ArrowLeftIcon, BookOpenIcon } from 'lucide-react';+import { memo, useEffect } from 'react';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import AsyncError from '@/components/AsyncError';+import { useAppOrigin } from '@/hooks/useAppOrigin';++import { useLinearIntegration } from '../useLinearIntegration';+import Connections from './Connections';+import { LINEAR_INTEGRATION } from './definition';+import { buildLinearInstallHref } from './installHref';++const styles = createStaticStyles(({ css, cssVar }) => ({+ back: css`+ cursor: pointer;++ display: inline-flex;+ gap: 6px;+ align-items: center;++ color: ${cssVar.colorTextSecondary};++ &:hover {+ color: ${cssVar.colorText};+ }+ `,+ docs: css`+ display: inline-flex;+ gap: 6px;+ align-items: center;+ color: ${cssVar.colorTextSecondary};++ &:hover {+ color: ${cssVar.colorText};+ }+ `,+ hero: css`+ display: flex;+ flex: none;+ align-items: center;+ justify-content: center;++ width: 56px;+ height: 56px;+ border-radius: ${cssVar.borderRadiusLG};++ color: ${cssVar.colorText};++ background: ${cssVar.colorFillTertiary};+ `,+}));++const KNOWN_ERRORS = new Set([+ 'access_denied',+ 'exchange_failed',+ 'invalid_state',+ 'missing_code',+ 'save_failed',+ 'workspace_forbidden',+]);++interface LinearIntegrationProps {+ onBack: () => void;+}++/**+ * The Linear integration page: the connected Linear workspaces. Connecting+ * hands off to the server route that owns the OAuth handshake; Linear sends+ * the user back here with the outcome in the query.+ */+const LinearIntegration = memo<LinearIntegrationProps>(({ onBack }) => {+ const { t, ready } = useTranslation('integration');+ const appOrigin = useAppOrigin();+ const workspaceSlug = useActiveWorkspaceSlug();+ const workspaceId = useActiveWorkspaceId();+ const scope = workspaceSlug ? 'workspace' : 'personal';+ const data = useLinearIntegration();++ useEffect(() => {+ if (typeof window === 'undefined' || !ready) return;+ const url = new URL(window.location.href);+ const installed = url.searchParams.get('installed');+ const error = url.searchParams.get('error');+ const account = url.searchParams.get('account');+ if (!installed && !error) return;++ if (installed === 'ok') toast.success(t('linear.installResult.success', { account }));+ else if (error && KNOWN_ERRORS.has(error)) {+ toast.error(t(`linear.installResult.error.${error}` as any));+ } else if (error) toast.error(t('linear.installResult.error.unknown', { code: error }));++ for (const key of ['installed', 'error', 'account']) url.searchParams.delete(key);+ window.history.replaceState({}, '', url.pathname + (url.search ? `?${url.searchParams}` : ''));+ }, [t, ready]);++ if (data.error && data.isInitialLoading) {+ return <AsyncError error={data.error} variant={'block'} onRetry={data.mutate} />;+ }++ const { config, connections } = data;+ const installHref =+ config?.enabled && config.installPath+ ? buildLinearInstallHref(config.installPath, { appOrigin, workspaceId, workspaceSlug })+ : undefined;+ const BrandIcon = LINEAR_INTEGRATION.icon;++ return (+ <Flexbox gap={24}>+ <span className={styles.back} onClick={onBack}>+ <Icon icon={ArrowLeftIcon} size="small" />+ <Text type="secondary">{t('overview.title')}</Text>+ </span>++ <Flexbox horizontal align="center" gap={16}>+ <span className={styles.hero}>+ <BrandIcon size={32} />+ </span>+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ <Text strong style={{ fontSize: 20 }}>+ {LINEAR_INTEGRATION.name}+ </Text>+ <Text type="secondary">{t('linear.tagline')}</Text>+ </Flexbox>+ <a+ className={styles.docs}+ href={LINEAR_INTEGRATION.docsUrl}+ rel="noreferrer"+ target="_blank"+ >+ <Icon icon={BookOpenIcon} size="small" />+ <Text style={{ fontSize: 13 }} type="secondary">+ {t('linear.docsLink')}+ </Text>+ </a>+ </Flexbox>++ {data.isInitialLoading ? (+ <Skeleton height={96} />+ ) : (+ <Connections+ configured={!!config?.enabled}+ connections={connections}+ installHref={installHref}+ scope={scope}+ onChanged={data.mutate}+ />+ )}+ </Flexbox>+ );+});++LinearIntegration.displayName = 'LinearIntegration';++export default LinearIntegration;diff --git a/src/features/Integrations/Linear/installHref.test.ts b/src/features/Integrations/Linear/installHref.test.tsnew file mode 100644index 00000000000..8b934fead56--- /dev/null+++ b/src/features/Integrations/Linear/installHref.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';++import { buildLinearInstallHref } from './installHref';++const PATH = '/api/webhooks/linear/install';++describe('buildLinearInstallHref', () => {+ it('returns nothing until the app origin is known', () => {+ expect(buildLinearInstallHref(PATH, {})).toBeUndefined();+ });++ it('returns to the personal settings page outside a workspace', () => {+ const href = new URL(buildLinearInstallHref(PATH, { appOrigin: 'https://app.test' })!);+ expect(href.pathname).toBe(PATH);+ expect(href.searchParams.get('returnTo')).toBe('/settings/integrations/linear');+ expect(href.searchParams.has('workspaceId')).toBe(false);+ });++ it('carries the workspace and mirrors the return path under its slug', () => {+ const href = new URL(+ buildLinearInstallHref(PATH, {+ appOrigin: 'https://app.test/',+ workspaceId: 'ws_1',+ workspaceSlug: 'acme',+ })!,+ );+ expect(href.searchParams.get('workspaceId')).toBe('ws_1');+ expect(href.searchParams.get('returnTo')).toBe('/acme/settings/integrations/linear');+ });++ it('starts a cloud-gateway install on the app login origin', () => {+ const href = new URL(+ buildLinearInstallHref(PATH, { appOrigin: 'https://lobehub.com/', workspaceSlug: 'acme' })!,+ );+ expect(href.origin).toBe('https://app.lobehub.com');+ expect(href.pathname).toBe(PATH);+ expect(href.searchParams.get('returnTo')).toBe('/acme/settings/integrations/linear');+ });+});diff --git a/src/features/Integrations/Linear/installHref.ts b/src/features/Integrations/Linear/installHref.tsnew file mode 100644index 00000000000..118ebb3456e--- /dev/null+++ b/src/features/Integrations/Linear/installHref.ts@@ -0,0 +1,35 @@+import urlJoin from 'url-join';++import { integrationInstallOrigin } from '@/utils/integrationInstallOrigin';++/** Where the OAuth callback sends the user back to. */+export const LINEAR_RETURN_TO = '/settings/integrations/linear';++interface LinearInstallHrefParams {+ /** Absolute origin of the LobeHub server that owns the install route. */+ appOrigin?: string;+ /** `null` outside a workspace; the id the connection should belong to inside one. */+ workspaceId?: string | null;+ /** `null` outside a workspace; the slug the return path is mirrored under. */+ workspaceSlug?: string | null;+}++/**+ * The "Connect Linear" target. Absolute for the same reason as GitHub's: on+ * desktop the renderer is not served from the server origin. The workspace+ * travels in the query because this is a full-page navigation, not a TRPC+ * call that would carry it in a header.+ */+export const buildLinearInstallHref = (+ installPath: string,+ { appOrigin, workspaceId, workspaceSlug }: LinearInstallHrefParams,+): string | undefined => {+ if (!appOrigin) return undefined;++ const query = new URLSearchParams({+ returnTo: workspaceSlug ? `/${workspaceSlug}${LINEAR_RETURN_TO}` : LINEAR_RETURN_TO,+ });+ if (workspaceId) query.set('workspaceId', workspaceId);++ return `${urlJoin(integrationInstallOrigin(appOrigin), installPath)}?${query}`;+};diff --git a/src/features/Integrations/Linear/swrKeys.ts b/src/features/Integrations/Linear/swrKeys.tsnew file mode 100644index 00000000000..7c95cbd2eaa--- /dev/null+++ b/src/features/Integrations/Linear/swrKeys.ts@@ -0,0 +1,10 @@+/**+ * SWR keys of the Linear integration. Kept beside the feature because the+ * central registry (`@/libs/swr/keys`) is over the file-size limit; they+ * follow its `'<domain>:<resource>'` convention.+ */+export const linearKeys = {+ config: () => ['linear:config'] as const,+ connections: (workspaceId: string | null | undefined) =>+ ['linear:connections', workspaceId ?? null] as const,+};diff --git a/src/features/Integrations/Overview.tsx b/src/features/Integrations/Overview.tsxindex dce352a6537..b41b8b2d038 100644--- a/src/features/Integrations/Overview.tsx+++ b/src/features/Integrations/Overview.tsx@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next';import IntegrationCard from './IntegrationCard';import { type IntegrationId, INTEGRATIONS, UPCOMING_INTEGRATIONS } from './registry';import { useGithubIntegration } from './useGithubIntegration';+import { useLinearIntegration } from './useLinearIntegration';const styles = createStaticStyles(({ css, cssVar }) => ({list: css`@@ -52,8 +53,12 @@ interface OverviewProps {const Overview = memo<OverviewProps>(({ onOpen }) => {const { t } = useTranslation('integration');const github = useGithubIntegration();+ const linear = useLinearIntegration();- const enabledById: Record<IntegrationId, boolean> = { github: github.enabled };+ const enabledById: Record<IntegrationId, boolean> = {+ github: github.enabled,+ linear: linear.enabled,+ };const enabled = INTEGRATIONS.filter((item) => enabledById[item.id]);return (diff --git a/src/features/Integrations/index.tsx b/src/features/Integrations/index.tsxindex 990b94ee678..f1a76039e53 100644--- a/src/features/Integrations/index.tsx+++ b/src/features/Integrations/index.tsx@@ -1,6 +1,7 @@'use client';import './Github/definition';+import './Linear/definition';import { memo, useEffect } from 'react';import { useParams } from 'react-router';@@ -9,6 +10,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport GithubIntegration from './Github';import IntegrationsLayout from './Layout';+import LinearIntegration from './Linear';import Overview from './Overview';import { type IntegrationId, isIntegrationId } from './registry';@@ -33,7 +35,13 @@ const IntegrationsSettings = memo(() => {return (<IntegrationsLayout>- {selected === 'github' ? <GithubIntegration onBack={back} /> : <Overview onOpen={open} />}+ {selected === 'github' ? (+ <GithubIntegration onBack={back} />+ ) : selected === 'linear' ? (+ <LinearIntegration onBack={back} />+ ) : (+ <Overview onOpen={open} />+ )}</IntegrationsLayout>);});diff --git a/src/features/Integrations/registry.test.ts b/src/features/Integrations/registry.test.tsindex b638587e827..ebdda33cdc6 100644--- a/src/features/Integrations/registry.test.ts+++ b/src/features/Integrations/registry.test.ts@@ -1,4 +1,5 @@import './Github/definition';+import './Linear/definition';import { describe, expect, it } from 'vitest';@@ -15,6 +16,8 @@ describe('integrations registry', () => {expect(isIntegrationId('slack')).toBe(false);expect(isIntegrationId(undefined)).toBe(false);expect(findIntegration('github')?.name).toBe('GitHub');+ expect(isIntegrationId('linear')).toBe(true);+ expect(findIntegration('linear')?.name).toBe('Linear');});it('keeps upcoming integrations out of the routable set', () => {diff --git a/src/features/Integrations/registry.ts b/src/features/Integrations/registry.tsindex a04c0c16f75..94223ecf5bc 100644--- a/src/features/Integrations/registry.ts+++ b/src/features/Integrations/registry.ts@@ -2,7 +2,7 @@ import { Cloudflare, Notion, Railway, Vercel } from '@lobehub/icons';import type { ComponentType } from 'react';/** Stable id of an integration; doubles as its settings sub-route (`/settings/integrations/<id>`). */-export type IntegrationId = 'github';+export type IntegrationId = 'github' | 'linear';export interface IntegrationDefinition {/** Documentation page for the integration. */diff --git a/src/features/Integrations/useLinearIntegration.ts b/src/features/Integrations/useLinearIntegration.tsnew file mode 100644index 00000000000..bddaf50a515--- /dev/null+++ b/src/features/Integrations/useLinearIntegration.ts@@ -0,0 +1,34 @@+import useSWR from 'swr';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { linearService } from '@/services/linear';++import { linearKeys } from './Linear/swrKeys';++/**+ * Everything the Linear integration surfaces need, shared by the overview+ * card and the detail page. `enabled` is "at least one active connection".+ */+export const useLinearIntegration = () => {+ const workspaceId = useActiveWorkspaceId();+ const config = useSWR(linearKeys.config(), () => linearService.getConfig());+ const connections = useSWR(linearKeys.connections(workspaceId), () =>+ linearService.listConnections(),+ );++ const isInitialLoading = config.data === undefined || connections.data === undefined;+ const error = config.error ?? connections.error;+ const mutate = () => {+ void config.mutate();+ void connections.mutate();+ };++ return {+ config: config.data,+ connections: connections.data ?? [],+ enabled: (connections.data?.length ?? 0) > 0,+ error,+ isInitialLoading,+ mutate,+ };+};diff --git a/src/services/linear.ts b/src/services/linear.tsnew file mode 100644index 00000000000..d88c2d4d98b--- /dev/null+++ b/src/services/linear.ts@@ -0,0 +1,12 @@+import { lambdaClient } from '@/libs/trpc/client';++class LinearService {+ disconnect = async (connectionId: string) =>+ lambdaClient.linear.disconnect.mutate({ connectionId });++ getConfig = async () => lambdaClient.linear.getConfig.query();++ listConnections = async () => lambdaClient.linear.listConnections.query();+}++export const linearService = new LinearService();