Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(linear): sync Linear issues into project tasks, one way (#21723)

Rdmclin23b84889b4e66
diff --git a/apps/server/src/routers/async/index.ts b/apps/server/src/routers/async/index.ts
index ee577df6fbd..d55985cb521 100644
--- a/apps/server/src/routers/async/index.ts
+++ b/apps/server/src/routers/async/index.ts
@@ -3,6 +3,7 @@ import { asyncRouter as router, publicProcedure } from '@/libs/trpc/async';
import { documentRouter } from './document';
import { fileRouter } from './file';
import { imageRouter } from './image';
+import { linearRouter } from './linear';
import { ragEvalRouter } from './ragEval';
import { videoRouter } from './video';
@@ -11,6 +12,7 @@ export const asyncRouter = router({
file: fileRouter,
healthcheck: publicProcedure.query(() => "i'm live!"),
image: imageRouter,
+ linear: linearRouter,
ragEval: ragEvalRouter,
video: videoRouter,
});
diff --git a/apps/server/src/routers/async/linear.ts b/apps/server/src/routers/async/linear.ts
new file mode 100644
index 00000000000..e92810dcf21
--- /dev/null
+++ b/apps/server/src/routers/async/linear.ts
@@ -0,0 +1,14 @@
+import { z } from 'zod';
+
+import { asyncAuthedProcedure, asyncRouter as router } from '@/libs/trpc/async';
+import { LinearSyncJobService } from '@/server/services/linear/syncJob';
+
+/** Background Linear issue syncs, queued by the lambda `linear` router. */
+export const linearRouter = router({
+ runSync: asyncAuthedProcedure
+ .input(z.object({ taskId: z.string().uuid(), workspaceId: z.string().optional() }))
+ .mutation(async ({ ctx, input }) => {
+ await new LinearSyncJobService(ctx.serverDB, ctx.userId, input.workspaceId).run(input.taskId);
+ return { ok: true };
+ }),
+});
diff --git a/apps/server/src/routers/lambda/__tests__/linear.test.ts b/apps/server/src/routers/lambda/__tests__/linear.test.ts
index 251c8cc58db..78ea0bf76d5 100644
--- a/apps/server/src/routers/lambda/__tests__/linear.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/linear.test.ts
@@ -1,25 +1,69 @@
// @vitest-environment node
import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LinearConnectionModel } from '@/database/models/linear';
-import { linearConnections, users, workspaceMembers, workspaces } from '@/database/schemas';
+import {
+ asyncTasks,
+ linearConnections,
+ linearSyncRules,
+ projects,
+ users,
+ workspaceMembers,
+ workspaces,
+} from '@/database/schemas';
+import { LinearSyncJobService } from '@/server/services/linear/syncJob';
import { linearRouter } from '../linear';
const serverDB = await getTestDB();
const userId = 'linear-router-user';
const otherUserId = 'linear-router-user-2';
+const projectId = 'linear-router-project';
+const otherProjectId = 'linear-router-project-2';
vi.mock('@/envs/linear', () => ({
linearEnv: { ENABLED_LINEAR: true },
}));
-const mocks = vi.hoisted(() => ({ revoke: vi.fn() }));
+const mocks = vi.hoisted(() => ({
+ getToken: vi.fn(),
+ listTeams: vi.fn(),
+ revoke: vi.fn(),
+ importIssues: vi.fn(),
+ runSync: vi.fn(),
+ syncByFilter: vi.fn(),
+}));
vi.mock('@/server/services/linear/client', () => ({
LINEAR_INSTALL_PATH: '/api/webhooks/linear/install',
+ LinearApiError: class LinearApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message);
+ }
+ },
revokeLinearToken: mocks.revoke,
}));
+vi.mock('@/server/services/linear/token', () => ({
+ getLinearAccessToken: mocks.getToken,
+ LinearReconnectRequiredError: class LinearReconnectRequiredError extends Error {},
+}));
+vi.mock('@/server/services/linear/issues', () => ({
+ listLinearProjects: vi.fn(),
+ listLinearTeams: mocks.listTeams,
+}));
+vi.mock('@/server/services/linear/issueSync', () => ({
+ LinearIssueSyncService: vi.fn().mockImplementation(function () {
+ return { importIssues: mocks.importIssues, syncByFilter: mocks.syncByFilter };
+ }),
+}));
+// The background half runs in the async router; here only the hand-off is seen.
+vi.mock('@/server/routers/async', () => ({
+ createAsyncCaller: async () => ({ linear: { runSync: mocks.runSync } }),
+}));
vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
KeyVaultsGateKeeper: {
initWithEnvKey: async () => ({
@@ -55,10 +99,16 @@ const connect = (scope: { userId: string; workspaceId?: string | null }) =>
beforeEach(async () => {
vi.clearAllMocks();
await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(projects).values([
+ { id: projectId, identifier: 'LRP', name: 'Mine', userId },
+ { id: otherProjectId, identifier: 'LRQ', name: 'Theirs', userId: otherUserId },
+ ]);
});
afterEach(async () => {
+ await serverDB.delete(linearSyncRules);
await serverDB.delete(linearConnections);
+ await serverDB.delete(projects);
await serverDB.delete(workspaces);
await serverDB.delete(users);
});
@@ -123,4 +173,278 @@ describe('linearRouter', () => {
caller({ userId }).disconnect({ connectionId: connection.id }),
).rejects.toMatchObject({ code: 'NOT_FOUND' });
});
+
+ describe('issue sync', () => {
+ const syncResult = {
+ closed: 0,
+ created: 2,
+ keptLocalEdits: 0,
+ skipped: [],
+ truncated: false,
+ unchanged: 0,
+ updated: 0,
+ };
+
+ it("does not read Linear through another scope's connection", async () => {
+ const other = await connect({ userId: otherUserId });
+
+ await expect(caller({ userId }).listTeams({ connectionId: other.id })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ expect(mocks.getToken).not.toHaveBeenCalled();
+ });
+
+ it('asks to reconnect when Linear rejects the token', async () => {
+ const connection = await connect({ userId });
+ const { LinearApiError } = await import('@/server/services/linear/client');
+ mocks.getToken.mockResolvedValue('token');
+ mocks.listTeams.mockRejectedValue(new LinearApiError('Linear API error: Unauthorized', 401));
+
+ await expect(
+ caller({ userId }).listTeams({ connectionId: connection.id }),
+ ).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED',
+ message: 'LINEAR_RECONNECT_REQUIRED',
+ });
+ });
+
+ it('runs a saved rule in the background and records the outcome on the job and the rule', async () => {
+ const connection = await connect({ userId });
+ mocks.getToken.mockResolvedValue('token');
+ mocks.runSync.mockResolvedValue({ ok: true });
+ mocks.syncByFilter.mockResolvedValue(syncResult);
+
+ const rule = await caller({ userId }).createSyncRule({
+ connectionId: connection.id,
+ projectId,
+ stateTypes: ['backlog', 'unstarted'],
+ teamId: 'team-1',
+ teamName: 'Engineering',
+ });
+ const { id } = await caller({ userId }).startRuleSync({ ruleId: rule.id });
+
+ // Queued and handed to the async router; nothing synced yet.
+ expect(mocks.runSync).toHaveBeenCalledWith({ taskId: id, workspaceId: undefined });
+ expect(mocks.syncByFilter).not.toHaveBeenCalled();
+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([
+ { id, kind: 'rule', ruleId: rule.id, status: 'pending' },
+ ]);
+ // Starting again while it is queued returns the same job.
+ expect(await caller({ userId }).startRuleSync({ ruleId: rule.id })).toEqual({ id });
+
+ const service = new LinearSyncJobService(serverDB, userId);
+ await service.run(id);
+ // A repeated hand-off does not run it twice.
+ await service.run(id);
+
+ expect(mocks.syncByFilter).toHaveBeenCalledTimes(1);
+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([
+ { error: null, id, result: syncResult, status: 'success' },
+ ]);
+ expect(mocks.syncByFilter).toHaveBeenCalledWith(
+ 'token',
+ { linearProjectId: null, stateTypes: ['backlog', 'unstarted'], teamId: 'team-1' },
+ { targetProjectId: projectId },
+ );
+ const [saved] = await caller({ userId }).listSyncRules({ projectId });
+ expect(saved).toMatchObject({
+ id: rule.id,
+ lastResult: syncResult,
+ projectId,
+ teamName: 'Engineering',
+ });
+ expect(saved.lastRunAt).toBeInstanceOf(Date);
+ });
+
+ it('queues one run when the same rule is started twice at once', async () => {
+ const connection = await connect({ userId });
+ mocks.getToken.mockResolvedValue('token');
+ mocks.runSync.mockResolvedValue({ ok: true });
+ const rule = await caller({ userId }).createSyncRule({
+ connectionId: connection.id,
+ projectId,
+ stateTypes: ['unstarted'],
+ teamId: 'team-1',
+ teamName: 'Engineering',
+ });
+
+ const [first, second] = await Promise.all([
+ caller({ userId }).startRuleSync({ ruleId: rule.id }),
+ caller({ userId }).startRuleSync({ ruleId: rule.id }),
+ ]);
+
+ expect(second).toEqual(first);
+ expect(await caller({ userId }).listSyncJobs({ projectId })).toHaveLength(1);
+ });
+
+ it('keeps a long sync alive, so it is not shown as cut off', async () => {
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ try {
+ const connection = await connect({ userId });
+ mocks.getToken.mockResolvedValue('token');
+ mocks.runSync.mockResolvedValue({ ok: true });
+ let finish: ((result: typeof syncResult) => void) | undefined;
+ mocks.syncByFilter.mockImplementation(() => new Promise((resolve) => (finish = resolve)));
+ const rule = await caller({ userId }).createSyncRule({
+ connectionId: connection.id,
+ projectId,
+ stateTypes: ['unstarted'],
+ teamId: 'team-1',
+ teamName: 'Engineering',
+ });
+ const { id } = await caller({ userId }).startRuleSync({ ruleId: rule.id });
+ const running = new LinearSyncJobService(serverDB, userId).run(id);
+ const settle = async (done: () => Promise<boolean> | boolean) => {
+ for (let i = 0; i < 200 && !(await done()); i++) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ };
+ await settle(() => !!finish);
+
+ // The run has been busy past the stale window since it last wrote.
+ await serverDB
+ .update(asyncTasks)
+ .set({ updatedAt: new Date(Date.now() - 20 * 60 * 1000) })
+ .where(eq(asyncTasks.id, id));
+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([
+ { error: 'timeout', id },
+ ]);
+
+ vi.advanceTimersByTime(60 * 1000);
+ const status = async () => (await caller({ userId }).listSyncJobs({ projectId }))[0];
+ await settle(async () => (await status()).status === 'processing');
+ expect(await status()).toMatchObject({ error: null, id, status: 'processing' });
+
+ finish!(syncResult);
+ await running;
+ expect(await status()).toMatchObject({ id, status: 'success' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("hides another user's personal rules", async () => {
+ const connection = await connect({ userId: otherUserId });
+ const rule = await caller({ userId: otherUserId }).createSyncRule({
+ connectionId: connection.id,
+ projectId: otherProjectId,
+ stateTypes: ['backlog'],
+ teamId: 'team-1',
+ teamName: 'Engineering',
+ });
+
+ await expect(
+ caller({ userId }).listSyncRules({ projectId: otherProjectId }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(caller({ userId }).startRuleSync({ ruleId: rule.id })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ await expect(caller({ userId }).deleteSyncRule({ ruleId: rule.id })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+
+ it('rejects a project the caller cannot see', async () => {
+ const connection = await connect({ userId });
+
+ await expect(
+ caller({ userId }).createSyncRule({
+ connectionId: connection.id,
+ projectId: otherProjectId,
+ stateTypes: ['backlog'],
+ teamId: 'team-1',
+ teamName: 'Engineering',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(
+ caller({ userId }).startImport({
+ connectionId: connection.id,
+ issueIds: ['issue-1'],
+ projectId: 'proj_missing',
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mocks.getToken).not.toHaveBeenCalled();
+ });
+
+ it('imports picked issues in the background and reports a revoked token as reconnect', async () => {
+ const connection = await connect({ userId });
+ mocks.getToken.mockResolvedValue('token');
+ mocks.runSync.mockResolvedValue({ ok: true });
+ mocks.importIssues.mockResolvedValue({ ...syncResult, created: 1 });
+
+ const { id } = await caller({ userId }).startImport({
+ connectionId: connection.id,
+ issueIds: ['issue-1', 'issue-1', 'issue-2'],
+ projectId,
+ });
+ await new LinearSyncJobService(serverDB, userId).run(id);
+
+ expect(mocks.importIssues).toHaveBeenCalledWith('token', ['issue-1', 'issue-2'], {
+ targetProjectId: projectId,
+ });
+ expect(await caller({ userId }).listSyncJobs({ projectId })).toMatchObject([
+ { id, issueCount: 2, kind: 'issues', result: { created: 1 }, status: 'success' },
+ ]);
+
+ // The token was revoked after the job was queued.
+ const { LinearReconnectRequiredError } = await import('@/server/services/linear/token');
+ const second = await caller({ userId }).startImport({
+ connectionId: connection.id,
+ issueIds: ['issue-3'],
+ projectId,
+ });
+ mocks.getToken.mockRejectedValue(new LinearReconnectRequiredError());
+ await new LinearSyncJobService(serverDB, userId).run(second.id);
+
+ const [latest] = await caller({ userId }).listSyncJobs({ projectId });
+ expect(latest).toMatchObject({ error: 'reconnect', id: second.id, status: 'error' });
+ });
+
+ it("lists only the project's own rules, and drops them with the project", async () => {
+ const connection = await connect({ userId });
+ await serverDB
+ .insert(projects)
+ .values({ id: 'linear-router-project-3', identifier: 'LRR', name: 'Other', userId });
+ const rule = await caller({ userId }).createSyncRule({
+ connectionId: connection.id,
+ projectId,
+ stateTypes: ['backlog'],
+ teamId: 'team-1',
+ teamName: 'Engineering',
+ });
+
+ expect(
+ await caller({ userId }).listSyncRules({ projectId: 'linear-router-project-3' }),
+ ).toEqual([]);
+ expect(await caller({ userId }).listSyncRules({ projectId })).toMatchObject([
+ { id: rule.id },
+ ]);
+
+ await serverDB.delete(projects).where(eq(projects.id, projectId));
+ expect(await serverDB.select().from(linearSyncRules)).toEqual([]);
+ });
+
+ it('keeps a rule removable after its connection is disconnected, and asks to reconnect on run', async () => {
+ const connection = await connect({ userId });
+ const rule = await caller({ userId }).createSyncRule({
+ connectionId: connection.id,
+ projectId,
+ stateTypes: ['backlog'],
+ teamId: 'team-1',
+ teamName: 'Engineering',
+ });
+ await LinearConnectionModel.revoke(serverDB, connection.id);
+ const { LinearReconnectRequiredError } = await import('@/server/services/linear/token');
+ mocks.getToken.mockRejectedValue(new LinearReconnectRequiredError());
+
+ await expect(caller({ userId }).startRuleSync({ ruleId: rule.id })).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED',
+ message: 'LINEAR_RECONNECT_REQUIRED',
+ });
+ await expect(caller({ userId }).deleteSyncRule({ ruleId: rule.id })).resolves.toEqual({
+ ok: true,
+ });
+ expect(await caller({ userId }).listSyncRules({ projectId })).toEqual([]);
+ });
+ });
});
diff --git a/apps/server/src/routers/lambda/linear.ts b/apps/server/src/routers/lambda/linear.ts
index d4f959c3a3e..d9301e03837 100644
--- a/apps/server/src/routers/lambda/linear.ts
+++ b/apps/server/src/routers/lambda/linear.ts
@@ -1,13 +1,30 @@
+import type { LinearSyncJobMetadata } from '@lobechat/types';
+import { LINEAR_ISSUE_STATE_TYPES } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
-import { LinearConnectionModel } from '@/database/models/linear';
+import {
+ LinearConnectionModel,
+ LinearSyncJobModel,
+ LinearSyncRuleModel,
+} from '@/database/models/linear';
+import { ProjectModel } from '@/database/models/project';
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 {
+ LINEAR_INSTALL_PATH,
+ LinearApiError,
+ revokeLinearToken,
+} from '@/server/services/linear/client';
+import { listLinearProjects, listLinearTeams } from '@/server/services/linear/issues';
+import { LinearIssueSyncService } from '@/server/services/linear/issueSync';
+import { startLinearRuleSyncJob, startLinearSyncJob } from '@/server/services/linear/startSyncJob';
+import { toLinearSyncJobView } from '@/server/services/linear/syncJob';
+import { getLinearAccessToken, LinearReconnectRequiredError } from '@/server/services/linear/token';
import { canWriteScmScope } from '@/server/services/scm/scope';
const linearProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
@@ -19,8 +36,46 @@ const linearProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =
const connectionInput = z.object({ connectionId: z.string().uuid() });
+const projectInput = z.object({ projectId: z.string().min(1) });
+
+/** Picked issues one background import takes. */
+const MAX_IMPORT_ISSUES = 500;
+
+const stateTypesInput = z.array(z.enum(LINEAR_ISSUE_STATE_TYPES)).min(1);
+
+const issueFilterInput = connectionInput.extend({
+ linearProjectId: z.string().nullish(),
+ stateTypes: stateTypesInput,
+ teamId: z.string().min(1),
+});
+
+/** Importing into tasks also needs task write access (viewers are read-only). */
+const linearTaskWriteProcedure = linearProcedure.use(withScopedPermission('agent:update'));
+
+/** Error code the client turns into a "reconnect Linear" prompt. */
+export const LINEAR_RECONNECT_REQUIRED = 'LINEAR_RECONNECT_REQUIRED';
+
+/** Run a Linear API call, mapping auth failures to one reconnect error. */
+const callLinear = async <T>(fn: () => Promise<T>): Promise<T> => {
+ try {
+ return await fn();
+ } catch (error) {
+ if (
+ error instanceof LinearReconnectRequiredError ||
+ (error instanceof LinearApiError && error.status === 401)
+ ) {
+ throw new TRPCError({ code: 'PRECONDITION_FAILED', message: LINEAR_RECONNECT_REQUIRED });
+ }
+ if (error instanceof LinearApiError) {
+ throw new TRPCError({ cause: error, code: 'BAD_REQUEST', message: error.message });
+ }
+ throw error;
+ }
+};
+
/**
- * The Linear integration for the settings page. Connecting happens through
+ * The Linear integration: connections for the settings page, issue sync for
+ * LobeHub projects. 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.
@@ -54,20 +109,159 @@ export const linearRouter = router({
const rows = await LinearConnectionModel.listByScope(ctx.serverDB, ctx.scope);
return rows.map((row) => LinearConnectionModel.toView(row));
}),
+
+ // ── Issue sync (Linear → tasks, one way; Linear is only read) ──
+
+ listTeams: linearProcedure.input(connectionInput).query(async ({ ctx, input }) => {
+ await requireConnection(ctx, input.connectionId);
+ return callLinear(async () =>
+ listLinearTeams(await getLinearAccessToken(ctx.serverDB, input.connectionId)),
+ );
+ }),
+
+ listProjects: linearProcedure
+ .input(connectionInput.extend({ teamId: z.string().min(1) }))
+ .query(async ({ ctx, input }) => {
+ await requireConnection(ctx, input.connectionId);
+ return callLinear(async () =>
+ listLinearProjects(
+ await getLinearAccessToken(ctx.serverDB, input.connectionId),
+ input.teamId,
+ ),
+ );
+ }),
+
+ listIssues: linearProcedure
+ .input(issueFilterInput.extend({ cursor: z.string().optional() }))
+ .query(async ({ ctx, input }) => {
+ await requireConnection(ctx, input.connectionId);
+ return callLinear(async () =>
+ syncService(ctx).listIssues(
+ await getLinearAccessToken(ctx.serverDB, input.connectionId),
+ input,
+ input.cursor,
+ ),
+ );
+ }),
+
+ /**
+ * Import (or re-sync) the picked issues into a LobeHub project. Runs in the
+ * background; poll `listSyncJobs` for the outcome.
+ */
+ startImport: linearTaskWriteProcedure
+ .input(
+ projectInput.extend({
+ connectionId: z.string().uuid(),
+ issueIds: z.array(z.string().min(1)).min(1).max(MAX_IMPORT_ISSUES),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ await requireWritableConnection(ctx, input.connectionId);
+ await requireProject(ctx, input.projectId);
+ // Fail fast on a revoked token instead of queueing a job that cannot run.
+ await callLinear(() => getLinearAccessToken(ctx.serverDB, input.connectionId));
+ const id = await startJob(ctx, {
+ connectionId: input.connectionId,
+ issueIds: [...new Set(input.issueIds)],
+ kind: 'issues',
+ projectId: input.projectId,
+ });
+ return { id };
+ }),
+
+ /** The project's recent background syncs, newest first. */
+ listSyncJobs: linearProcedure.input(projectInput).query(async ({ ctx, input }) => {
+ await requireProject(ctx, input.projectId);
+ const rows = await LinearSyncJobModel.listByProject(ctx.serverDB, ctx.scope, input.projectId);
+ return rows.map((row) => toLinearSyncJobView(row));
+ }),
+
+ /** The sync rules a LobeHub project saved. */
+ listSyncRules: linearProcedure.input(projectInput).query(async ({ ctx, input }) => {
+ await requireProject(ctx, input.projectId);
+ const rows = await LinearSyncRuleModel.listByProject(ctx.serverDB, ctx.scope, input.projectId);
+ return rows.map((row) => LinearSyncRuleModel.toView(row));
+ }),
+
+ createSyncRule: linearTaskWriteProcedure
+ .input(
+ issueFilterInput.merge(projectInput).extend({
+ linearProjectName: z.string().max(255).nullish(),
+ teamName: z.string().min(1).max(255),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ await requireWritableConnection(ctx, input.connectionId);
+ await requireProject(ctx, input.projectId);
+ const row = await LinearSyncRuleModel.create(ctx.serverDB, {
+ connectionId: input.connectionId,
+ linearProjectId: input.linearProjectId ?? null,
+ linearProjectName: input.linearProjectId ? (input.linearProjectName ?? null) : null,
+ projectId: input.projectId,
+ stateTypes: input.stateTypes,
+ teamId: input.teamId,
+ teamName: input.teamName,
+ userId: ctx.userId,
+ workspaceId: ctx.scope.workspaceId,
+ });
+ return LinearSyncRuleModel.toView(row);
+ }),
+
+ deleteSyncRule: linearTaskWriteProcedure
+ .input(z.object({ ruleId: z.string().uuid() }))
+ .mutation(async ({ ctx, input }) => {
+ const rule = await requireSyncRule(ctx, input.ruleId);
+ // A rule stays removable after its connection is disconnected.
+ await requireWritableScope(ctx);
+ await LinearSyncRuleModel.delete(ctx.serverDB, rule.id, ctx.scope);
+ return { ok: true };
+ }),
+
+ /**
+ * Run a saved rule now, in the background. A run of the same rule that is
+ * still going is returned instead of starting a second one.
+ */
+ startRuleSync: linearTaskWriteProcedure
+ .input(z.object({ ruleId: z.string().uuid() }))
+ .mutation(async ({ ctx, input }) => {
+ const rule = await requireSyncRule(ctx, input.ruleId);
+ // The rule is in the caller's scope, and so is the connection it was
+ // created with; a disconnected one fails below as "reconnect".
+ await requireWritableScope(ctx);
+ // Deleting the project deletes its rules; one the caller can no longer
+ // see is not synced into.
+ await requireProject(ctx, rule.projectId);
+ await callLinear(() => getLinearAccessToken(ctx.serverDB, rule.connectionId));
+ // Returns the run still going, if any; the check and insert are atomic.
+ const id = await startLinearRuleSyncJob(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.scope.workspaceId ?? undefined,
+ {
+ connectionId: rule.connectionId,
+ kind: 'rule',
+ projectId: rule.projectId,
+ ruleId: rule.id,
+ },
+ );
+ return { id };
+ }),
});
-/**
- * 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,
-) => {
+type LinearContext = {
+ scope: { userId: string; workspaceId: string | null };
+ serverDB: Parameters<typeof LinearConnectionModel.findById>[0];
+ userId: string;
+};
+
+const syncService = (ctx: LinearContext) =>
+ new LinearIssueSyncService(ctx.serverDB, ctx.userId, ctx.scope.workspaceId ?? undefined);
+
+const startJob = (ctx: LinearContext, metadata: LinearSyncJobMetadata) =>
+ startLinearSyncJob(ctx.serverDB, ctx.userId, ctx.scope.workspaceId ?? undefined, metadata);
+
+/** The connection, if it is active and visible in the caller's scope. */
+const requireConnection = async (ctx: LinearContext, connectionId: string) => {
const connection = await LinearConnectionModel.findById(ctx.serverDB, connectionId);
const inScope =
!!connection &&
@@ -76,11 +270,41 @@ const requireWritableConnection = async (
? connection.workspaceId === ctx.scope.workspaceId
: connection.userId === ctx.userId && !connection.workspaceId);
if (!inScope) throw new TRPCError({ code: 'NOT_FOUND', message: 'Linear connection not found' });
+ return connection;
+};
+const requireSyncRule = async (ctx: LinearContext, ruleId: string) => {
+ const rule = await LinearSyncRuleModel.findInScope(ctx.serverDB, ruleId, ctx.scope);
+ if (!rule) throw new TRPCError({ code: 'NOT_FOUND', message: 'Linear sync rule not found' });
+ return rule;
+};
+
+/** The LobeHub project, if the caller can see it; synced tasks land there. */
+const requireProject = async (ctx: LinearContext, projectId: string) => {
+ const project = await new ProjectModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.scope.workspaceId ?? undefined,
+ ).findById(projectId);
+ if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });
+ return project;
+};
+
+/**
+ * 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: LinearContext, connectionId: string) => {
+ const connection = await requireConnection(ctx, connectionId);
+ await requireWritableScope(ctx);
+ return connection;
+};
+
+/** In a workspace, only members who can edit may change its Linear setup. */
+const requireWritableScope = async (ctx: LinearContext) => {
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__/issueSync.integration.test.ts b/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts
new file mode 100644
index 00000000000..b8f00f5cf25
--- /dev/null
+++ b/apps/server/src/services/linear/__tests__/issueSync.integration.test.ts
@@ -0,0 +1,405 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskModel } from '@/database/models/task';
+import { TaskExternalLinkModel } from '@/database/models/taskExternalLink';
+import { tasks, users } from '@/database/schemas';
+
+import type * as IssuesModule from '../issues';
+import type { LinearIssue } from '../issues';
+import { LinearIssueSyncService, MAX_TASKS_CREATED_PER_SYNC } from '../issueSync';
+
+const linear = vi.hoisted(() => ({
+ getLinearIssuesByIds: vi.fn(),
+ listLinearIssues: vi.fn(),
+}));
+vi.mock('../issues', async (importOriginal) => ({
+ ...(await importOriginal<typeof IssuesModule>()),
+ getLinearIssuesByIds: linear.getLinearIssuesByIds,
+ listLinearIssues: linear.listLinearIssues,
+}));
+
+const userId = 'linear-issue-sync-user';
+const otherUserId = 'linear-issue-sync-other';
+const TOKEN = 'token';
+const TEAM = 'team-1';
+
+// Module-level: the first call migrates a fresh database.
+const db: LobeChatDatabase = await getTestDB();
+
+const issue = (overrides: Partial<LinearIssue> & { id: string }): LinearIssue => ({
+ description: `Body of ${overrides.id}`,
+ identifier: `ENG-${overrides.id}`,
+ priority: 2,
+ state: { name: 'Todo', type: 'unstarted' },
+ team: { id: TEAM, key: 'ENG' },
+ title: `Issue ${overrides.id}`,
+ updatedAt: '2026-10-01T00:00:00.000Z',
+ url: `https://linear.app/acme/issue/ENG-${overrides.id}`,
+ ...overrides,
+});
+
+/** Serve the given issues to both the filtered listing and the by-id lookup. */
+const serve = (issues: LinearIssue[]) => {
+ linear.listLinearIssues.mockImplementation(async () => ({ hasMore: false, issues }));
+ linear.getLinearIssuesByIds.mockImplementation(async (_token: string, ids: string[]) =>
+ issues.filter((item) => ids.includes(item.id)),
+ );
+};
+
+const filter = { stateTypes: ['backlog', 'unstarted', 'started'] as const, teamId: TEAM };
+
+const linkedTask = async (externalId: string, scopeUserId = userId) => {
+ const [link] = await new TaskExternalLinkModel(db, scopeUserId).findByExternalIds('linear', [
+ externalId,
+ ]);
+ return link ? new TaskModel(db, scopeUserId).findById(link.taskId) : null;
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ await db.delete(users).where(eq(users.id, userId));
+ await db.delete(users).where(eq(users.id, otherUserId));
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await db.delete(users).where(eq(users.id, userId));
+ await db.delete(users).where(eq(users.id, otherUserId));
+});
+
+describe('LinearIssueSyncService (real PostgreSQL)', () => {
+ it('creates one task per issue with the issue fields and a link back', async () => {
+ serve([issue({ id: '1', priority: 1 })]);
+ const service = new LinearIssueSyncService(db, userId);
+
+ const result = await service.syncByFilter(TOKEN, {
+ ...filter,
+ stateTypes: [...filter.stateTypes],
+ });
+
+ expect(result).toMatchObject({ created: 1, updated: 0, closed: 0, truncated: false });
+ const task = await linkedTask('1');
+ expect(task).toMatchObject({ name: 'Issue 1', priority: 1, status: 'backlog' });
+ expect(task?.instruction).toContain('[ENG-1](https://linear.app/acme/issue/ENG-1)');
+ expect(task?.instruction).toContain('Body of 1');
+ });
+
+ it('updates the same task on a second sync instead of creating another', async () => {
+ serve([issue({ id: '1' })]);
+ const service = new LinearIssueSyncService(db, userId);
+ await service.syncByFilter(TOKEN, { ...filter, stateTypes: [...filter.stateTypes] });
+
+ serve([issue({ id: '1', title: 'Renamed in Linear' })]);
+ const result = await service.syncByFilter(TOKEN, {
+ ...filter,
+ stateTypes: [...filter.stateTypes],
+ });
+
+ expect(result).toMatchObject({ created: 0, updated: 1 });
+ expect((await linkedTask('1'))?.name).toBe('Renamed in Linear');
+ const all = await db.select().from(tasks).where(eq(tasks.createdByUserId, userId));
+ expect(all).toHaveLength(1);
+ });
+
+ it('keeps a task edited in LobeHub instead of overwriting it', async () => {
+ serve([issue({ id: '1' })]);
+ const service = new LinearIssueSyncService(db, userId);
+ await service.syncByFilter(TOKEN, { ...filter, stateTypes: [...filter.stateTypes] });
+ const task = await linkedTask('1');
+ await new TaskModel(db, userId).update(task!.id, { name: 'My own title' });
+
+ serve([issue({ id: '1', title: 'Renamed in Linear' })]);
+ const result = await service.syncByFilter(TOKEN, {
+ ...filter,
+ stateTypes: [...filter.stateTypes],
+ });
+
+ expect(result).toMatchObject({ keptLocalEdits: 1, unchanged: 0, updated: 0 });
+ expect((await linkedTask('1'))?.name).toBe('My own title');
+ });
+
+ it('closes the task of an issue Linear completed, even when the filter excludes it', async () => {
+ serve([issue({ id: '1' })]);
+ const service = new LinearIssueSyncService(db, userId);
+ await service.syncByFilter(TOKEN, { ...filter, stateTypes: [...filter.stateTypes] });
+
+ // Completed issues no longer match the open-states filter.
+ const done = issue({ id: '1', state: { name: 'Done', type: 'completed' } });
+ linear.listLinearIssues.mockResolvedValue({ hasMore: false, issues: [] });
+ linear.getLinearIssuesByIds.mockResolvedValue([done]);
+ const result = await service.syncByFilter(TOKEN, {
+ ...filter,
+ stateTypes: [...filter.stateTypes],
+ });
+
+ expect(result.closed).toBe(1);
+ expect((await linkedTask('1'))?.status).toBe('completed');
+ });
+
+ it('does not interrupt a running task when its issue is closed', async () => {
+ serve([issue({ id: '1' })]);
+ const service = new LinearIssueSyncService(db, userId);
+ await service.syncByFilter(TOKEN, { ...filter, stateTypes: [...filter.stateTypes] });
+ const task = await linkedTask('1');
+ await db.update(tasks).set({ status: 'running' }).where(eq(tasks.id, task!.id));
+
+ serve([issue({ id: '1', state: { name: 'Canceled', type: 'canceled' } })]);
+ const result = await service.importIssues(TOKEN, ['1']);
+
+ expect(result).toMatchObject({ closed: 0, unchanged: 0 });
+ expect(result.skipped).toEqual([{ identifier: 'ENG-1', reason: 'running' }]);
+ expect((await linkedTask('1'))?.status).toBe('running');
+ });
+
+ it('skips closed issues it never imported, unless closed states were asked for', async () => {
+ serve([issue({ id: '1', state: { name: 'Done', type: 'completed' } })]);
+ const service = new LinearIssueSyncService(db, userId);
+
+ const result = await service.importIssues(TOKEN, ['1']);
+
+ // Picked explicitly: imported, then closed like its issue.
+ expect(result.created).toBe(1);
+ expect((await linkedTask('1'))?.status).toBe('completed');
+ });
+
+ it('nests a sub-issue under the task of its parent issue', async () => {
+ serve([issue({ id: 'child', parent: { id: 'parent' } }), issue({ id: 'parent' })]);
+ const service = new LinearIssueSyncService(db, userId);
+
+ await service.syncByFilter(TOKEN, { ...filter, stateTypes: [...filter.stateTypes] });
+
+ const parent = await linkedTask('parent');
+ const child = await linkedTask('child');
+ expect(child?.parentTaskId).toBe(parent?.id);
+ });
+
+ it('leaves no task behind when its link cannot be written', async () => {
+ serve([issue({ id: '1' })]);
+ const service = new LinearIssueSyncService(db, userId);
+ vi.spyOn(TaskExternalLinkModel.prototype, 'create').mockRejectedValueOnce(
+ new Error('connection lost'),
+ );
+
+ const failed = await service.importIssues(TOKEN, ['1']);
+ expect(failed.skipped).toEqual([{ identifier: 'ENG-1', reason: 'failed' }]);
+ expect(await db.select().from(tasks).where(eq(tasks.createdByUserId, userId))).toHaveLength(0);
+
+ // Retrying imports it once, with no orphan from the failed run.
+ const retried = await service.importIssues(TOKEN, ['1']);
+ expect(retried.created).toBe(1);
+ expect(await db.select().from(tasks).where(eq(tasks.createdByUserId, userId))).toHaveLength(1);
+ });
+
+ it('nests under the parent another run linked after this batch was loaded', async () => {
+ serve([issue({ id: 'parent' })]);
+ await new LinearIssueSyncService(db, userId).importIssues(TOKEN, ['parent']);
+ const winner = await linkedTask('parent');
+
+ serve([issue({ id: 'parent' }), issue({ id: 'child', parent: { id: 'parent' } })]);
+ // This run read its links before the other run linked the parent.
+ vi.spyOn(TaskExternalLinkModel.prototype, 'findByExternalIds').mockResolvedValueOnce([]);
+ const result = await new LinearIssueSyncService(db, userId).importIssues(TOKEN, [
+ 'parent',
+ 'child',
+ ]);
+
+ expect(result).toMatchObject({ created: 1, unchanged: 1 });
+ expect((await linkedTask('child'))?.parentTaskId).toBe(winner?.id);
+ expect(await db.select().from(tasks).where(eq(tasks.createdByUserId, userId))).toHaveLength(2);
+ });
+
+ it('counts every skipped issue, beyond the listed ones', async () => {
+ const ids = Array.from({ length: 105 }, (_, index) => `s${index}`);
+ serve(ids.map((id) => issue({ id })));
+ vi.spyOn(TaskExternalLinkModel.prototype, 'create').mockRejectedValue(new Error('down'));
+
+ const result = await new LinearIssueSyncService(db, userId).importIssues(TOKEN, ids);
+
+ expect(result.skipped).toHaveLength(100);
+ expect(result.skippedCount).toBe(105);
+ });
+
+ it('reports picked issues Linear no longer returns instead of an empty run', async () => {
+ serve([issue({ id: '1' })]);
+
+ const result = await new LinearIssueSyncService(db, userId).importIssues(TOKEN, ['1', 'gone']);
+
+ expect(result.created).toBe(1);
+ expect(result.skipped).toEqual([{ identifier: 'gone', reason: 'missing' }]);
+ expect(result.skippedCount).toBe(1);
+ });
+
+ it('keeps each scope separate: another user imports their own task', async () => {
+ serve([issue({ id: '1' })]);
+ await new LinearIssueSyncService(db, userId).importIssues(TOKEN, ['1']);
+
+ const page = await new LinearIssueSyncService(db, otherUserId).listIssues(TOKEN, {
+ ...filter,
+ stateTypes: [...filter.stateTypes],
+ });
+ expect(page.issues[0].linkedTaskIdentifier).toBeUndefined();
+
+ const result = await new LinearIssueSyncService(db, otherUserId).importIssues(TOKEN, ['1']);
+ expect(result.created).toBe(1);
+ expect((await linkedTask('1', otherUserId))?.createdByUserId).toBe(otherUserId);
+ });
+
+ it('reports a trashed task as unavailable instead of re-creating it', async () => {
+ serve([issue({ id: '1' })]);
+ const service = new LinearIssueSyncService(db, userId);
+ await service.importIssues(TOKEN, ['1']);
+ const task = await linkedTask('1');
+ await db
+ .update(tasks)
+ .set({ deletedAt: new Date(), isDeleted: true })
+ .where(eq(tasks.id, task!.id));
+
+ const result = await service.importIssues(TOKEN, ['1']);
+
+ expect(result).toMatchObject({ created: 0 });
+ expect(result.skipped).toEqual([{ identifier: 'ENG-1', reason: 'unavailable' }]);
+ });
+
+ it('marks issues already imported in the picker', async () => {
+ serve([issue({ id: '1' }), issue({ id: '2' })]);
+ const service = new LinearIssueSyncService(db, userId);
+ await service.importIssues(TOKEN, ['1']);
+
+ const page = await service.listIssues(TOKEN, { ...filter, stateTypes: [...filter.stateTypes] });
+
+ const task = await linkedTask('1');
+ expect(page.issues.map((item) => item.linkedTaskIdentifier)).toEqual([
+ task?.identifier,
+ undefined,
+ ]);
+ });
+
+ it('creates a bounded batch per run and continues on the next run', async () => {
+ const many = Array.from({ length: MAX_TASKS_CREATED_PER_SYNC + 1 }, (_, index) =>
+ issue({ id: `bulk-${index}` }),
+ );
+ serve(many);
+ const service = new LinearIssueSyncService(db, userId);
+ const options = { ...filter, stateTypes: [...filter.stateTypes] };
+
+ const first = await service.syncByFilter(TOKEN, options);
+ expect(first).toMatchObject({ created: MAX_TASKS_CREATED_PER_SYNC, truncated: true });
+
+ const second = await service.syncByFilter(TOKEN, options);
+ expect(second).toMatchObject({
+ created: 1,
+ truncated: false,
+ unchanged: MAX_TASKS_CREATED_PER_SYNC,
+ });
+ }, 60_000);
+
+ it('reads further pages on the next run once the first ones are imported', async () => {
+ const many = Array.from({ length: 160 }, (_, index) => issue({ id: `page-${index}` }));
+ linear.listLinearIssues.mockImplementation(
+ async (_token: string, _filter: unknown, { after }: { after?: string } = {}) => {
+ const start = after ? Number(after) : 0;
+ const end = start + 50;
+ return {
+ cursor: end < many.length ? String(end) : undefined,
+ hasMore: end < many.length,
+ issues: many.slice(start, end),
+ };
+ },
+ );
+ linear.getLinearIssuesByIds.mockResolvedValue([]);
+ const service = new LinearIssueSyncService(db, userId);
+ const options = { ...filter, stateTypes: [...filter.stateTypes] };
+
+ const first = await service.syncByFilter(TOKEN, options);
+ expect(first).toMatchObject({ created: 100, truncated: true });
+
+ const second = await service.syncByFilter(TOKEN, options);
+ expect(second).toMatchObject({ created: 60, truncated: false, unchanged: 100 });
+ }, 60_000);
+
+ it('keeps a LobeHub edit made after the batch was loaded', async () => {
+ serve([issue({ id: '1' })]);
+ const service = new LinearIssueSyncService(db, userId);
+ await service.importIssues(TOKEN, ['1']);
+ const task = await linkedTask('1');
+
+ // The edit lands while the sync is already running: after the batch read
+ // the task, before it writes Linear's new title.
+ const findByIds = TaskModel.prototype.findByIds;
+ const spy = vi.spyOn(TaskModel.prototype, 'findByIds').mockImplementation(async function (
+ this: TaskModel,
+ ids: string[],
+ ) {
+ const rows = await findByIds.call(this, ids);
+ await new TaskModel(db, userId).update(task!.id, { name: 'Edited mid-sync' });
+ return rows;
+ });
+ serve([issue({ id: '1', title: 'Renamed in Linear' })]);
+ const result = await service.importIssues(TOKEN, ['1']);
+ spy.mockRestore();
+
+ expect(result).toMatchObject({ keptLocalEdits: 1, updated: 0 });
+ expect((await linkedTask('1'))?.name).toBe('Edited mid-sync');
+ });
+
+ it('does not close a task that started running after the batch was loaded', async () => {
+ serve([issue({ id: '1' })]);
+ const service = new LinearIssueSyncService(db, userId);
+ await service.importIssues(TOKEN, ['1']);
+ const task = await linkedTask('1');
+
+ const findByIds = TaskModel.prototype.findByIds;
+ const spy = vi.spyOn(TaskModel.prototype, 'findByIds').mockImplementation(async function (
+ this: TaskModel,
+ ids: string[],
+ ) {
+ const rows = await findByIds.call(this, ids);
+ await db.update(tasks).set({ status: 'running' }).where(eq(tasks.id, task!.id));
+ return rows;
+ });
+ serve([issue({ id: '1', state: { name: 'Done', type: 'completed' } })]);
+ const result = await service.importIssues(TOKEN, ['1']);
+ spy.mockRestore();
+
+ expect(result).toMatchObject({ closed: 0 });
+ expect(result.skipped).toEqual([{ identifier: 'ENG-1', reason: 'running' }]);
+ expect((await linkedTask('1'))?.status).toBe('running');
+ });
+
+ it('keeps the hash a concurrent run wrote, so later Linear changes still apply', async () => {
+ serve([issue({ id: '1' })]);
+ await new LinearIssueSyncService(db, userId).importIssues(TOKEN, ['1']);
+
+ // Run B reads the batch; run A then syncs the same rename and commits first.
+ serve([issue({ id: '1', title: 'Renamed once', updatedAt: '2026-10-02T00:00:00.000Z' })]);
+ const findByIds = TaskModel.prototype.findByIds;
+ let raced = false;
+ const spy = vi.spyOn(TaskModel.prototype, 'findByIds').mockImplementation(async function (
+ this: TaskModel,
+ ids: string[],
+ ) {
+ const rows = await findByIds.call(this, ids);
+ if (!raced) {
+ raced = true;
+ spy.mockRestore();
+ await new LinearIssueSyncService(db, userId).importIssues(TOKEN, ['1']);
+ }
+ return rows;
+ });
+ await new LinearIssueSyncService(db, userId).importIssues(TOKEN, ['1']);
+ spy.mockRestore();
+ expect((await linkedTask('1'))?.name).toBe('Renamed once');
+
+ // A later Linear change must still apply, not be mistaken for a local edit.
+ serve([issue({ id: '1', title: 'Renamed twice', updatedAt: '2026-10-03T00:00:00.000Z' })]);
+ const result = await new LinearIssueSyncService(db, userId).importIssues(TOKEN, ['1']);
+
+ expect(result).toMatchObject({ keptLocalEdits: 0, updated: 1 });
+ expect((await linkedTask('1'))?.name).toBe('Renamed twice');
+ });
+});
diff --git a/apps/server/src/services/linear/__tests__/syncJob.test.ts b/apps/server/src/services/linear/__tests__/syncJob.test.ts
new file mode 100644
index 00000000000..d0c718afbab
--- /dev/null
+++ b/apps/server/src/services/linear/__tests__/syncJob.test.ts
@@ -0,0 +1,51 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import type { LinearSyncJobRow } from '@/database/models/linear';
+
+import { LINEAR_SYNC_STALE_MS, LINEAR_SYNC_UNCLAIMED_MS, toLinearSyncJobView } from '../syncJob';
+
+const now = Date.UTC(2026, 9, 27, 12);
+
+const row = (overrides: Partial<LinearSyncJobRow>): LinearSyncJobRow =>
+ ({
+ createdAt: new Date(now - 1000),
+ error: null,
+ id: 'job-1',
+ metadata: { connectionId: 'c', issueIds: ['a', 'b'], kind: 'issues', projectId: 'p' },
+ status: 'processing',
+ updatedAt: new Date(now - 1000),
+ ...overrides,
+ }) as LinearSyncJobRow;
+
+describe('toLinearSyncJobView', () => {
+ it('keeps a recently active job running', () => {
+ expect(toLinearSyncJobView(row({}), now)).toMatchObject({
+ error: null,
+ issueCount: 2,
+ status: 'processing',
+ });
+ });
+
+ it('shows a job that stopped moving as timed out, so it can be started again', () => {
+ const stale = row({ updatedAt: new Date(now - LINEAR_SYNC_STALE_MS - 1) });
+ expect(toLinearSyncJobView(stale, now)).toMatchObject({ error: 'timeout', status: 'error' });
+ });
+
+ it('gives up on a job the async router never picked up after a short wait', () => {
+ const waiting = row({ status: 'pending', updatedAt: new Date(now - 30_000) });
+ expect(toLinearSyncJobView(waiting, now)).toMatchObject({ status: 'pending' });
+ const lost = row({
+ status: 'pending',
+ updatedAt: new Date(now - LINEAR_SYNC_UNCLAIMED_MS - 1),
+ });
+ expect(toLinearSyncJobView(lost, now)).toMatchObject({ error: 'timeout', status: 'error' });
+ });
+
+ it('passes through a recorded failure, defaulting to a generic one', () => {
+ expect(
+ toLinearSyncJobView(row({ error: { code: 'reconnect' }, status: 'error' }), now),
+ ).toMatchObject({ error: 'reconnect', status: 'error' });
+ expect(toLinearSyncJobView(row({ status: 'error' }), now)).toMatchObject({ error: 'failed' });
+ });
+});
diff --git a/apps/server/src/services/linear/__tests__/token.test.ts b/apps/server/src/services/linear/__tests__/token.test.ts
new file mode 100644
index 00000000000..c30e82dda4f
--- /dev/null
+++ b/apps/server/src/services/linear/__tests__/token.test.ts
@@ -0,0 +1,84 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { LinearConnectionModel } from '@/database/models/linear';
+import { users } from '@/database/schemas';
+
+import { getLinearAccessToken, LinearReconnectRequiredError } from '../token';
+
+const refresh = vi.hoisted(() => vi.fn());
+vi.mock('../client', () => ({ refreshLinearToken: refresh }));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: {
+ initWithEnvKey: async () => ({
+ decrypt: async (ciphertext: string) => ({ plaintext: ciphertext }),
+ encrypt: async (plaintext: string) => plaintext,
+ }),
+ },
+}));
+
+const db = await getTestDB();
+const userId = 'linear-token-user';
+
+const connect = (tokenExpiresAt: Date | null, refreshToken?: string) =>
+ LinearConnectionModel.upsert(db, {
+ actorExternalId: 'linear-user',
+ actorName: 'Ada',
+ credentials: { accessToken: 'old', refreshToken },
+ organizationId: 'org-1',
+ organizationName: 'Acme',
+ organizationUrlKey: 'acme',
+ tokenExpiresAt,
+ userId,
+ });
+
+beforeEach(async () => {
+ refresh.mockReset();
+ await db.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ await db.delete(users).where(eq(users.id, userId));
+});
+
+describe('getLinearAccessToken', () => {
+ it('returns a live token without refreshing', async () => {
+ const connection = await connect(new Date(Date.now() + 3_600_000), 'refresh');
+
+ expect(await getLinearAccessToken(db, connection.id)).toBe('old');
+ expect(refresh).not.toHaveBeenCalled();
+ });
+
+ it('refreshes an expiring token and stores the new one', async () => {
+ const connection = await connect(new Date(Date.now() + 1000), 'refresh');
+ const expiresAt = new Date(Date.now() + 86_400_000);
+ refresh.mockResolvedValue({ accessToken: 'new', expiresAt, scopes: ['read'] });
+
+ expect(await getLinearAccessToken(db, connection.id)).toBe('new');
+ expect(refresh).toHaveBeenCalledWith('refresh');
+
+ const stored = await LinearConnectionModel.findDecryptedById(db, connection.id);
+ // Linear did not rotate the refresh token, so the old one is kept.
+ expect(stored?.credentials).toEqual({ accessToken: 'new', refreshToken: 'refresh' });
+ expect(stored?.tokenExpiresAt?.getTime()).toBe(expiresAt.getTime());
+ });
+
+ it('asks to reconnect when the token cannot be refreshed', async () => {
+ const expired = await connect(new Date(Date.now() - 1000));
+
+ await expect(getLinearAccessToken(db, expired.id)).rejects.toBeInstanceOf(
+ LinearReconnectRequiredError,
+ );
+ });
+
+ it('asks to reconnect for a revoked connection', async () => {
+ const connection = await connect(null);
+ await LinearConnectionModel.revoke(db, connection.id);
+
+ await expect(getLinearAccessToken(db, connection.id)).rejects.toBeInstanceOf(
+ LinearReconnectRequiredError,
+ );
+ });
+});
diff --git a/apps/server/src/services/linear/client.ts b/apps/server/src/services/linear/client.ts
index 0370833a36f..8df5afc003d 100644
--- a/apps/server/src/services/linear/client.ts
+++ b/apps/server/src/services/linear/client.ts
@@ -93,6 +93,9 @@ export const exchangeLinearCode = (code: string): Promise<LinearTokenSet> =>
redirect_uri: getLinearRedirectUri(),
});
+export const refreshLinearToken = (refreshToken: string): Promise<LinearTokenSet> =>
+ requestToken({ grant_type: 'refresh_token', refresh_token: refreshToken });
+
/**
* 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.
@@ -105,10 +108,7 @@ export const revokeLinearToken = async (
try {
let { accessToken } = credentials;
if (credentials.refreshToken && expiresAt && expiresAt.getTime() <= Date.now()) {
- const refreshed = await requestToken({
- grant_type: 'refresh_token',
- refresh_token: credentials.refreshToken,
- });
+ const refreshed = await refreshLinearToken(credentials.refreshToken);
accessToken = refreshed.accessToken;
}
diff --git a/apps/server/src/services/linear/issueSync.ts b/apps/server/src/services/linear/issueSync.ts
new file mode 100644
index 00000000000..8f4a78b777d
--- /dev/null
+++ b/apps/server/src/services/linear/issueSync.ts
@@ -0,0 +1,525 @@
+import { createHash } from 'node:crypto';
+
+import type {
+ LinearIssueLinkMetadata,
+ LinearIssuePage,
+ LinearIssueStateType,
+ LinearSyncResult,
+ LinearSyncSkipReason,
+ TaskItem,
+} from '@lobechat/types';
+import debug from 'debug';
+
+import { isTaskIdentifierUniqueViolation, TaskModel } from '@/database/models/task';
+import {
+ TaskExternalLinkModel,
+ type TaskExternalLinkWithTask,
+} from '@/database/models/taskExternalLink';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { TaskService } from '../task';
+import {
+ getLinearIssuesByIds,
+ LINEAR_PAGE_SIZE,
+ type LinearIssue,
+ type LinearIssueFilter,
+ listLinearIssues,
+} from './issues';
+
+const log = debug('lobe-server:linear:issue-sync');
+
+/** Safety bound on the issues one filtered sync reads (200 pages). */
+export const MAX_ISSUES_PER_SYNC = 10_000;
+/**
+ * Tasks one sync creates. Already linked issues are still checked, so running
+ * the sync again picks up where the previous run stopped.
+ */
+export const MAX_TASKS_CREATED_PER_SYNC = 100;
+/** Tries at creating one task when concurrent creates keep taking its identifier. */
+const MAX_CREATE_ATTEMPTS = 5;
+/** Skipped entries kept in a result, so a stored rule result stays small. */
+const MAX_SKIPPED_ENTRIES = 100;
+
+const CLOSED_STATE_TYPES = new Set<LinearIssueStateType>(['completed', 'canceled']);
+const CLOSED_TASK_STATUSES = new Set(['completed', 'canceled']);
+
+/** The task fields a sync owns. */
+interface SyncedFields {
+ instruction: string;
+ name: string;
+ priority: number;
+}
+
+interface SyncOptions {
+ /**
+ * Only close tasks whose issue Linear closed; never create or rewrite. Used
+ * for linked issues that a filtered sync no longer matches.
+ */
+ closeOnly?: boolean;
+ /** Import an issue that is already completed or canceled (as a closed task). */
+ createClosed?: boolean;
+ /** LobeHub project new tasks land in. */
+ targetProjectId?: string | null;
+}
+
+export const linearIssueToTaskFields = (issue: LinearIssue): SyncedFields => {
+ const source = `> Linear: [${issue.identifier}](${issue.url})`;
+ const body = issue.description?.trim() || issue.title;
+ return {
+ instruction: `${source}\n\n${body}`,
+ name: issue.title,
+ // Both sides use 0 none, 1 urgent, 2 high, 3 normal (Linear: medium), 4 low.
+ priority: issue.priority,
+ };
+};
+
+export const hashSyncedFields = (fields: SyncedFields): string =>
+ createHash('sha256')
+ .update(JSON.stringify([fields.name, fields.instruction, fields.priority]))
+ .digest('hex');
+
+const hashTask = (task: TaskItem): string =>
+ hashSyncedFields({
+ instruction: task.instruction,
+ name: task.name ?? '',
+ priority: task.priority ?? 0,
+ });
+
+const linkMetadata = (issue: LinearIssue): LinearIssueLinkMetadata => ({
+ assigneeName: issue.assignee?.displayName,
+ labels: issue.labels?.nodes.map((label) => label.name),
+ projectName: issue.project?.name,
+ stateName: issue.state.name,
+ stateType: issue.state.type,
+ teamKey: issue.team.key,
+});
+
+const emptyResult = (): LinearSyncResult => ({
+ closed: 0,
+ created: 0,
+ keptLocalEdits: 0,
+ skipped: [],
+ skippedCount: 0,
+ truncated: false,
+ unchanged: 0,
+ updated: 0,
+});
+
+/** Parents before their children, so a child can attach to a task created in the same run. */
+const parentsFirst = (issues: LinearIssue[]): LinearIssue[] => {
+ const ids = new Set(issues.map((issue) => issue.id));
+ const ordered: LinearIssue[] = [];
+ const placed = new Set<string>();
+ let pending = issues;
+ while (pending.length > 0) {
+ const ready = pending.filter(
+ (issue) => !issue.parent || !ids.has(issue.parent.id) || placed.has(issue.parent.id),
+ );
+ // A cycle cannot happen in Linear; guard anyway so the loop always ends.
+ const batch = ready.length > 0 ? ready : pending;
+ for (const issue of batch) {
+ ordered.push(issue);
+ placed.add(issue.id);
+ }
+ pending = pending.filter((issue) => !placed.has(issue.id));
+ }
+ return ordered;
+};
+
+/**
+ * One-way Linear → task sync for a scope (a workspace or a user's personal
+ * space). Linear is only read. An issue maps to one task per scope through
+ * `task_external_links`, so syncing again updates that task:
+ *
+ * - name, instruction and priority follow Linear unless the task was edited
+ * in LobeHub since the last sync, in which case the edit is kept;
+ * - a task whose issue Linear completed or canceled is closed the same way,
+ * except a running task, which is never interrupted;
+ * - a task is never reopened, deleted or recreated by a sync.
+ */
+export class LinearIssueSyncService {
+ private readonly db: LobeChatDatabase;
+ private readonly linkModel: TaskExternalLinkModel;
+ private readonly taskModel: TaskModel;
+ private readonly taskService: TaskService;
+ private readonly userId: string;
+ private readonly workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ this.linkModel = new TaskExternalLinkModel(db, userId, workspaceId);
+ this.taskModel = new TaskModel(db, userId, workspaceId);
+ this.taskService = new TaskService(db, userId, workspaceId);
+ }
+
+ /** A page of issues for the import picker, marking the ones already imported. */
+ async listIssues(
+ accessToken: string,
+ filter: LinearIssueFilter,
+ after?: string,
+ ): Promise<LinearIssuePage> {
+ const page = await listLinearIssues(accessToken, filter, { after });
+ const links = await this.visibleLinks(page.issues.map((issue) => issue.id));
+
+ return {
+ cursor: page.cursor,
+ hasMore: page.hasMore,
+ issues: page.issues.map((issue) => ({
+ assigneeName: issue.assignee?.displayName,
+ id: issue.id,
+ identifier: issue.identifier,
+ linkedTaskIdentifier: links.get(issue.id)?.taskIdentifier,
+ priority: issue.priority,
+ projectName: issue.project?.name,
+ stateName: issue.state.name,
+ stateType: issue.state.type,
+ title: issue.title,
+ updatedAt: issue.updatedAt,
+ url: issue.url,
+ })),
+ };
+ }
+
+ /** Import the issues the user picked, whatever their state. */
+ async importIssues(
+ accessToken: string,
+ issueIds: string[],
+ options: { targetProjectId?: string | null } = {},
+ ): Promise<LinearSyncResult> {
+ const issues = await getLinearIssuesByIds(accessToken, issueIds);
+ const result = emptyResult();
+ // An issue deleted or hidden since it was picked is not returned; say so
+ // instead of reporting an empty, "up to date" run.
+ const returned = new Set(issues.map((issue) => issue.id));
+ const missing = [...new Set(issueIds)].filter((id) => !returned.has(id));
+ if (missing.length > 0) {
+ const known = new Map(
+ (await this.linkModel.findByExternalIds('linear', missing)).map((link) => [
+ link.externalId,
+ link.externalIdentifier,
+ ]),
+ );
+ for (const id of missing) skip(result, known.get(id) ?? id, 'missing');
+ }
+ await this.syncIssues(
+ issues,
+ { createClosed: true, targetProjectId: options.targetProjectId },
+ result,
+ );
+ return result;
+ }
+
+ /**
+ * Sync every issue matching a filter, then close the tasks of linked issues
+ * in the same team that the filter no longer matches because Linear closed
+ * them.
+ */
+ async syncByFilter(
+ accessToken: string,
+ filter: LinearIssueFilter,
+ options: { targetProjectId?: string | null } = {},
+ ): Promise<LinearSyncResult> {
+ const result = emptyResult();
+ const issues: LinearIssue[] = [];
+ // Read until this run has as many not-yet-imported issues as it may create.
+ // Already linked issues do not count, so the next run reaches further.
+ let unlinked = 0;
+ let after: string | undefined;
+ do {
+ const page = await listLinearIssues(accessToken, filter, {
+ after,
+ first: Math.min(LINEAR_PAGE_SIZE, MAX_ISSUES_PER_SYNC - issues.length),
+ });
+ issues.push(...page.issues);
+ after = page.cursor;
+ const linked = await this.linkModel.findByExternalIds(
+ 'linear',
+ page.issues.map((issue) => issue.id),
+ );
+ unlinked += page.issues.length - linked.length;
+ } while (after && issues.length < MAX_ISSUES_PER_SYNC && unlinked < MAX_TASKS_CREATED_PER_SYNC);
+ result.truncated = !!after;
+
+ await this.syncIssues(
+ issues,
+ {
+ createClosed: filter.stateTypes.some((type) => CLOSED_STATE_TYPES.has(type)),
+ targetProjectId: options.targetProjectId,
+ },
+ result,
+ );
+
+ // Linked issues the filter missed: closed since, or moved out of the project.
+ const seen = new Set(issues.map((issue) => issue.id));
+ const unseen = (await this.linkModel.findByContainer('linear', filter.teamId)).filter(
+ (link) => !seen.has(link.externalId),
+ );
+ if (unseen.length > 0) {
+ const open = await this.taskModel.findByIds(unseen.map((link) => link.taskId));
+ const openTaskIds = new Set(
+ open.filter((task) => !CLOSED_TASK_STATUSES.has(task.status)).map((task) => task.id),
+ );
+ const toCheck = unseen.filter((link) => openTaskIds.has(link.taskId));
+ if (toCheck.length > 0) {
+ const fetched = await getLinearIssuesByIds(
+ accessToken,
+ toCheck.map((link) => link.externalId),
+ );
+ await this.syncIssues(fetched, { closeOnly: true }, result);
+ }
+ }
+
+ return result;
+ }
+
+ private async syncIssues(
+ issues: LinearIssue[],
+ options: SyncOptions,
+ result: LinearSyncResult,
+ ): Promise<void> {
+ if (issues.length === 0) return;
+
+ const parentIds = issues.flatMap((issue) => (issue.parent ? [issue.parent.id] : []));
+ // Every link in scope, visible or not: an issue whose task is trashed or
+ // private to someone else is still taken, and is reported, not re-created.
+ const links = new Map(
+ (
+ await this.linkModel.findByExternalIds('linear', [
+ ...new Set([...issues.map((issue) => issue.id), ...parentIds]),
+ ])
+ ).map((link) => [link.externalId, link]),
+ );
+ const tasks = new Map(
+ (await this.taskModel.findByIds([...links.values()].map((link) => link.taskId))).map(
+ (task) => [task.id, task],
+ ),
+ );
+
+ for (const issue of parentsFirst(issues)) {
+ try {
+ const link = links.get(issue.id);
+ if (link) {
+ await this.syncLinked(issue, link, tasks.get(link.taskId), options, result);
+ } else if (!options.closeOnly) {
+ const created = await this.create(issue, links, tasks, options, result);
+ if (created) {
+ links.set(issue.id, created.link);
+ tasks.set(created.task.id, created.task);
+ }
+ }
+ } catch (error) {
+ log('sync %s failed: %O', issue.identifier, error);
+ skip(result, issue.identifier, 'failed');
+ }
+ }
+ }
+
+ private async create(
+ issue: LinearIssue,
+ links: Map<string, TaskExternalLinkWithTask>,
+ tasks: Map<string, TaskItem>,
+ options: SyncOptions,
+ result: LinearSyncResult,
+ ): Promise<{ link: TaskExternalLinkWithTask; task: TaskItem } | undefined> {
+ const closed = CLOSED_STATE_TYPES.has(issue.state.type);
+ if (closed && !options.createClosed) {
+ skip(result, issue.identifier, 'closed');
+ return;
+ }
+ if (result.created >= MAX_TASKS_CREATED_PER_SYNC) {
+ result.truncated = true;
+ return;
+ }
+
+ const fields = linearIssueToTaskFields(issue);
+ const targetProjectId = options.targetProjectId ?? null;
+ // A subtask must share its parent's project, so attach only when it does.
+ const parentLink = issue.parent ? links.get(issue.parent.id) : undefined;
+ const parentTask = parentLink ? tasks.get(parentLink.taskId) : undefined;
+ const parentTaskId =
+ parentTask && (parentTask.projectId ?? null) === targetProjectId ? parentTask.id : undefined;
+
+ const created = await this.createLinked(issue, fields, {
+ parentTaskId,
+ projectId: targetProjectId ?? undefined,
+ });
+ if ('winner' in created) {
+ // A concurrent sync linked the issue first. Continue with its task, so
+ // this run's children still nest under it.
+ result.unchanged += 1;
+ return created.winner;
+ }
+
+ const { link, task } = created;
+ let current = task;
+ if (closed) current = (await this.close(task, issue.state.type)) ?? task;
+ result.created += 1;
+ return { link, task: current };
+ }
+
+ /**
+ * Create the task and its link in one transaction, so a run cut off between
+ * the two never leaves an unlinked task that the next run would duplicate.
+ * An identifier clash with a concurrent task create is retried as a whole;
+ * a link clash means another sync imported the issue first, and its link
+ * and task (if visible) are returned instead.
+ */
+ private async createLinked(
+ issue: LinearIssue,
+ fields: SyncedFields,
+ placement: { parentTaskId?: string; projectId?: string },
+ ): Promise<
+ | { link: TaskExternalLinkWithTask; task: TaskItem }
+ | { winner: { link: TaskExternalLinkWithTask; task: TaskItem } | undefined }
+ > {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ return await this.db.transaction(async (tx) => {
+ const task = await new TaskService(tx, this.userId, this.workspaceId).createTask(
+ { ...fields, ...placement },
+ { maxRetries: 1 },
+ );
+ const link = await new TaskExternalLinkModel(tx, this.userId, this.workspaceId).create({
+ externalContainerId: issue.team.id,
+ externalId: issue.id,
+ externalIdentifier: issue.identifier,
+ externalUpdatedAt: new Date(issue.updatedAt),
+ externalUrl: issue.url,
+ metadata: linkMetadata(issue),
+ provider: 'linear',
+ syncedHash: hashSyncedFields(fields),
+ taskId: task.id,
+ });
+ return { link: { ...link, taskIdentifier: task.identifier }, task };
+ });
+ } catch (error) {
+ if (!isTaskIdentifierUniqueViolation(error)) throw error;
+ const [link] = await this.linkModel.findByExternalIds('linear', [issue.id]);
+ if (link) {
+ const task = await this.taskModel.findById(link.taskId);
+ return { winner: task ? { link, task } : undefined };
+ }
+ if (attempt >= MAX_CREATE_ATTEMPTS) throw error;
+ }
+ }
+ }
+
+ private async syncLinked(
+ issue: LinearIssue,
+ link: TaskExternalLinkWithTask,
+ task: TaskItem | undefined,
+ options: SyncOptions,
+ result: LinearSyncResult,
+ ): Promise<void> {
+ if (!task) {
+ skip(result, issue.identifier, 'unavailable');
+ return;
+ }
+
+ // Every issue lands in exactly one bucket besides `closed`: updated, kept
+ // local edits, skipped, or unchanged.
+ let counted = false;
+ if (!options.closeOnly) {
+ const fields = linearIssueToTaskFields(issue);
+ const nextHash = hashSyncedFields(fields);
+ if (hashTask(task) !== link.syncedHash) {
+ result.keptLocalEdits += 1;
+ counted = true;
+ } else if (nextHash !== link.syncedHash) {
+ const applied = await this.applyLinearFields(task.id, link, fields, nextHash);
+ if (applied === 'updated') {
+ result.updated += 1;
+ } else {
+ // Edited (or removed) since the batch was loaded.
+ result.keptLocalEdits += 1;
+ }
+ counted = true;
+ }
+ }
+
+ if (CLOSED_STATE_TYPES.has(issue.state.type) && !CLOSED_TASK_STATUSES.has(task.status)) {
+ // Rechecked under the row lock: the task may have started since the batch was read.
+ const closed =
+ task.status !== 'running' && (await this.close(task, issue.state.type)) !== undefined;
+ if (closed) result.closed += 1;
+ else skip(result, issue.identifier, 'running');
+ counted = true;
+ }
+
+ if (!counted) result.unchanged += 1;
+
+ // Display facts only. `syncedHash` is written solely by `create` and
+ // `applyLinearFields`, together with the task, so a run working from an
+ // older read can never put a stale hash back.
+ const issueUpdatedAt = new Date(issue.updatedAt);
+ if (link.externalUpdatedAt?.getTime() === issueUpdatedAt.getTime()) return;
+
+ await this.linkModel.update(link.id, {
+ externalContainerId: issue.team.id,
+ externalIdentifier: issue.identifier,
+ externalUpdatedAt: issueUpdatedAt,
+ externalUrl: issue.url,
+ metadata: linkMetadata(issue),
+ });
+ }
+
+ /**
+ * Write Linear's fields only if the task still holds what the last sync
+ * wrote, recording the new hash in the same transaction. Rechecking under
+ * the row lock keeps a LobeHub edit made during the run; writing both rows
+ * together means a failure never leaves our own write looking like an edit.
+ */
+ private async applyLinearFields(
+ taskId: string,
+ link: TaskExternalLinkWithTask,
+ fields: SyncedFields,
+ nextHash: string,
+ ): Promise<'kept' | 'updated'> {
+ return this.db.transaction(async (tx) => {
+ const tasks = new TaskModel(tx, this.userId, this.workspaceId);
+ await tasks.lockForUpdate(taskId);
+ const current = await tasks.findById(taskId);
+ if (!current || hashTask(current) !== link.syncedHash) return 'kept';
+
+ await tasks.updateWithLog(taskId, fields, { userId: this.userId });
+ await new TaskExternalLinkModel(tx, this.userId, this.workspaceId).update(link.id, {
+ syncedHash: nextHash,
+ });
+ return 'updated';
+ });
+ }
+
+ /** Close the task like its issue; undefined when it is running and was left alone. */
+ private async close(
+ task: TaskItem,
+ stateType: LinearIssueStateType,
+ ): Promise<TaskItem | undefined> {
+ const { skippedRunning, task: updated } = await this.taskService.updateStatus(
+ {
+ id: task.id,
+ skipIfRunning: true,
+ status: stateType === 'completed' ? 'completed' : 'canceled',
+ },
+ { userId: this.userId },
+ );
+ return skippedRunning ? undefined : updated;
+ }
+
+ /** Links in this scope whose task the caller can still see. */
+ private async visibleLinks(externalIds: string[]) {
+ const links = await this.linkModel.findByExternalIds('linear', [...new Set(externalIds)]);
+ const visible = new Set(
+ (await this.taskModel.findByIds(links.map((link) => link.taskId))).map((task) => task.id),
+ );
+ return new Map(
+ links.filter((link) => visible.has(link.taskId)).map((link) => [link.externalId, link]),
+ );
+ }
+}
+
+const skip = (result: LinearSyncResult, identifier: string, reason: LinearSyncSkipReason) => {
+ result.skippedCount = (result.skippedCount ?? 0) + 1;
+ if (result.skipped.length < MAX_SKIPPED_ENTRIES) result.skipped.push({ identifier, reason });
+};
diff --git a/apps/server/src/services/linear/issues.ts b/apps/server/src/services/linear/issues.ts
new file mode 100644
index 00000000000..b21f7202eac
--- /dev/null
+++ b/apps/server/src/services/linear/issues.ts
@@ -0,0 +1,153 @@
+import type {
+ LinearIssueStateType,
+ LinearProjectSummary,
+ LinearTeamSummary,
+} from '@lobechat/types';
+
+import { linearGraphql } from './client';
+
+/** Linear's largest page size. */
+export const LINEAR_PAGE_SIZE = 50;
+
+/** An issue with everything a sync writes into a task. */
+export interface LinearIssue {
+ assignee?: { displayName: string } | null;
+ description?: string | null;
+ id: string;
+ identifier: string;
+ labels?: { nodes: { name: string }[] };
+ parent?: { id: string } | null;
+ priority: number;
+ project?: { id: string; name: string } | null;
+ state: { name: string; type: LinearIssueStateType };
+ team: { id: string; key: string };
+ title: string;
+ updatedAt: string;
+ url: string;
+}
+
+const ISSUE_FIELDS = `
+ id identifier title description url priority updatedAt
+ state { name type }
+ parent { id }
+ assignee { displayName }
+ labels(first: 10) { nodes { name } }
+ project { id name }
+ team { id key }
+`;
+
+interface Connection<T> {
+ nodes: T[];
+ pageInfo: { endCursor?: string | null; hasNextPage: boolean };
+}
+
+export const listLinearTeams = async (accessToken: string): Promise<LinearTeamSummary[]> => {
+ const teams: LinearTeamSummary[] = [];
+ let after: string | undefined;
+ do {
+ const data = await linearGraphql<{ teams: Connection<LinearTeamSummary> }>(
+ accessToken,
+ `query LobeTeams($first: Int!, $after: String) {
+ teams(first: $first, after: $after) {
+ nodes { id key name }
+ pageInfo { hasNextPage endCursor }
+ }
+ }`,
+ { after, first: LINEAR_PAGE_SIZE },
+ );
+ teams.push(...data.teams.nodes);
+ after = data.teams.pageInfo.hasNextPage
+ ? (data.teams.pageInfo.endCursor ?? undefined)
+ : undefined;
+ } while (after);
+ return teams.sort((a, b) => a.name.localeCompare(b.name));
+};
+
+export const listLinearProjects = async (
+ accessToken: string,
+ teamId: string,
+): Promise<LinearProjectSummary[]> => {
+ const projects: LinearProjectSummary[] = [];
+ let after: string | undefined;
+ do {
+ const data = await linearGraphql<{ team: { projects: Connection<LinearProjectSummary> } }>(
+ accessToken,
+ `query LobeTeamProjects($teamId: String!, $first: Int!, $after: String) {
+ team(id: $teamId) {
+ projects(first: $first, after: $after) {
+ nodes { id name }
+ pageInfo { hasNextPage endCursor }
+ }
+ }
+ }`,
+ { after, first: LINEAR_PAGE_SIZE, teamId },
+ );
+ const page = data.team.projects;
+ projects.push(...page.nodes);
+ after = page.pageInfo.hasNextPage ? (page.pageInfo.endCursor ?? undefined) : undefined;
+ } while (after);
+ return projects.sort((a, b) => a.name.localeCompare(b.name));
+};
+
+export interface LinearIssueFilter {
+ linearProjectId?: string | null;
+ stateTypes: LinearIssueStateType[];
+ teamId: string;
+}
+
+const toIssueFilter = ({ linearProjectId, stateTypes, teamId }: LinearIssueFilter) => ({
+ state: { type: { in: stateTypes } },
+ team: { id: { eq: teamId } },
+ ...(linearProjectId ? { project: { id: { eq: linearProjectId } } } : {}),
+});
+
+/** One page of issues matching a filter, most recently updated first. */
+export const listLinearIssues = async (
+ accessToken: string,
+ filter: LinearIssueFilter,
+ options: { after?: string; first?: number } = {},
+): Promise<{ cursor?: string; hasMore: boolean; issues: LinearIssue[] }> => {
+ const data = await linearGraphql<{ issues: Connection<LinearIssue> }>(
+ accessToken,
+ `query LobeIssues($first: Int!, $after: String, $filter: IssueFilter) {
+ issues(first: $first, after: $after, orderBy: updatedAt, filter: $filter) {
+ nodes { ${ISSUE_FIELDS} }
+ pageInfo { hasNextPage endCursor }
+ }
+ }`,
+ {
+ after: options.after,
+ filter: toIssueFilter(filter),
+ first: Math.min(options.first ?? LINEAR_PAGE_SIZE, LINEAR_PAGE_SIZE),
+ },
+ );
+ const { nodes, pageInfo } = data.issues;
+ return {
+ cursor: pageInfo.hasNextPage ? (pageInfo.endCursor ?? undefined) : undefined,
+ hasMore: pageInfo.hasNextPage,
+ issues: nodes,
+ };
+};
+
+/** Issues by id, in pages of the API's maximum size. Unknown or inaccessible ids are omitted. */
+export const getLinearIssuesByIds = async (
+ accessToken: string,
+ ids: string[],
+): Promise<LinearIssue[]> => {
+ const issues: LinearIssue[] = [];
+ for (let start = 0; start < ids.length; start += LINEAR_PAGE_SIZE) {
+ const batch = ids.slice(start, start + LINEAR_PAGE_SIZE);
+ const data = await linearGraphql<{ issues: Connection<LinearIssue> }>(
+ accessToken,
+ `query LobeIssuesById($first: Int!, $filter: IssueFilter) {
+ issues(first: $first, filter: $filter) {
+ nodes { ${ISSUE_FIELDS} }
+ pageInfo { hasNextPage endCursor }
+ }
+ }`,
+ { filter: { id: { in: batch } }, first: batch.length },
+ );
+ issues.push(...data.issues.nodes);
+ }
+ return issues;
+};
diff --git a/apps/server/src/services/linear/startSyncJob.ts b/apps/server/src/services/linear/startSyncJob.ts
new file mode 100644
index 00000000000..f031b22e00f
--- /dev/null
+++ b/apps/server/src/services/linear/startSyncJob.ts
@@ -0,0 +1,94 @@
+import type { LinearSyncJobErrorCode, LinearSyncJobMetadata } from '@lobechat/types';
+import { AsyncTaskStatus, AsyncTaskType } from '@lobechat/types';
+import debug from 'debug';
+
+import { AsyncTaskModel } from '@/database/models/asyncTask';
+import { LinearSyncJobModel, LinearSyncRuleModel } from '@/database/models/linear';
+import type { LobeChatDatabase } from '@/database/type';
+import { createAsyncCaller } from '@/server/routers/async';
+
+import { toLinearSyncJobView } from './syncJob';
+
+const log = debug('lobe-server:linear:sync-job');
+
+/**
+ * Record a Linear sync job and hand it to the async router, which runs it with
+ * `LinearSyncJobService`. Kept apart from that service so the async router can
+ * import it without importing itself back.
+ */
+export const startLinearSyncJob = async (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string | undefined,
+ metadata: LinearSyncJobMetadata,
+): Promise<string> => {
+ const taskId = await recordJob(db, userId, workspaceId, metadata);
+ await dispatchJob(db, userId, workspaceId, taskId);
+ return taskId;
+};
+
+/**
+ * Start a run of a saved rule, or return the one still going. The check and
+ * the insert happen under a lock on the rule row, so two concurrent starts
+ * (two tabs, two members) queue one run, not two.
+ */
+export const startLinearRuleSyncJob = async (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string | undefined,
+ metadata: LinearSyncJobMetadata & { kind: 'rule'; ruleId: string },
+): Promise<string> => {
+ const scope = { userId, workspaceId: workspaceId ?? null };
+ const { created, taskId } = await db.transaction(async (tx) => {
+ if (!(await LinearSyncRuleModel.lockInScope(tx, metadata.ruleId, scope))) {
+ throw new Error('Linear sync rule not found');
+ }
+ const running = await LinearSyncJobModel.findActiveForRule(
+ tx,
+ scope,
+ metadata.projectId,
+ metadata.ruleId,
+ );
+ if (running && toLinearSyncJobView(running).status !== 'error') {
+ return { created: false, taskId: running.id };
+ }
+ return { created: true, taskId: await recordJob(tx, userId, workspaceId, metadata) };
+ });
+ if (created) await dispatchJob(db, userId, workspaceId, taskId);
+ return taskId;
+};
+
+const recordJob = (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string | undefined,
+ metadata: LinearSyncJobMetadata,
+) =>
+ new AsyncTaskModel(db, userId, workspaceId).create({
+ metadata,
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.LinearIssueSync,
+ });
+
+const dispatchJob = async (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string | undefined,
+ taskId: string,
+) => {
+ try {
+ const asyncCaller = await createAsyncCaller({ userId });
+ // Fire and forget: the async router owns the job once the request reaches
+ // it, so a dropped response here (a proxy timing out a long run) is not a
+ // failed sync; only log it.
+ asyncCaller.linear
+ .runSync({ taskId, workspaceId })
+ .catch((error: unknown) => log('async sync %s request failed: %O', taskId, error));
+ } catch (error) {
+ log('trigger sync %s failed: %O', taskId, error);
+ await new AsyncTaskModel(db, userId, workspaceId).update(taskId, {
+ error: { code: 'failed' satisfies LinearSyncJobErrorCode },
+ status: AsyncTaskStatus.Error,
+ });
+ }
+};
diff --git a/apps/server/src/services/linear/syncJob.ts b/apps/server/src/services/linear/syncJob.ts
new file mode 100644
index 00000000000..33f98f1d00c
--- /dev/null
+++ b/apps/server/src/services/linear/syncJob.ts
@@ -0,0 +1,161 @@
+import type {
+ LinearSyncJobErrorCode,
+ LinearSyncJobMetadata,
+ LinearSyncJobView,
+ LinearSyncResult,
+} from '@lobechat/types';
+import { AsyncTaskStatus } from '@lobechat/types';
+import debug from 'debug';
+
+import { AsyncTaskModel } from '@/database/models/asyncTask';
+import type { LinearSyncJobRow } from '@/database/models/linear';
+import { LinearSyncJobModel, LinearSyncRuleModel } from '@/database/models/linear';
+import { ProjectModel } from '@/database/models/project';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { LinearApiError } from './client';
+import { LinearIssueSyncService } from './issueSync';
+import { getLinearAccessToken, LinearReconnectRequiredError } from './token';
+
+const log = debug('lobe-server:linear:sync-job');
+
+/**
+ * A run that has not moved for this long was cut off (a deploy, a crashed
+ * function); it is shown as failed so the user can start it again.
+ */
+export const LINEAR_SYNC_STALE_MS = 15 * 60 * 1000;
+/** How often a running sync records that it is still alive; well inside the stale window. */
+export const LINEAR_SYNC_HEARTBEAT_MS = 60 * 1000;
+/**
+ * A job the async router never picked up (the hand-off failed, or its token
+ * expired on the way) is given up on much sooner than a running one.
+ */
+export const LINEAR_SYNC_UNCLAIMED_MS = 2 * 60 * 1000;
+
+export const toLinearSyncJobView = (
+ row: LinearSyncJobRow,
+ now: number = Date.now(),
+): LinearSyncJobView => {
+ const metadata = row.metadata;
+ const idle = now - row.updatedAt.getTime();
+ const stale =
+ (row.status === AsyncTaskStatus.Pending && idle > LINEAR_SYNC_UNCLAIMED_MS) ||
+ (row.status === AsyncTaskStatus.Processing && idle > LINEAR_SYNC_STALE_MS);
+ const error = (row.error as { code?: LinearSyncJobErrorCode } | null)?.code ?? null;
+ return {
+ createdAt: row.createdAt,
+ error: stale ? 'timeout' : row.status === AsyncTaskStatus.Error ? (error ?? 'failed') : null,
+ id: row.id,
+ issueCount: metadata.issueIds?.length,
+ kind: metadata.kind,
+ projectId: metadata.projectId,
+ result: metadata.result ?? null,
+ ruleId: metadata.ruleId ?? null,
+ status: stale ? 'error' : ((row.status ?? 'pending') as LinearSyncJobView['status']),
+ updatedAt: row.updatedAt,
+ };
+};
+
+class LinearSyncJobError extends Error {
+ constructor(readonly code: LinearSyncJobErrorCode) {
+ super(code);
+ }
+}
+
+/**
+ * Runs a Linear → task sync in the background. The lambda request records
+ * the job and hands it to the async router (`linear.runSync`, see
+ * `startLinearSyncJob`), which runs it here and owns its status; the client
+ * polls the job instead of holding a request open, and may leave while it
+ * runs. Linear is only read.
+ */
+export class LinearSyncJobService {
+ private readonly asyncTaskModel: AsyncTaskModel;
+
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {
+ this.asyncTaskModel = new AsyncTaskModel(db, userId, workspaceId);
+ }
+
+ /** Run a recorded job to completion (async router side). */
+ async run(taskId: string): Promise<void> {
+ const task = await LinearSyncJobModel.claim(this.db, this.scope, taskId);
+ if (!task) return;
+
+ const metadata = task.metadata;
+ const startedAt = Date.now();
+ // A long sync keeps its lease, so it is not shown as cut off and the same
+ // rule cannot be started again while it still writes tasks.
+ const heartbeat = setInterval(() => {
+ LinearSyncJobModel.touch(this.db, this.scope, taskId).catch((error: unknown) =>
+ log('heartbeat %s failed: %O', taskId, error),
+ );
+ }, LINEAR_SYNC_HEARTBEAT_MS);
+ try {
+ const result = await this.execute(metadata);
+ await this.asyncTaskModel.update(taskId, {
+ duration: Date.now() - startedAt,
+ metadata: { ...metadata, result },
+ status: AsyncTaskStatus.Success,
+ });
+ } catch (error) {
+ const code = toErrorCode(error);
+ log('sync %s failed (%s): %O', taskId, code, error);
+ await this.asyncTaskModel.update(taskId, {
+ duration: Date.now() - startedAt,
+ error: { code },
+ status: AsyncTaskStatus.Error,
+ });
+ } finally {
+ clearInterval(heartbeat);
+ }
+ }
+
+ private get scope() {
+ return { userId: this.userId, workspaceId: this.workspaceId ?? null };
+ }
+
+ private async execute(metadata: LinearSyncJobMetadata): Promise<LinearSyncResult> {
+ const scope = this.scope;
+ // The project may have been deleted or hidden since the job was queued.
+ const project = await new ProjectModel(this.db, this.userId, this.workspaceId).findById(
+ metadata.projectId,
+ );
+ if (!project) throw new LinearSyncJobError('unavailable');
+
+ const sync = new LinearIssueSyncService(this.db, this.userId, this.workspaceId);
+ const options = { targetProjectId: metadata.projectId };
+
+ if (metadata.kind === 'issues') {
+ const token = await getLinearAccessToken(this.db, metadata.connectionId);
+ return sync.importIssues(token, metadata.issueIds ?? [], options);
+ }
+
+ const rule = metadata.ruleId
+ ? await LinearSyncRuleModel.findInScope(this.db, metadata.ruleId, scope)
+ : null;
+ if (!rule || rule.projectId !== metadata.projectId) throw new LinearSyncJobError('unavailable');
+ const token = await getLinearAccessToken(this.db, rule.connectionId);
+ const result = await sync.syncByFilter(
+ token,
+ { linearProjectId: rule.linearProjectId, stateTypes: rule.stateTypes, teamId: rule.teamId },
+ options,
+ );
+ await LinearSyncRuleModel.recordRun(this.db, rule.id, scope, result);
+ return result;
+ }
+}
+
+const toErrorCode = (error: unknown): LinearSyncJobErrorCode => {
+ if (error instanceof LinearSyncJobError) return error.code;
+ if (
+ error instanceof LinearReconnectRequiredError ||
+ (error instanceof LinearApiError && error.status === 401)
+ ) {
+ return 'reconnect';
+ }
+ return 'failed';
+};
diff --git a/apps/server/src/services/linear/token.ts b/apps/server/src/services/linear/token.ts
new file mode 100644
index 00000000000..15aa7e24a5f
--- /dev/null
+++ b/apps/server/src/services/linear/token.ts
@@ -0,0 +1,58 @@
+import { LinearConnectionModel } from '@/database/models/linear';
+import type { LobeChatDatabase } from '@/database/type';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+
+import { refreshLinearToken } from './client';
+
+/** Refresh this long before the recorded expiry so a call never races it. */
+const EXPIRY_MARGIN_MS = 60_000;
+
+/** The connection is revoked or its token can no longer be refreshed; the user must reconnect. */
+export class LinearReconnectRequiredError extends Error {
+ constructor() {
+ super('Linear connection needs to be reconnected');
+ this.name = 'LinearReconnectRequiredError';
+ }
+}
+
+/**
+ * A usable access token for a connection, refreshing (and storing) it first
+ * when it is about to expire.
+ */
+export const getLinearAccessToken = async (
+ db: LobeChatDatabase,
+ connectionId: string,
+): Promise<string> => {
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ const connection = await LinearConnectionModel.findDecryptedById(db, connectionId, gateKeeper);
+ if (!connection || connection.revokedAt || !connection.credentials) {
+ throw new LinearReconnectRequiredError();
+ }
+
+ const { credentials, tokenExpiresAt } = connection;
+ const expiring = !!tokenExpiresAt && tokenExpiresAt.getTime() - EXPIRY_MARGIN_MS <= Date.now();
+ if (!expiring) return credentials.accessToken;
+ if (!credentials.refreshToken) throw new LinearReconnectRequiredError();
+
+ let refreshed;
+ try {
+ refreshed = await refreshLinearToken(credentials.refreshToken);
+ } catch {
+ throw new LinearReconnectRequiredError();
+ }
+
+ await LinearConnectionModel.updateCredentials(
+ db,
+ connectionId,
+ {
+ credentials: {
+ accessToken: refreshed.accessToken,
+ // Linear may rotate the refresh token; keep the old one when it does not.
+ refreshToken: refreshed.refreshToken ?? credentials.refreshToken,
+ },
+ tokenExpiresAt: refreshed.expiresAt ?? null,
+ },
+ gateKeeper,
+ );
+ return refreshed.accessToken;
+};
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index 6df54703dda..800564b03a5 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -111,8 +111,14 @@ export class TaskService {
* `parentTaskId` if it's an identifier, and snapshots the assignee agent's
* current model/provider into `task.config` so later changes to the agent's
* default model don't silently affect this task.
+ *
+ * Inside a caller's transaction pass `maxRetries: 1`: an identifier clash
+ * aborts the transaction, so only the caller can retry it as a whole.
*/
- async createTask(input: CreateTaskInput): Promise<TaskItem> {
+ async createTask(
+ input: CreateTaskInput,
+ options: { maxRetries?: number } = {},
+ ): Promise<TaskItem> {
await this.assertAssigneeAgentBelongsToUser(input.assigneeAgentId);
const taskInput = input;
@@ -193,10 +199,10 @@ export class TaskService {
// produce a `Private parent + Public child` combo if the caller insists.
this.assertParentVisibilityCompat(createData.visibility, parentVisibility);
- const task = await this.createTaskWithAssigneeLock({
- ...createData,
- ...armScheduleOnCreate(createData),
- });
+ const task = await this.createTaskWithAssigneeLock(
+ { ...createData, ...armScheduleOnCreate(createData) },
+ options.maxRetries,
+ );
return task;
}
@@ -650,10 +656,13 @@ export class TaskService {
private async createTaskWithAssigneeLock(
createData: CreateTaskInput & { config?: Record<string, unknown>; status?: TaskStatus },
+ insertRetries?: number,
): Promise<TaskItem> {
if (!createData.assigneeUserId || !this.workspaceId) {
await this.assertAssigneeUserAssignable(createData.assigneeUserId);
- return this.taskModel.create(createData);
+ return insertRetries === undefined
+ ? this.taskModel.create(createData)
+ : this.taskModel.create(createData, { maxRetries: insertRetries });
}
// TaskModel's normal retry loop cannot continue after a unique violation
diff --git a/apps/server/src/services/task/statusTransitions.ts b/apps/server/src/services/task/statusTransitions.ts
index 376fecd6d8f..f7a0a6ea79e 100644
--- a/apps/server/src/services/task/statusTransitions.ts
+++ b/apps/server/src/services/task/statusTransitions.ts
@@ -26,6 +26,8 @@ export interface UpdateStatusResult {
parentTaskId?: string | null;
paused: string[];
pausedTasks?: { id: string; identifier: string }[];
+ /** `skipIfRunning` found the task running and left it unchanged. */
+ skippedRunning?: boolean;
task: TaskItem;
unlocked: string[];
unlockedTasks?: { id: string; identifier: string }[];
@@ -59,6 +61,12 @@ export async function updateStatus(
* interrupting the run mid-tool-call.
*/
operationId?: string;
+ /**
+ * Leave a running task alone instead of interrupting it, checked again
+ * under the row lock of the write. For system closes (an external issue
+ * closed) that must never stop work in progress.
+ */
+ skipIfRunning?: boolean;
status: TaskStatus;
},
/**
@@ -78,6 +86,9 @@ export async function updateStatus(
}
const resolved = await findTaskOrThrow(deps.taskModel, id);
+ if (input.skipIfRunning && resolved.status === 'running') {
+ return { paused: [], skippedRunning: true, task: resolved, unlocked: [] };
+ }
assertArchivedTaskStaysIdle(resolved, { status });
if (resolved.status === 'running' && status !== 'running') {
@@ -122,13 +133,25 @@ export async function updateStatus(
extra.completedAt = new Date();
if (errorMsg) extra.error = errorMsg;
- const task = await writeKeepingArchivedIdle(deps.db, (tx) => {
+ let startedMeanwhile: TaskItem | undefined;
+ const task = await writeKeepingArchivedIdle(deps.db, async (tx) => {
const model = new TaskModel(tx, deps.userId, deps.workspaceId);
+ if (input.skipIfRunning) {
+ await model.lockForUpdate(resolved.id);
+ const current = await model.findById(resolved.id);
+ if (current?.status === 'running') {
+ startedMeanwhile = current;
+ return current;
+ }
+ }
return actor
? model.updateWithLog(resolved.id, { status, ...extra }, actor)
: model.updateStatus(resolved.id, status, extra);
});
if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
+ if (startedMeanwhile) {
+ return { paused: [], skippedRunning: true, task: startedMeanwhile, unlocked: [] };
+ }
// Stamp the schedule run-count window each time the user (re)starts a
// scheduled task. The cron dispatcher itself flips a task running →
diff --git a/docs/usage/integrations/linear.mdx b/docs/usage/integrations/linear.mdx
index ffe6b11c48c..79444d807a8 100644
--- a/docs/usage/integrations/linear.mdx
+++ b/docs/usage/integrations/linear.mdx
@@ -1,8 +1,7 @@
---
title: Linear Integration
description: >-
- Connect a Linear workspace to LobeHub with OAuth, review who connected it,
- and disconnect it when you no longer need access.
+ Connect a Linear workspace to LobeHub with OAuth, import its issues as tasks, and disconnect it when you no longer need access.
tags:
- LobeHub
- Integration
@@ -14,7 +13,7 @@ tags:
**The Linear Integration connects a Linear workspace to LobeHub.** You authorize LobeHub once with Linear OAuth, and the connection is kept with your account or Workspace.
-LobeHub requests **read-only** access. The connection identifies your Linear workspace and the user who authorized it; it cannot create or change issues.
+LobeHub requests **read-only** access. It identifies your Linear workspace and the user who authorized it, and reads issues when you import them; it cannot create or change issues.
> \[!NOTE]
>
@@ -33,6 +32,34 @@ The workspace then appears under **Connections**, with who connected it and when
In a Workspace, the connection belongs to that Workspace. Only Workspace members who can edit can connect or disconnect Linear.
+## Import issues as tasks
+
+Bring Linear issues into a LobeHub project as its tasks to work on them here. Syncing is **one way**: LobeHub reads Linear and never changes, closes or deletes an issue.
+
+Syncing happens inside a project, so connect a Linear workspace first (above); every project in the same account or Workspace can then use it.
+
+1. Open the project, go to **Settings → Advanced**, and click **Import issues** under **Sync from Linear**. The Linear icon at the top of the project's **Tasks** page opens the same dialog. With several Linear workspaces connected, pick one first.
+2. **Choose scope**: pick a **Linear team**, and optionally one of its **Linear projects**. Only open states are ticked by default; completed and canceled issues are left out. Click **Next**.
+3. **Pick issues**: the list shows the issues in scope; ones already synced show their task number. Then either:
+ - tick the issues you want and click **Import N issues**, or
+ - click **Save as rule and sync all** to import every issue in scope and keep the scope as a sync rule.
+4. **Sync**: the sync runs in the background and the dialog shows its progress and outcome (created, updated, closed and skipped, with reasons). Click **Continue in background** to close the dialog; you are notified when it ends, and the outcome is listed under **Sync runs** in **Advanced** settings.
+
+Each issue becomes one task: the issue title becomes the task name, its description becomes the instruction (with a link back to the issue), and its priority carries over. A sub-issue is placed under its parent's task when both are in the same project. Comments, attachments, assignees and labels are not imported.
+
+### Sync again
+
+A project's saved rules are listed under **Sync rules** on its **Settings → Advanced** page. Click **Sync now** to run one again in the background; its progress and outcome appear under **Sync runs**. Importing an issue that is already linked does the same for that issue. A sync:
+
+- updates the task that issue already has, instead of creating another one; the import list marks such issues with a green check and the task number. An issue maps to one task per account or Workspace, so an issue already synced into another project keeps its task there;
+- keeps your changes: if you edited a task's name, instruction or priority in LobeHub, that task is no longer overwritten;
+- closes the task when the issue was completed or canceled in Linear. A task that is running is not interrupted;
+- never reopens or deletes a task. A task you moved to the trash is skipped.
+
+One sync creates up to 100 tasks. When more issues are waiting, the result says so; sync again to continue.
+
+Deleting a rule only removes the saved filter; tasks it created stay. Deleting the project also deletes its rules.
+
## Disconnect Linear
1. In **Connections**, open the menu next to the workspace and choose **Disconnect**.
@@ -49,6 +76,7 @@ Revocation is best-effort: if Linear cannot be reached, the workspace is still r
| **Linear authorized the connection, but LobeHub could not save it.** | Click **Connect workspace** again. |
| **Only workspace members can connect Linear here.** | Ask a Workspace owner or admin for a member role, or connect from your personal account. |
| **This deployment has no Linear application configured** | See [Self-hosted deployments](#self-hosted-deployments). |
+| **The Linear connection has expired.** | Click **Connect workspace** and authorize the same workspace again, then retry. |
## Self-hosted deployments
diff --git a/docs/usage/integrations/linear.zh-CN.mdx b/docs/usage/integrations/linear.zh-CN.mdx
index 334031777cd..51ebf0a3555 100644
--- a/docs/usage/integrations/linear.zh-CN.mdx
+++ b/docs/usage/integrations/linear.zh-CN.mdx
@@ -1,6 +1,6 @@
---
title: Linear 集成
-description: 通过 OAuth 把 Linear 工作区连接到 LobeHub,查看是谁连接的,不再需要时断开连接。
+description: 通过 OAuth 把 Linear 工作区连接到 LobeHub,把 Issue 导入为任务,不再需要时断开连接。
tags:
- LobeHub
- 集成
@@ -12,7 +12,7 @@ tags:
**Linear 集成把一个 Linear 工作区连接到 LobeHub。** 你通过 Linear OAuth 授权一次,连接就会保存在你的账号或工作区下。
-LobeHub 只申请 **只读** 权限。这个连接用来识别你的 Linear 工作区和授权的用户,不能创建或修改 issue。
+LobeHub 只申请 **只读** 权限。这个连接用来识别你的 Linear 工作区和授权的用户,并在你导入时读取 Issue,不能创建或修改 Issue。
> \[!NOTE]
>
@@ -31,6 +31,34 @@ LobeHub 只申请 **只读** 权限。这个连接用来识别你的 Linear 工
在 LobeHub 工作区中,连接属于该工作区。只有具备编辑权限的工作区成员才能连接或断开 Linear。
+## 将 Issue 导入为任务
+
+把 Linear 的 Issue 导入为某个 LobeHub 项目的任务,在这里继续处理。同步是 **单向** 的:LobeHub 只读取 Linear,不会修改、关闭或删除任何 Issue。
+
+同步在项目中进行,所以要先按上文连接 Linear 工作区;同一账号或工作区下的所有项目都可以使用这个连接。
+
+1. 打开项目,进入 **设置 → 高级设置**,在 **从 Linear 同步** 中点击 **导入 Issue**。项目 **任务** 页顶部的 Linear 图标也会打开同一个弹窗。连接了多个 Linear 工作区时,先选择其中一个。
+2. **选择范围**:选择 **Linear 团队**,也可以再选择其中一个 **Linear 项目**;状态默认只勾选未关闭的,不包含已完成和已取消的。点击 **下一步**。
+3. **选择 Issue**:列表显示符合范围的 Issue,已同步的会标出对应的任务编号。然后任选其一:
+ - 勾选需要的 Issue,点击 **导入 N 个 Issue**;
+ - 点击 **保存为规则并全部同步**,导入所有符合条件的 Issue,并把范围保存为同步规则。
+4. **同步**:同步在后台进行,弹窗会显示进度和结果(新建、更新、关闭、跳过的数量及原因)。可以点击 **后台继续** 关闭弹窗,同步结束时会收到提示,结果也会记在 **高级设置** 的 **同步记录** 中。
+
+每个 Issue 对应一个任务:Issue 标题成为任务名称,描述成为任务指令(附原 Issue 链接),优先级保持不变。子 Issue 和父 Issue 在同一项目中时,子任务会挂在父任务下。评论、附件、负责人和标签不会导入。
+
+### 再次同步
+
+项目保存的规则列在它的 **设置 → 高级设置** 页的 **同步规则** 中,点击 **立即同步** 即可在后台再次运行,进度和结果显示在 **同步记录** 中。再次导入已关联的 Issue 效果相同。同步时:
+
+- 更新该 Issue 已对应的任务,不会重复创建;导入列表会在这类 Issue 旁显示绿色对勾和任务编号。同一账号或工作区中一个 Issue 只对应一个任务,已同步到其他项目的 Issue 仍保留在原项目;
+- 保留你的修改:在 LobeHub 中改过名称、指令或优先级的任务,不再被覆盖;
+- Issue 在 Linear 中完成或取消后,对应任务也会关闭;正在运行的任务不会被打断;
+- 不会重新打开或删除任务;已移入回收站的任务会被跳过。
+
+一次同步最多新建 100 个任务。还有待导入的 Issue 时,结果中会提示,再次同步即可继续。
+
+删除规则只会删除保存的筛选条件,已创建的任务会保留。删除项目时,它的规则也会一起删除。
+
## 断开 Linear
1. 在 **连接** 中打开工作区右侧的菜单,选择 **断开连接**。
@@ -47,6 +75,7 @@ LobeHub 只申请 **只读** 权限。这个连接用来识别你的 Linear 工
| **Linear 已授权,但 LobeHub 未能保存此次连接** | 再次点击 **连接工作区**。 |
| **只有工作区成员可以在此连接 Linear。** | 请工作区所有者或管理员给你成员角色,或在个人账号下连接。 |
| **当前部署未配置 Linear 应用** | 见 [自托管部署](#自托管部署)。 |
+| **Linear 连接已失效** | 点击 **连接工作区**,重新授权同一工作区后再试。 |
## 自托管部署
diff --git a/locales/ar/integration.json b/locales/ar/integration.json
index ef274c99533..0306a519e21 100644
--- a/locales/ar/integration.json
+++ b/locales/ar/integration.json
@@ -66,6 +66,86 @@
"linear.installResult.error.unknown": "فشل الاتصال بـ Linear ({{code}}).",
"linear.installResult.error.workspace_forbidden": "يمكن فقط لأعضاء مساحة العمل الاتصال بـ Linear هنا.",
"linear.installResult.success": "تم الاتصال بـ Linear: {{account}}",
+ "linear.sync.error.generic": "فشل مزامنة Linear. يرجى المحاولة مرة أخرى.",
+ "linear.sync.error.reconnect": "انتهت صلاحية اتصال Linear. أعد الاتصال بمساحة العمل ثم حاول مرة أخرى.",
+ "linear.sync.filter.allProjects": "جميع المشاريع",
+ "linear.sync.filter.project": "مشروع Linear",
+ "linear.sync.filter.projectHint": "احتفظ بجميع المشاريع لتضمين كل القضايا في الفريق.",
+ "linear.sync.filter.states": "حالات القضايا للمزامنة",
+ "linear.sync.filter.statesHint": "يتم استبعاد القضايا المكتملة والملغاة افتراضيًا.",
+ "linear.sync.filter.statesSummary": "{{count}} حالات",
+ "linear.sync.filter.team": "فريق Linear",
+ "linear.sync.filter.teamPlaceholder": "اختر فريقًا",
+ "linear.sync.importIssues": "استيراد القضايا",
+ "linear.sync.job.background": "يمكنك إغلاق هذه النافذة؛ تستمر المزامنة في العمل وستتلقى إشعارًا عند انتهائها. يتم أيضًا إدراج النتيجة ضمن عمليات المزامنة في الإعدادات المتقدمة.",
+ "linear.sync.job.close": "تم",
+ "linear.sync.job.continuesInBackground": "تستمر المزامنة في الخلفية. ستتلقى إشعارًا عند انتهائها.",
+ "linear.sync.job.done": "تم الانتهاء من المزامنة",
+ "linear.sync.job.error.timeout": "توقفت المزامنة عن التقدم وتم قطعها. ابدأها مرة أخرى.",
+ "linear.sync.job.error.unavailable": "المشروع أو القاعدة أو اتصال Linear لم يعد متاحًا.",
+ "linear.sync.job.failed": "فشلت المزامنة",
+ "linear.sync.job.finished": "تم الانتهاء من مزامنة Linear: {{result}}",
+ "linear.sync.job.inProgress": "جارٍ المزامنة…",
+ "linear.sync.job.keptLocalEdits": "{{count}} مهام تم تحريرها في LobeHub؛ تم الاحتفاظ بتعديلاتك.",
+ "linear.sync.job.leave": "استمر في الخلفية",
+ "linear.sync.job.listTitle": "عمليات المزامنة",
+ "linear.sync.job.runningIssues": "جارٍ مزامنة {{count}} قضايا…",
+ "linear.sync.job.runningRule": "جارٍ مزامنة كل ما تطابقه القاعدة…",
+ "linear.sync.job.skipReason.closed": "مغلقة في Linear ولم يتم استيرادها أبدًا",
+ "linear.sync.job.skipReason.failed": "لم يتم كتابتها؛ ستتم إعادة المحاولة في المزامنة التالية",
+ "linear.sync.job.skipReason.missing": "لم يعد موجودًا في Linear أو غير مرئي لهذا الاتصال",
+ "linear.sync.job.skipReason.running": "المهمة قيد التشغيل، لذا لم يتم إغلاقها",
+ "linear.sync.job.skipReason.unavailable": "المهمة في سلة المهملات أو غير مرئية لك",
+ "linear.sync.job.skippedTitle": "{{count}} تم تخطيها",
+ "linear.sync.job.titleIssues": "استيراد {{count}} قضايا",
+ "linear.sync.job.titleRule": "قاعدة: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "قاعدة (محذوفة)",
+ "linear.sync.list.count": "{{count}} قضايا",
+ "linear.sync.list.empty": "لا توجد قضايا تطابق هذه الفلاتر.",
+ "linear.sync.list.linked": "تمت المزامنة · {{task}}",
+ "linear.sync.list.loadMore": "تحميل المزيد",
+ "linear.sync.list.openInLinear": "فتح في Linear",
+ "linear.sync.list.pickTeam": "اختر فريقًا لرؤية قضاياه.",
+ "linear.sync.list.selectAll": "حدد كل {{count}} المحملة",
+ "linear.sync.list.selected": "{{count}} محددة",
+ "linear.sync.modal.importNone": "استيراد القضايا",
+ "linear.sync.modal.importSelected": "استيراد {{count}} قضايا",
+ "linear.sync.modal.oneWayHint": "مزامنة باتجاه واحد. لا يتم تغيير أي شيء في Linear.",
+ "linear.sync.modal.saveRule": "حفظ كقاعدة ومزامنة الكل",
+ "linear.sync.modal.saveRuleHint": "قم بمزامنة كل قضية تطابق هذه الفلاتر الآن، واحتفظ بالفلاتر للمزامنة مرة أخرى لاحقًا",
+ "linear.sync.modal.title": "استيراد القضايا من {{account}}",
+ "linear.sync.project.connect": "اتصال Linear",
+ "linear.sync.project.description": "حوّل قضايا Linear إلى مهام لهذا المشروع، واحدة تلو الأخرى أو من خلال قاعدة فريق أو مشروع محفوظة. المزامنة باتجاه واحد: لا يتم تغيير أي شيء في Linear.",
+ "linear.sync.project.entry": "المزامنة من Linear",
+ "linear.sync.project.noConnection": "لم يتم الاتصال بأي مساحة عمل Linear حتى الآن.",
+ "linear.sync.project.title": "المزامنة من Linear",
+ "linear.sync.projectHint": "لمزامنة القضايا في مشروع، افتح المشروع وانتقل إلى الإعدادات → متقدم.",
+ "linear.sync.result.closed": "{{count}} مغلقة",
+ "linear.sync.result.created": "{{count}} تم إنشاؤها",
+ "linear.sync.result.keptLocalEdits": "{{count}} تم الاحتفاظ بالتعديلات المحلية",
+ "linear.sync.result.skipped": "{{count}} تم تخطيها",
+ "linear.sync.result.truncated": "تبقى المزيد من القضايا، قم بالمزامنة مرة أخرى للمتابعة",
+ "linear.sync.result.upToDate": "محدث بالفعل",
+ "linear.sync.result.updated": "{{count}} تم تحديثها",
+ "linear.sync.rules.delete": "حذف القاعدة",
+ "linear.sync.rules.deleteContent": "تظل المهام التي تمت مزامنتها كما هي. يتم فقط إزالة الفلتر المحفوظ.",
+ "linear.sync.rules.deleteTitle": "حذف قاعدة المزامنة هذه؟",
+ "linear.sync.rules.disconnected": "مساحة عمل Linear الخاصة بها غير متصلة. أعد الاتصال للمزامنة، أو احذف القاعدة.",
+ "linear.sync.rules.lastRun": "آخر مزامنة {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "تعذر تحميل قواعد المزامنة",
+ "linear.sync.rules.neverRun": "لم تتم المزامنة بعد",
+ "linear.sync.rules.run": "مزامنة الآن",
+ "linear.sync.rules.running": "جارٍ المزامنة",
+ "linear.sync.rules.title": "قواعد المزامنة",
+ "linear.sync.state.backlog": "قائمة الانتظار",
+ "linear.sync.state.canceled": "ملغاة",
+ "linear.sync.state.completed": "مكتملة",
+ "linear.sync.state.started": "قيد التنفيذ",
+ "linear.sync.state.triage": "فرز",
+ "linear.sync.state.unstarted": "لم تبدأ",
+ "linear.sync.viewerDisabled": "لا يمكن للمشاهدين استيراد القضايا إلى المهام",
+ "linear.sync.wizard.back": "رجوع",
+ "linear.sync.wizard.next": "التالي",
"linear.tagline": "قم بتوصيل مساحة عمل Linear الخاصة بك بـ LobeHub",
"overview.all": "جميع التكاملات",
"overview.comingSoon": "قريبًا",
diff --git a/locales/bg-BG/integration.json b/locales/bg-BG/integration.json
index 3bee973d637..e897250415d 100644
--- a/locales/bg-BG/integration.json
+++ b/locales/bg-BG/integration.json
@@ -66,6 +66,86 @@
"linear.installResult.error.unknown": "Свързването с Linear неуспешно ({{code}}).",
"linear.installResult.error.workspace_forbidden": "Само членове на работното пространство могат да свържат Linear тук.",
"linear.installResult.success": "Linear свързан: {{account}}",
+ "linear.sync.error.generic": "Синхронизацията с Linear не успя. Моля, опитайте отново.",
+ "linear.sync.error.reconnect": "Връзката с Linear е изтекла. Свържете отново работното пространство и опитайте пак.",
+ "linear.sync.filter.allProjects": "Всички проекти",
+ "linear.sync.filter.project": "Проект в Linear",
+ "linear.sync.filter.projectHint": "Оставете 'Всички проекти', за да включите всички задачи в екипа.",
+ "linear.sync.filter.states": "Състояния на задачите за синхронизация",
+ "linear.sync.filter.statesHint": "Завършените и отменените задачи са изключени по подразбиране.",
+ "linear.sync.filter.statesSummary": "{{count}} състояния",
+ "linear.sync.filter.team": "Екип в Linear",
+ "linear.sync.filter.teamPlaceholder": "Изберете екип",
+ "linear.sync.importIssues": "Импортиране на задачи",
+ "linear.sync.job.background": "Можете да затворите този прозорец; синхронизацията ще продължи и ще бъдете уведомени, когато приключи. Резултатът също е наличен в 'Синхронизации' в Разширени настройки.",
+ "linear.sync.job.close": "Готово",
+ "linear.sync.job.continuesInBackground": "Синхронизацията продължава във фонов режим. Ще бъдете уведомени, когато приключи.",
+ "linear.sync.job.done": "Синхронизацията е завършена",
+ "linear.sync.job.error.timeout": "Синхронизацията спря да напредва и беше прекъсната. Стартирайте я отново.",
+ "linear.sync.job.error.unavailable": "Проектът, правилото или връзката с Linear вече не са налични.",
+ "linear.sync.job.failed": "Синхронизацията не успя",
+ "linear.sync.job.finished": "Синхронизацията с Linear е завършена: {{result}}",
+ "linear.sync.job.inProgress": "Синхронизиране…",
+ "linear.sync.job.keptLocalEdits": "{{count}} задачи бяха редактирани в LobeHub; вашите редакции бяха запазени.",
+ "linear.sync.job.leave": "Продължете във фонов режим",
+ "linear.sync.job.listTitle": "Синхронизации",
+ "linear.sync.job.runningIssues": "Синхронизират се {{count}} задачи…",
+ "linear.sync.job.runningRule": "Синхронизират се всички съвпадащи с правилото…",
+ "linear.sync.job.skipReason.closed": "Затворено в Linear и никога не е било импортирано",
+ "linear.sync.job.skipReason.failed": "Не можа да бъде записано; следващата синхронизация ще го опита отново",
+ "linear.sync.job.skipReason.missing": "Вече не е в Linear или не е видимо за тази връзка",
+ "linear.sync.job.skipReason.running": "Задачата е в процес на изпълнение, затова не беше затворена",
+ "linear.sync.job.skipReason.unavailable": "Задачата е в кошчето или не е видима за вас",
+ "linear.sync.job.skippedTitle": "{{count}} пропуснати",
+ "linear.sync.job.titleIssues": "Импортиране на {{count}} задачи",
+ "linear.sync.job.titleRule": "Правило: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "Правило (изтрито)",
+ "linear.sync.list.count": "{{count}} задачи",
+ "linear.sync.list.empty": "Няма задачи, които да отговарят на тези филтри.",
+ "linear.sync.list.linked": "Синхронизирано · {{task}}",
+ "linear.sync.list.loadMore": "Зареди още",
+ "linear.sync.list.openInLinear": "Отвори в Linear",
+ "linear.sync.list.pickTeam": "Изберете екип, за да видите неговите задачи.",
+ "linear.sync.list.selectAll": "Изберете всички {{count}} заредени",
+ "linear.sync.list.selected": "{{count}} избрани",
+ "linear.sync.modal.importNone": "Импортиране на задачи",
+ "linear.sync.modal.importSelected": "Импортиране на {{count}} задачи",
+ "linear.sync.modal.oneWayHint": "Еднопосочна синхронизация. Нищо в Linear няма да бъде променено.",
+ "linear.sync.modal.saveRule": "Запазване като правило и синхронизация на всички",
+ "linear.sync.modal.saveRuleHint": "Синхронизирайте всички задачи, които отговарят на тези филтри сега, и запазете филтрите за бъдещи синхронизации",
+ "linear.sync.modal.title": "Импортиране на задачи от {{account}}",
+ "linear.sync.project.connect": "Свържете Linear",
+ "linear.sync.project.description": "Превърнете задачите от Linear в задачи на този проект, една по една или чрез запазено правило за екип или проект. Синхронизацията е еднопосочна: нищо в Linear няма да бъде променено.",
+ "linear.sync.project.entry": "Синхронизация от Linear",
+ "linear.sync.project.noConnection": "Все още няма свързано работно пространство в Linear.",
+ "linear.sync.project.title": "Синхронизация от Linear",
+ "linear.sync.projectHint": "За да синхронизирате задачи в проект, отворете проекта и отидете на Настройки → Разширени.",
+ "linear.sync.result.closed": "{{count}} затворени",
+ "linear.sync.result.created": "{{count}} създадени",
+ "linear.sync.result.keptLocalEdits": "{{count}} запазени локални редакции",
+ "linear.sync.result.skipped": "{{count}} пропуснати",
+ "linear.sync.result.truncated": "остават още задачи, синхронизирайте отново, за да продължите",
+ "linear.sync.result.upToDate": "Вече е актуално",
+ "linear.sync.result.updated": "{{count}} актуализирани",
+ "linear.sync.rules.delete": "Изтриване на правило",
+ "linear.sync.rules.deleteContent": "Задачите, които вече са синхронизирани, ще останат непроменени. Само запазеният филтър ще бъде премахнат.",
+ "linear.sync.rules.deleteTitle": "Изтриване на това правило за синхронизация?",
+ "linear.sync.rules.disconnected": "Работното пространство в Linear е прекъснато. Свържете го отново, за да синхронизирате, или изтрийте правилото.",
+ "linear.sync.rules.lastRun": "Последна синхронизация {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "Неуспешно зареждане на правилата за синхронизация",
+ "linear.sync.rules.neverRun": "Все още не е синхронизирано",
+ "linear.sync.rules.run": "Синхронизирай сега",
+ "linear.sync.rules.running": "Синхронизиране",
+ "linear.sync.rules.title": "Правила за синхронизация",
+ "linear.sync.state.backlog": "Изчакване",
+ "linear.sync.state.canceled": "Отменено",
+ "linear.sync.state.completed": "Завършено",
+ "linear.sync.state.started": "В процес",
+ "linear.sync.state.triage": "Оценка",
+ "linear.sync.state.unstarted": "За започване",
+ "linear.sync.viewerDisabled": "Наблюдателите не могат да импортират задачи в задачи",
+ "linear.sync.wizard.back": "Назад",
+ "linear.sync.wizard.next": "Напред",
"linear.tagline": "Свържете вашето Linear работно пространство с LobeHub",
"overview.all": "Всички интеграции",
"overview.comingSoon": "Очаквайте скоро",
diff --git a/locales/de-DE/integration.json b/locales/de-DE/integration.json
index de4381332e0..4381a1812f6 100644
--- a/locales/de-DE/integration.json
+++ b/locales/de-DE/integration.json
@@ -66,6 +66,86 @@
"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.sync.error.generic": "Linear-Synchronisierung fehlgeschlagen. Bitte versuchen Sie es erneut.",
+ "linear.sync.error.reconnect": "Die Linear-Verbindung ist abgelaufen. Verbinden Sie den Arbeitsbereich erneut und versuchen Sie es dann erneut.",
+ "linear.sync.filter.allProjects": "Alle Projekte",
+ "linear.sync.filter.project": "Linear-Projekt",
+ "linear.sync.filter.projectHint": "Behalten Sie 'Alle Projekte', um jedes Problem im Team einzubeziehen.",
+ "linear.sync.filter.states": "Probleme-Status zum Synchronisieren",
+ "linear.sync.filter.statesHint": "Abgeschlossene und stornierte Probleme werden standardmäßig ausgelassen.",
+ "linear.sync.filter.statesSummary": "{{count}} Status",
+ "linear.sync.filter.team": "Linear-Team",
+ "linear.sync.filter.teamPlaceholder": "Wählen Sie ein Team",
+ "linear.sync.importIssues": "Probleme importieren",
+ "linear.sync.job.background": "Sie können dieses Fenster schließen; die Synchronisierung läuft weiter und Sie werden benachrichtigt, wenn sie endet. Das Ergebnis wird auch unter Synchronisierungsläufe in den erweiterten Einstellungen aufgeführt.",
+ "linear.sync.job.close": "Fertig",
+ "linear.sync.job.continuesInBackground": "Die Synchronisierung läuft im Hintergrund weiter. Sie werden benachrichtigt, wenn sie endet.",
+ "linear.sync.job.done": "Synchronisierung abgeschlossen",
+ "linear.sync.job.error.timeout": "Die Synchronisierung hat keine Fortschritte mehr gemacht und wurde abgebrochen. Starten Sie sie erneut.",
+ "linear.sync.job.error.unavailable": "Das Projekt, die Regel oder die Linear-Verbindung ist nicht mehr verfügbar.",
+ "linear.sync.job.failed": "Synchronisierung fehlgeschlagen",
+ "linear.sync.job.finished": "Linear-Synchronisierung abgeschlossen: {{result}}",
+ "linear.sync.job.inProgress": "Synchronisiere…",
+ "linear.sync.job.keptLocalEdits": "{{count}} Aufgaben wurden in LobeHub bearbeitet; Ihre Änderungen wurden beibehalten.",
+ "linear.sync.job.leave": "Im Hintergrund fortsetzen",
+ "linear.sync.job.listTitle": "Synchronisierungsläufe",
+ "linear.sync.job.runningIssues": "{{count}} Probleme werden synchronisiert…",
+ "linear.sync.job.runningRule": "Alles synchronisieren, was der Regel entspricht…",
+ "linear.sync.job.skipReason.closed": "In Linear geschlossen und nie importiert",
+ "linear.sync.job.skipReason.failed": "Konnte nicht geschrieben werden; die nächste Synchronisierung versucht es erneut",
+ "linear.sync.job.skipReason.missing": "Nicht mehr in Linear vorhanden oder für diese Verbindung nicht sichtbar",
+ "linear.sync.job.skipReason.running": "Aufgabe läuft, daher wurde sie nicht geschlossen",
+ "linear.sync.job.skipReason.unavailable": "Aufgabe befindet sich im Papierkorb oder ist für Sie nicht sichtbar",
+ "linear.sync.job.skippedTitle": "{{count}} übersprungen",
+ "linear.sync.job.titleIssues": "{{count}} Probleme importieren",
+ "linear.sync.job.titleRule": "Regel: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "Regel (gelöscht)",
+ "linear.sync.list.count": "{{count}} Probleme",
+ "linear.sync.list.empty": "Keine Probleme entsprechen diesen Filtern.",
+ "linear.sync.list.linked": "Synchronisiert · {{task}}",
+ "linear.sync.list.loadMore": "Mehr laden",
+ "linear.sync.list.openInLinear": "In Linear öffnen",
+ "linear.sync.list.pickTeam": "Wählen Sie ein Team, um dessen Probleme zu sehen.",
+ "linear.sync.list.selectAll": "Alle {{count}} geladenen auswählen",
+ "linear.sync.list.selected": "{{count}} ausgewählt",
+ "linear.sync.modal.importNone": "Probleme importieren",
+ "linear.sync.modal.importSelected": "{{count}} Probleme importieren",
+ "linear.sync.modal.oneWayHint": "Einweg-Synchronisierung. In Linear wird nichts geändert.",
+ "linear.sync.modal.saveRule": "Als Regel speichern und alles synchronisieren",
+ "linear.sync.modal.saveRuleHint": "Synchronisieren Sie jetzt jedes Problem, das diesen Filtern entspricht, und speichern Sie die Filter, um später erneut zu synchronisieren.",
+ "linear.sync.modal.title": "Probleme von {{account}} importieren",
+ "linear.sync.project.connect": "Linear verbinden",
+ "linear.sync.project.description": "Verwandeln Sie Linear-Probleme in Aufgaben dieses Projekts, einzeln oder über eine gespeicherte Team- oder Projektregel. Die Synchronisierung ist einseitig: In Linear wird nichts geändert.",
+ "linear.sync.project.entry": "Von Linear synchronisieren",
+ "linear.sync.project.noConnection": "Es ist noch kein Linear-Arbeitsbereich verbunden.",
+ "linear.sync.project.title": "Von Linear synchronisieren",
+ "linear.sync.projectHint": "Um Probleme in ein Projekt zu synchronisieren, öffnen Sie das Projekt und gehen Sie zu Einstellungen → Erweitert.",
+ "linear.sync.result.closed": "{{count}} geschlossen",
+ "linear.sync.result.created": "{{count}} erstellt",
+ "linear.sync.result.keptLocalEdits": "{{count}} lokale Änderungen beibehalten",
+ "linear.sync.result.skipped": "{{count}} übersprungen",
+ "linear.sync.result.truncated": "Weitere Probleme verbleiben, synchronisieren Sie erneut, um fortzufahren",
+ "linear.sync.result.upToDate": "Bereits auf dem neuesten Stand",
+ "linear.sync.result.updated": "{{count}} aktualisiert",
+ "linear.sync.rules.delete": "Regel löschen",
+ "linear.sync.rules.deleteContent": "Bereits synchronisierte Aufgaben bleiben wie sie sind. Nur der gespeicherte Filter wird entfernt.",
+ "linear.sync.rules.deleteTitle": "Diese Synchronisierungsregel löschen?",
+ "linear.sync.rules.disconnected": "Der Linear-Arbeitsbereich ist getrennt. Verbinden Sie ihn erneut, um zu synchronisieren, oder löschen Sie die Regel.",
+ "linear.sync.rules.lastRun": "Zuletzt synchronisiert {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "Synchronisierungsregeln konnten nicht geladen werden",
+ "linear.sync.rules.neverRun": "Noch nicht synchronisiert",
+ "linear.sync.rules.run": "Jetzt synchronisieren",
+ "linear.sync.rules.running": "Synchronisiere",
+ "linear.sync.rules.title": "Synchronisierungsregeln",
+ "linear.sync.state.backlog": "Backlog",
+ "linear.sync.state.canceled": "Storniert",
+ "linear.sync.state.completed": "Abgeschlossen",
+ "linear.sync.state.started": "In Bearbeitung",
+ "linear.sync.state.triage": "Triage",
+ "linear.sync.state.unstarted": "Todo",
+ "linear.sync.viewerDisabled": "Betrachter können keine Probleme in Aufgaben importieren",
+ "linear.sync.wizard.back": "Zurück",
+ "linear.sync.wizard.next": "Weiter",
"linear.tagline": "Verbinden Sie Ihren Linear-Arbeitsbereich mit LobeHub",
"overview.all": "Alle Integrationen",
"overview.comingSoon": "Demnächst verfügbar",
diff --git a/locales/en-US/integration.json b/locales/en-US/integration.json
index d73ea085bc8..7c18d0f26eb 100644
--- a/locales/en-US/integration.json
+++ b/locales/en-US/integration.json
@@ -66,6 +66,86 @@
"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.sync.error.generic": "Linear sync failed. Please try again.",
+ "linear.sync.error.reconnect": "The Linear connection has expired. Reconnect the workspace, then try again.",
+ "linear.sync.filter.allProjects": "All projects",
+ "linear.sync.filter.project": "Linear project",
+ "linear.sync.filter.projectHint": "Keep All projects to include every issue in the team.",
+ "linear.sync.filter.states": "Issue states to sync",
+ "linear.sync.filter.statesHint": "Completed and canceled issues are left out by default.",
+ "linear.sync.filter.statesSummary": "{{count}} states",
+ "linear.sync.filter.team": "Linear team",
+ "linear.sync.filter.teamPlaceholder": "Choose a team",
+ "linear.sync.importIssues": "Import issues",
+ "linear.sync.job.background": "You can close this window; the sync keeps running and you will be notified when it ends. The outcome is also listed under Sync runs in Advanced settings.",
+ "linear.sync.job.close": "Done",
+ "linear.sync.job.continuesInBackground": "The sync continues in the background. You will be notified when it ends.",
+ "linear.sync.job.done": "Sync finished",
+ "linear.sync.job.error.timeout": "The sync stopped making progress and was cut off. Start it again.",
+ "linear.sync.job.error.unavailable": "The project, rule or Linear connection is no longer available.",
+ "linear.sync.job.failed": "Sync failed",
+ "linear.sync.job.finished": "Linear sync finished: {{result}}",
+ "linear.sync.job.inProgress": "Syncing…",
+ "linear.sync.job.keptLocalEdits": "{{count}} tasks were edited in LobeHub; your edits were kept.",
+ "linear.sync.job.leave": "Continue in background",
+ "linear.sync.job.listTitle": "Sync runs",
+ "linear.sync.job.runningIssues": "Syncing {{count}} issues…",
+ "linear.sync.job.runningRule": "Syncing everything the rule matches…",
+ "linear.sync.job.skipReason.closed": "Closed in Linear and never imported",
+ "linear.sync.job.skipReason.failed": "Could not be written; the next sync retries it",
+ "linear.sync.job.skipReason.missing": "No longer in Linear, or not visible to this connection",
+ "linear.sync.job.skipReason.running": "Task is running, so it was not closed",
+ "linear.sync.job.skipReason.unavailable": "Task is in the trash or not visible to you",
+ "linear.sync.job.skippedTitle": "{{count}} skipped",
+ "linear.sync.job.titleIssues": "Import {{count}} issues",
+ "linear.sync.job.titleRule": "Rule: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "Rule (deleted)",
+ "linear.sync.list.count": "{{count}} issues",
+ "linear.sync.list.empty": "No issues match these filters.",
+ "linear.sync.list.linked": "Synced · {{task}}",
+ "linear.sync.list.loadMore": "Load more",
+ "linear.sync.list.openInLinear": "Open in Linear",
+ "linear.sync.list.pickTeam": "Choose a team to see its issues.",
+ "linear.sync.list.selectAll": "Select all {{count}} loaded",
+ "linear.sync.list.selected": "{{count}} selected",
+ "linear.sync.modal.importNone": "Import issues",
+ "linear.sync.modal.importSelected": "Import {{count}} issues",
+ "linear.sync.modal.oneWayHint": "One-way sync. Nothing in Linear is changed.",
+ "linear.sync.modal.saveRule": "Save as rule and sync all",
+ "linear.sync.modal.saveRuleHint": "Sync every issue matching these filters now, and keep the filters to sync again later",
+ "linear.sync.modal.title": "Import issues from {{account}}",
+ "linear.sync.project.connect": "Connect Linear",
+ "linear.sync.project.description": "Turn Linear issues into tasks of this project, one by one or through a saved team or project rule. Syncing is one way: nothing in Linear is changed.",
+ "linear.sync.project.entry": "Sync from Linear",
+ "linear.sync.project.noConnection": "No Linear workspace is connected yet.",
+ "linear.sync.project.title": "Sync from Linear",
+ "linear.sync.projectHint": "To sync issues into a project, open the project and go to Settings → Advanced.",
+ "linear.sync.result.closed": "{{count}} closed",
+ "linear.sync.result.created": "{{count}} created",
+ "linear.sync.result.keptLocalEdits": "{{count}} kept local edits",
+ "linear.sync.result.skipped": "{{count}} skipped",
+ "linear.sync.result.truncated": "more issues remain, sync again to continue",
+ "linear.sync.result.upToDate": "Already up to date",
+ "linear.sync.result.updated": "{{count}} updated",
+ "linear.sync.rules.delete": "Delete rule",
+ "linear.sync.rules.deleteContent": "Tasks already synced stay as they are. Only the saved filter is removed.",
+ "linear.sync.rules.deleteTitle": "Delete this sync rule?",
+ "linear.sync.rules.disconnected": "Its Linear workspace is disconnected. Reconnect it to sync, or delete the rule.",
+ "linear.sync.rules.lastRun": "Last synced {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "Could not load sync rules",
+ "linear.sync.rules.neverRun": "Not synced yet",
+ "linear.sync.rules.run": "Sync now",
+ "linear.sync.rules.running": "Syncing",
+ "linear.sync.rules.title": "Sync rules",
+ "linear.sync.state.backlog": "Backlog",
+ "linear.sync.state.canceled": "Canceled",
+ "linear.sync.state.completed": "Completed",
+ "linear.sync.state.started": "In progress",
+ "linear.sync.state.triage": "Triage",
+ "linear.sync.state.unstarted": "Todo",
+ "linear.sync.viewerDisabled": "Viewers cannot import issues into tasks",
+ "linear.sync.wizard.back": "Back",
+ "linear.sync.wizard.next": "Next",
"linear.tagline": "Connect your Linear workspace to LobeHub",
"overview.all": "All integrations",
"overview.comingSoon": "Coming soon",
diff --git a/locales/es-ES/integration.json b/locales/es-ES/integration.json
index 0cbe453344b..ad1f1f7321e 100644
--- a/locales/es-ES/integration.json
+++ b/locales/es-ES/integration.json
@@ -66,6 +66,86 @@
"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.sync.error.generic": "La sincronización con Linear falló. Por favor, inténtalo de nuevo.",
+ "linear.sync.error.reconnect": "La conexión con Linear ha expirado. Reconecta el espacio de trabajo y luego inténtalo de nuevo.",
+ "linear.sync.filter.allProjects": "Todos los proyectos",
+ "linear.sync.filter.project": "Proyecto de Linear",
+ "linear.sync.filter.projectHint": "Mantén Todos los proyectos para incluir cada problema en el equipo.",
+ "linear.sync.filter.states": "Estados de problemas para sincronizar",
+ "linear.sync.filter.statesHint": "Los problemas completados y cancelados se excluyen por defecto.",
+ "linear.sync.filter.statesSummary": "{{count}} estados",
+ "linear.sync.filter.team": "Equipo de Linear",
+ "linear.sync.filter.teamPlaceholder": "Elige un equipo",
+ "linear.sync.importIssues": "Importar problemas",
+ "linear.sync.job.background": "Puedes cerrar esta ventana; la sincronización sigue ejecutándose y se te notificará cuando termine. El resultado también se lista en Ejecuciones de sincronización en Configuración avanzada.",
+ "linear.sync.job.close": "Hecho",
+ "linear.sync.job.continuesInBackground": "La sincronización continúa en segundo plano. Se te notificará cuando termine.",
+ "linear.sync.job.done": "Sincronización terminada",
+ "linear.sync.job.error.timeout": "La sincronización dejó de avanzar y fue interrumpida. Iníciala de nuevo.",
+ "linear.sync.job.error.unavailable": "El proyecto, regla o conexión con Linear ya no está disponible.",
+ "linear.sync.job.failed": "La sincronización falló",
+ "linear.sync.job.finished": "Sincronización con Linear terminada: {{result}}",
+ "linear.sync.job.inProgress": "Sincronizando…",
+ "linear.sync.job.keptLocalEdits": "{{count}} tareas fueron editadas en LobeHub; tus ediciones se mantuvieron.",
+ "linear.sync.job.leave": "Continuar en segundo plano",
+ "linear.sync.job.listTitle": "Ejecuciones de sincronización",
+ "linear.sync.job.runningIssues": "Sincronizando {{count}} problemas…",
+ "linear.sync.job.runningRule": "Sincronizando todo lo que coincide con la regla…",
+ "linear.sync.job.skipReason.closed": "Cerrado en Linear y nunca importado",
+ "linear.sync.job.skipReason.failed": "No se pudo escribir; la próxima sincronización lo reintentará",
+ "linear.sync.job.skipReason.missing": "Ya no está en Linear o no es visible para esta conexión",
+ "linear.sync.job.skipReason.running": "La tarea está en ejecución, por lo que no se cerró",
+ "linear.sync.job.skipReason.unavailable": "La tarea está en la papelera o no es visible para ti",
+ "linear.sync.job.skippedTitle": "{{count}} omitidos",
+ "linear.sync.job.titleIssues": "Importar {{count}} problemas",
+ "linear.sync.job.titleRule": "Regla: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "Regla (eliminada)",
+ "linear.sync.list.count": "{{count}} problemas",
+ "linear.sync.list.empty": "Ningún problema coincide con estos filtros.",
+ "linear.sync.list.linked": "Sincronizado · {{task}}",
+ "linear.sync.list.loadMore": "Cargar más",
+ "linear.sync.list.openInLinear": "Abrir en Linear",
+ "linear.sync.list.pickTeam": "Elige un equipo para ver sus problemas.",
+ "linear.sync.list.selectAll": "Seleccionar todos los {{count}} cargados",
+ "linear.sync.list.selected": "{{count}} seleccionados",
+ "linear.sync.modal.importNone": "Importar problemas",
+ "linear.sync.modal.importSelected": "Importar {{count}} problemas",
+ "linear.sync.modal.oneWayHint": "Sincronización unidireccional. Nada en Linear se cambia.",
+ "linear.sync.modal.saveRule": "Guardar como regla y sincronizar todo",
+ "linear.sync.modal.saveRuleHint": "Sincroniza cada problema que coincida con estos filtros ahora, y guarda los filtros para sincronizar de nuevo más tarde",
+ "linear.sync.modal.title": "Importar problemas desde {{account}}",
+ "linear.sync.project.connect": "Conectar Linear",
+ "linear.sync.project.description": "Convierte los problemas de Linear en tareas de este proyecto, uno por uno o a través de una regla guardada de equipo o proyecto. La sincronización es unidireccional: nada en Linear se cambia.",
+ "linear.sync.project.entry": "Sincronizar desde Linear",
+ "linear.sync.project.noConnection": "Aún no hay un espacio de trabajo de Linear conectado.",
+ "linear.sync.project.title": "Sincronizar desde Linear",
+ "linear.sync.projectHint": "Para sincronizar problemas en un proyecto, abre el proyecto y ve a Configuración → Avanzado.",
+ "linear.sync.result.closed": "{{count}} cerrados",
+ "linear.sync.result.created": "{{count}} creados",
+ "linear.sync.result.keptLocalEdits": "{{count}} ediciones locales mantenidas",
+ "linear.sync.result.skipped": "{{count}} omitidos",
+ "linear.sync.result.truncated": "quedan más problemas, sincroniza de nuevo para continuar",
+ "linear.sync.result.upToDate": "Ya está actualizado",
+ "linear.sync.result.updated": "{{count}} actualizados",
+ "linear.sync.rules.delete": "Eliminar regla",
+ "linear.sync.rules.deleteContent": "Las tareas ya sincronizadas permanecen como están. Solo se elimina el filtro guardado.",
+ "linear.sync.rules.deleteTitle": "¿Eliminar esta regla de sincronización?",
+ "linear.sync.rules.disconnected": "Su espacio de trabajo de Linear está desconectado. Reconéctalo para sincronizar o elimina la regla.",
+ "linear.sync.rules.lastRun": "Última sincronización {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "No se pudieron cargar las reglas de sincronización",
+ "linear.sync.rules.neverRun": "Aún no sincronizado",
+ "linear.sync.rules.run": "Sincronizar ahora",
+ "linear.sync.rules.running": "Sincronizando",
+ "linear.sync.rules.title": "Reglas de sincronización",
+ "linear.sync.state.backlog": "Pendiente",
+ "linear.sync.state.canceled": "Cancelado",
+ "linear.sync.state.completed": "Completado",
+ "linear.sync.state.started": "En progreso",
+ "linear.sync.state.triage": "Triage",
+ "linear.sync.state.unstarted": "Por hacer",
+ "linear.sync.viewerDisabled": "Los espectadores no pueden importar problemas en tareas",
+ "linear.sync.wizard.back": "Atrás",
+ "linear.sync.wizard.next": "Siguiente",
"linear.tagline": "Conecta tu espacio de trabajo de Linear a LobeHub",
"overview.all": "Todas las integraciones",
"overview.comingSoon": "Próximamente",
diff --git a/locales/fa-IR/integration.json b/locales/fa-IR/integration.json
index 642b74c08ea..27d0f427500 100644
--- a/locales/fa-IR/integration.json
+++ b/locales/fa-IR/integration.json
@@ -66,6 +66,86 @@
"linear.installResult.error.unknown": "اتصال به Linear ناموفق بود ({{code}}).",
"linear.installResult.error.workspace_forbidden": "فقط اعضای فضای کاری می‌توانند Linear را اینجا متصل کنند.",
"linear.installResult.success": "Linear متصل شد: {{account}}",
+ "linear.sync.error.generic": "همگام‌سازی Linear شکست خورد. لطفاً دوباره تلاش کنید.",
+ "linear.sync.error.reconnect": "اتصال Linear منقضی شده است. فضای کاری را دوباره متصل کنید و سپس دوباره تلاش کنید.",
+ "linear.sync.filter.allProjects": "همه پروژه‌ها",
+ "linear.sync.filter.project": "پروژه Linear",
+ "linear.sync.filter.projectHint": "همه پروژه‌ها را نگه دارید تا هر مسئله‌ای در تیم شامل شود.",
+ "linear.sync.filter.states": "وضعیت‌های مسئله برای همگام‌سازی",
+ "linear.sync.filter.statesHint": "مسائل تکمیل‌شده و لغوشده به‌طور پیش‌فرض کنار گذاشته می‌شوند.",
+ "linear.sync.filter.statesSummary": "{{count}} وضعیت",
+ "linear.sync.filter.team": "تیم Linear",
+ "linear.sync.filter.teamPlaceholder": "یک تیم انتخاب کنید",
+ "linear.sync.importIssues": "وارد کردن مسائل",
+ "linear.sync.job.background": "می‌توانید این پنجره را ببندید؛ همگام‌سازی ادامه دارد و زمانی که به پایان برسد به شما اطلاع داده خواهد شد. نتیجه همچنین در بخش اجرای همگام‌سازی در تنظیمات پیشرفته فهرست شده است.",
+ "linear.sync.job.close": "تمام شد",
+ "linear.sync.job.continuesInBackground": "همگام‌سازی در پس‌زمینه ادامه دارد. زمانی که به پایان برسد به شما اطلاع داده خواهد شد.",
+ "linear.sync.job.done": "همگام‌سازی به پایان رسید",
+ "linear.sync.job.error.timeout": "همگام‌سازی پیشرفت خود را متوقف کرد و قطع شد. دوباره شروع کنید.",
+ "linear.sync.job.error.unavailable": "پروژه، قانون یا اتصال Linear دیگر در دسترس نیست.",
+ "linear.sync.job.failed": "همگام‌سازی شکست خورد",
+ "linear.sync.job.finished": "همگام‌سازی Linear به پایان رسید: {{result}}",
+ "linear.sync.job.inProgress": "در حال همگام‌سازی…",
+ "linear.sync.job.keptLocalEdits": "{{count}} وظیفه در LobeHub ویرایش شده‌اند؛ ویرایش‌های شما حفظ شدند.",
+ "linear.sync.job.leave": "ادامه در پس‌زمینه",
+ "linear.sync.job.listTitle": "اجرای همگام‌سازی",
+ "linear.sync.job.runningIssues": "در حال همگام‌سازی {{count}} مسئله…",
+ "linear.sync.job.runningRule": "در حال همگام‌سازی همه مواردی که قانون مطابقت دارد…",
+ "linear.sync.job.skipReason.closed": "در Linear بسته شده و هرگز وارد نشده است",
+ "linear.sync.job.skipReason.failed": "نمی‌توانست نوشته شود؛ همگام‌سازی بعدی دوباره تلاش می‌کند",
+ "linear.sync.job.skipReason.missing": "دیگر در Linear وجود ندارد یا برای این اتصال قابل مشاهده نیست",
+ "linear.sync.job.skipReason.running": "وظیفه در حال اجرا است، بنابراین بسته نشده است",
+ "linear.sync.job.skipReason.unavailable": "وظیفه در سطل زباله است یا برای شما قابل مشاهده نیست",
+ "linear.sync.job.skippedTitle": "{{count}} کنار گذاشته شده",
+ "linear.sync.job.titleIssues": "وارد کردن {{count}} مسئله",
+ "linear.sync.job.titleRule": "قانون: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "قانون (حذف شده)",
+ "linear.sync.list.count": "{{count}} مسئله",
+ "linear.sync.list.empty": "هیچ مسئله‌ای با این فیلترها مطابقت ندارد.",
+ "linear.sync.list.linked": "همگام‌سازی شده · {{task}}",
+ "linear.sync.list.loadMore": "بارگذاری بیشتر",
+ "linear.sync.list.openInLinear": "باز کردن در Linear",
+ "linear.sync.list.pickTeam": "یک تیم انتخاب کنید تا مسائل آن را ببینید.",
+ "linear.sync.list.selectAll": "انتخاب همه {{count}} بارگذاری شده",
+ "linear.sync.list.selected": "{{count}} انتخاب شده",
+ "linear.sync.modal.importNone": "وارد کردن مسائل",
+ "linear.sync.modal.importSelected": "وارد کردن {{count}} مسئله",
+ "linear.sync.modal.oneWayHint": "همگام‌سازی یک‌طرفه. هیچ چیزی در Linear تغییر نمی‌کند.",
+ "linear.sync.modal.saveRule": "ذخیره به‌عنوان قانون و همگام‌سازی همه",
+ "linear.sync.modal.saveRuleHint": "اکنون همه مسائل مطابقت‌یافته با این فیلترها را همگام‌سازی کنید و فیلترها را برای همگام‌سازی مجدد بعداً نگه دارید",
+ "linear.sync.modal.title": "وارد کردن مسائل از {{account}}",
+ "linear.sync.project.connect": "اتصال به Linear",
+ "linear.sync.project.description": "مسائل Linear را به وظایف این پروژه تبدیل کنید، به‌صورت جداگانه یا از طریق قانون ذخیره‌شده تیم یا پروژه. همگام‌سازی یک‌طرفه است: هیچ چیزی در Linear تغییر نمی‌کند.",
+ "linear.sync.project.entry": "همگام‌سازی از Linear",
+ "linear.sync.project.noConnection": "هنوز هیچ فضای کاری Linear متصل نشده است.",
+ "linear.sync.project.title": "همگام‌سازی از Linear",
+ "linear.sync.projectHint": "برای همگام‌سازی مسائل به یک پروژه، پروژه را باز کنید و به تنظیمات → پیشرفته بروید.",
+ "linear.sync.result.closed": "{{count}} بسته شده",
+ "linear.sync.result.created": "{{count}} ایجاد شده",
+ "linear.sync.result.keptLocalEdits": "{{count}} ویرایش‌های محلی حفظ شده",
+ "linear.sync.result.skipped": "{{count}} کنار گذاشته شده",
+ "linear.sync.result.truncated": "مسائل بیشتری باقی مانده‌اند، برای ادامه دوباره همگام‌سازی کنید",
+ "linear.sync.result.upToDate": "قبلاً به‌روز شده",
+ "linear.sync.result.updated": "{{count}} به‌روز شده",
+ "linear.sync.rules.delete": "حذف قانون",
+ "linear.sync.rules.deleteContent": "وظایف همگام‌سازی‌شده همان‌طور که هستند باقی می‌مانند. فقط فیلتر ذخیره‌شده حذف می‌شود.",
+ "linear.sync.rules.deleteTitle": "آیا این قانون همگام‌سازی حذف شود؟",
+ "linear.sync.rules.disconnected": "فضای کاری Linear آن قطع شده است. برای همگام‌سازی دوباره متصل کنید یا قانون را حذف کنید.",
+ "linear.sync.rules.lastRun": "آخرین همگام‌سازی {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "قوانین همگام‌سازی بارگذاری نشدند",
+ "linear.sync.rules.neverRun": "هنوز همگام‌سازی نشده است",
+ "linear.sync.rules.run": "اکنون همگام‌سازی کنید",
+ "linear.sync.rules.running": "در حال همگام‌سازی",
+ "linear.sync.rules.title": "قوانین همگام‌سازی",
+ "linear.sync.state.backlog": "صف انتظار",
+ "linear.sync.state.canceled": "لغو شده",
+ "linear.sync.state.completed": "تکمیل شده",
+ "linear.sync.state.started": "در حال انجام",
+ "linear.sync.state.triage": "اولویت‌بندی",
+ "linear.sync.state.unstarted": "برای انجام",
+ "linear.sync.viewerDisabled": "بینندگان نمی‌توانند مسائل را به وظایف وارد کنند",
+ "linear.sync.wizard.back": "بازگشت",
+ "linear.sync.wizard.next": "بعدی",
"linear.tagline": "فضای کاری Linear خود را به LobeHub متصل کنید",
"overview.all": "همه یکپارچه‌سازی‌ها",
"overview.comingSoon": "به زودی",
diff --git a/locales/fr-FR/integration.json b/locales/fr-FR/integration.json
index 53b2c8b0ff2..5d41dba08be 100644
--- a/locales/fr-FR/integration.json
+++ b/locales/fr-FR/integration.json
@@ -66,6 +66,86 @@
"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.sync.error.generic": "La synchronisation Linear a échoué. Veuillez réessayer.",
+ "linear.sync.error.reconnect": "La connexion Linear a expiré. Reconnectez l'espace de travail, puis réessayez.",
+ "linear.sync.filter.allProjects": "Tous les projets",
+ "linear.sync.filter.project": "Projet Linear",
+ "linear.sync.filter.projectHint": "Gardez Tous les projets pour inclure chaque problème dans l'équipe.",
+ "linear.sync.filter.states": "États des problèmes à synchroniser",
+ "linear.sync.filter.statesHint": "Les problèmes terminés et annulés sont exclus par défaut.",
+ "linear.sync.filter.statesSummary": "{{count}} états",
+ "linear.sync.filter.team": "Équipe Linear",
+ "linear.sync.filter.teamPlaceholder": "Choisissez une équipe",
+ "linear.sync.importIssues": "Importer des problèmes",
+ "linear.sync.job.background": "Vous pouvez fermer cette fenêtre ; la synchronisation continue de fonctionner et vous serez informé lorsqu'elle se termine. Le résultat est également listé sous Exécutions de synchronisation dans les paramètres avancés.",
+ "linear.sync.job.close": "Terminé",
+ "linear.sync.job.continuesInBackground": "La synchronisation continue en arrière-plan. Vous serez informé lorsqu'elle se termine.",
+ "linear.sync.job.done": "Synchronisation terminée",
+ "linear.sync.job.error.timeout": "La synchronisation a cessé de progresser et a été interrompue. Relancez-la.",
+ "linear.sync.job.error.unavailable": "Le projet, la règle ou la connexion Linear n'est plus disponible.",
+ "linear.sync.job.failed": "La synchronisation a échoué",
+ "linear.sync.job.finished": "Synchronisation Linear terminée : {{result}}",
+ "linear.sync.job.inProgress": "Synchronisation en cours…",
+ "linear.sync.job.keptLocalEdits": "{{count}} tâches ont été modifiées dans LobeHub ; vos modifications ont été conservées.",
+ "linear.sync.job.leave": "Continuer en arrière-plan",
+ "linear.sync.job.listTitle": "Exécutions de synchronisation",
+ "linear.sync.job.runningIssues": "Synchronisation de {{count}} problèmes…",
+ "linear.sync.job.runningRule": "Synchronisation de tout ce que la règle correspond…",
+ "linear.sync.job.skipReason.closed": "Fermé dans Linear et jamais importé",
+ "linear.sync.job.skipReason.failed": "N'a pas pu être écrit ; la prochaine synchronisation le réessaiera",
+ "linear.sync.job.skipReason.missing": "N’existe plus dans Linear ou n’est pas visible pour cette connexion",
+ "linear.sync.job.skipReason.running": "La tâche est en cours d'exécution, elle n'a donc pas été fermée",
+ "linear.sync.job.skipReason.unavailable": "La tâche est dans la corbeille ou n'est pas visible pour vous",
+ "linear.sync.job.skippedTitle": "{{count}} ignorés",
+ "linear.sync.job.titleIssues": "Importer {{count}} problèmes",
+ "linear.sync.job.titleRule": "Règle : {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "Règle (supprimée)",
+ "linear.sync.list.count": "{{count}} problèmes",
+ "linear.sync.list.empty": "Aucun problème ne correspond à ces filtres.",
+ "linear.sync.list.linked": "Synchronisé · {{task}}",
+ "linear.sync.list.loadMore": "Charger plus",
+ "linear.sync.list.openInLinear": "Ouvrir dans Linear",
+ "linear.sync.list.pickTeam": "Choisissez une équipe pour voir ses problèmes.",
+ "linear.sync.list.selectAll": "Sélectionner tous les {{count}} chargés",
+ "linear.sync.list.selected": "{{count}} sélectionnés",
+ "linear.sync.modal.importNone": "Importer des problèmes",
+ "linear.sync.modal.importSelected": "Importer {{count}} problèmes",
+ "linear.sync.modal.oneWayHint": "Synchronisation unidirectionnelle. Rien dans Linear n'est modifié.",
+ "linear.sync.modal.saveRule": "Enregistrer comme règle et synchroniser tout",
+ "linear.sync.modal.saveRuleHint": "Synchronisez tous les problèmes correspondant à ces filtres maintenant, et conservez les filtres pour synchroniser à nouveau plus tard",
+ "linear.sync.modal.title": "Importer des problèmes depuis {{account}}",
+ "linear.sync.project.connect": "Connecter Linear",
+ "linear.sync.project.description": "Transformez les problèmes Linear en tâches de ce projet, une par une ou via une règle d'équipe ou de projet enregistrée. La synchronisation est unidirectionnelle : rien dans Linear n'est modifié.",
+ "linear.sync.project.entry": "Synchroniser depuis Linear",
+ "linear.sync.project.noConnection": "Aucun espace de travail Linear n'est encore connecté.",
+ "linear.sync.project.title": "Synchroniser depuis Linear",
+ "linear.sync.projectHint": "Pour synchroniser des problèmes dans un projet, ouvrez le projet et allez dans Paramètres → Avancé.",
+ "linear.sync.result.closed": "{{count}} fermés",
+ "linear.sync.result.created": "{{count}} créés",
+ "linear.sync.result.keptLocalEdits": "{{count}} modifications locales conservées",
+ "linear.sync.result.skipped": "{{count}} ignorés",
+ "linear.sync.result.truncated": "plus de problèmes restent, synchronisez à nouveau pour continuer",
+ "linear.sync.result.upToDate": "Déjà à jour",
+ "linear.sync.result.updated": "{{count}} mis à jour",
+ "linear.sync.rules.delete": "Supprimer la règle",
+ "linear.sync.rules.deleteContent": "Les tâches déjà synchronisées restent telles qu'elles sont. Seul le filtre enregistré est supprimé.",
+ "linear.sync.rules.deleteTitle": "Supprimer cette règle de synchronisation ?",
+ "linear.sync.rules.disconnected": "Son espace de travail Linear est déconnecté. Reconnectez-le pour synchroniser, ou supprimez la règle.",
+ "linear.sync.rules.lastRun": "Dernière synchronisation {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "Impossible de charger les règles de synchronisation",
+ "linear.sync.rules.neverRun": "Pas encore synchronisé",
+ "linear.sync.rules.run": "Synchroniser maintenant",
+ "linear.sync.rules.running": "Synchronisation en cours",
+ "linear.sync.rules.title": "Règles de synchronisation",
+ "linear.sync.state.backlog": "À faire",
+ "linear.sync.state.canceled": "Annulé",
+ "linear.sync.state.completed": "Terminé",
+ "linear.sync.state.started": "En cours",
+ "linear.sync.state.triage": "Triage",
+ "linear.sync.state.unstarted": "À faire",
+ "linear.sync.viewerDisabled": "Les spectateurs ne peuvent pas importer des problèmes en tâches",
+ "linear.sync.wizard.back": "Retour",
+ "linear.sync.wizard.next": "Suivant",
"linear.tagline": "Connectez votre espace de travail Linear à LobeHub",
"overview.all": "Toutes les intégrations",
"overview.comingSoon": "Bientôt disponible",
diff --git a/locales/it-IT/integration.json b/locales/it-IT/integration.json
index d9723b32c64..cf186bf4620 100644
--- a/locales/it-IT/integration.json
+++ b/locales/it-IT/integration.json
@@ -66,6 +66,86 @@
"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.sync.error.generic": "Sincronizzazione Linear fallita. Riprova.",
+ "linear.sync.error.reconnect": "La connessione a Linear è scaduta. Riconnetti il workspace, quindi riprova.",
+ "linear.sync.filter.allProjects": "Tutti i progetti",
+ "linear.sync.filter.project": "Progetto Linear",
+ "linear.sync.filter.projectHint": "Mantieni Tutti i progetti per includere ogni problema nel team.",
+ "linear.sync.filter.states": "Stati dei problemi da sincronizzare",
+ "linear.sync.filter.statesHint": "I problemi completati e annullati sono esclusi per impostazione predefinita.",
+ "linear.sync.filter.statesSummary": "{{count}} stati",
+ "linear.sync.filter.team": "Team Linear",
+ "linear.sync.filter.teamPlaceholder": "Scegli un team",
+ "linear.sync.importIssues": "Importa problemi",
+ "linear.sync.job.background": "Puoi chiudere questa finestra; la sincronizzazione continuerà e sarai notificato al termine. Il risultato sarà anche elencato sotto Esecuzioni di sincronizzazione nelle Impostazioni avanzate.",
+ "linear.sync.job.close": "Fatto",
+ "linear.sync.job.continuesInBackground": "La sincronizzazione continua in background. Sarai notificato al termine.",
+ "linear.sync.job.done": "Sincronizzazione completata",
+ "linear.sync.job.error.timeout": "La sincronizzazione ha smesso di fare progressi ed è stata interrotta. Avviala di nuovo.",
+ "linear.sync.job.error.unavailable": "Il progetto, la regola o la connessione a Linear non è più disponibile.",
+ "linear.sync.job.failed": "Sincronizzazione fallita",
+ "linear.sync.job.finished": "Sincronizzazione Linear completata: {{result}}",
+ "linear.sync.job.inProgress": "Sincronizzazione in corso…",
+ "linear.sync.job.keptLocalEdits": "{{count}} attività sono state modificate in LobeHub; le tue modifiche sono state mantenute.",
+ "linear.sync.job.leave": "Continua in background",
+ "linear.sync.job.listTitle": "Esecuzioni di sincronizzazione",
+ "linear.sync.job.runningIssues": "Sincronizzazione di {{count}} problemi…",
+ "linear.sync.job.runningRule": "Sincronizzazione di tutto ciò che corrisponde alla regola…",
+ "linear.sync.job.skipReason.closed": "Chiuso in Linear e mai importato",
+ "linear.sync.job.skipReason.failed": "Non è stato possibile scriverlo; la prossima sincronizzazione lo riproverà",
+ "linear.sync.job.skipReason.missing": "Non è più in Linear o non è visibile a questa connessione",
+ "linear.sync.job.skipReason.running": "L'attività è in corso, quindi non è stata chiusa",
+ "linear.sync.job.skipReason.unavailable": "L'attività è nel cestino o non è visibile per te",
+ "linear.sync.job.skippedTitle": "{{count}} saltati",
+ "linear.sync.job.titleIssues": "Importa {{count}} problemi",
+ "linear.sync.job.titleRule": "Regola: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "Regola (eliminata)",
+ "linear.sync.list.count": "{{count}} problemi",
+ "linear.sync.list.empty": "Nessun problema corrisponde a questi filtri.",
+ "linear.sync.list.linked": "Sincronizzato · {{task}}",
+ "linear.sync.list.loadMore": "Carica di più",
+ "linear.sync.list.openInLinear": "Apri in Linear",
+ "linear.sync.list.pickTeam": "Scegli un team per vedere i suoi problemi.",
+ "linear.sync.list.selectAll": "Seleziona tutti i {{count}} caricati",
+ "linear.sync.list.selected": "{{count}} selezionati",
+ "linear.sync.modal.importNone": "Importa problemi",
+ "linear.sync.modal.importSelected": "Importa {{count}} problemi",
+ "linear.sync.modal.oneWayHint": "Sincronizzazione unidirezionale. Nulla in Linear viene modificato.",
+ "linear.sync.modal.saveRule": "Salva come regola e sincronizza tutto",
+ "linear.sync.modal.saveRuleHint": "Sincronizza ora ogni problema che corrisponde a questi filtri e conserva i filtri per sincronizzare di nuovo in seguito",
+ "linear.sync.modal.title": "Importa problemi da {{account}}",
+ "linear.sync.project.connect": "Connetti Linear",
+ "linear.sync.project.description": "Trasforma i problemi di Linear in attività di questo progetto, uno per uno o tramite una regola salvata per team o progetto. La sincronizzazione è unidirezionale: nulla in Linear viene modificato.",
+ "linear.sync.project.entry": "Sincronizza da Linear",
+ "linear.sync.project.noConnection": "Nessun workspace Linear è ancora connesso.",
+ "linear.sync.project.title": "Sincronizza da Linear",
+ "linear.sync.projectHint": "Per sincronizzare i problemi in un progetto, apri il progetto e vai su Impostazioni → Avanzate.",
+ "linear.sync.result.closed": "{{count}} chiusi",
+ "linear.sync.result.created": "{{count}} creati",
+ "linear.sync.result.keptLocalEdits": "{{count}} modifiche locali mantenute",
+ "linear.sync.result.skipped": "{{count}} saltati",
+ "linear.sync.result.truncated": "rimangono altri problemi, sincronizza di nuovo per continuare",
+ "linear.sync.result.upToDate": "Già aggiornato",
+ "linear.sync.result.updated": "{{count}} aggiornati",
+ "linear.sync.rules.delete": "Elimina regola",
+ "linear.sync.rules.deleteContent": "Le attività già sincronizzate rimangono come sono. Solo il filtro salvato viene rimosso.",
+ "linear.sync.rules.deleteTitle": "Eliminare questa regola di sincronizzazione?",
+ "linear.sync.rules.disconnected": "Il suo workspace Linear è disconnesso. Riconnettilo per sincronizzare o elimina la regola.",
+ "linear.sync.rules.lastRun": "Ultima sincronizzazione {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "Impossibile caricare le regole di sincronizzazione",
+ "linear.sync.rules.neverRun": "Non ancora sincronizzato",
+ "linear.sync.rules.run": "Sincronizza ora",
+ "linear.sync.rules.running": "Sincronizzazione in corso",
+ "linear.sync.rules.title": "Regole di sincronizzazione",
+ "linear.sync.state.backlog": "Backlog",
+ "linear.sync.state.canceled": "Annullato",
+ "linear.sync.state.completed": "Completato",
+ "linear.sync.state.started": "In corso",
+ "linear.sync.state.triage": "Valutazione",
+ "linear.sync.state.unstarted": "Da fare",
+ "linear.sync.viewerDisabled": "I visualizzatori non possono importare problemi come attività",
+ "linear.sync.wizard.back": "Indietro",
+ "linear.sync.wizard.next": "Avanti",
"linear.tagline": "Connetti il tuo spazio di lavoro Linear a LobeHub",
"overview.all": "Tutte le integrazioni",
"overview.comingSoon": "In arrivo",
diff --git a/locales/ja-JP/integration.json b/locales/ja-JP/integration.json
index 6b3630a6d0f..e64472ff473 100644
--- a/locales/ja-JP/integration.json
+++ b/locales/ja-JP/integration.json
@@ -66,6 +66,86 @@
"linear.installResult.error.unknown": "Linearの接続に失敗しました({{code}})。",
"linear.installResult.error.workspace_forbidden": "ワークスペースメンバーのみがここでLinearを接続できます。",
"linear.installResult.success": "Linearが接続されました: {{account}}",
+ "linear.sync.error.generic": "Linearの同期に失敗しました。もう一度お試しください。",
+ "linear.sync.error.reconnect": "Linearの接続が期限切れです。ワークスペースを再接続してから、もう一度お試しください。",
+ "linear.sync.filter.allProjects": "すべてのプロジェクト",
+ "linear.sync.filter.project": "Linearプロジェクト",
+ "linear.sync.filter.projectHint": "すべてのプロジェクトを選択すると、チーム内のすべての課題が含まれます。",
+ "linear.sync.filter.states": "同期する課題の状態",
+ "linear.sync.filter.statesHint": "完了およびキャンセルされた課題はデフォルトで除外されます。",
+ "linear.sync.filter.statesSummary": "{{count}}の状態",
+ "linear.sync.filter.team": "Linearチーム",
+ "linear.sync.filter.teamPlaceholder": "チームを選択",
+ "linear.sync.importIssues": "課題をインポート",
+ "linear.sync.job.background": "このウィンドウを閉じても同期は続行され、終了時に通知されます。結果は詳細設定の「同期実行」にも記載されます。",
+ "linear.sync.job.close": "完了",
+ "linear.sync.job.continuesInBackground": "同期はバックグラウンドで続行されます。終了時に通知されます。",
+ "linear.sync.job.done": "同期が完了しました",
+ "linear.sync.job.error.timeout": "同期が進行しなくなり中断されました。再度開始してください。",
+ "linear.sync.job.error.unavailable": "プロジェクト、ルール、またはLinear接続が利用できなくなりました。",
+ "linear.sync.job.failed": "同期に失敗しました",
+ "linear.sync.job.finished": "Linearの同期が完了しました: {{result}}",
+ "linear.sync.job.inProgress": "同期中…",
+ "linear.sync.job.keptLocalEdits": "{{count}}件のタスクがLobeHubで編集されました。編集内容は保持されました。",
+ "linear.sync.job.leave": "バックグラウンドで続行",
+ "linear.sync.job.listTitle": "同期実行",
+ "linear.sync.job.runningIssues": "{{count}}件の課題を同期中…",
+ "linear.sync.job.runningRule": "ルールに一致するすべてを同期中…",
+ "linear.sync.job.skipReason.closed": "Linearでクローズされ、インポートされませんでした",
+ "linear.sync.job.skipReason.failed": "書き込みできませんでした。次回の同期で再試行されます",
+ "linear.sync.job.skipReason.missing": "Linear に存在しないか、この接続からは参照できません",
+ "linear.sync.job.skipReason.running": "タスクが実行中のため、クローズされませんでした",
+ "linear.sync.job.skipReason.unavailable": "タスクがゴミ箱にあるか、あなたには表示されません",
+ "linear.sync.job.skippedTitle": "{{count}}件がスキップされました",
+ "linear.sync.job.titleIssues": "{{count}}件の課題をインポート",
+ "linear.sync.job.titleRule": "ルール: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "ルール(削除済み)",
+ "linear.sync.list.count": "{{count}}件の課題",
+ "linear.sync.list.empty": "これらのフィルターに一致する課題はありません。",
+ "linear.sync.list.linked": "同期済み · {{task}}",
+ "linear.sync.list.loadMore": "さらに読み込む",
+ "linear.sync.list.openInLinear": "Linearで開く",
+ "linear.sync.list.pickTeam": "課題を表示するチームを選択してください。",
+ "linear.sync.list.selectAll": "読み込まれた{{count}}件をすべて選択",
+ "linear.sync.list.selected": "{{count}}件が選択されました",
+ "linear.sync.modal.importNone": "課題をインポート",
+ "linear.sync.modal.importSelected": "{{count}}件の課題をインポート",
+ "linear.sync.modal.oneWayHint": "一方向の同期です。Linearの内容は変更されません。",
+ "linear.sync.modal.saveRule": "ルールとして保存してすべて同期",
+ "linear.sync.modal.saveRuleHint": "これらのフィルターに一致するすべての課題を今すぐ同期し、後で再同期するためにフィルターを保存します",
+ "linear.sync.modal.title": "{{account}}から課題をインポート",
+ "linear.sync.project.connect": "Linearを接続",
+ "linear.sync.project.description": "Linearの課題をこのプロジェクトのタスクに変換します。1つずつ、または保存されたチームやプロジェクトルールを通じて同期します。同期は一方向で、Linearの内容は変更されません。",
+ "linear.sync.project.entry": "Linearから同期",
+ "linear.sync.project.noConnection": "まだLinearワークスペースが接続されていません。",
+ "linear.sync.project.title": "Linearから同期",
+ "linear.sync.projectHint": "プロジェクトに課題を同期するには、プロジェクトを開き、設定 → 詳細設定に移動してください。",
+ "linear.sync.result.closed": "{{count}}件がクローズされました",
+ "linear.sync.result.created": "{{count}}件が作成されました",
+ "linear.sync.result.keptLocalEdits": "{{count}}件のローカル編集が保持されました",
+ "linear.sync.result.skipped": "{{count}}件がスキップされました",
+ "linear.sync.result.truncated": "さらに課題が残っています。同期を再実行して続行してください。",
+ "linear.sync.result.upToDate": "すでに最新です",
+ "linear.sync.result.updated": "{{count}}件が更新されました",
+ "linear.sync.rules.delete": "ルールを削除",
+ "linear.sync.rules.deleteContent": "すでに同期されたタスクはそのままです。保存されたフィルターのみが削除されます。",
+ "linear.sync.rules.deleteTitle": "この同期ルールを削除しますか?",
+ "linear.sync.rules.disconnected": "Linearワークスペースが切断されています。再接続して同期するか、ルールを削除してください。",
+ "linear.sync.rules.lastRun": "最終同期 {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "同期ルールを読み込めませんでした",
+ "linear.sync.rules.neverRun": "まだ同期されていません",
+ "linear.sync.rules.run": "今すぐ同期",
+ "linear.sync.rules.running": "同期中",
+ "linear.sync.rules.title": "同期ルール",
+ "linear.sync.state.backlog": "バックログ",
+ "linear.sync.state.canceled": "キャンセル済み",
+ "linear.sync.state.completed": "完了",
+ "linear.sync.state.started": "進行中",
+ "linear.sync.state.triage": "トリアージ",
+ "linear.sync.state.unstarted": "未着手",
+ "linear.sync.viewerDisabled": "閲覧者は課題をタスクにインポートできません",
+ "linear.sync.wizard.back": "戻る",
+ "linear.sync.wizard.next": "次へ",
"linear.tagline": "LinearワークスペースをLobeHubに接続",
"overview.all": "すべての統合",
"overview.comingSoon": "近日公開",
diff --git a/locales/ko-KR/integration.json b/locales/ko-KR/integration.json
index c3144091304..3278810f778 100644
--- a/locales/ko-KR/integration.json
+++ b/locales/ko-KR/integration.json
@@ -66,6 +66,86 @@
"linear.installResult.error.unknown": "Linear 연결 실패 ({{code}}).",
"linear.installResult.error.workspace_forbidden": "작업 공간 멤버만 여기에서 Linear를 연결할 수 있습니다.",
"linear.installResult.success": "Linear 연결됨: {{account}}",
+ "linear.sync.error.generic": "Linear 동기화에 실패했습니다. 다시 시도해주세요.",
+ "linear.sync.error.reconnect": "Linear 연결이 만료되었습니다. 작업 공간을 다시 연결한 후 다시 시도하세요.",
+ "linear.sync.filter.allProjects": "모든 프로젝트",
+ "linear.sync.filter.project": "Linear 프로젝트",
+ "linear.sync.filter.projectHint": "팀의 모든 문제를 포함하려면 '모든 프로젝트'를 유지하세요.",
+ "linear.sync.filter.states": "동기화할 문제 상태",
+ "linear.sync.filter.statesHint": "완료된 문제와 취소된 문제는 기본적으로 제외됩니다.",
+ "linear.sync.filter.statesSummary": "{{count}} 상태",
+ "linear.sync.filter.team": "Linear 팀",
+ "linear.sync.filter.teamPlaceholder": "팀을 선택하세요",
+ "linear.sync.importIssues": "문제 가져오기",
+ "linear.sync.job.background": "이 창을 닫아도 됩니다. 동기화는 계속 진행되며 완료되면 알림을 받게 됩니다. 결과는 고급 설정의 동기화 실행 목록에서도 확인할 수 있습니다.",
+ "linear.sync.job.close": "완료",
+ "linear.sync.job.continuesInBackground": "동기화가 백그라운드에서 계속 진행됩니다. 완료되면 알림을 받게 됩니다.",
+ "linear.sync.job.done": "동기화 완료",
+ "linear.sync.job.error.timeout": "동기화가 진행되지 않아 중단되었습니다. 다시 시작하세요.",
+ "linear.sync.job.error.unavailable": "프로젝트, 규칙 또는 Linear 연결이 더 이상 사용할 수 없습니다.",
+ "linear.sync.job.failed": "동기화 실패",
+ "linear.sync.job.finished": "Linear 동기화 완료: {{result}}",
+ "linear.sync.job.inProgress": "동기화 중…",
+ "linear.sync.job.keptLocalEdits": "{{count}}개의 작업이 LobeHub에서 편집되었습니다. 편집 내용이 유지되었습니다.",
+ "linear.sync.job.leave": "백그라운드에서 계속",
+ "linear.sync.job.listTitle": "동기화 실행",
+ "linear.sync.job.runningIssues": "{{count}}개의 문제를 동기화 중…",
+ "linear.sync.job.runningRule": "규칙이 일치하는 모든 항목을 동기화 중…",
+ "linear.sync.job.skipReason.closed": "Linear에서 닫혔으며 가져오지 않음",
+ "linear.sync.job.skipReason.failed": "작성할 수 없었음; 다음 동기화에서 다시 시도됨",
+ "linear.sync.job.skipReason.missing": "Linear에 더 이상 없거나 이 연결에서 볼 수 없습니다",
+ "linear.sync.job.skipReason.running": "작업이 진행 중이므로 닫히지 않음",
+ "linear.sync.job.skipReason.unavailable": "작업이 휴지통에 있거나 사용자에게 보이지 않음",
+ "linear.sync.job.skippedTitle": "{{count}}개 건너뜀",
+ "linear.sync.job.titleIssues": "{{count}}개의 문제 가져오기",
+ "linear.sync.job.titleRule": "규칙: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "규칙 (삭제됨)",
+ "linear.sync.list.count": "{{count}}개의 문제",
+ "linear.sync.list.empty": "이 필터와 일치하는 문제가 없습니다.",
+ "linear.sync.list.linked": "동기화됨 · {{task}}",
+ "linear.sync.list.loadMore": "더 보기",
+ "linear.sync.list.openInLinear": "Linear에서 열기",
+ "linear.sync.list.pickTeam": "팀을 선택하여 해당 문제를 확인하세요.",
+ "linear.sync.list.selectAll": "로드된 {{count}}개 모두 선택",
+ "linear.sync.list.selected": "{{count}}개 선택됨",
+ "linear.sync.modal.importNone": "문제 가져오기",
+ "linear.sync.modal.importSelected": "{{count}}개의 문제 가져오기",
+ "linear.sync.modal.oneWayHint": "단방향 동기화. Linear에서는 아무것도 변경되지 않습니다.",
+ "linear.sync.modal.saveRule": "규칙으로 저장하고 모두 동기화",
+ "linear.sync.modal.saveRuleHint": "이 필터와 일치하는 모든 문제를 지금 동기화하고, 필터를 저장하여 나중에 다시 동기화하세요.",
+ "linear.sync.modal.title": "{{account}}에서 문제 가져오기",
+ "linear.sync.project.connect": "Linear 연결",
+ "linear.sync.project.description": "Linear 문제를 이 프로젝트의 작업으로 변환하세요. 하나씩 또는 저장된 팀 또는 프로젝트 규칙을 통해 가능합니다. 동기화는 단방향입니다: Linear에서는 아무것도 변경되지 않습니다.",
+ "linear.sync.project.entry": "Linear에서 동기화",
+ "linear.sync.project.noConnection": "아직 Linear 작업 공간이 연결되지 않았습니다.",
+ "linear.sync.project.title": "Linear에서 동기화",
+ "linear.sync.projectHint": "프로젝트에 문제를 동기화하려면 프로젝트를 열고 설정 → 고급으로 이동하세요.",
+ "linear.sync.result.closed": "{{count}}개 닫힘",
+ "linear.sync.result.created": "{{count}}개 생성됨",
+ "linear.sync.result.keptLocalEdits": "{{count}}개 로컬 편집 유지됨",
+ "linear.sync.result.skipped": "{{count}}개 건너뜀",
+ "linear.sync.result.truncated": "더 많은 문제가 남아 있습니다. 계속하려면 다시 동기화하세요.",
+ "linear.sync.result.upToDate": "이미 최신 상태입니다",
+ "linear.sync.result.updated": "{{count}}개 업데이트됨",
+ "linear.sync.rules.delete": "규칙 삭제",
+ "linear.sync.rules.deleteContent": "이미 동기화된 작업은 그대로 유지됩니다. 저장된 필터만 제거됩니다.",
+ "linear.sync.rules.deleteTitle": "이 동기화 규칙을 삭제하시겠습니까?",
+ "linear.sync.rules.disconnected": "Linear 작업 공간이 연결이 끊어졌습니다. 동기화하려면 다시 연결하거나 규칙을 삭제하세요.",
+ "linear.sync.rules.lastRun": "마지막 동기화 {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "동기화 규칙을 로드할 수 없습니다",
+ "linear.sync.rules.neverRun": "아직 동기화되지 않음",
+ "linear.sync.rules.run": "지금 동기화",
+ "linear.sync.rules.running": "동기화 중",
+ "linear.sync.rules.title": "동기화 규칙",
+ "linear.sync.state.backlog": "백로그",
+ "linear.sync.state.canceled": "취소됨",
+ "linear.sync.state.completed": "완료됨",
+ "linear.sync.state.started": "진행 중",
+ "linear.sync.state.triage": "분류",
+ "linear.sync.state.unstarted": "할 일",
+ "linear.sync.viewerDisabled": "뷰어는 문제를 작업으로 가져올 수 없습니다",
+ "linear.sync.wizard.back": "뒤로",
+ "linear.sync.wizard.next": "다음",
"linear.tagline": "Linear 작업 공간을 LobeHub에 연결하세요",
"overview.all": "모든 통합",
"overview.comingSoon": "곧 제공 예정",
diff --git a/locales/nl-NL/integration.json b/locales/nl-NL/integration.json
index 50cd46fcc70..04a059b81e8 100644
--- a/locales/nl-NL/integration.json
+++ b/locales/nl-NL/integration.json
@@ -66,6 +66,86 @@
"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.sync.error.generic": "Lineaire synchronisatie mislukt. Probeer het opnieuw.",
+ "linear.sync.error.reconnect": "De Lineaire verbinding is verlopen. Verbind de werkruimte opnieuw en probeer het opnieuw.",
+ "linear.sync.filter.allProjects": "Alle projecten",
+ "linear.sync.filter.project": "Lineair project",
+ "linear.sync.filter.projectHint": "Houd Alle projecten om elk probleem in het team op te nemen.",
+ "linear.sync.filter.states": "Probleemstatussen om te synchroniseren",
+ "linear.sync.filter.statesHint": "Voltooide en geannuleerde problemen worden standaard weggelaten.",
+ "linear.sync.filter.statesSummary": "{{count}} statussen",
+ "linear.sync.filter.team": "Lineair team",
+ "linear.sync.filter.teamPlaceholder": "Kies een team",
+ "linear.sync.importIssues": "Problemen importeren",
+ "linear.sync.job.background": "U kunt dit venster sluiten; de synchronisatie blijft doorgaan en u wordt op de hoogte gebracht wanneer deze eindigt. Het resultaat wordt ook vermeld onder Synchronisatieruns in Geavanceerde instellingen.",
+ "linear.sync.job.close": "Klaar",
+ "linear.sync.job.continuesInBackground": "De synchronisatie gaat door op de achtergrond. U wordt op de hoogte gebracht wanneer deze eindigt.",
+ "linear.sync.job.done": "Synchronisatie voltooid",
+ "linear.sync.job.error.timeout": "De synchronisatie stopte met voortgang maken en werd afgebroken. Start het opnieuw.",
+ "linear.sync.job.error.unavailable": "Het project, de regel of de Lineaire verbinding is niet langer beschikbaar.",
+ "linear.sync.job.failed": "Synchronisatie mislukt",
+ "linear.sync.job.finished": "Lineaire synchronisatie voltooid: {{result}}",
+ "linear.sync.job.inProgress": "Synchroniseren…",
+ "linear.sync.job.keptLocalEdits": "{{count}} taken zijn bewerkt in LobeHub; uw bewerkingen zijn behouden.",
+ "linear.sync.job.leave": "Doorgaan op de achtergrond",
+ "linear.sync.job.listTitle": "Synchronisatieruns",
+ "linear.sync.job.runningIssues": "{{count}} problemen synchroniseren…",
+ "linear.sync.job.runningRule": "Alles synchroniseren wat de regel overeenkomt…",
+ "linear.sync.job.skipReason.closed": "Gesloten in Lineair en nooit geïmporteerd",
+ "linear.sync.job.skipReason.failed": "Kon niet worden geschreven; de volgende synchronisatie probeert het opnieuw",
+ "linear.sync.job.skipReason.missing": "Niet meer in Linear of niet zichtbaar voor deze verbinding",
+ "linear.sync.job.skipReason.running": "Taak is bezig, dus deze is niet gesloten",
+ "linear.sync.job.skipReason.unavailable": "Taak bevindt zich in de prullenbak of is niet zichtbaar voor u",
+ "linear.sync.job.skippedTitle": "{{count}} overgeslagen",
+ "linear.sync.job.titleIssues": "{{count}} problemen importeren",
+ "linear.sync.job.titleRule": "Regel: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "Regel (verwijderd)",
+ "linear.sync.list.count": "{{count}} problemen",
+ "linear.sync.list.empty": "Geen problemen voldoen aan deze filters.",
+ "linear.sync.list.linked": "Gesynchroniseerd · {{task}}",
+ "linear.sync.list.loadMore": "Meer laden",
+ "linear.sync.list.openInLinear": "Openen in Lineair",
+ "linear.sync.list.pickTeam": "Kies een team om de problemen te zien.",
+ "linear.sync.list.selectAll": "Selecteer alle {{count}} geladen",
+ "linear.sync.list.selected": "{{count}} geselecteerd",
+ "linear.sync.modal.importNone": "Problemen importeren",
+ "linear.sync.modal.importSelected": "{{count}} problemen importeren",
+ "linear.sync.modal.oneWayHint": "Eenrichtingssynchronisatie. Niets in Lineair wordt gewijzigd.",
+ "linear.sync.modal.saveRule": "Opslaan als regel en alles synchroniseren",
+ "linear.sync.modal.saveRuleHint": "Synchroniseer nu elk probleem dat overeenkomt met deze filters en bewaar de filters om later opnieuw te synchroniseren",
+ "linear.sync.modal.title": "Problemen importeren van {{account}}",
+ "linear.sync.project.connect": "Verbind Lineair",
+ "linear.sync.project.description": "Maak van Lineaire problemen taken van dit project, één voor één of via een opgeslagen team- of projectregel. Synchronisatie is eenrichtingsverkeer: niets in Lineair wordt gewijzigd.",
+ "linear.sync.project.entry": "Synchroniseren vanuit Lineair",
+ "linear.sync.project.noConnection": "Er is nog geen Lineaire werkruimte verbonden.",
+ "linear.sync.project.title": "Synchroniseren vanuit Lineair",
+ "linear.sync.projectHint": "Om problemen in een project te synchroniseren, opent u het project en gaat u naar Instellingen → Geavanceerd.",
+ "linear.sync.result.closed": "{{count}} gesloten",
+ "linear.sync.result.created": "{{count}} gemaakt",
+ "linear.sync.result.keptLocalEdits": "{{count}} lokale bewerkingen behouden",
+ "linear.sync.result.skipped": "{{count}} overgeslagen",
+ "linear.sync.result.truncated": "meer problemen blijven over, synchroniseer opnieuw om door te gaan",
+ "linear.sync.result.upToDate": "Al up-to-date",
+ "linear.sync.result.updated": "{{count}} bijgewerkt",
+ "linear.sync.rules.delete": "Regel verwijderen",
+ "linear.sync.rules.deleteContent": "Taken die al gesynchroniseerd zijn blijven zoals ze zijn. Alleen het opgeslagen filter wordt verwijderd.",
+ "linear.sync.rules.deleteTitle": "Deze synchronisatieregel verwijderen?",
+ "linear.sync.rules.disconnected": "De Lineaire werkruimte is losgekoppeld. Verbind deze opnieuw om te synchroniseren, of verwijder de regel.",
+ "linear.sync.rules.lastRun": "Laatst gesynchroniseerd {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "Kon synchronisatieregels niet laden",
+ "linear.sync.rules.neverRun": "Nog niet gesynchroniseerd",
+ "linear.sync.rules.run": "Nu synchroniseren",
+ "linear.sync.rules.running": "Synchroniseren",
+ "linear.sync.rules.title": "Synchronisatieregels",
+ "linear.sync.state.backlog": "Achterstand",
+ "linear.sync.state.canceled": "Geannuleerd",
+ "linear.sync.state.completed": "Voltooid",
+ "linear.sync.state.started": "Bezig",
+ "linear.sync.state.triage": "Triage",
+ "linear.sync.state.unstarted": "Te doen",
+ "linear.sync.viewerDisabled": "Kijkers kunnen geen problemen importeren in taken",
+ "linear.sync.wizard.back": "Terug",
+ "linear.sync.wizard.next": "Volgende",
"linear.tagline": "Verbind je Linear-werkruimte met LobeHub",
"overview.all": "Alle integraties",
"overview.comingSoon": "Binnenkort beschikbaar",
diff --git a/locales/pl-PL/integration.json b/locales/pl-PL/integration.json
index 86bb5d18d64..b51685e1c6d 100644
--- a/locales/pl-PL/integration.json
+++ b/locales/pl-PL/integration.json
@@ -66,6 +66,86 @@
"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.sync.error.generic": "Synchronizacja Linear nie powiodła się. Spróbuj ponownie.",
+ "linear.sync.error.reconnect": "Połączenie z Linear wygasło. Połącz ponownie przestrzeń roboczą, a następnie spróbuj ponownie.",
+ "linear.sync.filter.allProjects": "Wszystkie projekty",
+ "linear.sync.filter.project": "Projekt Linear",
+ "linear.sync.filter.projectHint": "Pozostaw Wszystkie projekty, aby uwzględnić każde zadanie w zespole.",
+ "linear.sync.filter.states": "Stany zadań do synchronizacji",
+ "linear.sync.filter.statesHint": "Zadania ukończone i anulowane są domyślnie pomijane.",
+ "linear.sync.filter.statesSummary": "{{count}} stanów",
+ "linear.sync.filter.team": "Zespół Linear",
+ "linear.sync.filter.teamPlaceholder": "Wybierz zespół",
+ "linear.sync.importIssues": "Importuj zadania",
+ "linear.sync.job.background": "Możesz zamknąć to okno; synchronizacja będzie kontynuowana, a po jej zakończeniu zostaniesz powiadomiony. Wynik jest również widoczny w sekcji Synchronizacje w Ustawieniach zaawansowanych.",
+ "linear.sync.job.close": "Gotowe",
+ "linear.sync.job.continuesInBackground": "Synchronizacja trwa w tle. Zostaniesz powiadomiony po jej zakończeniu.",
+ "linear.sync.job.done": "Synchronizacja zakończona",
+ "linear.sync.job.error.timeout": "Synchronizacja przestała postępować i została przerwana. Uruchom ją ponownie.",
+ "linear.sync.job.error.unavailable": "Projekt, reguła lub połączenie z Linear nie są już dostępne.",
+ "linear.sync.job.failed": "Synchronizacja nie powiodła się",
+ "linear.sync.job.finished": "Synchronizacja Linear zakończona: {{result}}",
+ "linear.sync.job.inProgress": "Synchronizowanie…",
+ "linear.sync.job.keptLocalEdits": "{{count}} zadań zostało edytowanych w LobeHub; Twoje edycje zostały zachowane.",
+ "linear.sync.job.leave": "Kontynuuj w tle",
+ "linear.sync.job.listTitle": "Synchronizacje",
+ "linear.sync.job.runningIssues": "Synchronizowanie {{count}} zadań…",
+ "linear.sync.job.runningRule": "Synchronizowanie wszystkiego, co pasuje do reguły…",
+ "linear.sync.job.skipReason.closed": "Zamknięte w Linear i nigdy nie zaimportowane",
+ "linear.sync.job.skipReason.failed": "Nie można zapisać; następna synchronizacja spróbuje ponownie",
+ "linear.sync.job.skipReason.missing": "Nie ma go już w Linear lub nie jest widoczne dla tego połączenia",
+ "linear.sync.job.skipReason.running": "Zadanie jest w toku, więc nie zostało zamknięte",
+ "linear.sync.job.skipReason.unavailable": "Zadanie jest w koszu lub nie jest widoczne dla Ciebie",
+ "linear.sync.job.skippedTitle": "{{count}} pominiętych",
+ "linear.sync.job.titleIssues": "Importuj {{count}} zadań",
+ "linear.sync.job.titleRule": "Reguła: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "Reguła (usunięta)",
+ "linear.sync.list.count": "{{count}} zadań",
+ "linear.sync.list.empty": "Brak zadań pasujących do tych filtrów.",
+ "linear.sync.list.linked": "Zsynchronizowane · {{task}}",
+ "linear.sync.list.loadMore": "Załaduj więcej",
+ "linear.sync.list.openInLinear": "Otwórz w Linear",
+ "linear.sync.list.pickTeam": "Wybierz zespół, aby zobaczyć jego zadania.",
+ "linear.sync.list.selectAll": "Zaznacz wszystkie {{count}} załadowane",
+ "linear.sync.list.selected": "{{count}} zaznaczonych",
+ "linear.sync.modal.importNone": "Importuj zadania",
+ "linear.sync.modal.importSelected": "Importuj {{count}} zadań",
+ "linear.sync.modal.oneWayHint": "Synchronizacja jednokierunkowa. Nic w Linear nie zostanie zmienione.",
+ "linear.sync.modal.saveRule": "Zapisz jako regułę i synchronizuj wszystko",
+ "linear.sync.modal.saveRuleHint": "Synchronizuj teraz każde zadanie pasujące do tych filtrów i zachowaj filtry, aby synchronizować ponownie później",
+ "linear.sync.modal.title": "Importuj zadania z {{account}}",
+ "linear.sync.project.connect": "Połącz Linear",
+ "linear.sync.project.description": "Zamień zadania z Linear na zadania w tym projekcie, pojedynczo lub za pomocą zapisanej reguły zespołu lub projektu. Synchronizacja jest jednokierunkowa: nic w Linear nie zostanie zmienione.",
+ "linear.sync.project.entry": "Synchronizuj z Linear",
+ "linear.sync.project.noConnection": "Żadna przestrzeń robocza Linear nie jest jeszcze połączona.",
+ "linear.sync.project.title": "Synchronizuj z Linear",
+ "linear.sync.projectHint": "Aby synchronizować zadania z projektem, otwórz projekt i przejdź do Ustawienia → Zaawansowane.",
+ "linear.sync.result.closed": "{{count}} zamkniętych",
+ "linear.sync.result.created": "{{count}} utworzonych",
+ "linear.sync.result.keptLocalEdits": "{{count}} zachowanych lokalnych edycji",
+ "linear.sync.result.skipped": "{{count}} pominiętych",
+ "linear.sync.result.truncated": "więcej zadań pozostało, synchronizuj ponownie, aby kontynuować",
+ "linear.sync.result.upToDate": "Już aktualne",
+ "linear.sync.result.updated": "{{count}} zaktualizowanych",
+ "linear.sync.rules.delete": "Usuń regułę",
+ "linear.sync.rules.deleteContent": "Zadania już zsynchronizowane pozostaną bez zmian. Usunięty zostanie tylko zapisany filtr.",
+ "linear.sync.rules.deleteTitle": "Usunąć tę regułę synchronizacji?",
+ "linear.sync.rules.disconnected": "Jej przestrzeń robocza Linear jest odłączona. Połącz ją ponownie, aby synchronizować, lub usuń regułę.",
+ "linear.sync.rules.lastRun": "Ostatnia synchronizacja {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "Nie udało się załadować reguł synchronizacji",
+ "linear.sync.rules.neverRun": "Jeszcze nie zsynchronizowano",
+ "linear.sync.rules.run": "Synchronizuj teraz",
+ "linear.sync.rules.running": "Synchronizowanie",
+ "linear.sync.rules.title": "Reguły synchronizacji",
+ "linear.sync.state.backlog": "Backlog",
+ "linear.sync.state.canceled": "Anulowane",
+ "linear.sync.state.completed": "Ukończone",
+ "linear.sync.state.started": "W toku",
+ "linear.sync.state.triage": "Triage",
+ "linear.sync.state.unstarted": "Do zrobienia",
+ "linear.sync.viewerDisabled": "Przeglądający nie mogą importować zadań do zadań",
+ "linear.sync.wizard.back": "Wstecz",
+ "linear.sync.wizard.next": "Dalej",
"linear.tagline": "Połącz swoją przestrzeń roboczą Linear z LobeHub",
"overview.all": "Wszystkie integracje",
"overview.comingSoon": "Wkrótce",
diff --git a/locales/pt-BR/integration.json b/locales/pt-BR/integration.json
index 19dbcd3b375..265ed84bcd4 100644
--- a/locales/pt-BR/integration.json
+++ b/locales/pt-BR/integration.json
@@ -66,6 +66,86 @@
"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.sync.error.generic": "Falha na sincronização do Linear. Por favor, tente novamente.",
+ "linear.sync.error.reconnect": "A conexão com o Linear expirou. Reconecte o espaço de trabalho e tente novamente.",
+ "linear.sync.filter.allProjects": "Todos os projetos",
+ "linear.sync.filter.project": "Projeto Linear",
+ "linear.sync.filter.projectHint": "Mantenha Todos os projetos para incluir todas as tarefas da equipe.",
+ "linear.sync.filter.states": "Estados das tarefas para sincronizar",
+ "linear.sync.filter.statesHint": "Tarefas concluídas e canceladas são excluídas por padrão.",
+ "linear.sync.filter.statesSummary": "{{count}} estados",
+ "linear.sync.filter.team": "Equipe Linear",
+ "linear.sync.filter.teamPlaceholder": "Escolha uma equipe",
+ "linear.sync.importIssues": "Importar tarefas",
+ "linear.sync.job.background": "Você pode fechar esta janela; a sincronização continuará em execução e você será notificado quando terminar. O resultado também será listado em Execuções de sincronização nas Configurações avançadas.",
+ "linear.sync.job.close": "Concluído",
+ "linear.sync.job.continuesInBackground": "A sincronização continua em segundo plano. Você será notificado quando terminar.",
+ "linear.sync.job.done": "Sincronização concluída",
+ "linear.sync.job.error.timeout": "A sincronização parou de fazer progresso e foi interrompida. Inicie novamente.",
+ "linear.sync.job.error.unavailable": "O projeto, regra ou conexão com o Linear não está mais disponível.",
+ "linear.sync.job.failed": "Falha na sincronização",
+ "linear.sync.job.finished": "Sincronização do Linear concluída: {{result}}",
+ "linear.sync.job.inProgress": "Sincronizando…",
+ "linear.sync.job.keptLocalEdits": "{{count}} tarefas foram editadas no LobeHub; suas edições foram mantidas.",
+ "linear.sync.job.leave": "Continuar em segundo plano",
+ "linear.sync.job.listTitle": "Execuções de sincronização",
+ "linear.sync.job.runningIssues": "Sincronizando {{count}} tarefas…",
+ "linear.sync.job.runningRule": "Sincronizando tudo que a regra corresponde…",
+ "linear.sync.job.skipReason.closed": "Fechado no Linear e nunca importado",
+ "linear.sync.job.skipReason.failed": "Não pôde ser gravado; a próxima sincronização tentará novamente",
+ "linear.sync.job.skipReason.missing": "Não está mais no Linear ou não é visível para esta conexão",
+ "linear.sync.job.skipReason.running": "A tarefa está em execução, então não foi fechada",
+ "linear.sync.job.skipReason.unavailable": "A tarefa está na lixeira ou não está visível para você",
+ "linear.sync.job.skippedTitle": "{{count}} ignorados",
+ "linear.sync.job.titleIssues": "Importar {{count}} tarefas",
+ "linear.sync.job.titleRule": "Regra: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "Regra (excluída)",
+ "linear.sync.list.count": "{{count}} tarefas",
+ "linear.sync.list.empty": "Nenhuma tarefa corresponde a esses filtros.",
+ "linear.sync.list.linked": "Sincronizado · {{task}}",
+ "linear.sync.list.loadMore": "Carregar mais",
+ "linear.sync.list.openInLinear": "Abrir no Linear",
+ "linear.sync.list.pickTeam": "Escolha uma equipe para ver suas tarefas.",
+ "linear.sync.list.selectAll": "Selecionar todas as {{count}} carregadas",
+ "linear.sync.list.selected": "{{count}} selecionadas",
+ "linear.sync.modal.importNone": "Importar tarefas",
+ "linear.sync.modal.importSelected": "Importar {{count}} tarefas",
+ "linear.sync.modal.oneWayHint": "Sincronização unidirecional. Nada no Linear é alterado.",
+ "linear.sync.modal.saveRule": "Salvar como regra e sincronizar tudo",
+ "linear.sync.modal.saveRuleHint": "Sincronize todas as tarefas que correspondem a esses filtros agora e mantenha os filtros para sincronizar novamente mais tarde",
+ "linear.sync.modal.title": "Importar tarefas de {{account}}",
+ "linear.sync.project.connect": "Conectar ao Linear",
+ "linear.sync.project.description": "Transforme tarefas do Linear em tarefas deste projeto, uma por uma ou através de uma regra de equipe ou projeto salva. A sincronização é unidirecional: nada no Linear é alterado.",
+ "linear.sync.project.entry": "Sincronizar do Linear",
+ "linear.sync.project.noConnection": "Nenhum espaço de trabalho do Linear está conectado ainda.",
+ "linear.sync.project.title": "Sincronizar do Linear",
+ "linear.sync.projectHint": "Para sincronizar tarefas em um projeto, abra o projeto e vá para Configurações → Avançado.",
+ "linear.sync.result.closed": "{{count}} fechadas",
+ "linear.sync.result.created": "{{count}} criadas",
+ "linear.sync.result.keptLocalEdits": "{{count}} edições locais mantidas",
+ "linear.sync.result.skipped": "{{count}} ignoradas",
+ "linear.sync.result.truncated": "mais tarefas restantes, sincronize novamente para continuar",
+ "linear.sync.result.upToDate": "Já está atualizado",
+ "linear.sync.result.updated": "{{count}} atualizadas",
+ "linear.sync.rules.delete": "Excluir regra",
+ "linear.sync.rules.deleteContent": "As tarefas já sincronizadas permanecem como estão. Apenas o filtro salvo será removido.",
+ "linear.sync.rules.deleteTitle": "Excluir esta regra de sincronização?",
+ "linear.sync.rules.disconnected": "Seu espaço de trabalho do Linear está desconectado. Reconecte para sincronizar ou exclua a regra.",
+ "linear.sync.rules.lastRun": "Última sincronização {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "Não foi possível carregar as regras de sincronização",
+ "linear.sync.rules.neverRun": "Ainda não sincronizado",
+ "linear.sync.rules.run": "Sincronizar agora",
+ "linear.sync.rules.running": "Sincronizando",
+ "linear.sync.rules.title": "Regras de sincronização",
+ "linear.sync.state.backlog": "Backlog",
+ "linear.sync.state.canceled": "Cancelado",
+ "linear.sync.state.completed": "Concluído",
+ "linear.sync.state.started": "Em progresso",
+ "linear.sync.state.triage": "Triagem",
+ "linear.sync.state.unstarted": "A fazer",
+ "linear.sync.viewerDisabled": "Visualizadores não podem importar tarefas para tarefas",
+ "linear.sync.wizard.back": "Voltar",
+ "linear.sync.wizard.next": "Avançar",
"linear.tagline": "Conecte seu espaço de trabalho Linear ao LobeHub",
"overview.all": "Todas as integrações",
"overview.comingSoon": "Em breve",
diff --git a/locales/ru-RU/integration.json b/locales/ru-RU/integration.json
index 4244f580c08..9bdf90c7ec2 100644
--- a/locales/ru-RU/integration.json
+++ b/locales/ru-RU/integration.json
@@ -66,6 +66,86 @@
"linear.installResult.error.unknown": "Не удалось подключить Linear ({{code}}).",
"linear.installResult.error.workspace_forbidden": "Только участники рабочей области могут подключить Linear здесь.",
"linear.installResult.success": "Linear подключен: {{account}}",
+ "linear.sync.error.generic": "Синхронизация Linear не удалась. Пожалуйста, попробуйте еще раз.",
+ "linear.sync.error.reconnect": "Соединение с Linear истекло. Подключите рабочую область заново, затем попробуйте еще раз.",
+ "linear.sync.filter.allProjects": "Все проекты",
+ "linear.sync.filter.project": "Проект Linear",
+ "linear.sync.filter.projectHint": "Оставьте 'Все проекты', чтобы включить все задачи в команде.",
+ "linear.sync.filter.states": "Состояния задач для синхронизации",
+ "linear.sync.filter.statesHint": "Завершенные и отмененные задачи исключаются по умолчанию.",
+ "linear.sync.filter.statesSummary": "{{count}} состояний",
+ "linear.sync.filter.team": "Команда Linear",
+ "linear.sync.filter.teamPlaceholder": "Выберите команду",
+ "linear.sync.importIssues": "Импортировать задачи",
+ "linear.sync.job.background": "Вы можете закрыть это окно; синхронизация продолжится, и вы получите уведомление, когда она завершится. Результат также будет указан в разделе 'Запуски синхронизации' в расширенных настройках.",
+ "linear.sync.job.close": "Готово",
+ "linear.sync.job.continuesInBackground": "Синхронизация продолжается в фоновом режиме. Вы получите уведомление, когда она завершится.",
+ "linear.sync.job.done": "Синхронизация завершена",
+ "linear.sync.job.error.timeout": "Синхронизация прекратила прогресс и была прервана. Запустите ее снова.",
+ "linear.sync.job.error.unavailable": "Проект, правило или соединение с Linear больше недоступны.",
+ "linear.sync.job.failed": "Синхронизация не удалась",
+ "linear.sync.job.finished": "Синхронизация Linear завершена: {{result}}",
+ "linear.sync.job.inProgress": "Синхронизация…",
+ "linear.sync.job.keptLocalEdits": "{{count}} задач были изменены в LobeHub; ваши изменения сохранены.",
+ "linear.sync.job.leave": "Продолжить в фоновом режиме",
+ "linear.sync.job.listTitle": "Запуски синхронизации",
+ "linear.sync.job.runningIssues": "Синхронизация {{count}} задач…",
+ "linear.sync.job.runningRule": "Синхронизация всего, что соответствует правилу…",
+ "linear.sync.job.skipReason.closed": "Закрыто в Linear и никогда не импортировалось",
+ "linear.sync.job.skipReason.failed": "Не удалось записать; следующая синхронизация повторит попытку",
+ "linear.sync.job.skipReason.missing": "Больше нет в Linear или недоступно для этого подключения",
+ "linear.sync.job.skipReason.running": "Задача выполняется, поэтому она не была закрыта",
+ "linear.sync.job.skipReason.unavailable": "Задача находится в корзине или недоступна для вас",
+ "linear.sync.job.skippedTitle": "{{count}} пропущено",
+ "linear.sync.job.titleIssues": "Импортировать {{count}} задач",
+ "linear.sync.job.titleRule": "Правило: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "Правило (удалено)",
+ "linear.sync.list.count": "{{count}} задач",
+ "linear.sync.list.empty": "Нет задач, соответствующих этим фильтрам.",
+ "linear.sync.list.linked": "Синхронизировано · {{task}}",
+ "linear.sync.list.loadMore": "Загрузить еще",
+ "linear.sync.list.openInLinear": "Открыть в Linear",
+ "linear.sync.list.pickTeam": "Выберите команду, чтобы увидеть ее задачи.",
+ "linear.sync.list.selectAll": "Выбрать все {{count}} загруженные",
+ "linear.sync.list.selected": "{{count}} выбрано",
+ "linear.sync.modal.importNone": "Импортировать задачи",
+ "linear.sync.modal.importSelected": "Импортировать {{count}} задач",
+ "linear.sync.modal.oneWayHint": "Односторонняя синхронизация. В Linear ничего не изменяется.",
+ "linear.sync.modal.saveRule": "Сохранить как правило и синхронизировать все",
+ "linear.sync.modal.saveRuleHint": "Синхронизируйте все задачи, соответствующие этим фильтрам, сейчас и сохраните фильтры для повторной синхронизации позже",
+ "linear.sync.modal.title": "Импортировать задачи из {{account}}",
+ "linear.sync.project.connect": "Подключить Linear",
+ "linear.sync.project.description": "Превратите задачи Linear в задачи этого проекта, по одной или через сохраненное правило команды или проекта. Синхронизация односторонняя: в Linear ничего не изменяется.",
+ "linear.sync.project.entry": "Синхронизация с Linear",
+ "linear.sync.project.noConnection": "Рабочая область Linear еще не подключена.",
+ "linear.sync.project.title": "Синхронизация с Linear",
+ "linear.sync.projectHint": "Чтобы синхронизировать задачи с проектом, откройте проект и перейдите в Настройки → Расширенные.",
+ "linear.sync.result.closed": "{{count}} закрыто",
+ "linear.sync.result.created": "{{count}} создано",
+ "linear.sync.result.keptLocalEdits": "{{count}} сохранено локальных изменений",
+ "linear.sync.result.skipped": "{{count}} пропущено",
+ "linear.sync.result.truncated": "остались задачи, синхронизируйте снова, чтобы продолжить",
+ "linear.sync.result.upToDate": "Уже актуально",
+ "linear.sync.result.updated": "{{count}} обновлено",
+ "linear.sync.rules.delete": "Удалить правило",
+ "linear.sync.rules.deleteContent": "Задачи, которые уже были синхронизированы, останутся как есть. Будет удален только сохраненный фильтр.",
+ "linear.sync.rules.deleteTitle": "Удалить это правило синхронизации?",
+ "linear.sync.rules.disconnected": "Его рабочая область Linear отключена. Подключите ее для синхронизации или удалите правило.",
+ "linear.sync.rules.lastRun": "Последняя синхронизация {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "Не удалось загрузить правила синхронизации",
+ "linear.sync.rules.neverRun": "Еще не синхронизировано",
+ "linear.sync.rules.run": "Синхронизировать сейчас",
+ "linear.sync.rules.running": "Синхронизация",
+ "linear.sync.rules.title": "Правила синхронизации",
+ "linear.sync.state.backlog": "В ожидании",
+ "linear.sync.state.canceled": "Отменено",
+ "linear.sync.state.completed": "Завершено",
+ "linear.sync.state.started": "В процессе",
+ "linear.sync.state.triage": "Сортировка",
+ "linear.sync.state.unstarted": "К выполнению",
+ "linear.sync.viewerDisabled": "Просмотрщики не могут импортировать задачи в задачи",
+ "linear.sync.wizard.back": "Назад",
+ "linear.sync.wizard.next": "Далее",
"linear.tagline": "Подключите свою рабочую область Linear к LobeHub",
"overview.all": "Все интеграции",
"overview.comingSoon": "Скоро",
diff --git a/locales/tr-TR/integration.json b/locales/tr-TR/integration.json
index 94bfa34870f..a8707378cd9 100644
--- a/locales/tr-TR/integration.json
+++ b/locales/tr-TR/integration.json
@@ -66,6 +66,86 @@
"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.sync.error.generic": "Linear senkronizasyonu başarısız oldu. Lütfen tekrar deneyin.",
+ "linear.sync.error.reconnect": "Linear bağlantısının süresi doldu. Çalışma alanını yeniden bağlayın ve tekrar deneyin.",
+ "linear.sync.filter.allProjects": "Tüm projeler",
+ "linear.sync.filter.project": "Linear projesi",
+ "linear.sync.filter.projectHint": "Takımdaki her sorunu dahil etmek için Tüm projeler seçeneğini koruyun.",
+ "linear.sync.filter.states": "Senkronize edilecek sorun durumları",
+ "linear.sync.filter.statesHint": "Tamamlanmış ve iptal edilmiş sorunlar varsayılan olarak dışarıda bırakılır.",
+ "linear.sync.filter.statesSummary": "{{count}} durum",
+ "linear.sync.filter.team": "Linear takımı",
+ "linear.sync.filter.teamPlaceholder": "Bir takım seçin",
+ "linear.sync.importIssues": "Sorunları içe aktar",
+ "linear.sync.job.background": "Bu pencereyi kapatabilirsiniz; senkronizasyon devam ediyor ve bittiğinde size bildirim gönderilecek. Sonuç ayrıca Gelişmiş ayarlardaki Senkronizasyon çalışmaları altında listelenir.",
+ "linear.sync.job.close": "Tamamlandı",
+ "linear.sync.job.continuesInBackground": "Senkronizasyon arka planda devam ediyor. Bittiğinde size bildirim gönderilecek.",
+ "linear.sync.job.done": "Senkronizasyon tamamlandı",
+ "linear.sync.job.error.timeout": "Senkronizasyon ilerlemeyi durdurdu ve kesildi. Yeniden başlatın.",
+ "linear.sync.job.error.unavailable": "Proje, kural veya Linear bağlantısı artık mevcut değil.",
+ "linear.sync.job.failed": "Senkronizasyon başarısız oldu",
+ "linear.sync.job.finished": "Linear senkronizasyonu tamamlandı: {{result}}",
+ "linear.sync.job.inProgress": "Senkronize ediliyor…",
+ "linear.sync.job.keptLocalEdits": "{{count}} görev LobeHub'da düzenlendi; düzenlemeleriniz korundu.",
+ "linear.sync.job.leave": "Arka planda devam et",
+ "linear.sync.job.listTitle": "Senkronizasyon çalışmaları",
+ "linear.sync.job.runningIssues": "{{count}} sorun senkronize ediliyor…",
+ "linear.sync.job.runningRule": "Kuralın eşleştiği her şey senkronize ediliyor…",
+ "linear.sync.job.skipReason.closed": "Linear'da kapatıldı ve hiç içe aktarılmadı",
+ "linear.sync.job.skipReason.failed": "Yazılamadı; bir sonraki senkronizasyon bunu yeniden deneyecek",
+ "linear.sync.job.skipReason.missing": "Artık Linear’da yok veya bu bağlantı tarafından görülemiyor",
+ "linear.sync.job.skipReason.running": "Görev çalışıyor, bu yüzden kapatılmadı",
+ "linear.sync.job.skipReason.unavailable": "Görev çöp kutusunda veya size görünür değil",
+ "linear.sync.job.skippedTitle": "{{count}} atlandı",
+ "linear.sync.job.titleIssues": "{{count}} sorun içe aktar",
+ "linear.sync.job.titleRule": "Kural: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "Kural (silindi)",
+ "linear.sync.list.count": "{{count}} sorun",
+ "linear.sync.list.empty": "Bu filtrelere uyan sorun yok.",
+ "linear.sync.list.linked": "Senkronize edildi · {{task}}",
+ "linear.sync.list.loadMore": "Daha fazla yükle",
+ "linear.sync.list.openInLinear": "Linear'da aç",
+ "linear.sync.list.pickTeam": "Sorunlarını görmek için bir takım seçin.",
+ "linear.sync.list.selectAll": "Yüklenen {{count}} öğenin tümünü seç",
+ "linear.sync.list.selected": "{{count}} seçildi",
+ "linear.sync.modal.importNone": "Sorunları içe aktar",
+ "linear.sync.modal.importSelected": "{{count}} sorun içe aktar",
+ "linear.sync.modal.oneWayHint": "Tek yönlü senkronizasyon. Linear'da hiçbir şey değişmez.",
+ "linear.sync.modal.saveRule": "Kural olarak kaydet ve hepsini senkronize et",
+ "linear.sync.modal.saveRuleHint": "Bu filtrelere uyan her sorunu şimdi senkronize edin ve daha sonra tekrar senkronize etmek için filtreleri koruyun",
+ "linear.sync.modal.title": "{{account}}'dan sorunları içe aktar",
+ "linear.sync.project.connect": "Linear'ı bağla",
+ "linear.sync.project.description": "Linear sorunlarını bu projenin görevlerine dönüştürün, tek tek veya kaydedilmiş bir takım veya proje kuralı aracılığıyla. Senkronizasyon tek yönlüdür: Linear'da hiçbir şey değişmez.",
+ "linear.sync.project.entry": "Linear'dan senkronize et",
+ "linear.sync.project.noConnection": "Henüz hiçbir Linear çalışma alanı bağlı değil.",
+ "linear.sync.project.title": "Linear'dan senkronize et",
+ "linear.sync.projectHint": "Sorunları bir projeye senkronize etmek için projeyi açın ve Ayarlar → Gelişmiş'e gidin.",
+ "linear.sync.result.closed": "{{count}} kapatıldı",
+ "linear.sync.result.created": "{{count}} oluşturuldu",
+ "linear.sync.result.keptLocalEdits": "{{count}} yerel düzenleme korundu",
+ "linear.sync.result.skipped": "{{count}} atlandı",
+ "linear.sync.result.truncated": "daha fazla sorun kaldı, devam etmek için tekrar senkronize edin",
+ "linear.sync.result.upToDate": "Zaten güncel",
+ "linear.sync.result.updated": "{{count}} güncellendi",
+ "linear.sync.rules.delete": "Kuralı sil",
+ "linear.sync.rules.deleteContent": "Zaten senkronize edilmiş görevler olduğu gibi kalır. Sadece kaydedilmiş filtre kaldırılır.",
+ "linear.sync.rules.deleteTitle": "Bu senkronizasyon kuralını silmek istiyor musunuz?",
+ "linear.sync.rules.disconnected": "Linear çalışma alanı bağlantısı kesildi. Senkronize etmek için yeniden bağlayın veya kuralı silin.",
+ "linear.sync.rules.lastRun": "Son senkronizasyon {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "Senkronizasyon kuralları yüklenemedi",
+ "linear.sync.rules.neverRun": "Henüz senkronize edilmedi",
+ "linear.sync.rules.run": "Şimdi senkronize et",
+ "linear.sync.rules.running": "Senkronize ediliyor",
+ "linear.sync.rules.title": "Senkronizasyon kuralları",
+ "linear.sync.state.backlog": "Bekleme listesi",
+ "linear.sync.state.canceled": "İptal edildi",
+ "linear.sync.state.completed": "Tamamlandı",
+ "linear.sync.state.started": "Devam ediyor",
+ "linear.sync.state.triage": "Ayıklama",
+ "linear.sync.state.unstarted": "Yapılacak",
+ "linear.sync.viewerDisabled": "Görüntüleyiciler sorunları görevlere içe aktaramaz",
+ "linear.sync.wizard.back": "Geri",
+ "linear.sync.wizard.next": "İleri",
"linear.tagline": "Linear çalışma alanınızı LobeHub'a bağlayın",
"overview.all": "Tüm entegrasyonlar",
"overview.comingSoon": "Yakında geliyor",
diff --git a/locales/vi-VN/integration.json b/locales/vi-VN/integration.json
index 4b5d526bbc2..8cd40059bb0 100644
--- a/locales/vi-VN/integration.json
+++ b/locales/vi-VN/integration.json
@@ -66,6 +66,86 @@
"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.sync.error.generic": "Đồng bộ Linear thất bại. Vui lòng thử lại.",
+ "linear.sync.error.reconnect": "Kết nối Linear đã hết hạn. Kết nối lại không gian làm việc, sau đó thử lại.",
+ "linear.sync.filter.allProjects": "Tất cả dự án",
+ "linear.sync.filter.project": "Dự án Linear",
+ "linear.sync.filter.projectHint": "Giữ Tất cả dự án để bao gồm mọi vấn đề trong nhóm.",
+ "linear.sync.filter.states": "Trạng thái vấn đề để đồng bộ",
+ "linear.sync.filter.statesHint": "Các vấn đề đã hoàn thành và bị hủy sẽ bị loại trừ theo mặc định.",
+ "linear.sync.filter.statesSummary": "{{count}} trạng thái",
+ "linear.sync.filter.team": "Nhóm Linear",
+ "linear.sync.filter.teamPlaceholder": "Chọn một nhóm",
+ "linear.sync.importIssues": "Nhập vấn đề",
+ "linear.sync.job.background": "Bạn có thể đóng cửa sổ này; quá trình đồng bộ vẫn tiếp tục và bạn sẽ được thông báo khi nó kết thúc. Kết quả cũng được liệt kê trong Đồng bộ đã chạy ở Cài đặt nâng cao.",
+ "linear.sync.job.close": "Hoàn tất",
+ "linear.sync.job.continuesInBackground": "Quá trình đồng bộ tiếp tục trong nền. Bạn sẽ được thông báo khi nó kết thúc.",
+ "linear.sync.job.done": "Đồng bộ hoàn tất",
+ "linear.sync.job.error.timeout": "Quá trình đồng bộ đã dừng lại và bị cắt đứt. Hãy bắt đầu lại.",
+ "linear.sync.job.error.unavailable": "Dự án, quy tắc hoặc kết nối Linear không còn khả dụng.",
+ "linear.sync.job.failed": "Đồng bộ thất bại",
+ "linear.sync.job.finished": "Đồng bộ Linear hoàn tất: {{result}}",
+ "linear.sync.job.inProgress": "Đang đồng bộ…",
+ "linear.sync.job.keptLocalEdits": "{{count}} nhiệm vụ đã được chỉnh sửa trong LobeHub; các chỉnh sửa của bạn đã được giữ lại.",
+ "linear.sync.job.leave": "Tiếp tục trong nền",
+ "linear.sync.job.listTitle": "Đồng bộ đã chạy",
+ "linear.sync.job.runningIssues": "Đang đồng bộ {{count}} vấn đề…",
+ "linear.sync.job.runningRule": "Đang đồng bộ mọi thứ mà quy tắc khớp…",
+ "linear.sync.job.skipReason.closed": "Đã đóng trong Linear và chưa bao giờ được nhập",
+ "linear.sync.job.skipReason.failed": "Không thể ghi; lần đồng bộ tiếp theo sẽ thử lại",
+ "linear.sync.job.skipReason.missing": "Không còn trong Linear hoặc kết nối này không xem được",
+ "linear.sync.job.skipReason.running": "Nhiệm vụ đang chạy, vì vậy nó không được đóng",
+ "linear.sync.job.skipReason.unavailable": "Nhiệm vụ nằm trong thùng rác hoặc không hiển thị với bạn",
+ "linear.sync.job.skippedTitle": "{{count}} đã bị bỏ qua",
+ "linear.sync.job.titleIssues": "Nhập {{count}} vấn đề",
+ "linear.sync.job.titleRule": "Quy tắc: {{rule}}",
+ "linear.sync.job.titleRuleDeleted": "Quy tắc (đã xóa)",
+ "linear.sync.list.count": "{{count}} vấn đề",
+ "linear.sync.list.empty": "Không có vấn đề nào khớp với các bộ lọc này.",
+ "linear.sync.list.linked": "Đã đồng bộ · {{task}}",
+ "linear.sync.list.loadMore": "Tải thêm",
+ "linear.sync.list.openInLinear": "Mở trong Linear",
+ "linear.sync.list.pickTeam": "Chọn một nhóm để xem các vấn đề của nó.",
+ "linear.sync.list.selectAll": "Chọn tất cả {{count}} đã tải",
+ "linear.sync.list.selected": "{{count}} đã chọn",
+ "linear.sync.modal.importNone": "Nhập vấn đề",
+ "linear.sync.modal.importSelected": "Nhập {{count}} vấn đề",
+ "linear.sync.modal.oneWayHint": "Đồng bộ một chiều. Không có gì trong Linear bị thay đổi.",
+ "linear.sync.modal.saveRule": "Lưu làm quy tắc và đồng bộ tất cả",
+ "linear.sync.modal.saveRuleHint": "Đồng bộ mọi vấn đề khớp với các bộ lọc này ngay bây giờ, và giữ các bộ lọc để đồng bộ lại sau",
+ "linear.sync.modal.title": "Nhập vấn đề từ {{account}}",
+ "linear.sync.project.connect": "Kết nối Linear",
+ "linear.sync.project.description": "Biến các vấn đề Linear thành nhiệm vụ của dự án này, từng cái một hoặc thông qua một quy tắc nhóm hoặc dự án đã lưu. Đồng bộ là một chiều: không có gì trong Linear bị thay đổi.",
+ "linear.sync.project.entry": "Đồng bộ từ Linear",
+ "linear.sync.project.noConnection": "Chưa có không gian làm việc Linear nào được kết nối.",
+ "linear.sync.project.title": "Đồng bộ từ Linear",
+ "linear.sync.projectHint": "Để đồng bộ vấn đề vào một dự án, hãy mở dự án và đi đến Cài đặt → Nâng cao.",
+ "linear.sync.result.closed": "{{count}} đã đóng",
+ "linear.sync.result.created": "{{count}} đã tạo",
+ "linear.sync.result.keptLocalEdits": "{{count}} giữ lại chỉnh sửa cục bộ",
+ "linear.sync.result.skipped": "{{count}} đã bị bỏ qua",
+ "linear.sync.result.truncated": "còn nhiều vấn đề, đồng bộ lại để tiếp tục",
+ "linear.sync.result.upToDate": "Đã cập nhật",
+ "linear.sync.result.updated": "{{count}} đã cập nhật",
+ "linear.sync.rules.delete": "Xóa quy tắc",
+ "linear.sync.rules.deleteContent": "Các nhiệm vụ đã đồng bộ vẫn giữ nguyên. Chỉ bộ lọc đã lưu bị xóa.",
+ "linear.sync.rules.deleteTitle": "Xóa quy tắc đồng bộ này?",
+ "linear.sync.rules.disconnected": "Không gian làm việc Linear của nó đã bị ngắt kết nối. Kết nối lại để đồng bộ, hoặc xóa quy tắc.",
+ "linear.sync.rules.lastRun": "Đồng bộ lần cuối {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "Không thể tải quy tắc đồng bộ",
+ "linear.sync.rules.neverRun": "Chưa đồng bộ lần nào",
+ "linear.sync.rules.run": "Đồng bộ ngay",
+ "linear.sync.rules.running": "Đang đồng bộ",
+ "linear.sync.rules.title": "Quy tắc đồng bộ",
+ "linear.sync.state.backlog": "Công việc tồn đọng",
+ "linear.sync.state.canceled": "Đã hủy",
+ "linear.sync.state.completed": "Đã hoàn thành",
+ "linear.sync.state.started": "Đang tiến hành",
+ "linear.sync.state.triage": "Phân loại",
+ "linear.sync.state.unstarted": "Chưa bắt đầu",
+ "linear.sync.viewerDisabled": "Người xem không thể nhập vấn đề thành nhiệm vụ",
+ "linear.sync.wizard.back": "Quay lại",
+ "linear.sync.wizard.next": "Tiếp theo",
"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",
diff --git a/locales/zh-CN/integration.json b/locales/zh-CN/integration.json
index ee483e2d9ed..f4f7cf52870 100644
--- a/locales/zh-CN/integration.json
+++ b/locales/zh-CN/integration.json
@@ -66,6 +66,86 @@
"linear.installResult.error.unknown": "连接 Linear 失败({{code}})。",
"linear.installResult.error.workspace_forbidden": "只有工作区成员可以在此连接 Linear。",
"linear.installResult.success": "已连接 Linear:{{account}}",
+ "linear.sync.error.generic": "Linear 同步失败,请重试。",
+ "linear.sync.error.reconnect": "Linear 连接已失效,请重新连接工作区后再试。",
+ "linear.sync.filter.allProjects": "全部项目",
+ "linear.sync.filter.project": "Linear 项目",
+ "linear.sync.filter.projectHint": "保持「全部项目」即包含团队内的所有 Issue。",
+ "linear.sync.filter.states": "同步的 Issue 状态",
+ "linear.sync.filter.statesHint": "默认不包含已完成和已取消的 Issue。",
+ "linear.sync.filter.statesSummary": "{{count}} 种状态",
+ "linear.sync.filter.team": "Linear 团队",
+ "linear.sync.filter.teamPlaceholder": "选择团队",
+ "linear.sync.importIssues": "导入 Issue",
+ "linear.sync.job.background": "可以关闭窗口,同步会在后台继续,结束时会通知你;结果也会记在「高级设置」的同步记录里。",
+ "linear.sync.job.close": "完成",
+ "linear.sync.job.continuesInBackground": "同步会在后台继续,结束时会通知你。",
+ "linear.sync.job.done": "同步完成",
+ "linear.sync.job.error.timeout": "同步长时间没有进展,已中断,请重新开始。",
+ "linear.sync.job.error.unavailable": "项目、规则或 Linear 连接已不可用。",
+ "linear.sync.job.failed": "同步失败",
+ "linear.sync.job.finished": "Linear 同步完成:{{result}}",
+ "linear.sync.job.inProgress": "同步中…",
+ "linear.sync.job.keptLocalEdits": "有 {{count}} 个任务在 LobeHub 中改过,已保留你的修改。",
+ "linear.sync.job.leave": "后台继续",
+ "linear.sync.job.listTitle": "同步记录",
+ "linear.sync.job.runningIssues": "正在同步 {{count}} 个 Issue…",
+ "linear.sync.job.runningRule": "正在同步规则匹配的全部 Issue…",
+ "linear.sync.job.skipReason.closed": "在 Linear 中已关闭,未导入",
+ "linear.sync.job.skipReason.failed": "写入失败,下次同步会重试",
+ "linear.sync.job.skipReason.missing": "Linear 中已不存在,或当前连接无权访问",
+ "linear.sync.job.skipReason.running": "任务正在运行,未关闭",
+ "linear.sync.job.skipReason.unavailable": "任务在回收站或你无权查看",
+ "linear.sync.job.skippedTitle": "跳过 {{count}} 个",
+ "linear.sync.job.titleIssues": "导入 {{count}} 个 Issue",
+ "linear.sync.job.titleRule": "按规则同步:{{rule}}",
+ "linear.sync.job.titleRuleDeleted": "按规则同步(规则已删除)",
+ "linear.sync.list.count": "{{count}} 个 Issue",
+ "linear.sync.list.empty": "没有符合筛选条件的 Issue。",
+ "linear.sync.list.linked": "已同步 · {{task}}",
+ "linear.sync.list.loadMore": "加载更多",
+ "linear.sync.list.openInLinear": "在 Linear 中打开",
+ "linear.sync.list.pickTeam": "选择团队后查看其 Issue。",
+ "linear.sync.list.selectAll": "全选已加载的 {{count}} 个",
+ "linear.sync.list.selected": "已选 {{count}} 个",
+ "linear.sync.modal.importNone": "导入 Issue",
+ "linear.sync.modal.importSelected": "导入 {{count}} 个 Issue",
+ "linear.sync.modal.oneWayHint": "单向同步,不会修改 Linear 中的任何内容。",
+ "linear.sync.modal.saveRule": "保存为规则并全部同步",
+ "linear.sync.modal.saveRuleHint": "立即同步符合当前筛选的所有 Issue,并保存筛选条件以便之后再次同步",
+ "linear.sync.modal.title": "从 {{account}} 导入 Issue",
+ "linear.sync.project.connect": "连接 Linear",
+ "linear.sync.project.description": "把 Linear Issue 同步为本项目的任务,可以逐个导入,也可以按团队或 Linear 项目保存规则。同步是单向的,不会修改 Linear。",
+ "linear.sync.project.entry": "从 Linear 同步",
+ "linear.sync.project.noConnection": "还没有连接 Linear 工作区。",
+ "linear.sync.project.title": "从 Linear 同步",
+ "linear.sync.projectHint": "要把 Issue 同步到项目,请打开项目,进入「设置 → 高级设置」。",
+ "linear.sync.result.closed": "关闭 {{count}} 个",
+ "linear.sync.result.created": "新建 {{count}} 个",
+ "linear.sync.result.keptLocalEdits": "{{count}} 个保留本地修改",
+ "linear.sync.result.skipped": "跳过 {{count}} 个",
+ "linear.sync.result.truncated": "还有更多 Issue,请再次同步以继续",
+ "linear.sync.result.upToDate": "已是最新",
+ "linear.sync.result.updated": "更新 {{count}} 个",
+ "linear.sync.rules.delete": "删除规则",
+ "linear.sync.rules.deleteContent": "已同步的任务保持不变,只删除保存的筛选条件。",
+ "linear.sync.rules.deleteTitle": "删除这条同步规则?",
+ "linear.sync.rules.disconnected": "对应的 Linear 工作区已断开,重新连接后才能同步,也可以删除这条规则。",
+ "linear.sync.rules.lastRun": "上次同步 {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "同步规则加载失败",
+ "linear.sync.rules.neverRun": "尚未同步",
+ "linear.sync.rules.run": "立即同步",
+ "linear.sync.rules.running": "同步中",
+ "linear.sync.rules.title": "同步规则",
+ "linear.sync.state.backlog": "Backlog",
+ "linear.sync.state.canceled": "已取消",
+ "linear.sync.state.completed": "已完成",
+ "linear.sync.state.started": "进行中",
+ "linear.sync.state.triage": "待分拣",
+ "linear.sync.state.unstarted": "待办",
+ "linear.sync.viewerDisabled": "查看者不能把 Issue 导入为任务",
+ "linear.sync.wizard.back": "上一步",
+ "linear.sync.wizard.next": "下一步",
"linear.tagline": "将你的 Linear 工作区连接到 LobeHub",
"overview.all": "全部集成",
"overview.comingSoon": "即将支持",
diff --git a/locales/zh-TW/integration.json b/locales/zh-TW/integration.json
index 8431741f25b..0def135ee06 100644
--- a/locales/zh-TW/integration.json
+++ b/locales/zh-TW/integration.json
@@ -66,6 +66,86 @@
"linear.installResult.error.unknown": "連接 Linear 失敗({{code}})。",
"linear.installResult.error.workspace_forbidden": "只有工作區成員可以在此處連接 Linear。",
"linear.installResult.success": "Linear 已連接:{{account}}",
+ "linear.sync.error.generic": "Linear 同步失敗。請再試一次。",
+ "linear.sync.error.reconnect": "Linear 連線已過期。請重新連接工作區,然後再試一次。",
+ "linear.sync.filter.allProjects": "所有專案",
+ "linear.sync.filter.project": "Linear 專案",
+ "linear.sync.filter.projectHint": "保持「所有專案」以包含團隊中的每個問題。",
+ "linear.sync.filter.states": "要同步的問題狀態",
+ "linear.sync.filter.statesHint": "已完成和已取消的問題預設不包括在內。",
+ "linear.sync.filter.statesSummary": "{{count}} 個狀態",
+ "linear.sync.filter.team": "Linear 團隊",
+ "linear.sync.filter.teamPlaceholder": "選擇一個團隊",
+ "linear.sync.importIssues": "匯入問題",
+ "linear.sync.job.background": "您可以關閉此視窗;同步將繼續執行,並在結束時通知您。結果也會列在進階設定中的同步執行記錄中。",
+ "linear.sync.job.close": "完成",
+ "linear.sync.job.continuesInBackground": "同步繼續在背景中執行。結束時會通知您。",
+ "linear.sync.job.done": "同步完成",
+ "linear.sync.job.error.timeout": "同步停止進展並被中斷。請重新啟動。",
+ "linear.sync.job.error.unavailable": "專案、規則或 Linear 連線不再可用。",
+ "linear.sync.job.failed": "同步失敗",
+ "linear.sync.job.finished": "Linear 同步完成:{{result}}",
+ "linear.sync.job.inProgress": "正在同步…",
+ "linear.sync.job.keptLocalEdits": "{{count}} 個任務在 LobeHub 中被編輯;您的編輯已保留。",
+ "linear.sync.job.leave": "在背景中繼續",
+ "linear.sync.job.listTitle": "同步執行記錄",
+ "linear.sync.job.runningIssues": "正在同步 {{count}} 個問題…",
+ "linear.sync.job.runningRule": "正在同步符合規則的所有內容…",
+ "linear.sync.job.skipReason.closed": "在 Linear 中已關閉且從未匯入",
+ "linear.sync.job.skipReason.failed": "無法寫入;下一次同步會重試",
+ "linear.sync.job.skipReason.missing": "Linear 中已不存在,或目前的連線無權存取",
+ "linear.sync.job.skipReason.running": "任務正在執行,因此未被關閉",
+ "linear.sync.job.skipReason.unavailable": "任務在垃圾桶中或您無法查看",
+ "linear.sync.job.skippedTitle": "{{count}} 個被跳過",
+ "linear.sync.job.titleIssues": "匯入 {{count}} 個問題",
+ "linear.sync.job.titleRule": "規則:{{rule}}",
+ "linear.sync.job.titleRuleDeleted": "規則(已刪除)",
+ "linear.sync.list.count": "{{count}} 個問題",
+ "linear.sync.list.empty": "沒有符合這些篩選條件的問題。",
+ "linear.sync.list.linked": "已同步 · {{task}}",
+ "linear.sync.list.loadMore": "載入更多",
+ "linear.sync.list.openInLinear": "在 Linear 中開啟",
+ "linear.sync.list.pickTeam": "選擇一個團隊以查看其問題。",
+ "linear.sync.list.selectAll": "選擇所有已載入的 {{count}} 個",
+ "linear.sync.list.selected": "已選擇 {{count}} 個",
+ "linear.sync.modal.importNone": "匯入問題",
+ "linear.sync.modal.importSelected": "匯入 {{count}} 個問題",
+ "linear.sync.modal.oneWayHint": "單向同步。Linear 中的內容不會被更改。",
+ "linear.sync.modal.saveRule": "儲存為規則並同步所有",
+ "linear.sync.modal.saveRuleHint": "立即同步符合這些篩選條件的每個問題,並保留篩選條件以便稍後再次同步",
+ "linear.sync.modal.title": "從 {{account}} 匯入問題",
+ "linear.sync.project.connect": "連接 Linear",
+ "linear.sync.project.description": "將 Linear 問題轉換為此專案的任務,可以逐一轉換或通過已儲存的團隊或專案規則進行。同步是單向的:Linear 中的內容不會被更改。",
+ "linear.sync.project.entry": "從 Linear 同步",
+ "linear.sync.project.noConnection": "尚未連接任何 Linear 工作區。",
+ "linear.sync.project.title": "從 Linear 同步",
+ "linear.sync.projectHint": "要將問題同步到專案中,請打開專案並前往設定 → 進階。",
+ "linear.sync.result.closed": "{{count}} 個已關閉",
+ "linear.sync.result.created": "{{count}} 個已建立",
+ "linear.sync.result.keptLocalEdits": "{{count}} 個保留了本地編輯",
+ "linear.sync.result.skipped": "{{count}} 個被跳過",
+ "linear.sync.result.truncated": "還有更多問題,請再次同步以繼續",
+ "linear.sync.result.upToDate": "已是最新",
+ "linear.sync.result.updated": "{{count}} 個已更新",
+ "linear.sync.rules.delete": "刪除規則",
+ "linear.sync.rules.deleteContent": "已同步的任務保持不變。僅刪除已儲存的篩選條件。",
+ "linear.sync.rules.deleteTitle": "刪除此同步規則?",
+ "linear.sync.rules.disconnected": "其 Linear 工作區已斷開連接。重新連接以同步,或刪除規則。",
+ "linear.sync.rules.lastRun": "上次同步於 {{time}} · {{result}}",
+ "linear.sync.rules.loadFailed": "無法載入同步規則",
+ "linear.sync.rules.neverRun": "尚未同步",
+ "linear.sync.rules.run": "立即同步",
+ "linear.sync.rules.running": "正在同步",
+ "linear.sync.rules.title": "同步規則",
+ "linear.sync.state.backlog": "待辦清單",
+ "linear.sync.state.canceled": "已取消",
+ "linear.sync.state.completed": "已完成",
+ "linear.sync.state.started": "進行中",
+ "linear.sync.state.triage": "分類",
+ "linear.sync.state.unstarted": "待辦",
+ "linear.sync.viewerDisabled": "檢視者無法將問題匯入任務",
+ "linear.sync.wizard.back": "返回",
+ "linear.sync.wizard.next": "下一步",
"linear.tagline": "將您的 Linear 工作區連接到 LobeHub",
"overview.all": "所有整合",
"overview.comingSoon": "即將推出",
diff --git a/packages/database/src/models/__tests__/taskExternalLink.test.ts b/packages/database/src/models/__tests__/taskExternalLink.test.ts
new file mode 100644
index 00000000000..942571d5016
--- /dev/null
+++ b/packages/database/src/models/__tests__/taskExternalLink.test.ts
@@ -0,0 +1,73 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { users, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { TaskModel } from '../task';
+import { TaskExternalLinkModel } from '../taskExternalLink';
+
+const db: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-external-link-user';
+const otherUserId = 'task-external-link-other';
+const workspaceId = 'task-external-link-ws';
+
+const link = (taskId: string, externalId = 'issue-1') => ({
+ externalContainerId: 'team-1',
+ externalId,
+ externalIdentifier: 'ENG-1',
+ externalUrl: 'https://linear.app/acme/issue/ENG-1',
+ provider: 'linear' as const,
+ syncedHash: 'hash',
+ taskId,
+});
+
+beforeEach(async () => {
+ 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(workspaces).where(eq(workspaces.id, workspaceId));
+ await db.delete(users).where(eq(users.id, userId));
+ await db.delete(users).where(eq(users.id, otherUserId));
+});
+
+describe('TaskExternalLinkModel', () => {
+ it('maps an external item to at most one task per scope', async () => {
+ const model = new TaskExternalLinkModel(db, userId);
+ const tasks = new TaskModel(db, userId);
+ const first = await tasks.create({ instruction: 'one' });
+ const second = await tasks.create({ instruction: 'two' });
+
+ await model.create(link(first.id));
+
+ await expect(model.create(link(second.id))).rejects.toThrow();
+ });
+
+ it('keeps personal and workspace scopes apart', async () => {
+ const personal = new TaskExternalLinkModel(db, userId);
+ const shared = new TaskExternalLinkModel(db, userId, workspaceId);
+ const personalTask = await new TaskModel(db, userId).create({ instruction: 'mine' });
+ const sharedTask = await new TaskModel(db, userId, workspaceId).create({
+ instruction: 'ours',
+ });
+
+ await personal.create(link(personalTask.id));
+ await shared.create(link(sharedTask.id));
+
+ const [mine] = await personal.findByExternalIds('linear', ['issue-1']);
+ const [ours] = await shared.findByExternalIds('linear', ['issue-1']);
+ expect(mine.taskId).toBe(personalTask.id);
+ expect(mine.taskIdentifier).toBe(personalTask.identifier);
+ expect(ours.taskId).toBe(sharedTask.id);
+ expect(
+ await new TaskExternalLinkModel(db, otherUserId).findByExternalIds('linear', ['issue-1']),
+ ).toEqual([]);
+ expect(await shared.findByContainer('linear', 'team-1')).toHaveLength(1);
+ });
+});
diff --git a/packages/database/src/models/linear/connection.ts b/packages/database/src/models/linear/connection.ts
index 804a5578ba8..edfff3008a9 100644
--- a/packages/database/src/models/linear/connection.ts
+++ b/packages/database/src/models/linear/connection.ts
@@ -121,6 +121,23 @@ export class LinearConnectionModel {
return row;
};
+ /** Replace the token after a refresh. A revoked row keeps its revocation. */
+ static updateCredentials = async (
+ db: LobeChatDatabase,
+ id: string,
+ params: { credentials: LinearConnectionCredentials; tokenExpiresAt?: Date | null },
+ gateKeeper?: GateKeeper,
+ ): Promise<void> => {
+ await db
+ .update(linearConnections)
+ .set({
+ credentials: await encryptCredentials(params.credentials, gateKeeper),
+ tokenExpiresAt: params.tokenExpiresAt ?? null,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(linearConnections.id, id), isNull(linearConnections.revokedAt)));
+ };
+
/** Disconnect: drop the token and hide the row. A reconnect reuses it. */
static revoke = async (db: LobeChatDatabase, id: string): Promise<void> => {
await db
diff --git a/packages/database/src/models/linear/index.ts b/packages/database/src/models/linear/index.ts
index 0fb32617504..e57df9c9fd5 100644
--- a/packages/database/src/models/linear/index.ts
+++ b/packages/database/src/models/linear/index.ts
@@ -1 +1,3 @@
export * from './connection';
+export * from './syncJob';
+export * from './syncRule';
diff --git a/packages/database/src/models/linear/syncJob.ts b/packages/database/src/models/linear/syncJob.ts
new file mode 100644
index 00000000000..ca797363dce
--- /dev/null
+++ b/packages/database/src/models/linear/syncJob.ts
@@ -0,0 +1,118 @@
+import type { LinearSyncJobMetadata } from '@lobechat/types';
+import { AsyncTaskStatus, AsyncTaskType } from '@lobechat/types';
+import { and, desc, eq, inArray, sql } from 'drizzle-orm';
+
+import { asyncTasks } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+import type { LinearConnectionScope } from './connection';
+
+export type LinearSyncJobRow = typeof asyncTasks.$inferSelect & {
+ metadata: LinearSyncJobMetadata;
+};
+
+const ACTIVE_STATUSES = [AsyncTaskStatus.Pending, AsyncTaskStatus.Processing];
+
+/**
+ * Background Linear issue syncs. They live in `async_tasks` (type
+ * `linear_issue_sync`) with what to sync in `metadata`; these reads narrow
+ * them to a scope and a LobeHub project.
+ */
+export class LinearSyncJobModel {
+ static listByProject = async (
+ db: LobeChatDatabase,
+ scope: LinearConnectionScope,
+ projectId: string,
+ limit = 10,
+ ): Promise<LinearSyncJobRow[]> =>
+ (await db
+ .select()
+ .from(asyncTasks)
+ .where(projectCondition(scope, projectId))
+ .orderBy(desc(asyncTasks.createdAt))
+ .limit(limit)) as LinearSyncJobRow[];
+
+ /**
+ * Move a queued job to processing. Only one caller wins, so a retried
+ * request never runs the same sync twice.
+ */
+ static claim = async (
+ db: LobeChatDatabase,
+ scope: LinearConnectionScope,
+ taskId: string,
+ ): Promise<LinearSyncJobRow | null> => {
+ const [row] = await db
+ .update(asyncTasks)
+ .set({ status: AsyncTaskStatus.Processing, updatedAt: new Date() })
+ .where(
+ and(
+ eq(asyncTasks.id, taskId),
+ eq(asyncTasks.type, AsyncTaskType.LinearIssueSync),
+ eq(asyncTasks.status, AsyncTaskStatus.Pending),
+ buildWorkspaceWhere(
+ { userId: scope.userId, workspaceId: scope.workspaceId ?? undefined },
+ asyncTasks,
+ ),
+ ),
+ )
+ .returning();
+ return (row as LinearSyncJobRow | undefined) ?? null;
+ };
+
+ /**
+ * Record that a running job is still alive, so a long sync is not mistaken
+ * for one that was cut off. A job that already finished is left as is.
+ */
+ static touch = async (
+ db: LobeChatDatabase,
+ scope: LinearConnectionScope,
+ taskId: string,
+ ): Promise<void> => {
+ await db
+ .update(asyncTasks)
+ .set({ updatedAt: new Date() })
+ .where(
+ and(
+ eq(asyncTasks.id, taskId),
+ eq(asyncTasks.type, AsyncTaskType.LinearIssueSync),
+ eq(asyncTasks.status, AsyncTaskStatus.Processing),
+ buildWorkspaceWhere(
+ { userId: scope.userId, workspaceId: scope.workspaceId ?? undefined },
+ asyncTasks,
+ ),
+ ),
+ );
+ };
+
+ /** A run of this rule that has not finished yet, if any. */
+ static findActiveForRule = async (
+ db: LobeChatDatabase,
+ scope: LinearConnectionScope,
+ projectId: string,
+ ruleId: string,
+ ): Promise<LinearSyncJobRow | null> => {
+ const [row] = await db
+ .select()
+ .from(asyncTasks)
+ .where(
+ and(
+ projectCondition(scope, projectId),
+ inArray(asyncTasks.status, ACTIVE_STATUSES),
+ sql`${asyncTasks.metadata} ->> 'ruleId' = ${ruleId}`,
+ ),
+ )
+ .orderBy(desc(asyncTasks.createdAt))
+ .limit(1);
+ return (row as LinearSyncJobRow | undefined) ?? null;
+ };
+}
+
+const projectCondition = (scope: LinearConnectionScope, projectId: string) =>
+ and(
+ eq(asyncTasks.type, AsyncTaskType.LinearIssueSync),
+ sql`${asyncTasks.metadata} ->> 'projectId' = ${projectId}`,
+ buildWorkspaceWhere(
+ { userId: scope.userId, workspaceId: scope.workspaceId ?? undefined },
+ asyncTasks,
+ ),
+ );
diff --git a/packages/database/src/models/linear/syncRule.ts b/packages/database/src/models/linear/syncRule.ts
new file mode 100644
index 00000000000..3df17eb7bdf
--- /dev/null
+++ b/packages/database/src/models/linear/syncRule.ts
@@ -0,0 +1,101 @@
+import type { LinearSyncResult, LinearSyncRuleView } from '@lobechat/types';
+import { and, desc, eq, isNull } from 'drizzle-orm';
+
+import type { LinearSyncRuleItem, NewLinearSyncRule } from '../../schemas';
+import { linearSyncRules } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import type { LinearConnectionScope } from './connection';
+
+/**
+ * Saved Linear → task sync filters, each owned by a LobeHub project. Like
+ * `LinearConnectionModel` it exposes static methods; every read is narrowed
+ * to a scope (the workspace's rules, or the user's personal ones).
+ */
+export class LinearSyncRuleModel {
+ static listByProject = async (
+ db: LobeChatDatabase,
+ scope: LinearConnectionScope,
+ projectId: string,
+ ): Promise<LinearSyncRuleItem[]> =>
+ db
+ .select()
+ .from(linearSyncRules)
+ .where(and(eq(linearSyncRules.projectId, projectId), scopeCondition(scope)))
+ .orderBy(desc(linearSyncRules.createdAt));
+
+ static findInScope = async (
+ db: LobeChatDatabase,
+ id: string,
+ scope: LinearConnectionScope,
+ ): Promise<LinearSyncRuleItem | null> => {
+ const [row] = await db
+ .select()
+ .from(linearSyncRules)
+ .where(and(eq(linearSyncRules.id, id), scopeCondition(scope)));
+ return row ?? null;
+ };
+
+ /**
+ * Lock the rule row until the transaction ends, so concurrent starts of the
+ * same rule check for a running job one at a time. False when it is gone.
+ */
+ static lockInScope = async (
+ db: LobeChatDatabase,
+ id: string,
+ scope: LinearConnectionScope,
+ ): Promise<boolean> => {
+ const rows = await db
+ .select({ id: linearSyncRules.id })
+ .from(linearSyncRules)
+ .where(and(eq(linearSyncRules.id, id), scopeCondition(scope)))
+ .for('update');
+ return rows.length > 0;
+ };
+
+ static create = async (
+ db: LobeChatDatabase,
+ values: NewLinearSyncRule,
+ ): Promise<LinearSyncRuleItem> => {
+ const [row] = await db.insert(linearSyncRules).values(values).returning();
+ return row;
+ };
+
+ static delete = async (
+ db: LobeChatDatabase,
+ id: string,
+ scope: LinearConnectionScope,
+ ): Promise<void> => {
+ await db.delete(linearSyncRules).where(and(eq(linearSyncRules.id, id), scopeCondition(scope)));
+ };
+
+ static recordRun = async (
+ db: LobeChatDatabase,
+ id: string,
+ scope: LinearConnectionScope,
+ result: LinearSyncResult,
+ ): Promise<void> => {
+ await db
+ .update(linearSyncRules)
+ .set({ lastResult: result, lastRunAt: new Date(), updatedAt: new Date() })
+ .where(and(eq(linearSyncRules.id, id), scopeCondition(scope)));
+ };
+
+ static toView = (row: LinearSyncRuleItem): LinearSyncRuleView => ({
+ connectionId: row.connectionId,
+ createdAt: row.createdAt,
+ id: row.id,
+ lastResult: row.lastResult ?? null,
+ lastRunAt: row.lastRunAt,
+ linearProjectId: row.linearProjectId,
+ linearProjectName: row.linearProjectName,
+ projectId: row.projectId,
+ stateTypes: row.stateTypes,
+ teamId: row.teamId,
+ teamName: row.teamName,
+ });
+}
+
+const scopeCondition = (scope: LinearConnectionScope) =>
+ scope.workspaceId
+ ? eq(linearSyncRules.workspaceId, scope.workspaceId)
+ : and(eq(linearSyncRules.userId, scope.userId), isNull(linearSyncRules.workspaceId));
diff --git a/packages/database/src/models/taskExternalLink.ts b/packages/database/src/models/taskExternalLink.ts
new file mode 100644
index 00000000000..279e5574f67
--- /dev/null
+++ b/packages/database/src/models/taskExternalLink.ts
@@ -0,0 +1,127 @@
+import type { TaskExternalProvider } from '@lobechat/types';
+import { and, eq, inArray, isNull } from 'drizzle-orm';
+
+import type { NewTaskExternalLink, TaskExternalLinkItem } from '../schemas';
+import { taskExternalLinks, tasks } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+
+export type TaskExternalLinkCreate = Omit<
+ NewTaskExternalLink,
+ 'createdAt' | 'id' | 'updatedAt' | 'userId' | 'workspaceId'
+>;
+
+export type TaskExternalLinkWithTask = TaskExternalLinkItem & { taskIdentifier: string };
+
+/**
+ * Links between tasks and the external items they were imported from, scoped
+ * like tasks: the workspace's links, or the user's personal ones. An external
+ * item maps to at most one task per scope.
+ */
+export class TaskExternalLinkModel {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+ private readonly workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ }
+
+ /** Links for the given external ids, with the linked task's display identifier. */
+ async findByExternalIds(
+ provider: TaskExternalProvider,
+ externalIds: string[],
+ ): Promise<TaskExternalLinkWithTask[]> {
+ if (externalIds.length === 0) return [];
+ return this.selectWithTask().where(
+ and(
+ this.scope(),
+ eq(taskExternalLinks.provider, provider),
+ inArray(taskExternalLinks.externalId, externalIds),
+ ),
+ );
+ }
+
+ /** Every link in one external container (a Linear team). */
+ async findByContainer(
+ provider: TaskExternalProvider,
+ containerId: string,
+ ): Promise<TaskExternalLinkWithTask[]> {
+ return this.selectWithTask().where(
+ and(
+ this.scope(),
+ eq(taskExternalLinks.provider, provider),
+ eq(taskExternalLinks.externalContainerId, containerId),
+ ),
+ );
+ }
+
+ async findByTaskId(taskId: string): Promise<TaskExternalLinkItem | null> {
+ const [row] = await this.db
+ .select()
+ .from(taskExternalLinks)
+ .where(and(this.scope(), eq(taskExternalLinks.taskId, taskId)));
+ return row ?? null;
+ }
+
+ async create(data: TaskExternalLinkCreate): Promise<TaskExternalLinkItem> {
+ const [row] = await this.db
+ .insert(taskExternalLinks)
+ .values({ ...data, userId: this.userId, workspaceId: this.workspaceId ?? null })
+ .returning();
+ return row;
+ }
+
+ async update(
+ id: string,
+ data: Partial<
+ Pick<
+ TaskExternalLinkItem,
+ | 'externalContainerId'
+ | 'externalIdentifier'
+ | 'externalUpdatedAt'
+ | 'externalUrl'
+ | 'metadata'
+ | 'syncedHash'
+ >
+ >,
+ ): Promise<void> {
+ await this.db
+ .update(taskExternalLinks)
+ .set({ ...data, lastSyncedAt: new Date(), updatedAt: new Date() })
+ .where(and(this.scope(), eq(taskExternalLinks.id, id)));
+ }
+
+ private selectWithTask() {
+ return this.db
+ .select({
+ accessedAt: taskExternalLinks.accessedAt,
+ createdAt: taskExternalLinks.createdAt,
+ externalContainerId: taskExternalLinks.externalContainerId,
+ externalId: taskExternalLinks.externalId,
+ externalIdentifier: taskExternalLinks.externalIdentifier,
+ externalUpdatedAt: taskExternalLinks.externalUpdatedAt,
+ externalUrl: taskExternalLinks.externalUrl,
+ id: taskExternalLinks.id,
+ lastSyncedAt: taskExternalLinks.lastSyncedAt,
+ metadata: taskExternalLinks.metadata,
+ provider: taskExternalLinks.provider,
+ syncedHash: taskExternalLinks.syncedHash,
+ taskId: taskExternalLinks.taskId,
+ taskIdentifier: tasks.identifier,
+ updatedAt: taskExternalLinks.updatedAt,
+ userId: taskExternalLinks.userId,
+ workspaceId: taskExternalLinks.workspaceId,
+ })
+ .from(taskExternalLinks)
+ .innerJoin(tasks, eq(tasks.id, taskExternalLinks.taskId))
+ .$dynamic();
+ }
+
+ private scope() {
+ return this.workspaceId
+ ? eq(taskExternalLinks.workspaceId, this.workspaceId)
+ : and(eq(taskExternalLinks.userId, this.userId), isNull(taskExternalLinks.workspaceId));
+ }
+}
diff --git a/packages/locales/src/default/integration.ts b/packages/locales/src/default/integration.ts
index 32636745ae3..edb58043cd1 100644
--- a/packages/locales/src/default/integration.ts
+++ b/packages/locales/src/default/integration.ts
@@ -86,6 +86,96 @@ export default {
'linear.installResult.error.workspace_forbidden':
'Only workspace members can connect Linear here.',
'linear.installResult.success': 'Linear connected: {{account}}',
+ 'linear.sync.error.generic': 'Linear sync failed. Please try again.',
+ 'linear.sync.error.reconnect':
+ 'The Linear connection has expired. Reconnect the workspace, then try again.',
+ 'linear.sync.filter.allProjects': 'All projects',
+ 'linear.sync.filter.project': 'Linear project',
+ 'linear.sync.filter.projectHint': 'Keep All projects to include every issue in the team.',
+ 'linear.sync.filter.states': 'Issue states to sync',
+ 'linear.sync.filter.statesHint': 'Completed and canceled issues are left out by default.',
+ 'linear.sync.filter.statesSummary': '{{count}} states',
+ 'linear.sync.filter.team': 'Linear team',
+ 'linear.sync.filter.teamPlaceholder': 'Choose a team',
+ 'linear.sync.importIssues': 'Import issues',
+ 'linear.sync.job.background':
+ 'You can close this window; the sync keeps running and you will be notified when it ends. The outcome is also listed under Sync runs in Advanced settings.',
+ 'linear.sync.job.close': 'Done',
+ 'linear.sync.job.continuesInBackground':
+ 'The sync continues in the background. You will be notified when it ends.',
+ 'linear.sync.job.done': 'Sync finished',
+ 'linear.sync.job.error.timeout':
+ 'The sync stopped making progress and was cut off. Start it again.',
+ 'linear.sync.job.error.unavailable':
+ 'The project, rule or Linear connection is no longer available.',
+ 'linear.sync.job.failed': 'Sync failed',
+ 'linear.sync.job.finished': 'Linear sync finished: {{result}}',
+ 'linear.sync.job.inProgress': 'Syncing…',
+ 'linear.sync.job.keptLocalEdits': '{{count}} tasks were edited in LobeHub; your edits were kept.',
+ 'linear.sync.job.leave': 'Continue in background',
+ 'linear.sync.job.listTitle': 'Sync runs',
+ 'linear.sync.job.runningIssues': 'Syncing {{count}} issues…',
+ 'linear.sync.job.runningRule': 'Syncing everything the rule matches…',
+ 'linear.sync.job.skipReason.closed': 'Closed in Linear and never imported',
+ 'linear.sync.job.skipReason.failed': 'Could not be written; the next sync retries it',
+ 'linear.sync.job.skipReason.missing': 'No longer in Linear, or not visible to this connection',
+ 'linear.sync.job.skipReason.running': 'Task is running, so it was not closed',
+ 'linear.sync.job.skipReason.unavailable': 'Task is in the trash or not visible to you',
+ 'linear.sync.job.skippedTitle': '{{count}} skipped',
+ 'linear.sync.job.titleIssues': 'Import {{count}} issues',
+ 'linear.sync.job.titleRule': 'Rule: {{rule}}',
+ 'linear.sync.job.titleRuleDeleted': 'Rule (deleted)',
+ 'linear.sync.list.count': '{{count}} issues',
+ 'linear.sync.list.empty': 'No issues match these filters.',
+ 'linear.sync.list.linked': 'Synced · {{task}}',
+ 'linear.sync.list.loadMore': 'Load more',
+ 'linear.sync.list.openInLinear': 'Open in Linear',
+ 'linear.sync.list.pickTeam': 'Choose a team to see its issues.',
+ 'linear.sync.list.selectAll': 'Select all {{count}} loaded',
+ 'linear.sync.list.selected': '{{count}} selected',
+ 'linear.sync.modal.importNone': 'Import issues',
+ 'linear.sync.modal.importSelected': 'Import {{count}} issues',
+ 'linear.sync.modal.oneWayHint': 'One-way sync. Nothing in Linear is changed.',
+ 'linear.sync.modal.saveRule': 'Save as rule and sync all',
+ 'linear.sync.modal.saveRuleHint':
+ 'Sync every issue matching these filters now, and keep the filters to sync again later',
+ 'linear.sync.modal.title': 'Import issues from {{account}}',
+ 'linear.sync.project.connect': 'Connect Linear',
+ 'linear.sync.project.description':
+ 'Turn Linear issues into tasks of this project, one by one or through a saved team or project rule. Syncing is one way: nothing in Linear is changed.',
+ 'linear.sync.project.entry': 'Sync from Linear',
+ 'linear.sync.project.noConnection': 'No Linear workspace is connected yet.',
+ 'linear.sync.project.title': 'Sync from Linear',
+ 'linear.sync.projectHint':
+ 'To sync issues into a project, open the project and go to Settings → Advanced.',
+ 'linear.sync.result.closed': '{{count}} closed',
+ 'linear.sync.result.created': '{{count}} created',
+ 'linear.sync.result.keptLocalEdits': '{{count}} kept local edits',
+ 'linear.sync.result.skipped': '{{count}} skipped',
+ 'linear.sync.result.truncated': 'more issues remain, sync again to continue',
+ 'linear.sync.result.upToDate': 'Already up to date',
+ 'linear.sync.result.updated': '{{count}} updated',
+ 'linear.sync.rules.delete': 'Delete rule',
+ 'linear.sync.rules.deleteContent':
+ 'Tasks already synced stay as they are. Only the saved filter is removed.',
+ 'linear.sync.rules.deleteTitle': 'Delete this sync rule?',
+ 'linear.sync.rules.disconnected':
+ 'Its Linear workspace is disconnected. Reconnect it to sync, or delete the rule.',
+ 'linear.sync.rules.lastRun': 'Last synced {{time}} · {{result}}',
+ 'linear.sync.rules.loadFailed': 'Could not load sync rules',
+ 'linear.sync.rules.neverRun': 'Not synced yet',
+ 'linear.sync.rules.run': 'Sync now',
+ 'linear.sync.rules.running': 'Syncing',
+ 'linear.sync.rules.title': 'Sync rules',
+ 'linear.sync.state.backlog': 'Backlog',
+ 'linear.sync.state.canceled': 'Canceled',
+ 'linear.sync.state.completed': 'Completed',
+ 'linear.sync.state.started': 'In progress',
+ 'linear.sync.state.triage': 'Triage',
+ 'linear.sync.state.unstarted': 'Todo',
+ 'linear.sync.viewerDisabled': 'Viewers cannot import issues into tasks',
+ 'linear.sync.wizard.back': 'Back',
+ 'linear.sync.wizard.next': 'Next',
'linear.tagline': 'Connect your Linear workspace to LobeHub',
'overview.all': 'All integrations',
'overview.comingSoon': 'Coming soon',
diff --git a/packages/types/src/asyncTask.ts b/packages/types/src/asyncTask.ts
index 7122b11fb88..b8806d44244 100644
--- a/packages/types/src/asyncTask.ts
+++ b/packages/types/src/asyncTask.ts
@@ -4,6 +4,8 @@ export enum AsyncTaskType {
Chunking = 'chunk',
Embedding = 'embedding',
ImageGeneration = 'image_generation',
+ /** One-way Linear issue → task sync run in the background (`linear_issue_sync`). */
+ LinearIssueSync = 'linear_issue_sync',
UserMemoryExtractionHourly = 'user_memory_extraction:hourly',
UserMemoryExtractionWithChatTopic = 'user_memory_extraction:chat_topic',
VideoGeneration = 'video_generation',
diff --git a/packages/types/src/linear.ts b/packages/types/src/linear.ts
index 045d542b1d4..32fcbd0b7f2 100644
--- a/packages/types/src/linear.ts
+++ b/packages/types/src/linear.ts
@@ -108,7 +108,9 @@ export type LinearSyncSkipReason =
/** Closed in Linear and never imported, so there is nothing to close. */
| 'closed'
/** Writing the task failed; the next sync retries it. */
- | 'failed';
+ | 'failed'
+ /** Picked for import, but Linear no longer returns it (deleted, or not visible). */
+ | 'missing';
export interface LinearSyncResult {
/** Tasks closed because their issue was completed or canceled in Linear. */
@@ -116,7 +118,10 @@ export interface LinearSyncResult {
created: number;
/** Tasks edited in LobeHub, so their name, instruction and priority were kept. */
keptLocalEdits: number;
+ /** The first skipped issues with why; `skippedCount` holds the full count. */
skipped: { identifier: string; reason: LinearSyncSkipReason }[];
+ /** Every skipped issue, including those past the `skipped` list. Absent in older results. */
+ skippedCount?: number;
/** More issues matched than one run imports; run again for the rest. */
truncated: boolean;
unchanged: number;
@@ -137,3 +142,39 @@ export interface LinearSyncRuleView {
teamId: string;
teamName: string;
}
+
+/** Why a background sync stopped without a result. */
+export type LinearSyncJobErrorCode =
+ /** The Linear token was revoked or expired; reconnect the workspace. */
+ | 'reconnect'
+ /** The project, rule or connection is gone or no longer visible. */
+ | 'unavailable'
+ /** No progress for too long; the run was likely cut off. */
+ | 'timeout'
+ | 'failed';
+
+/** What a background sync was asked to do, kept on its `async_tasks` row. */
+export interface LinearSyncJobMetadata {
+ connectionId: string;
+ /** Picked issues (`kind: 'issues'`). */
+ issueIds?: string[];
+ kind: 'issues' | 'rule';
+ projectId: string;
+ result?: LinearSyncResult;
+ /** The saved rule being run (`kind: 'rule'`). */
+ ruleId?: string;
+}
+
+export interface LinearSyncJobView {
+ createdAt: Date;
+ error: LinearSyncJobErrorCode | null;
+ id: string;
+ /** Number of picked issues; absent for a rule run. */
+ issueCount?: number;
+ kind: 'issues' | 'rule';
+ projectId: string;
+ result: LinearSyncResult | null;
+ ruleId: string | null;
+ status: 'pending' | 'processing' | 'success' | 'error';
+ updatedAt: Date;
+}
diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
index 7310421ff80..e50431c3bf3 100644
--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx
@@ -9,7 +9,7 @@ import {
TabsTab,
} from '@lobehub/ui';
import { Plus } from 'lucide-react';
-import { memo, useCallback, useEffect, useMemo, useState } from 'react';
+import { memo, type ReactNode, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router';
@@ -118,6 +118,8 @@ interface AgentTasksPageProps {
* shows tasks across all agents.
*/
agentId?: string;
+ /** Extra header actions of the task list, e.g. a project's Linear sync. */
+ headerActions?: ReactNode;
/** When provided, shows the complete task workspace scoped to one project. */
projectId?: string;
}
@@ -203,7 +205,7 @@ export const resolveTaskCollectionView = (
viewMode: TaskViewMode,
): 'board' | 'list' => (collection !== 'scheduled' && viewMode === 'kanban' ? 'board' : 'list');
-const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
+const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, projectId }) => {
const { t } = useTranslation('chat');
const navigate = useWorkspaceAwareNavigate();
const isMobile = useIsMobile();
@@ -456,6 +458,7 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, projectId }) => {
right={
<Flexbox horizontal align={'center'} gap={4}>
{isOrdinaryCollection && !agentId && !projectId && <TaskListVisibilityFilter />}
+ {isOrdinaryCollection && headerActions}
{isOrdinaryCollection && (inlineCollapsed || viewMode === 'kanban') && (
<ActionIcon
disabled={createActionBehavior.disabled}
diff --git a/src/features/Integrations/Linear/Connections.tsx b/src/features/Integrations/Linear/Connections.tsx
index 79f37a3456f..9726b441f7d 100644
--- a/src/features/Integrations/Linear/Connections.tsx
+++ b/src/features/Integrations/Linear/Connections.tsx
@@ -121,6 +121,12 @@ const Connections = memo<ConnectionsProps>(
</Text>
)}
+ {connections.length > 0 && (
+ <Text style={{ fontSize: 13 }} type="secondary">
+ {t('linear.sync.projectHint')}
+ </Text>
+ )}
+
{connections.length === 0 ? (
<div className={styles.emptyState}>{t('linear.connections.empty')}</div>
) : (
diff --git a/src/features/Integrations/Linear/swrKeys.ts b/src/features/Integrations/Linear/swrKeys.ts
index 7c95cbd2eaa..42ae7756661 100644
--- a/src/features/Integrations/Linear/swrKeys.ts
+++ b/src/features/Integrations/Linear/swrKeys.ts
@@ -1,3 +1,5 @@
+import type { LinearIssueStateType } from '@lobechat/types';
+
/**
* SWR keys of the Linear integration. Kept beside the feature because the
* central registry (`@/libs/swr/keys`) is over the file-size limit; they
@@ -7,4 +9,22 @@ export const linearKeys = {
config: () => ['linear:config'] as const,
connections: (workspaceId: string | null | undefined) =>
['linear:connections', workspaceId ?? null] as const,
+ issues: (params: {
+ connectionId: string;
+ linearProjectId?: string | null;
+ stateTypes: LinearIssueStateType[];
+ teamId: string;
+ }) =>
+ [
+ 'linear:issues',
+ params.connectionId,
+ params.teamId,
+ params.linearProjectId ?? null,
+ [...params.stateTypes].sort().join(','),
+ ] as const,
+ projects: (connectionId: string, teamId: string) =>
+ ['linear:projects', connectionId, teamId] as const,
+ syncRules: (projectId: string) => ['linear:syncRules', projectId] as const,
+ syncJobs: (projectId: string) => ['linear:syncJobs', projectId] as const,
+ teams: (connectionId: string) => ['linear:teams', connectionId] as const,
};
diff --git a/src/features/Projects/LinearSync/ImportIssuesContent.tsx b/src/features/Projects/LinearSync/ImportIssuesContent.tsx
new file mode 100644
index 00000000000..ccafe2efde7
--- /dev/null
+++ b/src/features/Projects/LinearSync/ImportIssuesContent.tsx
@@ -0,0 +1,257 @@
+'use client';
+
+import { Button, Flexbox, Icon, Text, toast, useModalContext } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import { ChevronLeftIcon, InfoIcon } from 'lucide-react';
+import { memo, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import useSWR from 'swr';
+
+import { linearKeys } from '@/features/Integrations/Linear/swrKeys';
+import { linearService } from '@/services/linear';
+
+import IssueList from './IssueList';
+import RunStep from './RunStep';
+import ScopeStep from './ScopeStep';
+import {
+ initialImportFilter,
+ type LinearImportFilter,
+ type LinearIssueImportModalOptions,
+} from './types';
+import { jobsShownInDialog, useLinearSyncJobs } from './useLinearSyncJobs';
+import { isActiveLinearSyncJob, linearSyncErrorMessage } from './utils';
+
+type Step = 'scope' | 'issues' | 'run';
+
+/**
+ * Import Linear issues into the project in three steps: pick the scope (team,
+ * Linear project, states), pick issues — or save the scope as a rule and sync
+ * all of it — then watch the sync. The sync runs in the background, so the
+ * dialog can be closed while it works. Linear is only read.
+ */
+const ImportIssuesContent = memo<LinearIssueImportModalOptions>(
+ ({ connection, onSynced, projectId }) => {
+ const { t } = useTranslation('integration');
+ const { close } = useModalContext();
+ const [step, setStep] = useState<Step>('scope');
+ const [filter, setFilter] = useState<LinearImportFilter>(initialImportFilter);
+ const [selected, setSelected] = useState<Set<string>>(() => new Set());
+ const [starting, setStarting] = useState<'import' | 'rule' | null>(null);
+ const [jobId, setJobId] = useState<string>();
+ // Shown as the running title until the job loads, so a single import never reads as a rule sync.
+ const [startedIssueCount, setStartedIssueCount] = useState<number>();
+ // A rule saved by a start that then failed; retrying runs it instead of saving another.
+ const [savedRuleId, setSavedRuleId] = useState<string>();
+ // Without the project list, "All projects" may be a mistake; wait for it.
+ const { error: projectsError, isLoading: projectsLoading } = useSWR(
+ filter.teamId ? linearKeys.projects(connection.id, filter.teamId) : null,
+ );
+ const jobs = useLinearSyncJobs(projectId);
+ const job = jobId ? jobs.data?.find((item) => item.id === jobId) : undefined;
+ const running = !!jobId && (!job || isActiveLinearSyncJob(job));
+
+ // While this dialog shows the job, the background notifier stays quiet.
+ useEffect(() => {
+ if (!jobId) return;
+ jobsShownInDialog.add(jobId);
+ return () => {
+ jobsShownInDialog.delete(jobId);
+ };
+ }, [jobId]);
+
+ const updateFilter = (patch: Partial<LinearImportFilter>) => {
+ setFilter((current) => ({ ...current, ...patch }));
+ setSavedRuleId(undefined);
+ // The list changes with the scope; a hidden selection would import blind.
+ setSelected(new Set());
+ };
+
+ const changeSelection = (ids: string[], checked: boolean) =>
+ setSelected((current) => {
+ const next = new Set(current);
+ for (const id of ids) {
+ if (checked) next.add(id);
+ else next.delete(id);
+ }
+ return next;
+ });
+
+ const start = async (kind: 'import' | 'rule', action: () => Promise<{ id: string }>) => {
+ setStarting(kind);
+ try {
+ const { id } = await action();
+ setStartedIssueCount(kind === 'import' ? selected.size : undefined);
+ setJobId(id);
+ setStep('run');
+ await jobs.mutate();
+ onSynced?.();
+ } catch (error) {
+ toast.error(linearSyncErrorMessage(error, t));
+ } finally {
+ setStarting(null);
+ }
+ };
+
+ const importSelected = () =>
+ start('import', () =>
+ linearService.startImport({
+ connectionId: connection.id,
+ issueIds: [...selected],
+ projectId,
+ }),
+ );
+
+ const syncAll = () =>
+ start('rule', async () => {
+ let ruleId = savedRuleId;
+ if (!ruleId) {
+ const rule = await linearService.createSyncRule({
+ connectionId: connection.id,
+ linearProjectId: filter.linearProjectId,
+ linearProjectName: filter.linearProjectName,
+ projectId,
+ stateTypes: filter.stateTypes,
+ teamId: filter.teamId!,
+ teamName: filter.teamName!,
+ });
+ ruleId = rule.id;
+ setSavedRuleId(rule.id);
+ }
+ return linearService.startRuleSync(ruleId);
+ });
+
+ const leaveRunning = () => {
+ toast.info(t('linear.sync.job.continuesInBackground'));
+ close();
+ };
+
+ const scopeLabel = [
+ filter.teamName,
+ filter.linearProjectName ?? t('linear.sync.filter.allProjects'),
+ t('linear.sync.filter.statesSummary', { count: filter.stateTypes.length }),
+ ].join(' · ');
+
+ const footer = (() => {
+ if (step === 'scope') {
+ return (
+ <Button
+ disabled={!filter.teamId || projectsLoading || !!projectsError}
+ type={'primary'}
+ onClick={() => setStep('issues')}
+ >
+ {t('linear.sync.wizard.next')}
+ </Button>
+ );
+ }
+ if (step === 'issues') {
+ return (
+ <>
+ <Button
+ disabled={starting !== null}
+ icon={<Icon icon={ChevronLeftIcon} />}
+ style={{ marginInlineEnd: 'auto' }}
+ type={'text'}
+ onClick={() => setStep('scope')}
+ >
+ {t('linear.sync.wizard.back')}
+ </Button>
+ <Button
+ disabled={starting === 'import'}
+ loading={starting === 'rule'}
+ title={t('linear.sync.modal.saveRuleHint')}
+ onClick={syncAll}
+ >
+ {t('linear.sync.modal.saveRule')}
+ </Button>
+ <Button
+ disabled={selected.size === 0 || starting === 'rule'}
+ loading={starting === 'import'}
+ type={'primary'}
+ onClick={importSelected}
+ >
+ {selected.size > 0
+ ? t('linear.sync.modal.importSelected', { count: selected.size })
+ : t('linear.sync.modal.importNone')}
+ </Button>
+ </>
+ );
+ }
+ return null;
+ })();
+
+ // The run step's buttons sit under its result, the main one as primary.
+ const runActions = (() => {
+ if (running) {
+ return (
+ <Button type={'primary'} onClick={leaveRunning}>
+ {t('linear.sync.job.leave')}
+ </Button>
+ );
+ }
+ if (job?.status === 'error') {
+ return (
+ <>
+ <Button onClick={close}>{t('linear.sync.job.close')}</Button>
+ <Button type={'primary'} onClick={() => setStep('issues')}>
+ {t('linear.sync.wizard.back')}
+ </Button>
+ </>
+ );
+ }
+ return (
+ <Button type={'primary'} onClick={close}>
+ {t('linear.sync.job.close')}
+ </Button>
+ );
+ })();
+
+ return (
+ <Flexbox gap={20}>
+ {step === 'scope' ? (
+ <ScopeStep connectionId={connection.id} value={filter} onChange={updateFilter} />
+ ) : null}
+
+ {step === 'issues' ? (
+ <Flexbox gap={12}>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {scopeLabel}
+ </Text>
+ <IssueList
+ disabled={starting !== null}
+ selected={selected}
+ filter={{
+ connectionId: connection.id,
+ linearProjectId: filter.linearProjectId,
+ stateTypes: filter.stateTypes,
+ teamId: filter.teamId!,
+ }}
+ onSelectionChange={changeSelection}
+ />
+ </Flexbox>
+ ) : null}
+
+ {step === 'run' ? (
+ <RunStep actions={runActions} job={job} pendingIssueCount={startedIssueCount} />
+ ) : null}
+
+ {step === 'run' ? null : (
+ <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>
+ {step === 'scope' ? (
+ <Flexbox horizontal align={'center'} flex={1} gap={6} style={{ minWidth: 0 }}>
+ <Icon color={cssVar.colorTextTertiary} icon={InfoIcon} size={14} />
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {t('linear.sync.modal.oneWayHint')}
+ </Text>
+ </Flexbox>
+ ) : null}
+ {footer}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+ImportIssuesContent.displayName = 'LinearImportIssuesContent';
+
+export default ImportIssuesContent;
diff --git a/src/features/Projects/LinearSync/ImportTrigger.tsx b/src/features/Projects/LinearSync/ImportTrigger.tsx
new file mode 100644
index 00000000000..97eba4b732b
--- /dev/null
+++ b/src/features/Projects/LinearSync/ImportTrigger.tsx
@@ -0,0 +1,70 @@
+'use client';
+
+import type { LinearConnectionView } from '@lobechat/types';
+import { ActionIcon, Button, DropdownMenu, Icon } from '@lobehub/ui';
+import { DownloadIcon } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+import LinearIcon from '@/features/Integrations/Linear/LinearIcon';
+
+import { openLinearIssueImportModal } from './openImportModal';
+
+interface ImportTriggerProps {
+ connections: LinearConnectionView[];
+ disabled?: boolean;
+ onSynced?: () => void;
+ projectId: string;
+ /** A labelled button in settings, or a bare Linear icon in a page header. */
+ variant: 'button' | 'icon';
+}
+
+/**
+ * Opens the import dialog for this project. With several connected Linear
+ * workspaces it first asks which one.
+ */
+const ImportTrigger = memo<ImportTriggerProps>(
+ ({ connections, disabled, onSynced, projectId, variant }) => {
+ const { t } = useTranslation('integration');
+ const open = (connection: LinearConnectionView) =>
+ openLinearIssueImportModal({ connection, onSynced, projectId });
+
+ const single = connections.length === 1 ? connections[0] : undefined;
+ const onClick = single ? () => open(single) : undefined;
+ const trigger: ReactNode =
+ variant === 'icon' ? (
+ <ActionIcon
+ aria-label={t('linear.sync.project.entry')}
+ disabled={disabled}
+ icon={LinearIcon}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ title={t('linear.sync.project.entry')}
+ onClick={onClick}
+ />
+ ) : (
+ <Button disabled={disabled} icon={<Icon icon={DownloadIcon} />} onClick={onClick}>
+ {t('linear.sync.importIssues')}
+ </Button>
+ );
+
+ if (single || disabled) return trigger;
+
+ return (
+ <DropdownMenu
+ placement={'bottomRight'}
+ items={connections.map((connection) => ({
+ key: connection.id,
+ label: connection.organizationName,
+ onClick: () => open(connection),
+ }))}
+ >
+ {trigger}
+ </DropdownMenu>
+ );
+ },
+);
+
+ImportTrigger.displayName = 'LinearImportTrigger';
+
+export default ImportTrigger;
diff --git a/src/features/Projects/LinearSync/IssueList.tsx b/src/features/Projects/LinearSync/IssueList.tsx
new file mode 100644
index 00000000000..29a7a1c152b
--- /dev/null
+++ b/src/features/Projects/LinearSync/IssueList.tsx
@@ -0,0 +1,218 @@
+'use client';
+
+import type { LinearIssuePage, LinearIssueSummary } from '@lobechat/types';
+import { ActionIcon, Button, Center, Checkbox, Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CheckIcon, ExternalLinkIcon } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+import useSWRInfinite from 'swr/infinite';
+
+import LinearIcon from '@/features/Integrations/Linear/LinearIcon';
+import { linearKeys } from '@/features/Integrations/Linear/swrKeys';
+import { type LinearIssueFilterParams, linearService } from '@/services/linear';
+
+import StateIcon from './StateIcon';
+import { linearSyncErrorMessage } from './utils';
+
+const styles = stylex.create({
+ body: {
+ height: 320,
+ overflowY: 'auto',
+ },
+ // Without the 40px header the frame keeps the same height, so picking a team does not move the footer.
+ bodyWithoutHead: {
+ height: 360,
+ },
+ frame: {
+ borderColor: cssVar.colorBorder,
+ borderRadius: cssVar.borderRadiusLG,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ overflow: 'hidden',
+ },
+ head: {
+ backgroundColor: cssVar.colorFillQuaternary,
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ height: 40,
+ paddingInline: 12,
+ },
+ identifier: {
+ color: cssVar.colorTextTertiary,
+ flexShrink: 0,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ width: 64,
+ },
+ row: {
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
+ cursor: 'pointer',
+ height: 40,
+ paddingInline: 12,
+ },
+ rowDisabled: {
+ cursor: 'default',
+ },
+ synced: {
+ color: cssVar.colorTextSecondary,
+ flexShrink: 0,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ },
+});
+
+interface IssueListProps {
+ disabled?: boolean;
+ /** Null until a team is chosen. */
+ filter: LinearIssueFilterParams | null;
+ onSelectionChange: (ids: string[], selected: boolean) => void;
+ selected: Set<string>;
+}
+
+/** The issues matching the filter, pick-able one by one, newest activity first. */
+const IssueList = memo<IssueListProps>(({ disabled, filter, onSelectionChange, selected }) => {
+ const { t } = useTranslation('integration');
+
+ const { data, error, isLoading, isValidating, setSize, size } = useSWRInfinite(
+ (index: number, previous: LinearIssuePage | null) => {
+ if (!filter || (previous && !previous.hasMore)) return null;
+ return [...linearKeys.issues(filter), index === 0 ? null : previous?.cursor] as const;
+ },
+ ([, , , , , cursor]) => linearService.listIssues({ ...filter!, cursor: cursor ?? undefined }),
+ // The first page is refetched even when cached: an import since it was read
+ // changes which issues show as synced.
+ { revalidateOnFocus: false },
+ );
+
+ const issues: LinearIssueSummary[] = (data ?? []).flatMap((page) => page.issues ?? []);
+ const ids = issues.map((issue) => issue.id);
+ const selectedCount = ids.filter((id) => selected.has(id)).length;
+ const allSelected = ids.length > 0 && selectedCount === ids.length;
+ const hasMore = data?.at(-1)?.hasMore;
+
+ const placeholder = (content: ReactNode) => (
+ <Center gap={8} height={'100%'} paddingInline={24}>
+ {content}
+ </Center>
+ );
+
+ let body: ReactNode;
+ if (!filter) {
+ body = placeholder(
+ <>
+ <LinearIcon size={24} style={{ opacity: 0.25 }} />
+ <Text type={'secondary'}>{t('linear.sync.list.pickTeam')}</Text>
+ </>,
+ );
+ } else if (error) {
+ body = placeholder(<Text type={'danger'}>{linearSyncErrorMessage(error, t)}</Text>);
+ } else if (isLoading || !data) {
+ body = (
+ <Flexbox gap={12} padding={12}>
+ {[0, 1, 2, 3].map((index) => (
+ <Skeleton height={16} key={index} />
+ ))}
+ </Flexbox>
+ );
+ } else if (issues.length === 0) {
+ body = placeholder(<Text type={'secondary'}>{t('linear.sync.list.empty')}</Text>);
+ } else {
+ body = (
+ <>
+ {issues.map((issue) => {
+ const checked = selected.has(issue.id);
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={12}
+ key={issue.id}
+ {...stylex.props(styles.row, disabled && styles.rowDisabled)}
+ onClick={(event) => {
+ // The checkbox and the Linear link handle their own clicks.
+ const target = event.target as HTMLElement;
+ if (disabled || target.closest('button, a, [role="button"], [role="checkbox"]'))
+ return;
+ onSelectionChange([issue.id], !checked);
+ }}
+ >
+ <Checkbox
+ aria-label={issue.identifier}
+ checked={checked}
+ disabled={disabled}
+ onChange={(next) => onSelectionChange([issue.id], next)}
+ />
+ <StateIcon name={issue.stateName} type={issue.stateType} />
+ <span {...stylex.props(styles.identifier)}>{issue.identifier}</span>
+ <Text ellipsis style={{ flex: 1, minWidth: 0 }} title={issue.title}>
+ {issue.title}
+ </Text>
+ {issue.linkedTaskIdentifier ? (
+ <Flexbox
+ horizontal
+ align={'center'}
+ aria-label={t('linear.sync.list.linked', { task: issue.linkedTaskIdentifier })}
+ gap={4}
+ role={'img'}
+ title={t('linear.sync.list.linked', { task: issue.linkedTaskIdentifier })}
+ {...stylex.props(styles.synced)}
+ >
+ <Icon color={cssVar.colorSuccess} icon={CheckIcon} size={14} />
+ {issue.linkedTaskIdentifier}
+ </Flexbox>
+ ) : null}
+ <ActionIcon
+ icon={ExternalLinkIcon}
+ size={'small'}
+ title={t('linear.sync.list.openInLinear')}
+ onClick={() => window.open(issue.url, '_blank', 'noopener,noreferrer')}
+ />
+ </Flexbox>
+ );
+ })}
+ {hasMore ? (
+ <Center paddingBlock={8}>
+ <Button
+ disabled={disabled}
+ loading={isValidating && size > data.length}
+ size={'small'}
+ type={'text'}
+ onClick={() => setSize(size + 1)}
+ >
+ {t('linear.sync.list.loadMore')}
+ </Button>
+ </Center>
+ ) : null}
+ </>
+ );
+ }
+
+ return (
+ <div {...stylex.props(styles.frame)}>
+ {filter ? (
+ <Flexbox horizontal align={'center'} gap={12} {...stylex.props(styles.head)}>
+ <Checkbox
+ aria-label={t('linear.sync.list.selectAll', { count: issues.length })}
+ checked={allSelected}
+ disabled={disabled || issues.length === 0}
+ indeterminate={selectedCount > 0 && !allSelected}
+ onChange={(checked) => onSelectionChange(ids, checked)}
+ />
+ <Text fontSize={12} type={'secondary'}>
+ {selectedCount > 0
+ ? t('linear.sync.list.selected', { count: selectedCount })
+ : t('linear.sync.list.count', { count: issues.length })}
+ </Text>
+ </Flexbox>
+ ) : null}
+ <div {...stylex.props(styles.body, !filter && styles.bodyWithoutHead)}>{body}</div>
+ </div>
+ );
+});
+
+IssueList.displayName = 'LinearIssueList';
+
+export default IssueList;
diff --git a/src/features/Projects/LinearSync/LinearSyncEntry.tsx b/src/features/Projects/LinearSync/LinearSyncEntry.tsx
new file mode 100644
index 00000000000..85ab5d80d2b
--- /dev/null
+++ b/src/features/Projects/LinearSync/LinearSyncEntry.tsx
@@ -0,0 +1,50 @@
+'use client';
+
+import { memo } from 'react';
+
+import { useLinearIntegration } from '@/features/Integrations/useLinearIntegration';
+import { useTaskStore } from '@/store/task';
+
+import { useCanManageProject } from '../useCanManageProject';
+import ImportTrigger from './ImportTrigger';
+import { useLinearSyncRules } from './SyncRules';
+import { useLinearSyncJobNotifier, useLinearSyncJobs } from './useLinearSyncJobs';
+
+interface LinearSyncEntryProps {
+ projectId: string;
+}
+
+/**
+ * The project task list's shortcut into a Linear import. Shown only to
+ * members who can manage the project once a Linear workspace is connected,
+ * so projects that do not use Linear see nothing.
+ */
+const LinearSyncEntry = memo<LinearSyncEntryProps>(({ projectId }) => {
+ const { connections, enabled } = useLinearIntegration();
+ const canManage = useCanManageProject();
+ const shown = enabled && canManage;
+ const syncRules = useLinearSyncRules(shown ? projectId : null);
+ const syncJobs = useLinearSyncJobs(shown ? projectId : null);
+ const refreshTaskList = useTaskStore((s) => s.refreshTaskList);
+ // A sync started here may end after its dialog was closed; its tasks then
+ // appear in the list below.
+ useLinearSyncJobNotifier(syncJobs.data, refreshTaskList);
+
+ if (!shown) return null;
+
+ return (
+ <ImportTrigger
+ connections={connections}
+ projectId={projectId}
+ variant={'icon'}
+ onSynced={() => {
+ void syncRules.mutate();
+ void syncJobs.mutate();
+ }}
+ />
+ );
+});
+
+LinearSyncEntry.displayName = 'ProjectLinearSyncEntry';
+
+export default LinearSyncEntry;
diff --git a/src/features/Projects/LinearSync/RunStep.tsx b/src/features/Projects/LinearSync/RunStep.tsx
new file mode 100644
index 00000000000..064e9a53909
--- /dev/null
+++ b/src/features/Projects/LinearSync/RunStep.tsx
@@ -0,0 +1,152 @@
+'use client';
+
+import type { LinearSyncJobView, LinearSyncResult } from '@lobechat/types';
+import { Center, Flexbox, Result, Spin, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ formatLinearSyncResult,
+ isActiveLinearSyncJob,
+ linearSyncJobErrorMessage,
+ linearSyncSkippedCount,
+} from './utils';
+
+const styles = stylex.create({
+ identifier: {
+ color: cssVar.colorTextSecondary,
+ flexShrink: 0,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ width: 72,
+ },
+ skipped: {
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ maxHeight: 180,
+ overflowY: 'auto',
+ },
+ skippedRow: {
+ minHeight: 36,
+ paddingBlock: 8,
+ paddingInline: 12,
+ },
+ skippedRowDivider: {
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartWidth: 1,
+ },
+});
+
+/** Issues the sync left alone, each with why. */
+const SkippedList = ({
+ skipped,
+ total,
+}: {
+ skipped: NonNullable<LinearSyncResult['skipped']>;
+ /** Every skipped issue; the list may stop short of it. */
+ total: number;
+}) => {
+ const { t } = useTranslation('integration');
+ return (
+ <Flexbox gap={8}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('linear.sync.job.skippedTitle', { count: total })}
+ </Text>
+ <div {...stylex.props(styles.skipped)}>
+ {skipped.map((item, index) => (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={12}
+ key={item.identifier}
+ {...stylex.props(styles.skippedRow, index > 0 && styles.skippedRowDivider)}
+ >
+ <span {...stylex.props(styles.identifier)}>{item.identifier}</span>
+ <Text fontSize={13}>{t(`linear.sync.job.skipReason.${item.reason}`)}</Text>
+ </Flexbox>
+ ))}
+ </div>
+ </Flexbox>
+ );
+};
+
+interface RunStepProps {
+ /** The dialog's buttons for this state, centered under the result. */
+ actions?: ReactNode;
+ job: LinearSyncJobView | undefined;
+ /** Issues the dialog asked to import, until the job itself has loaded; absent for a rule sync. */
+ pendingIssueCount?: number;
+}
+
+/**
+ * The sync this dialog started. It keeps running if the dialog is closed; the
+ * outcome is then shown under the project's sync runs.
+ */
+const RunStep = memo<RunStepProps>(({ actions, job, pendingIssueCount }) => {
+ const { t } = useTranslation('integration');
+
+ if (!job || isActiveLinearSyncJob(job)) {
+ const issueCount = job ? (job.kind === 'rule' ? undefined : job.issueCount) : pendingIssueCount;
+ return (
+ <Result
+ extra={actions}
+ subTitle={t('linear.sync.job.background')}
+ icon={
+ // As tall as the status badge that replaces it, so the result does not jump.
+ <Center height={72} width={72}>
+ <Spin size={'large'} />
+ </Center>
+ }
+ title={
+ issueCount
+ ? t('linear.sync.job.runningIssues', { count: issueCount })
+ : t('linear.sync.job.runningRule')
+ }
+ />
+ );
+ }
+
+ if (job.status === 'error') {
+ return (
+ <Result
+ extra={actions}
+ status={'error'}
+ subTitle={linearSyncJobErrorMessage(job.error, t)}
+ title={t('linear.sync.job.failed')}
+ />
+ );
+ }
+
+ const result = job.result;
+ // An older server may omit the list.
+ const skipped = result?.skipped ?? [];
+ const skippedTotal = result ? linearSyncSkippedCount(result) : 0;
+ return (
+ <Result
+ extra={actions}
+ status={'success'}
+ subTitle={result ? formatLinearSyncResult(result, t) : undefined}
+ title={t('linear.sync.job.done')}
+ >
+ {result && result.keptLocalEdits > 0 ? (
+ <Text fontSize={12} type={'secondary'}>
+ {t('linear.sync.job.keptLocalEdits', { count: result.keptLocalEdits })}
+ </Text>
+ ) : null}
+ {skipped.length > 0 ? (
+ <Flexbox style={{ alignSelf: 'stretch', textAlign: 'start' }}>
+ <SkippedList skipped={skipped} total={skippedTotal} />
+ </Flexbox>
+ ) : null}
+ </Result>
+ );
+});
+
+RunStep.displayName = 'LinearImportRunStep';
+
+export default RunStep;
diff --git a/src/features/Projects/LinearSync/ScopeStep.tsx b/src/features/Projects/LinearSync/ScopeStep.tsx
new file mode 100644
index 00000000000..29e751269e4
--- /dev/null
+++ b/src/features/Projects/LinearSync/ScopeStep.tsx
@@ -0,0 +1,137 @@
+'use client';
+
+import type { LinearIssueStateType } from '@lobechat/types';
+import { LINEAR_ISSUE_STATE_TYPES } from '@lobechat/types';
+import { Flexbox, Select, Text } from '@lobehub/ui';
+import { Form, useForm } from '@lobehub/ui/form';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import useSWR from 'swr';
+
+import { linearKeys } from '@/features/Integrations/Linear/swrKeys';
+import { linearService } from '@/services/linear';
+
+import StateIcon from './StateIcon';
+import type { LinearImportFilter } from './types';
+import { linearSyncErrorMessage } from './utils';
+
+const ALL_PROJECTS = '__all__';
+
+interface ScopeStepProps {
+ connectionId: string;
+ onChange: (patch: Partial<LinearImportFilter>) => void;
+ value: LinearImportFilter;
+}
+
+/** Step 1: which Linear issues to look at — a team, optionally one Linear project, and states. */
+const ScopeStep = memo<ScopeStepProps>(({ connectionId, onChange, value }) => {
+ const { t } = useTranslation('integration');
+
+ const teams = useSWR(linearKeys.teams(connectionId), () => linearService.listTeams(connectionId));
+ const projects = useSWR(
+ value.teamId ? linearKeys.projects(connectionId, value.teamId) : null,
+ () => linearService.listProjects(connectionId, value.teamId!),
+ );
+
+ const form = useForm();
+
+ const stateOptions = LINEAR_ISSUE_STATE_TYPES.map((type) => ({
+ label: (
+ <Flexbox horizontal align={'center'} gap={6}>
+ <StateIcon decorative name={t(`linear.sync.state.${type}`)} type={type} />
+ {t(`linear.sync.state.${type}`)}
+ </Flexbox>
+ ),
+ title: t(`linear.sync.state.${type}`),
+ value: type,
+ }));
+
+ // A failed read belongs under the field it fills, not at the foot of the form.
+ const fieldError = (error: unknown) =>
+ error ? (
+ <Text fontSize={12} type={'danger'}>
+ {linearSyncErrorMessage(error, t)}
+ </Text>
+ ) : null;
+
+ return (
+ <Form form={form} gap={0} layout={'vertical'}>
+ <Form.Field label={t('linear.sync.filter.team')}>
+ <Flexbox gap={4}>
+ <Select
+ aria-label={t('linear.sync.filter.team')}
+ loading={teams.isLoading}
+ placeholder={t('linear.sync.filter.teamPlaceholder')}
+ value={value.teamId}
+ variant={'filled'}
+ options={(teams.data ?? []).map((team) => ({
+ label: `${team.name} (${team.key})`,
+ value: team.id,
+ }))}
+ onChange={(teamId) => {
+ const team = teams.data?.find((item) => item.id === teamId);
+ onChange({
+ linearProjectId: null,
+ linearProjectName: null,
+ teamId: team?.id ?? null,
+ teamName: team?.name ?? null,
+ });
+ }}
+ />
+ {fieldError(teams.error)}
+ </Flexbox>
+ </Form.Field>
+ <Form.Field
+ desc={t('linear.sync.filter.projectHint')}
+ label={t('linear.sync.filter.project')}
+ >
+ <Flexbox gap={4}>
+ <Select
+ aria-label={t('linear.sync.filter.project')}
+ disabled={!value.teamId}
+ loading={projects.isLoading}
+ value={value.linearProjectId ?? ALL_PROJECTS}
+ variant={'filled'}
+ options={[
+ { label: t('linear.sync.filter.allProjects'), value: ALL_PROJECTS },
+ ...(projects.data ?? []).map((project) => ({
+ label: project.name,
+ value: project.id,
+ })),
+ ]}
+ onChange={(projectId) => {
+ const project = projects.data?.find((item) => item.id === projectId);
+ onChange({
+ linearProjectId: project?.id ?? null,
+ linearProjectName: project?.name ?? null,
+ });
+ }}
+ />
+ {fieldError(projects.error)}
+ </Flexbox>
+ </Form.Field>
+ <Form.Field
+ desc={t('linear.sync.filter.statesHint')}
+ label={t('linear.sync.filter.states')}
+ style={{ marginBottom: 0 }}
+ >
+ <Select
+ aria-label={t('linear.sync.filter.states')}
+ mode={'multiple'}
+ options={stateOptions}
+ value={value.stateTypes}
+ variant={'filled'}
+ onChange={(types) => {
+ const next = (Array.isArray(types) ? types : []) as LinearIssueStateType[];
+ // At least one state, or nothing could ever match.
+ if (next.length > 0) onChange({ stateTypes: next });
+ }}
+ />
+ </Form.Field>
+ </Form>
+ );
+});
+
+ScopeStep.displayName = 'LinearImportScopeStep';
+
+export default ScopeStep;
diff --git a/src/features/Projects/LinearSync/StateIcon.tsx b/src/features/Projects/LinearSync/StateIcon.tsx
new file mode 100644
index 00000000000..960ae423292
--- /dev/null
+++ b/src/features/Projects/LinearSync/StateIcon.tsx
@@ -0,0 +1,50 @@
+import type { LinearIssueStateType } from '@lobechat/types';
+import { cssVar, Icon } from '@lobehub/ui';
+import type { LucideIcon } from 'lucide-react';
+import {
+ CircleArrowRightIcon,
+ CircleCheckIcon,
+ CircleDashedIcon,
+ CircleDotIcon,
+ CircleIcon,
+ CircleXIcon,
+} from 'lucide-react';
+import { memo } from 'react';
+
+/** Linear's state categories drawn the way Linear draws them: shape first, color second. */
+const STATE_ICONS: Record<LinearIssueStateType, { color: string; icon: LucideIcon }> = {
+ backlog: { color: cssVar.colorTextQuaternary, icon: CircleDashedIcon },
+ canceled: { color: cssVar.colorTextQuaternary, icon: CircleXIcon },
+ completed: { color: cssVar.colorSuccess, icon: CircleCheckIcon },
+ started: { color: cssVar.colorWarning, icon: CircleDotIcon },
+ triage: { color: cssVar.colorInfo, icon: CircleArrowRightIcon },
+ unstarted: { color: cssVar.colorTextTertiary, icon: CircleIcon },
+};
+
+interface StateIconProps {
+ /** Next to a text label already naming the state: hidden from screen readers. */
+ decorative?: boolean;
+ /** The team's own state name, e.g. "In Review"; read out and shown on hover. */
+ name: string;
+ type: LinearIssueStateType;
+}
+
+const StateIcon = memo<StateIconProps>(({ decorative, name, type }) => {
+ const { color, icon } = STATE_ICONS[type] ?? STATE_ICONS.unstarted;
+ if (decorative) {
+ return (
+ <span aria-hidden style={{ display: 'inline-flex' }}>
+ <Icon color={color} icon={icon} size={14} />
+ </span>
+ );
+ }
+ return (
+ <span aria-label={name} role={'img'} style={{ display: 'inline-flex' }} title={name}>
+ <Icon color={color} icon={icon} size={14} />
+ </span>
+ );
+});
+
+StateIcon.displayName = 'LinearStateIcon';
+
+export default StateIcon;
diff --git a/src/features/Projects/LinearSync/SyncJobs.tsx b/src/features/Projects/LinearSync/SyncJobs.tsx
new file mode 100644
index 00000000000..12a87aace0c
--- /dev/null
+++ b/src/features/Projects/LinearSync/SyncJobs.tsx
@@ -0,0 +1,103 @@
+'use client';
+
+import type { LinearSyncJobView, LinearSyncRuleView } from '@lobechat/types';
+import { Flexbox, Icon, Spin, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CircleAlertIcon, CircleCheckIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatLinearSyncResult, isActiveLinearSyncJob, linearSyncJobErrorMessage } from './utils';
+
+const styles = stylex.create({
+ list: {
+ borderColor: cssVar.colorBorder,
+ borderRadius: cssVar.borderRadiusLG,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ overflow: 'hidden',
+ },
+ row: {
+ minHeight: 44,
+ paddingBlock: 10,
+ paddingInline: 16,
+ },
+ rowDivider: {
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartWidth: 1,
+ },
+ status: {
+ flexShrink: 0,
+ width: 16,
+ },
+});
+
+interface SyncJobsProps {
+ jobs: LinearSyncJobView[];
+ rules: LinearSyncRuleView[];
+}
+
+/** The project's recent background syncs: running ones first in time, then their outcomes. */
+const SyncJobs = memo<SyncJobsProps>(({ jobs, rules }) => {
+ const { t } = useTranslation('integration');
+ if (jobs.length === 0) return null;
+
+ const titleOf = (job: LinearSyncJobView) => {
+ if (job.kind === 'issues')
+ return t('linear.sync.job.titleIssues', { count: job.issueCount ?? 0 });
+ const rule = rules.find((item) => item.id === job.ruleId);
+ return rule
+ ? t('linear.sync.job.titleRule', {
+ rule: [rule.teamName, rule.linearProjectName].filter(Boolean).join(' › '),
+ })
+ : t('linear.sync.job.titleRuleDeleted');
+ };
+
+ const detailOf = (job: LinearSyncJobView) => {
+ if (isActiveLinearSyncJob(job)) return t('linear.sync.job.inProgress');
+ if (job.status === 'error') return linearSyncJobErrorMessage(job.error, t);
+ return job.result ? formatLinearSyncResult(job.result, t) : '';
+ };
+
+ return (
+ <Flexbox gap={8}>
+ <Text type={'secondary'}>{t('linear.sync.job.listTitle')}</Text>
+ <div {...stylex.props(styles.list)}>
+ {jobs.map((job, index) => (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={12}
+ key={job.id}
+ {...stylex.props(styles.row, index > 0 && styles.rowDivider)}
+ >
+ <Flexbox align={'center'} {...stylex.props(styles.status)}>
+ {isActiveLinearSyncJob(job) ? (
+ <Spin size={'small'} />
+ ) : job.status === 'error' ? (
+ <Icon color={cssVar.colorError} icon={CircleAlertIcon} size={16} />
+ ) : (
+ <Icon color={cssVar.colorSuccess} icon={CircleCheckIcon} size={16} />
+ )}
+ </Flexbox>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Text ellipsis>{titleOf(job)}</Text>
+ <Text ellipsis fontSize={12} type={job.status === 'error' ? 'danger' : 'secondary'}>
+ {detailOf(job)}
+ </Text>
+ </Flexbox>
+ <Text fontSize={12} style={{ flexShrink: 0 }} type={'secondary'}>
+ {new Date(job.createdAt).toLocaleString()}
+ </Text>
+ </Flexbox>
+ ))}
+ </div>
+ </Flexbox>
+ );
+});
+
+SyncJobs.displayName = 'LinearSyncJobs';
+
+export default SyncJobs;
diff --git a/src/features/Projects/LinearSync/SyncRules.tsx b/src/features/Projects/LinearSync/SyncRules.tsx
new file mode 100644
index 00000000000..7831f708eb1
--- /dev/null
+++ b/src/features/Projects/LinearSync/SyncRules.tsx
@@ -0,0 +1,178 @@
+'use client';
+
+import type { LinearConnectionView, LinearSyncJobView, LinearSyncRuleView } from '@lobechat/types';
+import { ActionIcon, Button, confirmModal, Flexbox, Icon, Text, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { RefreshCwIcon, Trash2Icon } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import useSWR from 'swr';
+
+import { useIsWorkspaceViewer } from '@/business/client/hooks/useIsWorkspaceViewer';
+import AsyncError from '@/components/AsyncError';
+import { linearKeys } from '@/features/Integrations/Linear/swrKeys';
+import { linearService } from '@/services/linear';
+
+import { formatLinearSyncResult, isActiveLinearSyncJob, linearSyncErrorMessage } from './utils';
+
+const styles = stylex.create({
+ list: {
+ borderColor: cssVar.colorBorder,
+ borderRadius: cssVar.borderRadiusLG,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ overflow: 'hidden',
+ },
+ row: {
+ paddingBlock: 12,
+ paddingInline: 16,
+ },
+ rowDivider: {
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartWidth: 1,
+ },
+});
+
+export const useLinearSyncRules = (projectId: string | null) =>
+ useSWR(projectId ? linearKeys.syncRules(projectId) : null, () =>
+ linearService.listSyncRules(projectId!),
+ );
+
+interface SyncRulesProps {
+ connections: LinearConnectionView[];
+ /** The project's background syncs, to show which rule is running. */
+ jobs: LinearSyncJobView[];
+ onJobStarted: () => void;
+ projectId: string;
+}
+
+/**
+ * The project's saved sync rules: re-run one in the background, or remove
+ * it. Running never writes to Linear.
+ */
+const SyncRules = memo<SyncRulesProps>(({ connections, jobs, onJobStarted, projectId }) => {
+ const { t } = useTranslation('integration');
+ const { data, error, isValidating, mutate } = useLinearSyncRules(projectId);
+ const rules = data ?? [];
+ // Viewers can see the rules but not run or remove them.
+ const isViewer = useIsWorkspaceViewer();
+ const viewerHint = isViewer ? t('linear.sync.viewerDisabled') : undefined;
+ const [starting, setStarting] = useState<string | null>(null);
+ const runningRuleIds = new Set(
+ jobs.filter(isActiveLinearSyncJob).flatMap((job) => (job.ruleId ? [job.ruleId] : [])),
+ );
+
+ if (error && !data) {
+ return (
+ <AsyncError
+ error={error}
+ retrying={isValidating}
+ title={t('linear.sync.rules.loadFailed')}
+ variant={'block'}
+ onRetry={() => void mutate()}
+ />
+ );
+ }
+ if (rules.length === 0) return null;
+
+ const organizationOf = (rule: LinearSyncRuleView) =>
+ connections.find((connection) => connection.id === rule.connectionId)?.organizationName;
+
+ const runRule = async (rule: LinearSyncRuleView) => {
+ setStarting(rule.id);
+ try {
+ await linearService.startRuleSync(rule.id);
+ onJobStarted();
+ } catch (error) {
+ toast.error(linearSyncErrorMessage(error, t));
+ } finally {
+ setStarting(null);
+ }
+ };
+
+ const deleteRule = (rule: LinearSyncRuleView) =>
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('linear.sync.rules.deleteContent'),
+ okButtonProps: { danger: true },
+ okText: t('linear.sync.rules.delete'),
+ onOk: async () => {
+ try {
+ await linearService.deleteSyncRule(rule.id);
+ void mutate();
+ } catch {
+ toast.error(t('linear.sync.error.generic'));
+ }
+ },
+ title: t('linear.sync.rules.deleteTitle'),
+ });
+
+ return (
+ <Flexbox gap={8}>
+ <Text type={'secondary'}>{t('linear.sync.rules.title')}</Text>
+ <div {...stylex.props(styles.list)}>
+ {rules.map((rule, index) => {
+ // A disconnected workspace's rule can still be deleted, not run.
+ const disconnected = !organizationOf(rule);
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={12}
+ key={rule.id}
+ {...stylex.props(styles.row, index > 0 && styles.rowDivider)}
+ >
+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
+ <Text ellipsis weight={500}>
+ {[organizationOf(rule), rule.teamName, rule.linearProjectName]
+ .filter(Boolean)
+ .join(' › ')}
+ </Text>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {[
+ (rule.stateTypes ?? [])
+ .map((type) => t(`linear.sync.state.${type}`))
+ .join('、'),
+ rule.lastRunAt
+ ? t('linear.sync.rules.lastRun', {
+ result: rule.lastResult ? formatLinearSyncResult(rule.lastResult, t) : '',
+ time: new Date(rule.lastRunAt).toLocaleString(),
+ })
+ : t('linear.sync.rules.neverRun'),
+ ].join(' · ')}
+ </Text>
+ </Flexbox>
+ <Button
+ disabled={isViewer || disconnected}
+ icon={<Icon icon={RefreshCwIcon} />}
+ loading={starting === rule.id || runningRuleIds.has(rule.id)}
+ size={'small'}
+ title={
+ viewerHint ?? (disconnected ? t('linear.sync.rules.disconnected') : undefined)
+ }
+ onClick={() => runRule(rule)}
+ >
+ {runningRuleIds.has(rule.id)
+ ? t('linear.sync.rules.running')
+ : t('linear.sync.rules.run')}
+ </Button>
+ <ActionIcon
+ disabled={isViewer || runningRuleIds.has(rule.id)}
+ icon={Trash2Icon}
+ size={'small'}
+ title={viewerHint ?? t('linear.sync.rules.delete')}
+ onClick={() => deleteRule(rule)}
+ />
+ </Flexbox>
+ );
+ })}
+ </div>
+ </Flexbox>
+ );
+});
+
+SyncRules.displayName = 'LinearSyncRules';
+
+export default SyncRules;
diff --git a/src/features/Projects/LinearSync/index.ts b/src/features/Projects/LinearSync/index.ts
new file mode 100644
index 00000000000..01945276b3b
--- /dev/null
+++ b/src/features/Projects/LinearSync/index.ts
@@ -0,0 +1,3 @@
+export { default as LinearSyncEntry } from './LinearSyncEntry';
+export { openLinearIssueImportModal } from './openImportModal';
+export { useProjectLinearSync } from './useProjectLinearSync';
diff --git a/src/features/Projects/LinearSync/openImportModal.tsx b/src/features/Projects/LinearSync/openImportModal.tsx
new file mode 100644
index 00000000000..20f13824231
--- /dev/null
+++ b/src/features/Projects/LinearSync/openImportModal.tsx
@@ -0,0 +1,23 @@
+'use client';
+
+import { createModal } from '@lobehub/ui';
+import { t } from 'i18next';
+
+import ImportIssuesContent from './ImportIssuesContent';
+import type { LinearIssueImportModalOptions } from './types';
+
+export const openLinearIssueImportModal = (options: LinearIssueImportModalOptions) =>
+ createModal({
+ content: <ImportIssuesContent {...options} />,
+ footer: null,
+ maskClosable: false,
+ title: t('linear.sync.modal.title', {
+ account: options.connection.organizationName,
+ ns: 'integration',
+ }),
+ styles: {
+ content: { paddingBlock: '8px 24px', paddingInline: 24 },
+ header: { paddingBlock: '20px 8px', paddingInline: 24 },
+ },
+ width: 'min(92vw, 560px)',
+ });
diff --git a/src/features/Projects/LinearSync/types.ts b/src/features/Projects/LinearSync/types.ts
new file mode 100644
index 00000000000..e6c37f29a4e
--- /dev/null
+++ b/src/features/Projects/LinearSync/types.ts
@@ -0,0 +1,27 @@
+import type { LinearConnectionView, LinearIssueStateType } from '@lobechat/types';
+import { LINEAR_OPEN_ISSUE_STATE_TYPES } from '@lobechat/types';
+
+/** What the import picker is filtered to. */
+export interface LinearImportFilter {
+ linearProjectId: string | null;
+ linearProjectName: string | null;
+ stateTypes: LinearIssueStateType[];
+ teamId: string | null;
+ teamName: string | null;
+}
+
+export const initialImportFilter = (): LinearImportFilter => ({
+ linearProjectId: null,
+ linearProjectName: null,
+ stateTypes: [...LINEAR_OPEN_ISSUE_STATE_TYPES],
+ teamId: null,
+ teamName: null,
+});
+
+export interface LinearIssueImportModalOptions {
+ connection: LinearConnectionView;
+ /** Called after issues were imported or a sync rule was saved. */
+ onSynced?: () => void;
+ /** LobeHub project the issues are synced into. */
+ projectId: string;
+}
diff --git a/src/features/Projects/LinearSync/useLinearSyncJobs.ts b/src/features/Projects/LinearSync/useLinearSyncJobs.ts
new file mode 100644
index 00000000000..8026c363565
--- /dev/null
+++ b/src/features/Projects/LinearSync/useLinearSyncJobs.ts
@@ -0,0 +1,65 @@
+import type { LinearSyncJobView } from '@lobechat/types';
+import { toast } from '@lobehub/ui';
+import { useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import useSWR from 'swr';
+
+import { linearKeys } from '@/features/Integrations/Linear/swrKeys';
+import { linearService } from '@/services/linear';
+
+import { formatLinearSyncResult, isActiveLinearSyncJob, linearSyncJobErrorMessage } from './utils';
+
+const POLL_MS = 2000;
+
+/** Jobs whose outcome an open import dialog is already showing; no toast for those. */
+export const jobsShownInDialog = new Set<string>();
+
+/**
+ * The project's recent background syncs. Polls only while one is still
+ * running, so an idle settings page makes no requests.
+ */
+export const useLinearSyncJobs = (projectId: string | null) => {
+ // A number, not a callback: React Compiler would freeze a closure over `data`.
+ const [refreshInterval, setRefreshInterval] = useState(0);
+ const swr = useSWR(
+ projectId ? linearKeys.syncJobs(projectId) : null,
+ () => linearService.listSyncJobs(projectId!),
+ { refreshInterval },
+ );
+ const hasActive = !!swr.data?.some(isActiveLinearSyncJob);
+ useEffect(() => setRefreshInterval(hasActive ? POLL_MS : 0), [hasActive]);
+ return swr;
+};
+
+/**
+ * Tell the user when a sync that was left running in the background ends —
+ * the dialog that started it may be long closed.
+ */
+export const useLinearSyncJobNotifier = (
+ jobs: LinearSyncJobView[] | undefined,
+ /** Called once per finished sync, e.g. to reload the task list it wrote to. */
+ onFinished?: () => void,
+) => {
+ const { t } = useTranslation('integration');
+ const running = useRef<Set<string> | null>(null);
+
+ useEffect(() => {
+ if (!jobs) return;
+ const previous = running.current;
+ running.current = new Set(jobs.filter(isActiveLinearSyncJob).map((job) => job.id));
+ // The first load only records what is running; it ended nothing.
+ if (!previous) return;
+ const finished = jobs.filter((job) => previous.has(job.id) && !isActiveLinearSyncJob(job));
+ if (finished.length > 0) onFinished?.();
+ for (const job of finished) {
+ if (jobsShownInDialog.has(job.id)) continue;
+ if (job.status === 'success' && job.result) {
+ toast.success(
+ t('linear.sync.job.finished', { result: formatLinearSyncResult(job.result, t) }),
+ );
+ } else if (job.status === 'error') {
+ toast.error(linearSyncJobErrorMessage(job.error, t));
+ }
+ }
+ }, [jobs, onFinished, t]);
+};
diff --git a/src/features/Projects/LinearSync/useProjectLinearSync.tsx b/src/features/Projects/LinearSync/useProjectLinearSync.tsx
new file mode 100644
index 00000000000..09c6f79e004
--- /dev/null
+++ b/src/features/Projects/LinearSync/useProjectLinearSync.tsx
@@ -0,0 +1,88 @@
+'use client';
+
+import type { FormFieldProps } from '@lobehub/ui';
+import { Button, Flexbox, Icon } from '@lobehub/ui';
+import { LinkIcon } from 'lucide-react';
+import { type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useIsWorkspaceViewer } from '@/business/client/hooks/useIsWorkspaceViewer';
+import AsyncError from '@/components/AsyncError';
+import { useLinearIntegration } from '@/features/Integrations/useLinearIntegration';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+
+import ImportTrigger from './ImportTrigger';
+import SyncJobs from './SyncJobs';
+import SyncRules, { useLinearSyncRules } from './SyncRules';
+import { useLinearSyncJobNotifier, useLinearSyncJobs } from './useLinearSyncJobs';
+
+const LINEAR_SETTINGS_PATH = '/settings/integrations/linear';
+
+/**
+ * Project settings → Advanced → "Sync from Linear": a settings row that
+ * imports Linear issues as this project's tasks, plus the project's saved
+ * sync rules and recent background syncs below the settings form. Syncing is one way; Linear is only
+ * read. Connecting a Linear workspace stays in Settings → Integrations,
+ * shared by every project in the scope. A deployment without a Linear app,
+ * and no connection left, contributes nothing.
+ */
+export const useProjectLinearSync = (
+ projectId: string,
+): { item: FormFieldProps | null; rules: ReactNode } => {
+ const { t } = useTranslation('integration');
+ const navigate = useWorkspaceAwareNavigate();
+ const { config, connections, error, isInitialLoading, mutate } = useLinearIntegration();
+ const syncRules = useLinearSyncRules(projectId);
+ const syncJobs = useLinearSyncJobs(projectId);
+ // A rule's last run is written when its job ends, not when it starts.
+ useLinearSyncJobNotifier(syncJobs.data, () => void syncRules.mutate());
+ const refresh = () => {
+ void syncRules.mutate();
+ void syncJobs.mutate();
+ };
+ // Viewers can see what is synced but cannot create tasks.
+ const isViewer = useIsWorkspaceViewer();
+
+ if (error && isInitialLoading) {
+ return { item: null, rules: <AsyncError error={error} variant={'block'} onRetry={mutate} /> };
+ }
+ if (isInitialLoading || (!config?.enabled && connections.length === 0)) {
+ return { item: null, rules: null };
+ }
+
+ const connected = connections.length > 0;
+ return {
+ item: {
+ children: connected ? (
+ <ImportTrigger
+ connections={connections}
+ disabled={isViewer}
+ projectId={projectId}
+ variant={'button'}
+ onSynced={refresh}
+ />
+ ) : (
+ <Button icon={<Icon icon={LinkIcon} />} onClick={() => navigate(LINEAR_SETTINGS_PATH)}>
+ {t('linear.sync.project.connect')}
+ </Button>
+ ),
+ desc: connected
+ ? t('linear.sync.project.description')
+ : t('linear.sync.project.noConnection'),
+ label: t('linear.sync.project.title'),
+ minWidth: undefined,
+ },
+ // Rules outlive a disconnect, so they stay listed and removable.
+ rules: (
+ <Flexbox gap={16}>
+ <SyncRules
+ connections={connections}
+ jobs={syncJobs.data ?? []}
+ projectId={projectId}
+ onJobStarted={refresh}
+ />
+ <SyncJobs jobs={syncJobs.data ?? []} rules={syncRules.data ?? []} />
+ </Flexbox>
+ ),
+ };
+};
diff --git a/src/features/Projects/LinearSync/utils.test.ts b/src/features/Projects/LinearSync/utils.test.ts
new file mode 100644
index 00000000000..f17cde26d7f
--- /dev/null
+++ b/src/features/Projects/LinearSync/utils.test.ts
@@ -0,0 +1,69 @@
+import type { LinearSyncResult } from '@lobechat/types';
+import type { TFunction } from 'i18next';
+import { describe, expect, it } from 'vitest';
+
+import { formatLinearSyncResult, isActiveLinearSyncJob, linearSyncJobErrorMessage } from './utils';
+
+const t = ((key: string, options?: { count?: number }) =>
+ options?.count === undefined
+ ? key
+ : `${key}:${options.count}`) as unknown as TFunction<'integration'>;
+
+const result = (overrides: Partial<LinearSyncResult>): LinearSyncResult => ({
+ closed: 0,
+ created: 0,
+ keptLocalEdits: 0,
+ skipped: [],
+ truncated: false,
+ unchanged: 0,
+ updated: 0,
+ ...overrides,
+});
+
+describe('formatLinearSyncResult', () => {
+ it('lists only what changed, and says when more remain', () => {
+ expect(
+ formatLinearSyncResult(
+ result({
+ closed: 1,
+ created: 2,
+ skipped: [{ identifier: 'ENG-1', reason: 'running' }],
+ truncated: true,
+ }),
+ t,
+ ),
+ ).toBe(
+ 'linear.sync.result.created:2 · linear.sync.result.closed:1 · linear.sync.result.skipped:1 · linear.sync.result.truncated',
+ );
+ });
+
+ it('counts skipped issues past the stored list', () => {
+ expect(
+ formatLinearSyncResult(
+ result({ skipped: [{ identifier: 'ENG-1', reason: 'failed' }], skippedCount: 150 }),
+ t,
+ ),
+ ).toBe('linear.sync.result.skipped:150');
+ });
+
+ it('says up to date when nothing changed', () => {
+ expect(formatLinearSyncResult(result({ unchanged: 3 }), t)).toBe('linear.sync.result.upToDate');
+ });
+});
+
+describe('background sync jobs', () => {
+ it('treats queued and running jobs as active', () => {
+ expect(isActiveLinearSyncJob({ status: 'pending' })).toBe(true);
+ expect(isActiveLinearSyncJob({ status: 'processing' })).toBe(true);
+ expect(isActiveLinearSyncJob({ status: 'success' })).toBe(false);
+ expect(isActiveLinearSyncJob({ status: 'error' })).toBe(false);
+ });
+
+ it('explains each way a job can fail', () => {
+ expect(linearSyncJobErrorMessage('reconnect', t)).toBe('linear.sync.error.reconnect');
+ expect(linearSyncJobErrorMessage('unavailable', t)).toBe('linear.sync.job.error.unavailable');
+ expect(linearSyncJobErrorMessage('timeout', t)).toBe('linear.sync.job.error.timeout');
+ expect(linearSyncJobErrorMessage('failed', t)).toBe('linear.sync.error.generic');
+ expect(linearSyncJobErrorMessage(null, t)).toBe('linear.sync.error.generic');
+ });
+});
diff --git a/src/features/Projects/LinearSync/utils.ts b/src/features/Projects/LinearSync/utils.ts
new file mode 100644
index 00000000000..9638f3e2ffd
--- /dev/null
+++ b/src/features/Projects/LinearSync/utils.ts
@@ -0,0 +1,58 @@
+import type { LinearSyncJobErrorCode, LinearSyncJobView, LinearSyncResult } from '@lobechat/types';
+import { TRPCClientError } from '@trpc/client';
+import type { TFunction } from 'i18next';
+
+/** Server message for a revoked or expired Linear token (`LINEAR_RECONNECT_REQUIRED`). */
+const RECONNECT_REQUIRED = 'LINEAR_RECONNECT_REQUIRED';
+
+export const linearSyncErrorMessage = (error: unknown, t: TFunction<'integration'>): string =>
+ error instanceof TRPCClientError && error.message === RECONNECT_REQUIRED
+ ? t('linear.sync.error.reconnect')
+ : t('linear.sync.error.generic');
+
+/** All skipped issues; the stored list stops at its cap, and older results lack the count. */
+export const linearSyncSkippedCount = (result: LinearSyncResult): number =>
+ result.skippedCount ?? result.skipped?.length ?? 0;
+
+/** One-line outcome of a sync, e.g. "2 created · 1 updated · 1 closed". */
+export const formatLinearSyncResult = (
+ result: LinearSyncResult,
+ t: TFunction<'integration'>,
+): string => {
+ const skipped = linearSyncSkippedCount(result);
+ const parts = [
+ result.created && t('linear.sync.result.created', { count: result.created }),
+ result.updated && t('linear.sync.result.updated', { count: result.updated }),
+ result.closed && t('linear.sync.result.closed', { count: result.closed }),
+ result.keptLocalEdits &&
+ t('linear.sync.result.keptLocalEdits', { count: result.keptLocalEdits }),
+ skipped && t('linear.sync.result.skipped', { count: skipped }),
+ ].filter(Boolean) as string[];
+ if (parts.length === 0) parts.push(t('linear.sync.result.upToDate'));
+ if (result.truncated) parts.push(t('linear.sync.result.truncated'));
+ return parts.join(' · ');
+};
+
+export const isActiveLinearSyncJob = (job: Pick<LinearSyncJobView, 'status'>) =>
+ job.status === 'pending' || job.status === 'processing';
+
+/** Why a background sync did not finish, for the user. */
+export const linearSyncJobErrorMessage = (
+ code: LinearSyncJobErrorCode | null,
+ t: TFunction<'integration'>,
+): string => {
+ switch (code) {
+ case 'reconnect': {
+ return t('linear.sync.error.reconnect');
+ }
+ case 'unavailable': {
+ return t('linear.sync.job.error.unavailable');
+ }
+ case 'timeout': {
+ return t('linear.sync.job.error.timeout');
+ }
+ default: {
+ return t('linear.sync.error.generic');
+ }
+ }
+};
diff --git a/src/features/Projects/WorkingDirectories/AdvancedSettings.tsx b/src/features/Projects/WorkingDirectories/AdvancedSettings.tsx
index a8a065afb0f..609988d9846 100644
--- a/src/features/Projects/WorkingDirectories/AdvancedSettings.tsx
+++ b/src/features/Projects/WorkingDirectories/AdvancedSettings.tsx
@@ -10,6 +10,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwar
import type { ProjectDetail } from '@/store/project';
import { useProjectStore } from '@/store/project';
+import { useProjectLinearSync } from '../LinearSync';
import { useCanManageProject } from '../useCanManageProject';
export function AdvancedSettings({ project }: { project: ProjectDetail['project'] }) {
@@ -18,6 +19,7 @@ export function AdvancedSettings({ project }: { project: ProjectDetail['project'
const deleteProject = useProjectStore((s) => s.deleteProject);
const canManage = useCanManageProject();
const [pending, setPending] = useState(false);
+ const linearSync = useProjectLinearSync(project.id);
// Destructive settings need edit permission; the page hides this tab from viewers.
if (!canManage) return null;
@@ -46,6 +48,14 @@ export function AdvancedSettings({ project }: { project: ProjectDetail['project'
return (
<Flexbox gap={24}>
+ {linearSync.item ? (
+ <Flexbox gap={16}>
+ <Form {...FORM_STYLE} items={[linearSync.item]} itemsType="flat" variant="filled" />
+ {linearSync.rules}
+ </Flexbox>
+ ) : (
+ linearSync.rules
+ )}
<Form
{...FORM_STYLE}
itemsType="flat"
diff --git a/src/routes/(main)/project/[projectId]/tasks/index.tsx b/src/routes/(main)/project/[projectId]/tasks/index.tsx
index 1ee1e46b195..3297295cfe5 100644
--- a/src/routes/(main)/project/[projectId]/tasks/index.tsx
+++ b/src/routes/(main)/project/[projectId]/tasks/index.tsx
@@ -3,6 +3,7 @@
import AsyncError from '@/components/AsyncError';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import { AgentTasksPage } from '@/features/AgentTasks';
+import { LinearSyncEntry } from '@/features/Projects/LinearSync';
import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
@@ -19,7 +20,12 @@ const ProjectTasks = () => {
return <AsyncError error={error} variant={'page'} onRetry={() => void revalidate()} />;
if (!detail) return null;
- return <AgentTasksPage projectId={detail.project.id} />;
+ return (
+ <AgentTasksPage
+ headerActions={<LinearSyncEntry projectId={detail.project.id} />}
+ projectId={detail.project.id}
+ />
+ );
};
export default ProjectTasks;
diff --git a/src/services/linear.ts b/src/services/linear.ts
index d88c2d4d98b..157dd738344 100644
--- a/src/services/linear.ts
+++ b/src/services/linear.ts
@@ -1,5 +1,14 @@
+import type { LinearIssueStateType } from '@lobechat/types';
+
import { lambdaClient } from '@/libs/trpc/client';
+export interface LinearIssueFilterParams {
+ connectionId: string;
+ linearProjectId?: string | null;
+ stateTypes: LinearIssueStateType[];
+ teamId: string;
+}
+
class LinearService {
disconnect = async (connectionId: string) =>
lambdaClient.linear.disconnect.mutate({ connectionId });
@@ -7,6 +16,38 @@ class LinearService {
getConfig = async () => lambdaClient.linear.getConfig.query();
listConnections = async () => lambdaClient.linear.listConnections.query();
+
+ // ── Issue sync ──
+
+ listTeams = async (connectionId: string) => lambdaClient.linear.listTeams.query({ connectionId });
+
+ listProjects = async (connectionId: string, teamId: string) =>
+ lambdaClient.linear.listProjects.query({ connectionId, teamId });
+
+ listIssues = async (params: LinearIssueFilterParams & { cursor?: string }) =>
+ lambdaClient.linear.listIssues.query(params);
+
+ /** Starts a background import; returns the job id. */
+ startImport = async (params: { connectionId: string; issueIds: string[]; projectId: string }) =>
+ lambdaClient.linear.startImport.mutate(params);
+
+ listSyncJobs = async (projectId: string) => lambdaClient.linear.listSyncJobs.query({ projectId });
+
+ listSyncRules = async (projectId: string) =>
+ lambdaClient.linear.listSyncRules.query({ projectId });
+
+ createSyncRule = async (
+ params: LinearIssueFilterParams & {
+ linearProjectName?: string | null;
+ projectId: string;
+ teamName: string;
+ },
+ ) => lambdaClient.linear.createSyncRule.mutate(params);
+
+ deleteSyncRule = async (ruleId: string) => lambdaClient.linear.deleteSyncRule.mutate({ ruleId });
+
+ /** Starts a background run of a saved rule; returns the job id. */
+ startRuleSync = async (ruleId: string) => lambdaClient.linear.startRuleSync.mutate({ ruleId });
}
export const linearService = new LinearService();