From d8f31588b0ddd6499c90ef0187e3906e08a0b968 Mon Sep 17 00:00:00 2001 From: Pixel Perfect Date: Fri, 20 Nov 2026 13:43:19 -0800 Subject: [PATCH 1/6] feat(issues): wake, snooze and settle threads from Linear team statuses A Linear team's workflow statuses can be sorted into Wake, Snooze and Settle under Settings, Source control & issues. The server reads the status of every issue linked to an active thread once a minute and organizes the thread when a status changes: any wake wins, it settles only when every linked issue settles, and otherwise it snoozes. An unread or unmapped status leaves the thread alone. The first read and any manual organizing stand until an issue moves again. A snooze from a rule has no wake time: thread.snooze accepts a null snoozedUntil, the snoozed list shows it as infinity, and a rule's wake ends the snooze the way its timer would, so clients show the thread woke. An open issue detail reads the issue again when a rule sees its status change. --- ...ettingsSourceControlDetailRouteScreens.tsx | 8 + .../components/IssueAutomationSection.tsx | 334 +++++++++++++ .../src/features/threads/threadListV2.ts | 10 +- apps/mobile/src/i18n/translations/de.json | 24 + apps/mobile/src/i18n/translations/en.json | 24 + apps/mobile/src/i18n/translations/es.json | 24 + apps/mobile/src/i18n/translations/fr.json | 24 + apps/mobile/src/i18n/translations/ja.json | 24 + apps/mobile/src/i18n/translations/ko.json | 24 + apps/mobile/src/i18n/translations/pt-BR.json | 24 + apps/mobile/src/i18n/translations/ru.json | 24 + apps/mobile/src/i18n/translations/sv.json | 24 + apps/mobile/src/i18n/translations/zh.json | 24 + apps/server/src/auth/RpcAuthorization.ts | 4 + .../IssueThreadAutomationService.test.ts | 464 ++++++++++++++++++ .../src/issue/IssueThreadAutomationService.ts | 422 ++++++++++++++++ .../src/issue/IssueThreadAutomationWorker.ts | 47 ++ apps/server/src/issue/issueAutomation.test.ts | 26 + apps/server/src/issue/issueAutomation.ts | 37 ++ .../src/mcp/OrchestratorMcpService.test.ts | 7 +- apps/server/src/mcp/OrchestratorMcpService.ts | 9 +- .../src/observability/RpcInstrumentation.ts | 4 + .../orchestration-v2/IdleCompaction.test.ts | 8 +- .../src/orchestration-v2/IdleCompaction.ts | 6 +- .../Orchestrator.control-reads.test.ts | 163 ++++++ .../src/orchestration-v2/Orchestrator.ts | 134 ++++- .../orchestration-v2/ProjectionStore.test.ts | 37 ++ .../src/orchestration-v2/ProjectionStore.ts | 59 ++- .../ProviderTurnControlService.test.ts | 2 + .../RestartContinuation.test.ts | 1 + .../orchestration-v2/RestartContinuation.ts | 3 +- .../ThreadSettlementService.test.ts | 7 + .../ThreadSettlementService.ts | 4 +- .../UsageLimitRecoveryWorker.test.ts | 16 + .../UsageLimitRecoveryWorker.ts | 8 +- .../threadOrganizationEvent.ts | 20 + .../src/orchestration-v2/threadSnooze.ts | 18 + .../src/persistence/IssueThreadAutomation.ts | 82 ++++ apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/111_IssueThreadAutomation.ts | 21 + .../reconcileV2PreviewMigration.test.ts | 2 + apps/server/src/server.ts | 12 + apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 17 + apps/web/src/components/Sidebar.tsx | 18 +- .../settings/IssueAutomationSettings.tsx | 365 ++++++++++++++ .../settings/IssueTrackerSettings.tsx | 10 + .../src/components/settings/settingsSearch.ts | 8 + apps/web/src/i18n/translations/de.json | 25 + apps/web/src/i18n/translations/en.json | 25 + apps/web/src/i18n/translations/es.json | 25 + apps/web/src/i18n/translations/fr.json | 25 + apps/web/src/i18n/translations/ja.json | 25 + apps/web/src/i18n/translations/ko.json | 25 + apps/web/src/i18n/translations/pt-BR.json | 25 + apps/web/src/i18n/translations/ru.json | 25 + apps/web/src/i18n/translations/sv.json | 25 + apps/web/src/i18n/translations/zh.json | 25 + docs/user/source-control.md | 17 + .../client-runtime/src/operations/commands.ts | 3 +- packages/client-runtime/src/rpc/client.ts | 1 + .../src/state/commandPermissions.test.ts | 40 +- .../client-runtime/src/state/issueTrackers.ts | 23 + packages/client-runtime/src/state/issues.ts | 10 + .../src/state/threadCommands.ts | 6 +- .../client-runtime/src/state/threadSettled.ts | 14 +- .../src/state/threadSnoozed.test.ts | 15 + .../src/state/threadUndo.test.ts | 25 + .../client-runtime/src/state/threadUndo.ts | 17 +- .../contracts/src/clientRpcPermissions.ts | 3 +- packages/contracts/src/issue.ts | 79 +++ packages/contracts/src/orchestrationV2.ts | 16 +- packages/contracts/src/rpc.ts | 43 ++ packages/contracts/src/settings.ts | 19 +- .../src/server/LinearApi.graphql | 21 + .../src/server/LinearApi.graphql.ts | 88 +++- .../src/server/LinearApi.ts | 32 ++ .../src/server/LinearIssueTracker.test.ts | 58 +++ .../src/server/LinearIssueTracker.ts | 45 ++ .../src/server/IssueTracker.ts | 30 ++ 80 files changed, 3398 insertions(+), 94 deletions(-) create mode 100644 apps/mobile/src/features/settings/components/IssueAutomationSection.tsx create mode 100644 apps/server/src/issue/IssueThreadAutomationService.test.ts create mode 100644 apps/server/src/issue/IssueThreadAutomationService.ts create mode 100644 apps/server/src/issue/IssueThreadAutomationWorker.ts create mode 100644 apps/server/src/issue/issueAutomation.test.ts create mode 100644 apps/server/src/issue/issueAutomation.ts create mode 100644 apps/server/src/orchestration-v2/threadOrganizationEvent.ts create mode 100644 apps/server/src/orchestration-v2/threadSnooze.ts create mode 100644 apps/server/src/persistence/IssueThreadAutomation.ts create mode 100644 apps/server/src/persistence/Migrations/111_IssueThreadAutomation.ts create mode 100644 apps/web/src/components/settings/IssueAutomationSettings.tsx create mode 100644 packages/client-runtime/src/state/threadUndo.test.ts diff --git a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx index 94c5a682f537f..808f5972ea79b 100644 --- a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx +++ b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx @@ -24,6 +24,7 @@ import { useEnvironmentQuery } from "../../state/query"; import { serverEnvironment } from "../../state/server"; import { useEnvironmentsWithScope } from "../../state/session"; import { sourceControlEnvironment } from "../../state/sourceControl"; +import { IssueAutomationSection } from "./components/IssueAutomationSection"; import { IssueTrackerCredentialForm, IssueTrackerProjectRows, @@ -238,6 +239,13 @@ export function SettingsIssueTrackerRouteScreen({ /> ) : null} + {usable && tracker.automationContainer !== undefined ? ( + + ) : null} )} diff --git a/apps/mobile/src/features/settings/components/IssueAutomationSection.tsx b/apps/mobile/src/features/settings/components/IssueAutomationSection.tsx new file mode 100644 index 0000000000000..f5c86bc54d135 --- /dev/null +++ b/apps/mobile/src/features/settings/components/IssueAutomationSection.tsx @@ -0,0 +1,334 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { + EnvironmentId, + IssueAutomationAction, + IssueAutomationRule, + IssueTrackerKind, + StandaloneIssueTrackerDescriptor, +} from "@t3tools/contracts"; +import { useGT } from "gt-react-native"; +import { useState } from "react"; +import { Pressable, View } from "react-native"; + +import { AppText as Text } from "../../../components/ui/AppText"; +import { SymbolView } from "../../../components/ui/AppSymbol"; +import { Button } from "../../../components/ui/Button"; +import { Chip } from "../../../components/ui/Chip"; +import { Menu } from "../../../components/ui/Menu"; +import { ThemedSwitch } from "../../../components/ui/ThemedSwitch"; +import { uuidv4 } from "../../../lib/uuid"; +import { issueTrackerEnvironment } from "../../../state/issueTrackers"; +import { useEnvironmentQuery } from "../../../state/query"; +import { useAtomCommand } from "../../../state/use-atom-command"; +import { SettingsSection } from "./SettingsSection"; + +type Container = NonNullable; + +/** + * Issue status rules for one tracker: each team or board sorts its workflow statuses into Wake, + * Snooze, and Settle, and the server organizes every thread linked to one of its issues. + */ +export function IssueAutomationSection({ + environmentId, + tracker, + container, +}: { + readonly environmentId: EnvironmentId; + readonly tracker: IssueTrackerKind; + readonly container: Container; +}) { + const gt = useGT(); + const query = useEnvironmentQuery( + issueTrackerEnvironment.automation({ environmentId, input: {} }), + ); + const catalog = useEnvironmentQuery( + issueTrackerEnvironment.automationCatalog({ environmentId, input: { tracker } }), + ); + const allowed = useAtomValue( + issueTrackerEnvironment.saveAutomation.permissionAtom(environmentId), + ); + const [draft, setDraft] = useState(null); + const rules = (query.data?.rules ?? []).filter((rule) => rule.tracker === tracker); + const available = (catalog.data?.containers ?? []).filter( + (option) => !rules.some((rule) => rule.containerId === option.id), + ); + const team = container === "team"; + const addLabel = team ? gt("Add team") : gt("Add board"); + return ( + 0 + ? available.map((option) => ({ id: option.id, title: option.name })) + : [ + { + id: "retry", + title: catalog.isPending + ? gt("Loading…") + : catalog.error + ? gt("Retry") + : team + ? gt("Every team already has a rule.") + : gt("Every board already has a rule."), + attributes: { disabled: catalog.error === null }, + }, + ] + } + onPressAction={({ nativeEvent }) => { + const option = available.find((candidate) => candidate.id === nativeEvent.event); + if (option !== undefined && catalog.data !== null) + setDraft({ + id: uuidv4(), + enabled: true, + tracker, + workspace: catalog.data.workspace, + containerId: option.id, + containerName: option.name, + mappings: {}, + }); + else if (nativeEvent.event === "retry") catalog.refresh(); + }} + > + + + {addLabel} + + + } + > + {query.error ? ( + + {query.error} + + ) : null} + {rules.map((rule) => ( + status.ruleId === rule.id)?.error != null + } + /> + ))} + {draft ? ( + setDraft(null)} + /> + ) : null} + {rules.length === 0 && draft === null && !query.isPending ? ( + + {team + ? gt("Add a team to organize the threads linked to its issues.") + : gt("Add a board to organize the threads linked to its issues.")} + + ) : null} + + ); +} + +function RuleCard({ + environmentId, + rule, + container, + lastReadFailed, + onDone, +}: { + readonly environmentId: EnvironmentId; + readonly rule: IssueAutomationRule; + readonly container: Container; + readonly lastReadFailed: boolean; + /** Present for a rule not saved yet; called once it is saved or abandoned. */ + readonly onDone?: () => void; +}) { + const gt = useGT(); + const [mappings, setMappings] = useState(rule.mappings); + const [enabled, setEnabled] = useState(rule.enabled); + const [busy, setBusy] = useState(false); + const [failure, setFailure] = useState(null); + const allowed = useAtomValue( + issueTrackerEnvironment.saveAutomation.permissionAtom(environmentId), + ); + const save = useAtomCommand(issueTrackerEnvironment.saveAutomation, { + label: `save ${rule.containerName} status rule`, + }); + const workflow = useEnvironmentQuery( + issueTrackerEnvironment.automationCatalog({ + environmentId, + input: { tracker: rule.tracker, containerId: rule.containerId }, + }), + ); + const states = workflow.data?.states ?? []; + const unsorted = states.filter((state) => mappings[state.id] === undefined); + const otherWorkspace = + workflow.data !== null && + workflow.data.workspace.toLowerCase() !== rule.workspace.toLowerCase(); + const dirty = + onDone !== undefined || + enabled !== rule.enabled || + Object.keys(mappings).length !== Object.keys(rule.mappings).length || + Object.entries(mappings).some(([id, action]) => rule.mappings[id] !== action); + const locked = !allowed || busy; + const team = container === "team"; + const buckets: ReadonlyArray<{ readonly action: IssueAutomationAction; readonly label: string }> = + [ + { action: "wake", label: gt("Wake") }, + { action: "snooze", label: gt("Snooze") }, + { action: "settle", label: gt("Settle") }, + ]; + const submit = async (remove: boolean) => { + setBusy(true); + setFailure(null); + const result = await save({ + environmentId, + input: { id: rule.id, rule: remove ? null : { ...rule, enabled, mappings } }, + }); + setBusy(false); + if (result._tag === "Success") onDone?.(); + else setFailure(gt("The rule could not be saved.")); + }; + const alert = + failure ?? + workflow.error ?? + (otherWorkspace + ? gt("This rule belongs to another workspace. Add the team or board again to use it here.") + : lastReadFailed + ? gt("The last status check failed. Threads were left as they are.") + : null); + return ( + + + + {rule.containerName} + + + (onDone ? onDone() : void submit(true))} + className="min-h-9 min-w-9 items-center justify-center active:opacity-70" + > + + + + + {team + ? gt("Applies to threads linked to this team's issues, in every project.") + : gt("Applies to threads linked to this board's issues, in every project.")} + + {buckets.map(({ action, label }) => ( + + + {label} + 0 + ? unsorted.map((state) => ({ id: state.id, title: state.name })) + : [ + { + id: "empty", + title: gt("Every status is in a bucket."), + attributes: { disabled: true }, + }, + ] + } + onPressAction={({ nativeEvent }) => { + if (unsorted.some((state) => state.id === nativeEvent.event)) + setMappings((current) => ({ ...current, [nativeEvent.event]: action })); + }} + > + + + + + + + {Object.entries(mappings) + .filter(([, value]) => value === action) + .map(([id]) => { + const name = states.find((state) => state.id === id)?.name ?? id; + return ( + + setMappings((current) => + Object.fromEntries(Object.entries(current).filter(([key]) => key !== id)), + ) + } + /> + ); + })} + + + ))} + {alert ? ( + + {alert} + + ) : null} + {workflow.error ? ( + + ) : ( + + )} + +
+ {buckets.map(({ action, label }) => ( +
+
+ {label} + + + } + > + + + + {unsorted.map((state) => ( + setMappings((current) => ({ ...current, [state.id]: action }))} + > + {state.name} + + ))} + {unsorted.length === 0 ? ( + {gt("Every status is in a bucket.")} + ) : null} + + +
+
+ {Object.entries(mappings) + .filter(([, value]) => value === action) + .map(([id]) => { + const name = states.find((state) => state.id === id)?.name ?? id; + return ( + + {name} + + + ); + })} +
+
+ ))} +
+ {alert ? ( +

+ {alert} +

+ ) : null} +
+ {workflow.error ? ( + + ) : null} + {dirty ? ( + <> + + {onDone ? null : ( + + )} + + ) : null} +
+ + ); +} diff --git a/apps/web/src/components/settings/IssueTrackerSettings.tsx b/apps/web/src/components/settings/IssueTrackerSettings.tsx index b418ac3e73064..c43bce9d34f57 100644 --- a/apps/web/src/components/settings/IssueTrackerSettings.tsx +++ b/apps/web/src/components/settings/IssueTrackerSettings.tsx @@ -32,6 +32,7 @@ import { Button, InlineButton } from "../ui/button"; import { Collapsible, CollapsibleContent } from "../ui/collapsible"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; import { Skeleton } from "../ui/skeleton"; +import { IssueAutomationSettings } from "./IssueAutomationSettings"; import { SecretInput } from "./SecretInput"; import { SettingsRow, SettingsSection } from "./settingsLayout"; import { useSearchableSetting } from "./settingsSearch"; @@ -266,6 +267,15 @@ function TrackerRow({ ) : null} + {usable && tracker.automationContainer !== undefined ? ( +
+ +
+ ) : null} diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 1f38ed958d368..12253c9ba2d1a 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1256,6 +1256,14 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "environment-defaults", searchTerms: [msg("linear jira issues tracker team api key connect bind project")], }, + { + id: "issue-status-rules", + targetId: "issue-trackers", + title: msg("Issue status rules"), + to: "/settings/source-control", + scope: "environment-defaults", + searchTerms: [msg("linear team jira board issue status workflow wake snooze settle thread")], + }, { id: "source-control", title: msg("Source control"), diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 7900e73186091..9ed1a4e15df36 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -8749,6 +8749,19 @@ ], "e913ae62f3907911": "Du wirst von den zugehörigen Websites abgemeldet. Server-Browser-Tabs in diesem Profil werden sofort geschlossen.", "7a4464dfc6c856e5": "Daten löschen", + "13e6f2309e418404": "Erledigen", + "470388c152e293cb": "Die Regel konnte nicht gespeichert werden.", + "7c8c86f94f9d13bf": "Diese Regel gehört zu einem anderen Workspace. Füge das Team oder Board erneut hinzu, um sie hier zu nutzen.", + "5efcecd685ad1dac": "Die letzte Statusprüfung ist fehlgeschlagen. Die Threads wurden nicht verändert.", + "63c5271568e4f9c6": "Gilt für Threads, die mit Issues dieses Teams verknüpft sind, in jedem Projekt.", + "0cc9c4463ea35891": "Gilt für Threads, die mit Issues dieses Boards verknüpft sind, in jedem Projekt.", + "666b6f323f7f3274": "Regel aktivieren", + "7792add570638f64": "Team entfernen", + "65d7900a7a9d57e7": "Board entfernen", + "245038c3d0fc7c5e": "Status zu {bucket} hinzufügen", + "da5ac1b89bbc2e15": "Jeder Status ist bereits zugeordnet.", + "183dc01e105d82e5": "{status} entfernen", + "bf5602410d695db3": "Verwerfen", "92da88ddc3c21020": "Issue-Tracker", "58e0e226493150e7": "Issue-Tracker konnten nicht geladen werden", "77cfcbde543df32d": "Details zu {tracker} ein-/ausblenden", @@ -10205,6 +10218,16 @@ "f9b912a818bd869d": "Basisverzeichnis für neue Projekte auf Standard zurücksetzen", "6fc9e5e722cf3c73": "Klone landen unter github.com/owner/repo im Ordner oben, wie bei ghq.", "bee548d674abd0d2": "In Host-Ordner klonen auf Standard zurücksetzen", + "30cc3b0b7c5223f9": "Teams", + "f42c4d6d05dfcacf": "Boards", + "24b5619c501032bf": "Threads wecken, zurückstellen oder erledigen, wenn sich der Status eines verknüpften Issues ändert.", + "647234c5dc75e791": "Team hinzufügen", + "2f3d6b74fac5b143": "Board hinzufügen", + "7692d28fbe45f1cd": "Jedes Team hat bereits eine Regel.", + "58a6276de6d8988e": "Jedes Board hat bereits eine Regel.", + "0ca7ece5adb2141b": "Füge ein Team hinzu, um die mit seinen Issues verknüpften Threads zu ordnen.", + "ade2fad0438c0ef7": "Füge ein Board hinzu, um die mit seinen Issues verknüpften Threads zu ordnen.", + "f903e7f0ca23602c": "Wecken", "ef27c4211844aef9": "Zurückstellen", "4df30d44eb0b0728": "Threads automatisch fortsetzen, wenn ihre Nutzungslimits zurückgesetzt werden. Du kannst das automatische Fortsetzen in jedem Thread abbrechen.", "0769f91ca46e3003": "Threads zurückstellen, bis ihre Nutzungslimits zurückgesetzt werden. Aktiviere automatisches Fortsetzen, damit der Agent nach dem Zurücksetzen weiterarbeitet.", @@ -11960,6 +11983,8 @@ "a22700a2aa679898": "Standard-Merge-Methode", "c4548ce84893201b": "pull request merge squash rebase zuletzt gewählt", "f6c5ffe0b40ce8e2": "linear jira issues tracker team api-schlüssel verbinden zuordnen projekt", + "03c5083adeb3ac5e": "Issue-Statusregeln", + "5f4cd500513df9ca": "linear team jira board issue status workflow wecken zurückstellen erledigen thread", "a4380762611c94e4": "Versionskontrolle", "2f251b69a6c324f3": "Git-Fetch-Intervall", "deed4a583dfa2c44": "automatisch remote branch aktualisieren hintergrund zugangsdaten sicherheitsschlüssel sekunden aus", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 5bdd7c383d319..a7ed27dfed37c 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -8757,6 +8757,19 @@ ], "e913ae62f3907911": "You are signed out of its sites. Server browser tabs open in this profile close now.", "7a4464dfc6c856e5": "Clear data", + "13e6f2309e418404": "Settle", + "470388c152e293cb": "The rule could not be saved.", + "7c8c86f94f9d13bf": "This rule belongs to another workspace. Add the team or board again to use it here.", + "5efcecd685ad1dac": "The last status check failed. Threads were left as they are.", + "63c5271568e4f9c6": "Applies to threads linked to this team's issues, in every project.", + "0cc9c4463ea35891": "Applies to threads linked to this board's issues, in every project.", + "666b6f323f7f3274": "Enable rule", + "7792add570638f64": "Remove team", + "65d7900a7a9d57e7": "Remove board", + "245038c3d0fc7c5e": "Add a status to {bucket}", + "da5ac1b89bbc2e15": "Every status is in a bucket.", + "183dc01e105d82e5": "Remove {status}", + "bf5602410d695db3": "Discard", "92da88ddc3c21020": "Issue trackers", "58e0e226493150e7": "Could not load issue trackers", "77cfcbde543df32d": "Toggle {tracker} details", @@ -10214,6 +10227,16 @@ "f9b912a818bd869d": "Reset add project base directory to default", "6fc9e5e722cf3c73": "Clones go to github.com/owner/repo under the folder above, like ghq.", "bee548d674abd0d2": "Reset clone into host folders to default", + "30cc3b0b7c5223f9": "Teams", + "f42c4d6d05dfcacf": "Boards", + "24b5619c501032bf": "Wake, snooze, or settle threads when a linked issue's status changes.", + "647234c5dc75e791": "Add team", + "2f3d6b74fac5b143": "Add board", + "7692d28fbe45f1cd": "Every team already has a rule.", + "58a6276de6d8988e": "Every board already has a rule.", + "0ca7ece5adb2141b": "Add a team to organize the threads linked to its issues.", + "ade2fad0438c0ef7": "Add a board to organize the threads linked to its issues.", + "f903e7f0ca23602c": "Wake", "ef27c4211844aef9": "Snooze", "4df30d44eb0b0728": "Automatically resume threads when their usage limits reset. You can cancel auto-resume in each thread.", "0769f91ca46e3003": "Snooze threads until their usage limits reset. Enable auto-resume to continue the agent after the reset.", @@ -11968,6 +11991,8 @@ "a22700a2aa679898": "Default merge method", "c4548ce84893201b": "pull request merge squash rebase last selected", "f6c5ffe0b40ce8e2": "linear jira issues tracker team api key connect bind project", + "03c5083adeb3ac5e": "Issue status rules", + "5f4cd500513df9ca": "linear team jira board issue status workflow wake snooze settle thread", "a4380762611c94e4": "Source control", "2f251b69a6c324f3": "Git fetch interval", "deed4a583dfa2c44": "automatic remote branch refresh background credentials security keys seconds off", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 91dbb2b07f50f..49f32eb074ed6 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -8747,6 +8747,19 @@ ], "e913ae62f3907911": "Se cerrará tu sesión en sus sitios. Las pestañas del navegador del servidor abiertas en este perfil se cierran ahora.", "7a4464dfc6c856e5": "Borrar datos", + "13e6f2309e418404": "Resolver", + "470388c152e293cb": "No se pudo guardar la regla.", + "7c8c86f94f9d13bf": "Esta regla pertenece a otro espacio de trabajo. Vuelve a añadir el equipo o tablero para usarla aquí.", + "5efcecd685ad1dac": "La última comprobación de estado falló. Los hilos se quedaron como estaban.", + "63c5271568e4f9c6": "Se aplica a los hilos vinculados a issues de este equipo, en todos los proyectos.", + "0cc9c4463ea35891": "Se aplica a los hilos vinculados a issues de este tablero, en todos los proyectos.", + "666b6f323f7f3274": "Activar regla", + "7792add570638f64": "Quitar equipo", + "65d7900a7a9d57e7": "Quitar tablero", + "245038c3d0fc7c5e": "Añadir un estado a {bucket}", + "da5ac1b89bbc2e15": "Todos los estados ya están en un grupo.", + "183dc01e105d82e5": "Quitar {status}", + "bf5602410d695db3": "Descartar", "92da88ddc3c21020": "Gestores de issues", "58e0e226493150e7": "No se pudieron cargar los gestores de issues", "77cfcbde543df32d": "Mostrar u ocultar detalles de {tracker}", @@ -10202,6 +10215,16 @@ "f9b912a818bd869d": "Restablecer el directorio base para añadir proyectos al valor predeterminado", "6fc9e5e722cf3c73": "Los clones van a github.com/owner/repo dentro de la carpeta de arriba, como en ghq.", "bee548d674abd0d2": "Restablecer clonar en carpetas del host al valor predeterminado", + "30cc3b0b7c5223f9": "Equipos", + "f42c4d6d05dfcacf": "Tableros", + "24b5619c501032bf": "Reactiva, pospone o resuelve hilos cuando cambia el estado de una issue vinculada.", + "647234c5dc75e791": "Añadir equipo", + "2f3d6b74fac5b143": "Añadir tablero", + "7692d28fbe45f1cd": "Todos los equipos ya tienen una regla.", + "58a6276de6d8988e": "Todos los tableros ya tienen una regla.", + "0ca7ece5adb2141b": "Añade un equipo para organizar los hilos vinculados a sus issues.", + "ade2fad0438c0ef7": "Añade un tablero para organizar los hilos vinculados a sus issues.", + "f903e7f0ca23602c": "Reactivar", "ef27c4211844aef9": "Posponer", "4df30d44eb0b0728": "Reanuda automáticamente los hilos cuando se restablecen sus límites de uso. Puedes cancelar la reanudación automática en cada hilo.", "0769f91ca46e3003": "Pospone los hilos hasta que se restablezcan sus límites de uso. Activa la reanudación automática para que el agente continúe tras el restablecimiento.", @@ -11953,6 +11976,8 @@ "a22700a2aa679898": "Método de merge predeterminado", "c4548ce84893201b": "pull request fusionar squash rebase último seleccionado", "f6c5ffe0b40ce8e2": "linear jira issues gestor equipo clave api conectar vincular proyecto", + "03c5083adeb3ac5e": "Reglas de estado de issues", + "5f4cd500513df9ca": "linear equipo jira tablero issue estado flujo reactivar posponer resolver hilo", "a4380762611c94e4": "Control de versiones", "2f251b69a6c324f3": "Intervalo de git fetch", "deed4a583dfa2c44": "automático remoto rama actualizar segundo plano credenciales llaves de seguridad segundos desactivado", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index f5cf7e62a4744..f76edd3cba68f 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -8748,6 +8748,19 @@ ], "e913ae62f3907911": "Vous êtes déconnecté de ses sites. Les onglets du navigateur serveur ouverts dans ce profil se ferment maintenant.", "7a4464dfc6c856e5": "Effacer les données", + "13e6f2309e418404": "Clore", + "470388c152e293cb": "La règle n’a pas pu être enregistrée.", + "7c8c86f94f9d13bf": "Cette règle appartient à un autre espace de travail. Ajoutez de nouveau l’équipe ou le tableau pour l’utiliser ici.", + "5efcecd685ad1dac": "La dernière vérification des statuts a échoué. Les fils sont restés inchangés.", + "63c5271568e4f9c6": "S’applique aux fils liés aux tickets de cette équipe, dans tous les projets.", + "0cc9c4463ea35891": "S’applique aux fils liés aux tickets de ce tableau, dans tous les projets.", + "666b6f323f7f3274": "Activer la règle", + "7792add570638f64": "Retirer l’équipe", + "65d7900a7a9d57e7": "Retirer le tableau", + "245038c3d0fc7c5e": "Ajouter un statut à {bucket}", + "da5ac1b89bbc2e15": "Chaque statut est déjà dans un groupe.", + "183dc01e105d82e5": "Retirer {status}", + "bf5602410d695db3": "Abandonner", "92da88ddc3c21020": "Gestionnaires de tickets", "58e0e226493150e7": "Impossible de charger les gestionnaires de tickets", "77cfcbde543df32d": "Afficher ou masquer les détails de {tracker}", @@ -10204,6 +10217,16 @@ "f9b912a818bd869d": "Réinitialiser le répertoire de base pour l’ajout de projets à la valeur par défaut", "6fc9e5e722cf3c73": "Les clones vont dans github.com/owner/repo sous le dossier ci-dessus, comme ghq.", "bee548d674abd0d2": "Réinitialiser le clonage dans les dossiers de l’hôte à la valeur par défaut", + "30cc3b0b7c5223f9": "Équipes", + "f42c4d6d05dfcacf": "Tableaux", + "24b5619c501032bf": "Réveillez, reportez ou closez des fils quand le statut d’un ticket lié change.", + "647234c5dc75e791": "Ajouter une équipe", + "2f3d6b74fac5b143": "Ajouter un tableau", + "7692d28fbe45f1cd": "Chaque équipe a déjà une règle.", + "58a6276de6d8988e": "Chaque tableau a déjà une règle.", + "0ca7ece5adb2141b": "Ajoutez une équipe pour organiser les fils liés à ses tickets.", + "ade2fad0438c0ef7": "Ajoutez un tableau pour organiser les fils liés à ses tickets.", + "f903e7f0ca23602c": "Réveiller", "ef27c4211844aef9": "Report", "4df30d44eb0b0728": "Reprend automatiquement les fils quand leurs limites d’utilisation sont réinitialisées. Vous pouvez annuler la reprise automatique dans chaque fil.", "0769f91ca46e3003": "Reporte les fils jusqu’à la réinitialisation de leurs limites d’utilisation. Activez la reprise automatique pour que l’agent continue après la réinitialisation.", @@ -11958,6 +11981,8 @@ "a22700a2aa679898": "Méthode de fusion par défaut", "c4548ce84893201b": "pull request fusion squash rebase dernière sélection", "f6c5ffe0b40ce8e2": "linear jira tickets gestionnaire équipe clé api connecter lier projet", + "03c5083adeb3ac5e": "Règles de statut des tickets", + "5f4cd500513df9ca": "linear équipe jira tableau ticket statut workflow réveiller reporter clore fil", "a4380762611c94e4": "Gestion de versions", "2f251b69a6c324f3": "Intervalle de git fetch", "deed4a583dfa2c44": "automatique branche distante actualisation arrière-plan identifiants clés de sécurité secondes désactivé", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 7e3be343b068b..7c45702ae0c27 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -8705,6 +8705,19 @@ ], "e913ae62f3907911": "各サイトからサインアウトされます。このプロファイルで開いているサーバーのブラウザータブはすぐに閉じます。", "7a4464dfc6c856e5": "データを消去", + "13e6f2309e418404": "対応済みにする", + "470388c152e293cb": "ルールを保存できませんでした。", + "7c8c86f94f9d13bf": "このルールは別のワークスペースのものです。ここで使うには、チームまたはボードを追加し直してください。", + "5efcecd685ad1dac": "前回のステータス確認に失敗しました。スレッドはそのままです。", + "63c5271568e4f9c6": "すべてのプロジェクトで、このチームの Issue にリンクされたスレッドに適用されます。", + "0cc9c4463ea35891": "すべてのプロジェクトで、このボードの Issue にリンクされたスレッドに適用されます。", + "666b6f323f7f3274": "ルールを有効にする", + "7792add570638f64": "チームを削除", + "65d7900a7a9d57e7": "ボードを削除", + "245038c3d0fc7c5e": "{bucket} にステータスを追加", + "da5ac1b89bbc2e15": "すべてのステータスが割り当て済みです。", + "183dc01e105d82e5": "{status} を削除", + "bf5602410d695db3": "破棄", "92da88ddc3c21020": "Issue トラッカー", "58e0e226493150e7": "Issue トラッカーを読み込めませんでした", "77cfcbde543df32d": "{tracker} の詳細を切り替え", @@ -10157,6 +10170,16 @@ "f9b912a818bd869d": "プロジェクト追加のベースディレクトリをデフォルトにリセット", "6fc9e5e722cf3c73": "ghq と同様に、上のフォルダーの下の github.com/owner/repo にクローンします。", "bee548d674abd0d2": "「ホスト別フォルダーにクローン」をデフォルトにリセット", + "30cc3b0b7c5223f9": "チーム", + "f42c4d6d05dfcacf": "ボード", + "24b5619c501032bf": "リンクされた Issue のステータスが変わったときに、スレッドを再開、スヌーズ、または対応済みにします。", + "647234c5dc75e791": "チームを追加", + "2f3d6b74fac5b143": "ボードを追加", + "7692d28fbe45f1cd": "すべてのチームにルールがあります。", + "58a6276de6d8988e": "すべてのボードにルールがあります。", + "0ca7ece5adb2141b": "チームを追加すると、その Issue にリンクされたスレッドを整理します。", + "ade2fad0438c0ef7": "ボードを追加すると、その Issue にリンクされたスレッドを整理します。", + "f903e7f0ca23602c": "再開", "ef27c4211844aef9": "スヌーズ", "4df30d44eb0b0728": "使用量の上限がリセットされたら、スレッドを自動的に再開します。自動再開は各スレッドでキャンセルできます。", "0769f91ca46e3003": "使用量の上限がリセットされるまでスレッドをスヌーズします。リセット後にエージェントを続行するには、自動再開を有効にしてください。", @@ -11909,6 +11932,8 @@ "a22700a2aa679898": "デフォルトのマージ方法", "c4548ce84893201b": "プルリクエスト マージ スカッシュ リベース 前回選択 merge method", "f6c5ffe0b40ce8e2": "linear jira issue トラッカー チーム api キー 接続 バインド プロジェクト", + "03c5083adeb3ac5e": "Issue ステータスのルール", + "5f4cd500513df9ca": "linear チーム jira ボード issue ステータス ワークフロー 再開 スヌーズ 対応済み スレッド", "a4380762611c94e4": "ソース管理", "2f251b69a6c324f3": "Git フェッチの間隔", "deed4a583dfa2c44": "自動 リモート ブランチ 更新 バックグラウンド 資格情報 セキュリティキー 秒 オフ fetch", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index ef69858aead11..79708093e1bb0 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -8708,6 +8708,19 @@ ], "e913ae62f3907911": "해당 사이트에서 로그아웃됩니다. 이 프로필로 열린 서버 브라우저 탭은 지금 닫힙니다.", "7a4464dfc6c856e5": "데이터 지우기", + "13e6f2309e418404": "정리", + "470388c152e293cb": "규칙을 저장하지 못했습니다.", + "7c8c86f94f9d13bf": "이 규칙은 다른 워크스페이스에 속합니다. 여기서 사용하려면 팀이나 보드를 다시 추가하세요.", + "5efcecd685ad1dac": "마지막 상태 확인에 실패했습니다. 스레드는 그대로 두었습니다.", + "63c5271568e4f9c6": "모든 프로젝트에서 이 팀의 이슈에 연결된 스레드에 적용됩니다.", + "0cc9c4463ea35891": "모든 프로젝트에서 이 보드의 이슈에 연결된 스레드에 적용됩니다.", + "666b6f323f7f3274": "규칙 사용", + "7792add570638f64": "팀 제거", + "65d7900a7a9d57e7": "보드 제거", + "245038c3d0fc7c5e": "{bucket}에 상태 추가", + "da5ac1b89bbc2e15": "모든 상태가 이미 배정되었습니다.", + "183dc01e105d82e5": "{status} 제거", + "bf5602410d695db3": "버리기", "92da88ddc3c21020": "이슈 트래커", "58e0e226493150e7": "이슈 트래커를 불러올 수 없습니다", "77cfcbde543df32d": "{tracker} 세부 정보 전환", @@ -10159,6 +10172,16 @@ "f9b912a818bd869d": "프로젝트 추가 기본 디렉터리 기본값으로 재설정", "6fc9e5e722cf3c73": "ghq처럼 위 폴더 아래 github.com/owner/repo에 복제합니다.", "bee548d674abd0d2": "호스트 폴더로 복제 기본값으로 재설정", + "30cc3b0b7c5223f9": "팀", + "f42c4d6d05dfcacf": "보드", + "24b5619c501032bf": "연결된 이슈의 상태가 바뀌면 스레드를 깨우거나, 다시 알림으로 미루거나, 정리합니다.", + "647234c5dc75e791": "팀 추가", + "2f3d6b74fac5b143": "보드 추가", + "7692d28fbe45f1cd": "모든 팀에 이미 규칙이 있습니다.", + "58a6276de6d8988e": "모든 보드에 이미 규칙이 있습니다.", + "0ca7ece5adb2141b": "팀을 추가하면 해당 팀의 이슈에 연결된 스레드를 정리합니다.", + "ade2fad0438c0ef7": "보드를 추가하면 해당 보드의 이슈에 연결된 스레드를 정리합니다.", + "f903e7f0ca23602c": "깨우기", "ef27c4211844aef9": "다시 알림", "4df30d44eb0b0728": "사용량 한도가 초기화되면 스레드를 자동으로 재개합니다. 각 스레드에서 자동 재개를 취소할 수 있습니다.", "0769f91ca46e3003": "사용량 한도가 초기화될 때까지 스레드를 미룹니다. 초기화 후 에이전트를 계속하려면 자동 재개를 사용하세요.", @@ -11905,6 +11928,8 @@ "a22700a2aa679898": "기본 병합 방법", "c4548ce84893201b": "풀 리퀘스트 병합 스쿼시 리베이스 마지막 선택", "f6c5ffe0b40ce8e2": "linear jira 이슈 트래커 팀 api 키 연결 바인딩 프로젝트", + "03c5083adeb3ac5e": "이슈 상태 규칙", + "5f4cd500513df9ca": "linear 팀 jira 보드 이슈 상태 워크플로 깨우기 다시 알림 정리 스레드", "a4380762611c94e4": "소스 제어", "2f251b69a6c324f3": "Git fetch 간격", "deed4a583dfa2c44": "자동 원격 브랜치 새로 고침 백그라운드 자격 증명 보안 키 초 끔", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b2f82a27a416..53d06f49e1694 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -8747,6 +8747,19 @@ ], "e913ae62f3907911": "Você será desconectado dos sites dele. As abas do navegador do servidor abertas neste perfil fecham agora.", "7a4464dfc6c856e5": "Limpar dados", + "13e6f2309e418404": "Concluir", + "470388c152e293cb": "Não foi possível salvar a regra.", + "7c8c86f94f9d13bf": "Esta regra pertence a outro espaço de trabalho. Adicione a equipe ou o quadro novamente para usá-la aqui.", + "5efcecd685ad1dac": "A última verificação de status falhou. As threads ficaram como estavam.", + "63c5271568e4f9c6": "Vale para threads vinculadas às issues desta equipe, em todos os projetos.", + "0cc9c4463ea35891": "Vale para threads vinculadas às issues deste quadro, em todos os projetos.", + "666b6f323f7f3274": "Ativar regra", + "7792add570638f64": "Remover equipe", + "65d7900a7a9d57e7": "Remover quadro", + "245038c3d0fc7c5e": "Adicionar um status a {bucket}", + "da5ac1b89bbc2e15": "Todos os status já estão em um grupo.", + "183dc01e105d82e5": "Remover {status}", + "bf5602410d695db3": "Descartar", "92da88ddc3c21020": "Rastreadores de issues", "58e0e226493150e7": "Não foi possível carregar os rastreadores de issues", "77cfcbde543df32d": "Mostrar ou ocultar detalhes de {tracker}", @@ -10204,6 +10217,16 @@ "f9b912a818bd869d": "Redefinir o diretório base para adicionar projetos para o padrão", "6fc9e5e722cf3c73": "Os clones vão para github.com/owner/repo dentro da pasta acima, como no ghq.", "bee548d674abd0d2": "Redefinir a clonagem em pastas por host para o padrão", + "30cc3b0b7c5223f9": "Equipes", + "f42c4d6d05dfcacf": "Quadros", + "24b5619c501032bf": "Desperte, adie ou conclua threads quando o status de uma issue vinculada mudar.", + "647234c5dc75e791": "Adicionar equipe", + "2f3d6b74fac5b143": "Adicionar quadro", + "7692d28fbe45f1cd": "Todas as equipes já têm uma regra.", + "58a6276de6d8988e": "Todos os quadros já têm uma regra.", + "0ca7ece5adb2141b": "Adicione uma equipe para organizar as threads vinculadas às issues dela.", + "ade2fad0438c0ef7": "Adicione um quadro para organizar as threads vinculadas às issues dele.", + "f903e7f0ca23602c": "Despertar", "ef27c4211844aef9": "Adiar", "4df30d44eb0b0728": "Retoma as threads automaticamente quando os limites de uso delas forem redefinidos. Você pode cancelar a retomada automática em cada thread.", "0769f91ca46e3003": "Adia as threads até os limites de uso delas serem redefinidos. Ative a retomada automática para continuar o agente após a redefinição.", @@ -11958,6 +11981,8 @@ "a22700a2aa679898": "Método de merge padrão", "c4548ce84893201b": "pull request merge mesclar squash rebase último selecionado", "f6c5ffe0b40ce8e2": "linear jira issues rastreador equipe chave api conectar vincular projeto", + "03c5083adeb3ac5e": "Regras de status de issues", + "5f4cd500513df9ca": "linear equipe jira quadro issue status fluxo despertar adiar concluir thread", "a4380762611c94e4": "Controle de versão", "2f251b69a6c324f3": "Intervalo do git fetch", "deed4a583dfa2c44": "automático remoto branch atualização em segundo plano credenciais chaves de segurança segundos desativado", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 2891cb8165d7c..0149ce75cdbc9 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -8749,6 +8749,19 @@ ], "e913ae62f3907911": "Вы выйдете из аккаунтов на его сайтах. Вкладки серверного браузера, открытые в этом профиле, закроются сейчас.", "7a4464dfc6c856e5": "Очистить данные", + "13e6f2309e418404": "Разобрать", + "470388c152e293cb": "Не удалось сохранить правило.", + "7c8c86f94f9d13bf": "Это правило относится к другому рабочему пространству. Чтобы использовать его здесь, добавьте команду или доску заново.", + "5efcecd685ad1dac": "Последняя проверка статусов не удалась. Треды оставлены как есть.", + "63c5271568e4f9c6": "Действует для тредов, связанных с issue этой команды, во всех проектах.", + "0cc9c4463ea35891": "Действует для тредов, связанных с issue этой доски, во всех проектах.", + "666b6f323f7f3274": "Включить правило", + "7792add570638f64": "Удалить команду", + "65d7900a7a9d57e7": "Удалить доску", + "245038c3d0fc7c5e": "Добавить статус в «{bucket}»", + "da5ac1b89bbc2e15": "Все статусы уже распределены.", + "183dc01e105d82e5": "Удалить «{status}»", + "bf5602410d695db3": "Отменить", "92da88ddc3c21020": "Issue-трекеры", "58e0e226493150e7": "Не удалось загрузить issue-трекеры", "77cfcbde543df32d": "Показать или скрыть подробности {tracker}", @@ -10207,6 +10220,16 @@ "f9b912a818bd869d": "Сбросить базовый каталог для добавления проектов к значению по умолчанию", "6fc9e5e722cf3c73": "Клоны попадают в github.com/owner/repo внутри папки выше, как в ghq.", "bee548d674abd0d2": "Сбросить клонирование в папки хоста к значению по умолчанию", + "30cc3b0b7c5223f9": "Команды", + "f42c4d6d05dfcacf": "Доски", + "24b5619c501032bf": "Будит, откладывает или разбирает треды, когда меняется статус связанной issue.", + "647234c5dc75e791": "Добавить команду", + "2f3d6b74fac5b143": "Добавить доску", + "7692d28fbe45f1cd": "У каждой команды уже есть правило.", + "58a6276de6d8988e": "У каждой доски уже есть правило.", + "0ca7ece5adb2141b": "Добавьте команду, чтобы упорядочивать треды, связанные с её issue.", + "ade2fad0438c0ef7": "Добавьте доску, чтобы упорядочивать треды, связанные с её issue.", + "f903e7f0ca23602c": "Разбудить", "ef27c4211844aef9": "Отложить", "4df30d44eb0b0728": "Автоматически возобновлять треды при сбросе лимитов использования. Автовозобновление можно отменить в каждом треде.", "0769f91ca46e3003": "Откладывать треды до сброса лимитов использования. Включите автовозобновление, чтобы агент продолжил после сброса.", @@ -11959,6 +11982,8 @@ "a22700a2aa679898": "Способ слияния по умолчанию", "c4548ce84893201b": "пул-реквест слияние squash rebase последний выбранный", "f6c5ffe0b40ce8e2": "linear jira issue трекер задачи команда api ключ подключить привязать проект", + "03c5083adeb3ac5e": "Правила статусов issue", + "5f4cd500513df9ca": "linear команда jira доска issue статус процесс разбудить отложить разобрать тред", "a4380762611c94e4": "Контроль версий", "2f251b69a6c324f3": "Интервал git fetch", "deed4a583dfa2c44": "автоматическое обновление удалённых веток фон учётные данные ключи безопасности секунды выкл", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index c792d6fb4a981..d8b6e85ae056b 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -8755,6 +8755,19 @@ ], "e913ae62f3907911": "Du loggas ut från dess webbplatser. Serverns webbläsarflikar som är öppna i profilen stängs nu.", "7a4464dfc6c856e5": "Rensa data", + "13e6f2309e418404": "Markera som klar", + "470388c152e293cb": "Regeln kunde inte sparas.", + "7c8c86f94f9d13bf": "Den här regeln hör till en annan arbetsyta. Lägg till teamet eller tavlan igen för att använda den här.", + "5efcecd685ad1dac": "Den senaste statuskontrollen misslyckades. Trådarna lämnades som de var.", + "63c5271568e4f9c6": "Gäller trådar som är länkade till teamets ärenden, i alla projekt.", + "0cc9c4463ea35891": "Gäller trådar som är länkade till tavlans ärenden, i alla projekt.", + "666b6f323f7f3274": "Aktivera regel", + "7792add570638f64": "Ta bort team", + "65d7900a7a9d57e7": "Ta bort tavla", + "245038c3d0fc7c5e": "Lägg till en status i {bucket}", + "da5ac1b89bbc2e15": "Alla statusar är redan placerade.", + "183dc01e105d82e5": "Ta bort {status}", + "bf5602410d695db3": "Kasta", "92da88ddc3c21020": "Ärendehanterare", "58e0e226493150e7": "Kunde inte läsa in ärendehanterare", "77cfcbde543df32d": "Visa/dölj detaljer för {tracker}", @@ -10212,6 +10225,16 @@ "f9b912a818bd869d": "Återställ baskatalog för nya projekt till standard", "6fc9e5e722cf3c73": "Kloner hamnar i github.com/owner/repo under mappen ovan, som ghq.", "bee548d674abd0d2": "Återställ kloning till värdmappar till standard", + "30cc3b0b7c5223f9": "Team", + "f42c4d6d05dfcacf": "Tavlor", + "24b5619c501032bf": "Väck, snooza eller markera trådar som klara när statusen för ett länkat ärende ändras.", + "647234c5dc75e791": "Lägg till team", + "2f3d6b74fac5b143": "Lägg till tavla", + "7692d28fbe45f1cd": "Alla team har redan en regel.", + "58a6276de6d8988e": "Alla tavlor har redan en regel.", + "0ca7ece5adb2141b": "Lägg till ett team för att ordna trådarna som är länkade till dess ärenden.", + "ade2fad0438c0ef7": "Lägg till en tavla för att ordna trådarna som är länkade till dess ärenden.", + "f903e7f0ca23602c": "Väck", "ef27c4211844aef9": "Snooza", "4df30d44eb0b0728": "Återuppta trådar automatiskt när deras användningsgränser återställs. Du kan avbryta automatisk återupptagning i varje tråd.", "0769f91ca46e3003": "Snooza trådar tills deras användningsgränser återställs. Aktivera automatisk återupptagning för att fortsätta agenten efter återställningen.", @@ -11966,6 +11989,8 @@ "a22700a2aa679898": "Standardmetod för merge", "c4548ce84893201b": "pull request merge squash rebase senast vald", "f6c5ffe0b40ce8e2": "linear jira ärenden ärendehanterare team api-nyckel anslut koppla projekt issues", + "03c5083adeb3ac5e": "Regler för ärendestatus", + "5f4cd500513df9ca": "linear team jira tavla ärende status arbetsflöde väck snooza klar tråd", "a4380762611c94e4": "Versionshantering", "2f251b69a6c324f3": "Intervall för Git-fetch", "deed4a583dfa2c44": "automatisk fjärrgren uppdatera bakgrund autentiseringsuppgifter säkerhetsnycklar sekunder av fetch", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index cd80e9a35102a..a1c7eece5c793 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -8765,6 +8765,19 @@ ], "e913ae62f3907911": "你将退出此浏览器配置中各网站的登录。服务器上使用此配置的浏览器标签页会立即关闭。", "7a4464dfc6c856e5": "清除数据", + "13e6f2309e418404": "收尾", + "470388c152e293cb": "无法保存规则。", + "7c8c86f94f9d13bf": "此规则属于另一个工作区。要在这里使用,请重新添加该团队或看板。", + "5efcecd685ad1dac": "上次状态检查失败。线程保持不变。", + "63c5271568e4f9c6": "适用于所有项目中关联到此团队 issue 的线程。", + "0cc9c4463ea35891": "适用于所有项目中关联到此看板 issue 的线程。", + "666b6f323f7f3274": "启用规则", + "7792add570638f64": "移除团队", + "65d7900a7a9d57e7": "移除看板", + "245038c3d0fc7c5e": "向{bucket}添加状态", + "da5ac1b89bbc2e15": "所有状态都已分配。", + "183dc01e105d82e5": "移除{status}", + "bf5602410d695db3": "放弃", "92da88ddc3c21020": "issue 跟踪器", "58e0e226493150e7": "无法加载 issue 跟踪器", "77cfcbde543df32d": "切换 {tracker} 详情", @@ -10220,6 +10233,16 @@ "f9b912a818bd869d": "重置添加项目基础目录为默认值", "6fc9e5e722cf3c73": "克隆的仓库会放到上方文件夹下的 github.com/owner/repo 中,与 ghq 相同。", "bee548d674abd0d2": "重置克隆到主机文件夹为默认值", + "30cc3b0b7c5223f9": "团队", + "f42c4d6d05dfcacf": "看板", + "24b5619c501032bf": "当关联 issue 的状态变化时,唤醒、暂缓或收尾线程。", + "647234c5dc75e791": "添加团队", + "2f3d6b74fac5b143": "添加看板", + "7692d28fbe45f1cd": "每个团队都已有规则。", + "58a6276de6d8988e": "每个看板都已有规则。", + "0ca7ece5adb2141b": "添加团队,以整理关联到其 issue 的线程。", + "ade2fad0438c0ef7": "添加看板,以整理关联到其 issue 的线程。", + "f903e7f0ca23602c": "唤醒", "ef27c4211844aef9": "暂缓", "4df30d44eb0b0728": "用量限制重置后自动继续会话。你可以在每个会话中取消自动继续。", "0769f91ca46e3003": "将会话暂缓到用量限制重置。开启自动继续后,智能体会在重置后接着工作。", @@ -11983,6 +12006,8 @@ "a22700a2aa679898": "默认合并方式", "c4548ce84893201b": "PR 合并 压缩 变基 上次选择", "f6c5ffe0b40ce8e2": "linear jira issue 跟踪器 团队 api 密钥 连接 绑定 项目", + "03c5083adeb3ac5e": "issue 状态规则", + "5f4cd500513df9ca": "linear 团队 jira 看板 issue 状态 工作流 唤醒 暂缓 收尾 线程", "a4380762611c94e4": "版本控制", "2f251b69a6c324f3": "Git 获取间隔", "deed4a583dfa2c44": "自动 远程分支 刷新 后台 凭据 安全 密钥 秒 关闭", diff --git a/docs/user/source-control.md b/docs/user/source-control.md index ba951c3fe9bda..4764a735a8e29 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -434,6 +434,23 @@ work on with the `link_issue` tool. Writing to a tracker over a remote connection requires the `source-control:write` scope. +### Organize threads by issue status + +Threads can follow the status of the issues linked to them. Open the connected tracker under +**Settings → Source control & issues**, choose **Add team**, and use the **+** buttons to put the +team's statuses in **Wake**, **Snooze**, or **Settle**. The rule applies to every thread linked +to one of the team's issues, in any project. It changes threads, never issues. Linear is the +supported tracker. + +The server checks linked issues about once a minute while it runs, with or without a client +open. Only a status change counts: saving a rule records the current statuses first, and a thread +you organize by hand stays that way until one of its issues moves again. A thread with several +linked issues wakes when any of them maps to **Wake**, settles only when all of them map to +**Settle**, and otherwise snoozes. A status in no bucket, or one that could not be read, leaves +the thread as it is. A snooze from a rule has no wake time; the thread shows **∞** in the +Snoozed list until a status change, **Wake thread**, or a message wakes it. A thread with work +still running waits until it is idle before it snoozes or settles. + ## GitHub stacks The Pull requests page shows each PR's position in its GitHub stack. Open the stack badge in a diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 0ea95420460a7..22c5414c9baf2 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -132,7 +132,8 @@ export interface ReorderActiveThreadInput extends ThreadCommandInput { } export interface SnoozeThreadInput extends ThreadCommandInput { - readonly snoozedUntil: string; + /** Null snoozes until the thread is woken. */ + readonly snoozedUntil: string | null; } export interface UnsnoozeThreadInput extends ThreadCommandInput { diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index d86da6082dc29..aca2f5b76f2a7 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -81,6 +81,7 @@ export type EnvironmentSubscriptionRpcTag = | typeof WS_METHODS.subscribeDeviceState | typeof WS_METHODS.subscribeResourceTelemetry | typeof WS_METHODS.pullRequestsSubscribeRefreshes + | typeof WS_METHODS.issuesSubscribeStatusRefreshes | typeof WS_METHODS.pullRequestsSubscribeLinkedThreadRefreshes | typeof WS_METHODS.subscribeVcsStatus | typeof WS_METHODS.subscribeVcsBranch diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index a3b1861ca0351..73f3a611cccd0 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -179,25 +179,27 @@ describe("command permissions", () => { }), ); - it.effect.each([WS_METHODS.serverCheckOtlpEndpoint, WS_METHODS.serverCheckSecretSource])( - "requires the destination settings grant for %s", - (method) => - Effect.gen(function* () { - const registry = yield* setup; - const check = createCommandPermissions(runtime, method); - registry.set(sessions(env), AsyncResult.success(grant(true))); - expect(registry.get(check.permissionAtom(env))).toBe(false); - registry.set( - sessions(env), - AsyncResult.success({ - ...grant(false), - scopes: [AuthSettingsWriteScope], - permissions: [AuthSettingsWriteScope], - }), - ); - expect(registry.get(check.permissionAtom(env))).toBe(true); - yield* check.authorize(registry, env); - }), + it.effect.each([ + WS_METHODS.serverCheckOtlpEndpoint, + WS_METHODS.serverCheckSecretSource, + WS_METHODS.issueTrackersSaveAutomation, + ])("requires the destination settings grant for %s", (method) => + Effect.gen(function* () { + const registry = yield* setup; + const check = createCommandPermissions(runtime, method); + registry.set(sessions(env), AsyncResult.success(grant(true))); + expect(registry.get(check.permissionAtom(env))).toBe(false); + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(false), + scopes: [AuthSettingsWriteScope], + permissions: [AuthSettingsWriteScope], + }), + ); + expect(registry.get(check.permissionAtom(env))).toBe(true); + yield* check.authorize(registry, env); + }), ); it.effect("requires the destination settings grant to connect or bind an issue tracker", () => diff --git a/packages/client-runtime/src/state/issueTrackers.ts b/packages/client-runtime/src/state/issueTrackers.ts index 74c6bfb0674d8..5d549cd6236db 100644 --- a/packages/client-runtime/src/state/issueTrackers.ts +++ b/packages/client-runtime/src/state/issueTrackers.ts @@ -34,6 +34,14 @@ export function createIssueTrackerEnvironmentAtoms( label: "environment-data:issue-trackers:connections", tag: WS_METHODS.issueTrackersList, }); + const automation = createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:issue-trackers:automation", + tag: WS_METHODS.issueTrackersAutomation, + }); + const automationCatalog = createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:issue-trackers:automation-catalog", + tag: WS_METHODS.issueTrackersAutomationCatalog, + }); const refresh = (environmentId: Parameters[0]["environmentId"]) => connections({ environmentId, input: {} }); // Connect, disconnect and bind all edit one environment's tracker state; serialized so a @@ -44,6 +52,21 @@ export function createIssueTrackerEnvironmentAtoms( }; return { connections, + /** Issue status rules, and how each one's last status read went. */ + automation, + /** A tracker's teams or boards, and with `containerId` that one's workflow statuses. */ + automationCatalog, + /** Saves a rule the tracker can reach, or removes one with a null rule. */ + saveAutomation: createEnvironmentRpcCommand(runtime, { + label: "environment-data:issue-trackers:save-automation", + tag: WS_METHODS.issueTrackersSaveAutomation, + scheduler: commandScheduler, + concurrency: serialPerEnvironment, + onSettled: (target, registry) => + Effect.sync(() => + registry.refresh(automation({ environmentId: target.environmentId, input: {} })), + ), + }), /** Saves a credential the tracker accepted, or removes the stored one with a null token. */ connect: createEnvironmentRpcCommand(runtime, { label: "environment-data:issue-trackers:connect", diff --git a/packages/client-runtime/src/state/issues.ts b/packages/client-runtime/src/state/issues.ts index 6e482c33febb4..95195430b44a8 100644 --- a/packages/client-runtime/src/state/issues.ts +++ b/packages/client-runtime/src/state/issues.ts @@ -170,10 +170,20 @@ export function createIssueEnvironmentAtoms( mode: "serial", key: ({ environmentId }: { readonly environmentId: string }) => environmentId, } as const; + const statusRefreshes = createEnvironmentRpcSubscriptionAtomFamily(runtime, { + label: "environment-data:issues:status-refreshes", + tag: WS_METHODS.issuesSubscribeStatusRefreshes, + }); const detail = createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:issues:detail", tag: WS_METHODS.issuesDetail, staleTimeMs: 30_000, + // An issue status rule saw this issue move, so an open detail reads it again. + refreshTrigger: ({ environmentId, input }) => + statusRefreshes({ + environmentId, + input: { tracker: input.tracker, key: input.key.toUpperCase() }, + }), }); const detailRef = ({ projectId, tracker, host, scope, key }: IssueRef): IssueRef => ({ projectId, diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index 98d88407b85b4..3c644a3bb5fe7 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -568,11 +568,13 @@ export function createThreadEnvironmentAtoms( ((thread.pendingRuntimeRequest !== null && thread.pendingRuntimeRequest.kind !== "user_input") || ["preparing", "queued", "starting"].includes(thread.status))) || - !(Date.parse(input.snoozedUntil) > DateTime.toEpochMillis(now)) + (input.snoozedUntil !== null && + !(Date.parse(input.snoozedUntil) > DateTime.toEpochMillis(now))) ? thread : { ...thread, - snoozedUntil: DateTime.makeUnsafe(input.snoozedUntil), + snoozedUntil: + input.snoozedUntil === null ? null : DateTime.makeUnsafe(input.snoozedUntil), snoozedAt: now, }, ), diff --git a/packages/client-runtime/src/state/threadSettled.ts b/packages/client-runtime/src/state/threadSettled.ts index 25ff6a8f5bfa6..5cb698a65cf04 100644 --- a/packages/client-runtime/src/state/threadSettled.ts +++ b/packages/client-runtime/src/state/threadSettled.ts @@ -159,7 +159,9 @@ export function effectiveSnoozed( shell: ThreadSnoozeShell, options: { readonly now: string }, ): boolean { - if (shell.snoozedUntil == null) return false; + // With no wake time, a snooze holds until the thread is woken. + if (shell.snoozedUntil == null) + return shell.snoozedAt != null && !threadRaisedHandWhileSnoozed(shell); const wakeAtMs = Date.parse(shell.snoozedUntil); if (Number.isNaN(wakeAtMs)) return false; if (wakeAtMs <= Date.parse(options.now)) return false; @@ -170,8 +172,9 @@ export function threadWokeAt( shell: ThreadSnoozeShell, options: { readonly now: string }, ): string | null { - if (shell.snoozedUntil == null) return null; - const wakeAtMs = Date.parse(shell.snoozedUntil); + if (shell.snoozedUntil == null && shell.snoozedAt == null) return null; + const wakeAtMs = + shell.snoozedUntil == null ? Number.POSITIVE_INFINITY : Date.parse(shell.snoozedUntil); if (Number.isNaN(wakeAtMs)) return null; // An early hand-raise wake stays authoritative even after the scheduled // wake time passes: reporting snoozedUntil then would resurface a Woke @@ -194,7 +197,7 @@ export function threadWokeAt( const runtime = shell.runtime ?? shell.session ?? null; return runtime?.updatedAt ?? shell.snoozedAt ?? null; } - return wakeAtMs <= Date.parse(options.now) ? shell.snoozedUntil : null; + return wakeAtMs <= Date.parse(options.now) ? (shell.snoozedUntil ?? null) : null; } const HOUR_MS = 60 * 60 * 1_000; @@ -398,10 +401,11 @@ export function pickSnoozePreset(input: { } export function snoozeWakeLabel( - snoozedUntil: string, + snoozedUntil: string | null, options: { readonly now: string }, resolve: MFunctionType = mFallback, ): string { + if (snoozedUntil === null) return "∞"; const wakeMs = Date.parse(snoozedUntil); const nowMs = Date.parse(options.now); const now = () => resolve(msg("now", { $context: "a snoozed thread wakes now" })); diff --git a/packages/client-runtime/src/state/threadSnoozed.test.ts b/packages/client-runtime/src/state/threadSnoozed.test.ts index fa5561025c85c..a982b9baee7b6 100644 --- a/packages/client-runtime/src/state/threadSnoozed.test.ts +++ b/packages/client-runtime/src/state/threadSnoozed.test.ts @@ -78,6 +78,20 @@ function makeQueuedTurnShell(overrides: Partial = {}): QueuedTu } describe("effectiveSnoozed", () => { + it("holds a snooze with no wake time until a new question wakes it", () => { + const shell = makeShell({ snoozedUntil: null, snoozedAt: SNOOZED_AT }); + expect(effectiveSnoozed(shell, { now: NOW })).toBe(true); + expect(threadWokeAt(shell, { now: NOW })).toBeNull(); + const asking = makeShell({ + snoozedAt: SNOOZED_AT, + pending: "user-input", + pendingUserInputAt: "2026-04-10T11:00:00.000Z", + }); + expect(effectiveSnoozed(asking, { now: NOW })).toBe(false); + expect(threadWokeAt(asking, { now: NOW })).toBe("2026-04-10T11:00:00.000Z"); + expect(effectiveSnoozed(makeShell({}), { now: NOW })).toBe(false); + }); + it("never hides on malformed wake data", () => { expect(effectiveSnoozed(makeShell({ snoozedUntil: "not-a-date" }), { now: NOW })).toBe(false); }); @@ -525,6 +539,7 @@ describe("snoozeWakeLabel", () => { expect(snoozeWakeLabel(wake, { now: "2026-04-10T12:01:00.000Z" })).toBe("59m"); expect(snoozeWakeLabel(wake, { now: "2026-04-10T13:00:10.000Z" })).toBe("1m"); expect(snoozeWakeLabel(wake, { now: "2026-04-10T13:00:30.000Z" })).toBe("now"); + expect(snoozeWakeLabel(null, { now: NOW })).toBe("∞"); }); }); diff --git a/packages/client-runtime/src/state/threadUndo.test.ts b/packages/client-runtime/src/state/threadUndo.test.ts new file mode 100644 index 0000000000000..accdc8837872f --- /dev/null +++ b/packages/client-runtime/src/state/threadUndo.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vite-plus/test"; +import { executeThreadUndo, planThreadUndo } from "./threadUndo.ts"; + +describe("planThreadUndo", () => { + it("restores a snooze with no wake time after undoing a settle", async () => { + const plan = planThreadUndo("settle", { + snoozedAt: "2026-11-17T00:00:00Z", + snoozedUntil: null, + }); + expect(plan).toEqual([ + { action: "unsettle", restoreUnsettledAt: null }, + { action: "snooze", snoozedUntil: null }, + ]); + const executed: string[] = []; + await executeThreadUndo( + plan, + async (step) => { + executed.push(step.action); + return true; + }, + (result) => result, + ); + expect(executed).toEqual(["unsettle", "snooze"]); + }); +}); diff --git a/packages/client-runtime/src/state/threadUndo.ts b/packages/client-runtime/src/state/threadUndo.ts index 20ea56400c284..4cd62f333569e 100644 --- a/packages/client-runtime/src/state/threadUndo.ts +++ b/packages/client-runtime/src/state/threadUndo.ts @@ -40,7 +40,8 @@ export type ThreadUndoStep = | { readonly action: "unsnooze" } | { readonly action: "pin"; readonly orderKey?: string } | { readonly action: "reorderActive"; readonly orderKey: string } - | { readonly action: "snooze"; readonly snoozedUntil: string }; + /** A null wake time restores a snooze that lasts until the thread is woken. */ + | { readonly action: "snooze"; readonly snoozedUntil: string | null }; export type ThreadUndoPlan = readonly [ThreadUndoStep, ...ThreadUndoStep[]]; @@ -52,6 +53,7 @@ export function planThreadUndo( readonly activeOrderKey?: string | null; readonly unsettledAt?: string | null; readonly snoozedUntil?: string | null; + readonly snoozedAt?: string | null; } | null, ): ThreadUndoPlan { if (action === "snooze") return [{ action: "unsnooze" }]; @@ -61,8 +63,8 @@ export function planThreadUndo( }; // Pinning clears snooze on the server; restore it after restoring pin placement. const snooze = - thread?.snoozedUntil != null - ? [{ action: "snooze" as const, snoozedUntil: thread.snoozedUntil }] + thread?.snoozedUntil != null || thread?.snoozedAt != null + ? [{ action: "snooze" as const, snoozedUntil: thread.snoozedUntil ?? null }] : []; if (action === "unpin") return [pin, ...snooze]; // Settling clears a manual active position; pinned threads are placed by their pin instead. @@ -88,8 +90,13 @@ export async function executeThreadUndo( for (const step of plan.slice(1)) { if (!succeeded(result)) return result; // A snooze can expire before Undo runs, and the server rejects an expired restore. - // @effect-diagnostics-next-line globalDate:off - if (step.action === "snooze" && Date.parse(step.snoozedUntil) <= Date.now()) continue; + if ( + step.action === "snooze" && + step.snoozedUntil !== null && + // @effect-diagnostics-next-line globalDate:off + Date.parse(step.snoozedUntil) <= Date.now() + ) + continue; result = await execute(step); } return result; diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index b23b4650b20a9..87ce60e4b86d3 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -48,9 +48,10 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.issuesUpdate]: AuthSourceControlWriteScope, [WS_METHODS.issuesSetState]: AuthSourceControlWriteScope, [WS_METHODS.issuesReact]: AuthSourceControlWriteScope, - // A tracker credential and a project's binding are settings, saved under the same grant. + // A tracker credential, a project's binding, and status rules are settings, under one grant. [WS_METHODS.issueTrackersConnect]: AuthSettingsWriteScope, [WS_METHODS.issueTrackersBindProject]: AuthSettingsWriteScope, + [WS_METHODS.issueTrackersSaveAutomation]: AuthSettingsWriteScope, // Writing a guide runs a model on this environment's providers, which reading one does not. [WS_METHODS.pullRequestsGenerateReviewGuide]: AuthOrchestrationOperateScope, [WS_METHODS.projectsCreateFromThread]: AuthOrchestrationOperateScope, diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 48ca2933b4039..501a1add06918 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -589,6 +589,8 @@ export const StandaloneIssueTrackerDescriptor = Schema.Struct({ /** Where to mint one, or null when the tracker has no stable page for it. */ helpUrl: Schema.NullOr(TrimmedNonEmptyString), }), + /** What issue status rules watch, when the tracker supports them: a Linear team, a Jira board. */ + automationContainer: Schema.optional(Schema.Literals(["team", "board"])), }); export type StandaloneIssueTrackerDescriptor = typeof StandaloneIssueTrackerDescriptor.Type; @@ -702,3 +704,80 @@ export class IssueTrackerConnectionError extends Schema.TaggedError()( + "IssueAutomationError", + { + operation: Schema.String, + detail: Schema.optional(TrimmedNonEmptyString), + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return this.detail ?? "Issue status automation could not complete this operation."; + } +} diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 8843d8cacf805..96129b676e81e 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -541,6 +541,7 @@ export const OrchestrationV2AppThread = Schema.Struct({ ), unsettledAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), + /** Set with no `snoozedUntil`, the thread is snoozed until it is woken. */ snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), lastSnoozeWakeAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecovery)), @@ -3404,7 +3405,8 @@ export const OrchestrationV2Command = Schema.Union([ type: Schema.Literal("thread.snooze"), commandId: CommandId, threadId: ThreadId, - snoozedUntil: IsoDateTime, + /** Null snoozes until someone or something wakes the thread. */ + snoozedUntil: Schema.NullOr(IsoDateTime), }), Schema.Struct({ type: Schema.Literal("thread.unsnooze"), @@ -3826,6 +3828,18 @@ export type OrchestrationV2Command = typeof OrchestrationV2Command.Type; // Excluded from dispatchCommand so only the server can send these. const OrchestrationV2InternalCommand = Schema.Union([ + /** + * A linked issue's status change, applied only if nothing organized the thread and no rule + * changed since the decision: `expectedRevision` and `rulesFingerprint` are what it saw. + */ + Schema.Struct({ + type: Schema.Literal("thread.issue-automation.apply"), + commandId: CommandId, + threadId: ThreadId, + action: Schema.Literals(["wake", "snooze", "settle"]), + expectedRevision: NonNegativeInt, + rulesFingerprint: Schema.String, + }), // The server issues this after checking the value against the run's declared schema. Schema.Struct({ type: Schema.Literal("run.output.submit"), diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index c7fe990a4be7e..3a81343a31012 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -195,6 +195,11 @@ import { } from "./provider.ts"; import { ProviderInstanceId, ProviderInstanceMutation } from "./providerInstance.ts"; import { + IssueAutomationCatalog, + IssueAutomationCatalogInput, + IssueAutomationError, + IssueAutomationOverview, + IssueAutomationSaveInput, IssueCandidates, IssueCommentInput, IssueCommentsPage, @@ -212,6 +217,7 @@ import { IssueSetStateInput, IssueTemplateList, IssueTrackerBindProjectInput, + IssueTrackerKind, IssueTrackerConnectInput, IssueTrackerConnection, IssueTrackerConnectionError, @@ -706,9 +712,13 @@ export const WS_METHODS = { issuesSetState: "issues.setState", issuesReact: "issues.react", issuesLinkedThreads: "issues.linkedThreads", + issuesSubscribeStatusRefreshes: "issues.subscribeStatusRefreshes", issueTrackersList: "issueTrackers.list", issueTrackersConnect: "issueTrackers.connect", issueTrackersBindProject: "issueTrackers.bindProject", + issueTrackersAutomation: "issueTrackers.automation", + issueTrackersAutomationCatalog: "issueTrackers.automationCatalog", + issueTrackersSaveAutomation: "issueTrackers.saveAutomation", sourceControlLookupRepository: "sourceControl.lookupRepository", sourceControlCloneRepository: "sourceControl.cloneRepository", @@ -1534,6 +1544,35 @@ const WsIssueTrackersBindProjectRpc = Rpc.make(WS_METHODS.issueTrackersBindProje error: IssueTrackerRpcError, }); +const IssueAutomationRpcError = Schema.Union([IssueAutomationError, EnvironmentAuthorizationError]); + +/** Issue status rules and how each one's last status read went. */ +const WsIssueTrackersAutomationRpc = Rpc.make(WS_METHODS.issueTrackersAutomation, { + payload: Schema.Struct({}), + success: IssueAutomationOverview, + error: IssueAutomationRpcError, +}); + +const WsIssueTrackersAutomationCatalogRpc = Rpc.make(WS_METHODS.issueTrackersAutomationCatalog, { + payload: IssueAutomationCatalogInput, + success: IssueAutomationCatalog, + error: IssueAutomationRpcError, +}); + +const WsIssueTrackersSaveAutomationRpc = Rpc.make(WS_METHODS.issueTrackersSaveAutomation, { + payload: IssueAutomationSaveInput, + success: IssueAutomationOverview, + error: IssueAutomationRpcError, +}); + +/** Counts each status change rules saw on one issue, so an open detail reads it again. */ +const WsIssuesSubscribeStatusRefreshesRpc = Rpc.make(WS_METHODS.issuesSubscribeStatusRefreshes, { + payload: Schema.Struct({ tracker: IssueTrackerKind, key: TrimmedNonEmptyString }), + success: NonNegativeInt, + error: EnvironmentAuthorizationError, + stream: true, +}); + const WsSourceControlLookupRepositoryRpc = Rpc.make(WS_METHODS.sourceControlLookupRepository, { payload: SourceControlRepositoryLookupInput, success: SourceControlRepositoryInfo, @@ -2465,6 +2504,7 @@ export const WsRpcGroup = RpcGroup.make( WsIssuesTemplatesRpc, WsIssuesCandidatesRpc, WsIssuesLinkedThreadsRpc, + WsIssuesSubscribeStatusRefreshesRpc, WsIssuesCreateRpc, WsIssuesCommentRpc, WsIssuesUpdateRpc, @@ -2473,6 +2513,9 @@ export const WsRpcGroup = RpcGroup.make( WsIssueTrackersListRpc, WsIssueTrackersConnectRpc, WsIssueTrackersBindProjectRpc, + WsIssueTrackersAutomationRpc, + WsIssueTrackersAutomationCatalogRpc, + WsIssueTrackersSaveAutomationRpc, WsGuestShareCreateRpc, WsServerProbeRpc, WsServerGetConfigRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index e7887f88f0369..eb06c9d6f95e4 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1,4 +1,5 @@ import { EasDeviceHostConfigs, SimlockDeviceHostConfigs, SshDeviceHostConfigs } from "./device.ts"; +import { IssueAutomationRule } from "./issue.ts"; import { AuthOrchestrationOperateScope, AuthAccessWriteScope, @@ -1477,6 +1478,10 @@ export const ServerSettings = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed(false)), ), idleCompaction: Schema.optionalKey(IdleCompactionMode), + /** Saved through IssueThreadAutomationService, which checks each rule with its tracker. */ + issueThreadAutomationRules: Schema.Array(IssueAutomationRule).pipe( + Schema.withDecodingDefault(Effect.succeed([])), + ), snoozeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), autoResumeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), snoozePresets: SnoozePresetSettings.pipe( @@ -1931,6 +1936,7 @@ export const ServerSettingsPatch = Schema.Struct({ sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)), compactIdleThreads: Schema.optionalKey(LegacyCompactIdleThreads), idleCompaction: Schema.optionalKey(IdleCompactionMode), + issueThreadAutomationRules: Schema.optionalKey(Schema.Array(IssueAutomationRule)), sidebarAutoSettleKeepPullRequests: Schema.optionalKey(Schema.Boolean), sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean), autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean), @@ -2017,9 +2023,18 @@ export const ServerSettingsPatch = Schema.Struct({ }); export type ServerSettingsPatch = typeof ServerSettingsPatch.Type; -/** The theme service sets theme defaults after it validates them, so clients cannot. */ +/** + * The theme service sets theme defaults, and the issue automation service its rules, after they + * validate them, so clients cannot. + */ export const ClientServerSettingsPatch = ServerSettingsPatch.mapFields( - Struct.omit(["defaultTheme", "defaultThemeSetAt", "defaultAppearance", "defaultAppearanceSetAt"]), + Struct.omit([ + "defaultTheme", + "defaultThemeSetAt", + "defaultAppearance", + "defaultAppearanceSetAt", + "issueThreadAutomationRules", + ]), ); export function requiredScopesForServerSettingsPatch( diff --git a/packages/issue-tracker-linear/src/server/LinearApi.graphql b/packages/issue-tracker-linear/src/server/LinearApi.graphql index 3fdfaf2580380..e271e1d47749a 100644 --- a/packages/issue-tracker-linear/src/server/LinearApi.graphql +++ b/packages/issue-tracker-linear/src/server/LinearApi.graphql @@ -301,3 +301,24 @@ query T3CommentReactions($id: String!) { } } } + +query T3TeamStates($id: String!) { + team(id: $id) { + states(first: 250) { + nodes { + ...LinearWorkflowState + } + } + } +} + +query T3IssueStates($teamId: ID!, $numbers: [Float!]!) { + issues(first: 250, filter: { team: { id: { eq: $teamId } }, number: { in: $numbers } }) { + nodes { + identifier + state { + id + } + } + } +} diff --git a/packages/issue-tracker-linear/src/server/LinearApi.graphql.ts b/packages/issue-tracker-linear/src/server/LinearApi.graphql.ts index 84d552be425ff..f3e962bfb050e 100644 --- a/packages/issue-tracker-linear/src/server/LinearApi.graphql.ts +++ b/packages/issue-tracker-linear/src/server/LinearApi.graphql.ts @@ -232,11 +232,11 @@ export declare namespace T3Viewer { export type Result = typeof T3Viewer.result.Type } -export const IssueConnection = Schema.Struct({ +export const T3IssuesIssuesIssueConnection = Schema.Struct({ nodes: Schema.Array(LinearIssue), pageInfo: LinearPageInfo }) -export interface IssueConnection extends Schema.Struct.Type {} +export interface T3IssuesIssuesIssueConnection extends Schema.Struct.Type {} /** `query T3Issues` */ export const T3Issues = GraphQL.query("T3Issues", { @@ -267,7 +267,7 @@ export const T3Issues = GraphQL.query("T3Issues", { }, result: Schema.Struct({ /** All issues. Returns a paginated list of issues visible to the authenticated user. Can be filtered by various criteria including team, assignee, state, labels, project, and cycle. */ - issues: IssueConnection + issues: T3IssuesIssuesIssueConnection }) }) export declare namespace T3Issues { @@ -815,5 +815,85 @@ export declare namespace T3CommentReactions { export type Result = typeof T3CommentReactions.result.Type } +/** A team is the primary organizational unit in Linear. Issues belong to teams, and each team has its own workflow states, cycles, labels, and settings. Teams can be public (visible to all workspace members), private (visible only to team members), or restricted (visible only within an enclosing private-team boundary). Teams can also have sub-teams that inherit settings from their parent. */ +export const T3TeamStatesTeamTeam = Schema.Struct({ + /** The states that define the workflow associated with the team. */ + states: TeamStatesWorkflowStateConnection +}) +export interface T3TeamStatesTeamTeam extends Schema.Struct.Type {} + +/** `query T3TeamStates` */ +export const T3TeamStates = GraphQL.query("T3TeamStates", { + document: { + variables: [ + { name: "id", body: "String!" } + ], + selections: [ + { name: "team", body: ["(id:$", "id", "){states(first:250){nodes{...LinearWorkflowState}}}"] } + ], + fragments: [ + { name: "LinearWorkflowState", body: ["on WorkflowState{id name type position}"] } + ] + }, + variables: { + id: Schema.String + }, + result: Schema.Struct({ + /** Fetches a specific team by its ID. */ + team: T3TeamStatesTeamTeam + }) +}) +export declare namespace T3TeamStates { + export type Variables = typeof T3TeamStates.variables.Type + export type Result = typeof T3TeamStates.result.Type +} + +/** A state in a team's workflow, representing an issue status such as Triage, Backlog, Todo, In Progress, In Review, Done, or Canceled. Each team has its own set of workflow states that define the progression of issues through the team's process. Workflow states have a type that categorizes them (triage, backlog, unstarted, started, completed, canceled), a position that determines their display order, and a color for visual identification. States can be inherited from parent teams to sub-teams. */ +export const WorkflowState = Schema.Struct({ + /** The unique identifier of the entity. */ + id: Shared.ID +}) +export interface WorkflowState extends Schema.Struct.Type {} + +/** An issue is the core work item in Linear. Issues belong to a team, have a workflow status, can be assigned to users, carry a priority level, and can be organized into projects and cycles. Issues support sub-issues (parent-child hierarchy up to 10 levels deep), labels, due dates, estimates, and SLA tracking. They can also be linked to other issues via relations, attached to releases, and tracked through their full history of changes. */ +export const NodesIssue = Schema.Struct({ + /** Issue's human readable identifier (e.g. ENG-123). */ + identifier: Schema.String, + /** The workflow state (issue status) that the issue is currently in. Workflow states represent the issue's progress through the team's workflow, such as Triage, Todo, In Progress, Done, or Canceled. */ + state: WorkflowState +}) +export interface NodesIssue extends Schema.Struct.Type {} + +export const T3IssueStatesIssuesIssueConnection = Schema.Struct({ + nodes: Schema.Array(NodesIssue) +}) +export interface T3IssueStatesIssuesIssueConnection extends Schema.Struct.Type {} + +/** `query T3IssueStates` */ +export const T3IssueStates = GraphQL.query("T3IssueStates", { + document: { + variables: [ + { name: "teamId", body: "ID!" }, + { name: "numbers", body: "[Float!]!" } + ], + selections: [ + { name: "issues", body: ["(first:250 filter:{team:{id:{eq:$", "teamId", "}}number:{in:$", "numbers", "}}){nodes{identifier state{id}}}"] } + ], + fragments: [] + }, + variables: { + teamId: Shared.ID, + numbers: Schema.Array(Shared.Float) + }, + result: Schema.Struct({ + /** All issues. Returns a paginated list of issues visible to the authenticated user. Can be filtered by various criteria including team, assignee, state, labels, project, and cycle. */ + issues: T3IssueStatesIssuesIssueConnection + }) +}) +export declare namespace T3IssueStates { + export type Variables = typeof T3IssueStates.variables.Type + export type Result = typeof T3IssueStates.result.Type +} + /** Every operation in LinearApi.graphql. */ -export const LinearApiGraphQLGroup = GraphQLGroup.make(T3Viewer, T3Issues, T3Issue, T3Comments, T3Team, T3IssueCreate, T3IssueUpdate, T3CommentCreate, T3ReactionCreate, T3ReactionDelete, T3IssueReactions, T3CommentReactions) +export const LinearApiGraphQLGroup = GraphQLGroup.make(T3Viewer, T3Issues, T3Issue, T3Comments, T3Team, T3IssueCreate, T3IssueUpdate, T3CommentCreate, T3ReactionCreate, T3ReactionDelete, T3IssueReactions, T3CommentReactions, T3TeamStates, T3IssueStates) diff --git a/packages/issue-tracker-linear/src/server/LinearApi.ts b/packages/issue-tracker-linear/src/server/LinearApi.ts index 9f353f302eae0..1c1cdbd6641c6 100644 --- a/packages/issue-tracker-linear/src/server/LinearApi.ts +++ b/packages/issue-tracker-linear/src/server/LinearApi.ts @@ -37,6 +37,7 @@ import { type LinearReaction, type LinearTeamLabel, type LinearUser, + type LinearWorkflowState, type T3Issue, type T3Team, type Template, @@ -130,6 +131,18 @@ export class LinearApi extends Context.Service< IssueTrackerError >; readonly getTeam: (key: string) => Effect.Effect; + /** A team's workflow states by the team's id, which stays when its key is renamed. */ + readonly getTeamStates: ( + teamId: string, + ) => Effect.Effect, IssueTrackerError>; + /** The state of each issue with one of these numbers in the team; up to 250 numbers. */ + readonly getIssueStates: (input: { + readonly teamId: string; + readonly numbers: ReadonlyArray; + }) => Effect.Effect< + ReadonlyArray<{ readonly identifier: string; readonly stateId: string }>, + IssueTrackerError + >; readonly createIssue: ( input: IssueCreateInput, ) => Effect.Effect<{ readonly identifier: string; readonly url: string }, IssueTrackerError>; @@ -371,6 +384,23 @@ export const make = Effect.gen(function* () { }), ); + const getTeamStates: LinearApi["Service"]["getTeamStates"] = (teamId) => + call("getTeamStates", (linear) => linear.T3TeamStates({ id: teamId })).pipe( + Effect.map((data) => data.team.states.nodes), + ); + + const getIssueStates: LinearApi["Service"]["getIssueStates"] = (input) => + call("getIssueStates", (linear) => + linear.T3IssueStates({ teamId: input.teamId, numbers: input.numbers }), + ).pipe( + Effect.map((data) => + data.issues.nodes.map((issue) => ({ + identifier: issue.identifier, + stateId: issue.state.id, + })), + ), + ); + const createIssue: LinearApi["Service"]["createIssue"] = (input) => call("createIssue", (linear) => linear.T3IssueCreate({ input })).pipe( Effect.flatMap(({ issueCreate }) => @@ -430,6 +460,8 @@ export const make = Effect.gen(function* () { getIssue, getComments, getTeam, + getTeamStates, + getIssueStates, createIssue, updateIssue, createComment, diff --git a/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts b/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts index 3ed0d87426ae1..1fc060d71c4da 100644 --- a/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts +++ b/packages/issue-tracker-linear/src/server/LinearIssueTracker.test.ts @@ -643,4 +643,62 @@ describe("LinearIssueTracker", () => { link: { name: "Intake", about: "", url: "https://linear.app/team/ENG/new?template=tpl_2" }, }); }); + + it.effect("reads a team's workflow and its issues' states by team id for status rules", () => + Effect.gen(function* () { + const numbers: Array> = []; + const { tracker } = fakeLinear({ + T3Viewer: () => ({ + viewer: JULIUS, + organization: { urlKey: "acme" }, + teams: { nodes: [{ id: "team_eng", key: "ENG", name: "Engineering" }] }, + }), + T3TeamStates: (variables) => { + expect(variables.id).toBe("team_eng"); + return { + team: { + states: { + nodes: [ + state("Done", "completed", 2), + state("In Progress", "started", 1), + state("Todo", "unstarted", 0), + ], + }, + }, + }; + }, + T3IssueStates: (variables) => { + expect(variables.teamId).toBe("team_eng"); + const batch = variables.numbers as ReadonlyArray; + numbers.push(batch); + return { + issues: { + nodes: batch.includes(1) ? [{ identifier: "ENG-1", state: { id: "st_done" } }] : [], + }, + }; + }, + }); + const automation = (yield* tracker).automation; + expect(yield* automation.listContainers()).toEqual({ + workspace: "acme", + containers: [{ id: "team_eng", name: "Engineering (ENG)" }], + }); + expect( + (yield* automation.listStates({ workspace: "acme", containerId: "team_eng" })).map( + (option) => option.name, + ), + ).toEqual(["Todo", "In Progress", "Done"]); + const keys = [ + "ENG-1", + "eng-1", + "not a key", + ...Array.from({ length: 250 }, (_, i) => `ENG-${i + 2}`), + ]; + expect( + yield* automation.readStatuses({ workspace: "acme", containerId: "team_eng", keys }), + ).toEqual([{ key: "ENG-1", stateId: "st_done" }]); + // Numbers are deduplicated and read 250 at a time. + expect(numbers.map((batch) => batch.length)).toEqual([250, 1]); + }), + ); }); diff --git a/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts b/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts index a407b842f79c8..e936cbdede910 100644 --- a/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts +++ b/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts @@ -38,6 +38,7 @@ const DESCRIPTOR: StandaloneIssueTrackerDescriptor = { label: "Personal API key", helpUrl: "https://linear.app/settings/account/security", }, + automationContainer: "team", }; /** @@ -121,6 +122,9 @@ const CONTENT_BY_EMOJI = new Map( ), ); +/** Linear filters issues by number, at most this many per read. */ +const STATUS_READ_BATCH = 250; + /** `ENG-123`, or null for anything that is not a Linear identifier. */ function parseIdentifier(key: string): string | null { return /^[A-Za-z][A-Za-z0-9]*-[1-9]\d*$/.test(key.trim()) ? key.trim().toUpperCase() : null; @@ -427,6 +431,47 @@ export const make: Effect.Effect + linear.viewer().pipe( + Effect.map((data) => ({ + workspace: data.workspace, + containers: data.teams.map((team) => ({ + id: team.id, + name: `${team.name} (${team.key})`, + })), + })), + ), + listStates: ({ containerId }) => + linear + .getTeamStates(containerId) + .pipe( + Effect.map((states) => inWorkflowOrder(states).map(({ id, name }) => ({ id, name }))), + ), + readStatuses: ({ containerId, keys }) => { + const numbers = [ + ...new Set( + keys.flatMap((key) => { + const identifier = parseIdentifier(key); + return identifier === null ? [] : [Number(identifier.split("-")[1])]; + }), + ), + ]; + const batches = Array.from( + { length: Math.ceil(numbers.length / STATUS_READ_BATCH) }, + (_, index) => numbers.slice(index * STATUS_READ_BATCH, (index + 1) * STATUS_READ_BATCH), + ); + return Effect.forEach(batches, (batch) => + linear.getIssueStates({ teamId: containerId, numbers: batch }), + ).pipe( + Effect.map((pages) => + pages.flat().map((issue) => ({ key: issue.identifier, stateId: issue.stateId })), + ), + ); + }, + }, + // The id, not the display name: it is what the involvement filters compare against. getViewer: () => linear.viewer().pipe(Effect.map((data) => toActor(data.viewer).login)), diff --git a/packages/source-control-core/src/server/IssueTracker.ts b/packages/source-control-core/src/server/IssueTracker.ts index eecbde1ed2267..d07ec6270af45 100644 --- a/packages/source-control-core/src/server/IssueTracker.ts +++ b/packages/source-control-core/src/server/IssueTracker.ts @@ -5,6 +5,7 @@ import * as Schema from "effect/Schema"; import type * as Effect from "effect/Effect"; import type { + IssueAutomationOption, IssueState, IssueCandidates, IssueCapabilities, @@ -227,6 +228,35 @@ export interface StandaloneIssueTrackerApi extends IssueTrackerApi { }, IssueTrackerError >; + /** + * What issue status rules read, present when `standalone.automationContainer` is. A container + * is the team or board a rule watches; its id must be unique across the tracker's workspaces, + * or the tracker must refuse a workspace other than the credential's. + */ + readonly automation?: { + readonly listContainers: () => Effect.Effect< + { + /** The credential's workspace, as `parseIssueUrl` names it. */ + readonly workspace: string; + readonly containers: ReadonlyArray; + }, + IssueTrackerError + >; + /** Every status an issue in the container can be in, in workflow order. */ + readonly listStates: (input: { + readonly workspace: string; + readonly containerId: string; + }) => Effect.Effect, IssueTrackerError>; + /** The status id of each issue key found in the container; keys outside it are left out. */ + readonly readStatuses: (input: { + readonly workspace: string; + readonly containerId: string; + readonly keys: ReadonlyArray; + }) => Effect.Effect< + ReadonlyArray<{ readonly key: string; readonly stateId: string }>, + IssueTrackerError + >; + }; } export function isStandaloneIssueTracker(api: IssueTrackerApi): api is StandaloneIssueTrackerApi { From 0ff42f028a972445814e76cbafb8fdceebe65fa7 Mon Sep 17 00:00:00 2001 From: Pixel Perfect Date: Fri, 20 Nov 2026 15:22:04 -0800 Subject: [PATCH 2/6] fix(issues): address review findings on issue status automation - A rule never settles a pinned thread, as auto-settle never does for a merged pull request; Wake and Snooze still apply. - Settle waits while the thread's provider session runs background work. - An action that fails for any reason other than a stale decision is kept and retried; waking an already awake thread is accepted as a no-op. - Disabling a rule re-reads it under the save lock, so a removed rule stays removed. - Event pruning keeps each thread's newest organizing event. - Older settled threads with an indefinite snooze stay in snapshots, and Undo restores a snooze only if it was still in effect. - Linear automation reads get named spans, and the workspace test now fails when the wrong workspace matches. --- .../IssueThreadAutomationService.test.ts | 82 ++++++++++++------- .../src/issue/IssueThreadAutomationService.ts | 30 ++++--- .../FoundationPersistence.test.ts | 7 +- .../Orchestrator.control-reads.test.ts | 35 ++++++++ .../src/orchestration-v2/Orchestrator.ts | 33 ++++++-- .../ProjectionMaintenance.test.ts | 31 ++++++- .../orchestration-v2/ProjectionMaintenance.ts | 9 ++ .../orchestration-v2/ProjectionStore.test.ts | 2 + .../src/orchestration-v2/ProjectionStore.ts | 8 +- .../src/orchestration-v2/ShellStream.ts | 5 +- .../ProviderSwitch.integration.test.ts | 62 +++++++++----- apps/server/src/ws.test.ts | 8 +- docs/user/source-control.md | 3 +- .../src/state/threadUndo.test.ts | 16 +++- .../client-runtime/src/state/threadUndo.ts | 25 +++--- .../src/server/LinearIssueTracker.ts | 10 ++- 16 files changed, 276 insertions(+), 90 deletions(-) diff --git a/apps/server/src/issue/IssueThreadAutomationService.test.ts b/apps/server/src/issue/IssueThreadAutomationService.test.ts index 4eafbe5469a5a..7ec0c1964ea25 100644 --- a/apps/server/src/issue/IssueThreadAutomationService.test.ts +++ b/apps/server/src/issue/IssueThreadAutomationService.test.ts @@ -109,8 +109,9 @@ function setup( reads: [] as ReadonlyArray[], fail: false, busy: false, - previouslyRejected: false, + refuseOnce: null as "previously rejected" | "projection error" | null, beforeRead: Effect.void as Effect.Effect, + beforeCatalog: Effect.void as Effect.Effect, }; const tracker: StandaloneIssueTrackerApi = { kind: LINEAR, @@ -147,10 +148,12 @@ function setup( getComments: () => Effect.die("unused"), automation: { listContainers: () => - Effect.succeed({ - workspace: "acme", - containers: rules.map((item) => ({ id: item.containerId, name: item.containerName })), - }), + state.beforeCatalog.pipe( + Effect.as({ + workspace: "acme", + containers: rules.map((item) => ({ id: item.containerId, name: item.containerName })), + }), + ), listStates: () => Effect.succeed([ { id: "open", name: "Open" }, @@ -183,14 +186,16 @@ function setup( dispatch: (command) => Effect.gen(function* () { state.attempts.push(command); - if (state.previouslyRejected) { - state.previouslyRejected = false; + const refusal = state.refuseOnce; + state.refuseOnce = null; + if (refusal === "previously rejected") return yield* new Orchestrator.OrchestratorCommandPreviouslyRejectedError({ commandId: command.commandId, commandType: command.type, detail: "busy before restart", }); - } + if (refusal === "projection error") + return yield* new Orchestrator.OrchestratorProjectionError({ threadId }); if (state.busy) return yield* new Orchestrator.OrchestratorDispatchError({ commandId: command.commandId, @@ -328,15 +333,20 @@ describe("IssueThreadAutomationService", () => { it.effect("ignores the same issue key in another workspace", () => { const { state, layer } = setup( [rule()], - [link("ENG-1"), link("ENG-1", { url: "https://linear.app/another/issue/ENG-1" })], + [link("ENG-1", { url: "https://linear.app/another/issue/ENG-1" })], ); + const local = ThreadId.make("thread:local"); return Effect.gen(function* () { const automation = yield* Automation.IssueThreadAutomationService; yield* automation.sweep; + expect(state.reads).toEqual([]); + state.threads.push({ ...thread([link("ENG-1")]), id: local }); + yield* automation.sweep; state.statuses.set("team-a", [{ key: "ENG-1", stateId: "done" }]); yield* automation.sweep; expect(state.reads).toEqual([["ENG-1"], ["ENG-1"]]); - expect(actions(state.commands)).toEqual(["settle"]); + expect(state.commands).toHaveLength(1); + expect(state.commands).toMatchObject([{ threadId: local, action: "settle" }]); }).pipe(Effect.provide(layer)); }); @@ -360,23 +370,26 @@ describe("IssueThreadAutomationService", () => { }).pipe(Effect.provide(layer)); }); - it.effect("retries a refused command id with a new one at the same revision", () => { - const { state, layer } = setup(); - return Effect.gen(function* () { - const automation = yield* Automation.IssueThreadAutomationService; - const store = yield* Observations.IssueThreadAutomation; - yield* automation.sweep; - state.statuses.set("team-a", [{ key: "ENG-1", stateId: "done" }]); - state.previouslyRejected = true; - yield* automation.sweep; - const pending = (yield* store.list).get(threadId)?.pending; - expect(pending?.revision).toBe(1); - expect(pending?.commandId).not.toBe(state.attempts[0]?.commandId); - yield* automation.sweep; - expect(actions(state.commands)).toEqual(["settle"]); - expect((yield* store.list).get(threadId)?.pending).toBeNull(); - }).pipe(Effect.provide(layer)); - }); + it.effect.each(["previously rejected", "projection error"] as const)( + "retries a %s command with a new id at the same revision", + (refusal) => { + const { state, layer } = setup(); + return Effect.gen(function* () { + const automation = yield* Automation.IssueThreadAutomationService; + const store = yield* Observations.IssueThreadAutomation; + yield* automation.sweep; + state.statuses.set("team-a", [{ key: "ENG-1", stateId: "done" }]); + state.refuseOnce = refusal; + yield* automation.sweep; + const pending = (yield* store.list).get(threadId)?.pending; + expect(pending?.revision).toBe(1); + expect(pending?.commandId).not.toBe(state.attempts[0]?.commandId); + yield* automation.sweep; + expect(actions(state.commands)).toEqual(["settle"]); + expect((yield* store.list).get(threadId)?.pending).toBeNull(); + }).pipe(Effect.provide(layer)); + }, + ); it.effect("keeps the last status through a failed read and acts once the read recovers", () => { const { state, layer } = setup(); @@ -397,7 +410,7 @@ describe("IssueThreadAutomationService", () => { }); it.effect("saves a rule only for a reachable team, once per team, and in its workspace", () => { - const { layer } = setup(); + const { state, layer } = setup(); return Effect.gen(function* () { const automation = yield* Automation.IssueThreadAutomationService; expect( @@ -422,6 +435,19 @@ describe("IssueThreadAutomationService", () => { rule: rule("team-a", { enabled: false, workspace: "another" }), }); expect(disabled.rules).toMatchObject([{ enabled: false, workspace: "acme" }]); + // A rule removed while switching it off waited on the tracker stays removed. + const started = yield* Deferred.make(); + const finish = yield* Deferred.make(); + state.beforeCatalog = Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(finish)), + ); + const switchingOff = yield* automation + .save({ id: "team-a", rule: rule("team-a", { enabled: false, workspace: "another" }) }) + .pipe(Effect.forkChild); + yield* Deferred.await(started); + yield* automation.save({ id: "team-a", rule: null }); + yield* Deferred.succeed(finish, undefined); + expect((yield* Fiber.join(switchingOff)).rules).toEqual([]); }).pipe(Effect.provide(layer)); }); diff --git a/apps/server/src/issue/IssueThreadAutomationService.ts b/apps/server/src/issue/IssueThreadAutomationService.ts index 62090077cacfe..995a1f7179a22 100644 --- a/apps/server/src/issue/IssueThreadAutomationService.ts +++ b/apps/server/src/issue/IssueThreadAutomationService.ts @@ -38,7 +38,7 @@ import { aggregateIssueActions, automationFingerprint, changedIssueStatuses, - ISSUE_AUTOMATION_WAITS_FOR_IDLE, + ISSUE_AUTOMATION_STALE, } from "./issueAutomation.ts"; export class IssueThreadAutomationService extends Context.Service< @@ -148,7 +148,8 @@ const make = Effect.gen(function* () { const save = Effect.fn("IssueThreadAutomationService.save")( function* (input: IssueAutomationSaveInput) { - let rule = input.rule; + const rule = input.rule; + let disableStored = false; if (rule !== null) { if (rule.id !== input.id) return yield* new IssueAutomationError({ @@ -176,15 +177,21 @@ const make = Effect.gen(function* () { operation: "save", detail: "The connected account is in another workspace.", }); - rule = { ...existing, enabled: false }; + disableStored = true; } } - const saved = rule === null ? null : { ...rule, generation: yield* newCommandId }; + const generation = yield* newCommandId; return yield* saveLock.withPermit( Effect.gen(function* () { - const rules = (yield* settings.getSettings).issueThreadAutomationRules.filter( - (candidate) => candidate.id !== input.id, - ); + const stored = (yield* settings.getSettings).issueThreadAutomationRules; + const rules = stored.filter((candidate) => candidate.id !== input.id); + // Switching off disables the rule as stored now; one removed meanwhile stays removed. + const base = disableStored ? stored.find((candidate) => candidate.id === input.id) : rule; + if (base === undefined) return yield* overview; + const saved = + base === null + ? null + : { ...base, ...(disableStored ? { enabled: false } : {}), generation }; if (saved !== null) { if ( rules.some( @@ -375,12 +382,13 @@ const make = Effect.gen(function* () { return false; return yield* orchestrator.dispatch(command).pipe( Effect.as(false), - // A busy thread keeps the action for the next sweep; any other refusal drops it. + // Only a stale decision is dropped; a busy thread or a failed attempt tries again. Effect.catch((error) => Effect.succeed( - error._tag === "OrchestratorCommandPreviouslyRejectedError" || - (error._tag === "OrchestratorDispatchError" && - error.cause === ISSUE_AUTOMATION_WAITS_FOR_IDLE), + !( + error._tag === "OrchestratorDispatchError" && + error.cause === ISSUE_AUTOMATION_STALE + ), ), ), ); diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 5e208fc7fd658..dc69fddb1aa62 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -1558,9 +1558,14 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { AND stream_id = ${threadId} ORDER BY sequence ASC `; + // The newest user message stays as the thread's issue automation revision. assert.deepEqual( remaining.map((row) => row.event_id), - ["event:foundation-compact:create", "event:foundation-compact:tags-2"], + [ + "event:foundation-compact:create", + "event:foundation-compact:message-2", + "event:foundation-compact:tags-2", + ], ); const remainingV1 = yield* sql<{ readonly stream_id: string }>` diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 815eda1a7c014..2284f75c8f110 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -167,6 +167,41 @@ it.effect("issue automation settles, snoozes until woken, and wakes like a timer }).pipe(Effect.provide(layerTest)), ); +it.effect.each(["settle of a pinned thread", "wake of an awake thread"] as const)( + "issue automation accepts a %s and changes nothing", + (change) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const events = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make(`thread:automation-noop:${change}`); + yield* createThread(threadId); + if (change === "settle of a pinned thread") { + yield* orchestrator.dispatch({ + type: "thread.pin", + commandId: CommandId.make(`pin:${change}`), + threadId, + }); + } + const before = yield* projections.getThread(threadId); + const command = { + type: "thread.issue-automation.apply" as const, + commandId: CommandId.make(`automation-noop:${change}`), + threadId, + action: change === "wake of an awake thread" ? ("wake" as const) : ("settle" as const), + expectedRevision: yield* projections.getIssueAutomationRevision(threadId), + rulesFingerprint: automationFingerprint([]), + }; + yield* orchestrator.dispatch(command); + const committed = yield* events + .readByCommandId({ commandId: command.commandId }) + .pipe(Stream.runCollect); + assert.lengthOf(committed, 0); + assert.deepEqual(yield* projections.getThread(threadId), before); + assert.isTrue((yield* orchestrator.dispatch(command)).replayed); + }).pipe(Effect.provide(layerTest)), +); + it.effect.each(["same-value manual wake", "user message", "changed rules"] as const)( "issue automation refuses a decision made before a %s", (change) => diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index f20df99949e16..21644b9f3863c 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -15928,22 +15928,43 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); break; } + // Like a merged pull request, a rule never settles a pinned thread. + if (command.action === "settle" && thread.pinnedAt != null) break; const { runs, runtimeRequests } = yield* projectionStore .getThreadRecords(command.threadId, ["runs", "runtimeRequests"]) .pipe(Effect.mapError(toProjectionError)); + const waitsForIdle = new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: ISSUE_AUTOMATION_WAITS_FOR_IDLE, + }); if ( runs.some((run) => ["queued", "preparing", "starting", "running", "waiting"].includes(run.status), ) || runtimeRequests.some((request) => request.status === "pending") ) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: ISSUE_AUTOMATION_WAITS_FOR_IDLE, - }); + return yield* waitsForIdle; } if (command.action === "settle") { + // Settling detaches the provider sessions, which ends background work still in them. + const { providerSessions } = yield* projectionStore + .getThreadProviderContext(command.threadId) + .pipe(Effect.mapError(toProjectionError)); + const live = providerSessions.filter( + (session) => session.status !== "stopped" && session.status !== "error", + ); + if (live.length > 0) { + const { providerThreads } = yield* projectionStore + .getThreadRecords(command.threadId, ["providerThreads"], { + omitSettledSubagentRecords: true, + }) + .pipe(Effect.mapError(toProjectionError)); + for (const session of live) { + if (yield* sessionHasBackgroundWork(session, providerThreads)) + return yield* waitsForIdle; + } + } yield* dispatchThreadMutation( { type: "thread.settle", commandId: command.commandId, threadId: thread.id }, events, @@ -16510,6 +16531,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio planned.events.length > 0 || isUnobservedAcknowledgement(command) || command.type === "thread.background-work.settle" || + // A rule's wake of an awake thread, or its settle of a pinned one, has nothing to do. + command.type === "thread.issue-automation.apply" || // A stale visit changes no read state. command.type === "thread.visit" || // A read can answer a watch again before a push's reopen lands; nothing is left to clear. diff --git a/apps/server/src/orchestration-v2/ProjectionMaintenance.test.ts b/apps/server/src/orchestration-v2/ProjectionMaintenance.test.ts index 1f42953cc4ec3..6789f39616da1 100644 --- a/apps/server/src/orchestration-v2/ProjectionMaintenance.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionMaintenance.test.ts @@ -81,6 +81,21 @@ function threadCreated(thread: OrchestrationV2AppThread, now: DateTime.Utc) { } satisfies OrchestrationV2DomainEvent; } +function threadOrganized( + thread: OrchestrationV2AppThread, + now: DateTime.Utc, + type: "thread.pinned" | "thread.unpinned", +) { + return { + id: EventId.make(`event:prune:${type}`), + type, + threadId: thread.id, + providerInstanceId, + occurredAt: now, + payload: thread, + } satisfies OrchestrationV2DomainEvent; +} + const itemSpecs = [ { key: "command", type: "command_execution", ordinal: 10 }, { key: "reasoning", type: "reasoning", ordinal: 20 }, @@ -254,7 +269,14 @@ it.effect("prunes events the projections cover once the retained day has passed" const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2; const now = yield* DateTime.now; const threadId = ThreadId.make("thread:prune"); - yield* sink.write({ events: [threadCreated(makeThread(threadId, now), now)] }); + const thread = makeThread(threadId, now); + yield* sink.write({ events: [threadCreated(thread, now)] }); + yield* sink.write({ + events: [ + threadOrganized(thread, now, "thread.pinned"), + threadOrganized(thread, now, "thread.unpinned"), + ], + }); for (const revision of [0, 1, 2]) { yield* sink.write({ events: [itemEvent(threadId, now, itemSpecs[0], revision)] }); } @@ -271,14 +293,17 @@ it.effect("prunes events the projections cover once the retained day has passed" yield* sink.write({ events: [itemEvent(threadId, now, itemSpecs[0], 3)] }); const highWater = yield* eventStore.latestSequence(); const projection = yield* projections.getThreadProjection(threadId); + const revision = yield* projections.getIssueAutomationRevision(threadId); yield* TestClock.adjust("23 hours"); assert.equal((yield* maintenance.pruneEventStore()).deletedEventCount, 0); yield* TestClock.adjust("1 hour"); - assert.equal((yield* maintenance.pruneEventStore()).deletedEventCount, 4); + assert.equal((yield* maintenance.pruneEventStore()).deletedEventCount, 5); + // Only the newest organizing event stays, so issue automation's revision does not move. assert.deepEqual(yield* remainingEventIds(threadId), [ "event:turn-item-compaction:thread", + "event:prune:thread.unpinned", "event:turn-item-compaction:subagent:0", "event:turn-item-compaction:subagent-item:0", "event:prune:run-running", @@ -290,6 +315,8 @@ it.effect("prunes events the projections cover once the retained day has passed" assert.equal(yield* eventStore.latestSequence(), highWater); assert.equal(yield* eventStore.latestSequence({ threadId }), highWater); assert.deepEqual(yield* projections.getThreadProjection(threadId), projection); + assert.isAbove(revision, 0); + assert.equal(yield* projections.getIssueAutomationRevision(threadId), revision); const repeated = yield* eventStore .read({ threadId, eventType: "subagent.updated", afterSequence: markedThrough }) .pipe(Stream.runCollect); diff --git a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts index 210322aed686f..0e29bb4f2943a 100644 --- a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts +++ b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts @@ -12,6 +12,7 @@ import { EVENT_LOG_PRUNED_THROUGH, } from "../persistence/OrchestrationEventStore.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; +import { THREAD_ORGANIZATION_EVENT_CONDITION } from "./threadOrganizationEvent.ts"; export class ProjectionMaintenanceError extends Schema.TaggedError()( "ProjectionMaintenanceError", @@ -134,6 +135,14 @@ export const layer: Layer.Layer, ) => ({ id: row.id, @@ -167,6 +168,7 @@ const assertShellIndexCoversShells = Effect.fnUntraced(function* () { pinnedAt: iso(row.pinnedAt), pinOrderKey: row.pinOrderKey ?? null, snoozedUntil: iso(row.snoozedUntil), + snoozedAt: iso(row.snoozedAt), }); assert.deepEqual(index.map(trimmed), shells.map(trimmed)); shells.forEach((shell, position) => { diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 4d9b0634307d6..276017a5be260 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -516,6 +516,7 @@ export interface ActiveShellIndexEntry extends Pick< | "pinnedAt" | "pinOrderKey" | "snoozedUntil" + | "snoozedAt" > { /** False only when no run, request, work item, or watch can make the shell live. */ readonly mayBeLive: boolean; @@ -9006,8 +9007,8 @@ export const layer: Layer.Layer = ) .pipe(Effect.mapError((cause) => new ProjectionStoreSetupError({ cause }))); - // Pruning old events can only move a revision, which drops a waiting action rather than - // applying one that is stale. Without the hint, SQLite walks every event of the thread. + // Event pruning keeps this row, so a revision never goes back to one a waiting action + // recorded. Without the hint, SQLite walks every event of the thread. const issueAutomationRevision = (threadId: Statement.Fragment) => sql`( SELECT COALESCE(MAX(sequence), 0) FROM orchestration_events INDEXED BY idx_orchestration_events_thread_organization @@ -9597,6 +9598,7 @@ export const layer: Layer.Layer = readonly pinned_at: string | null; readonly pin_order_key: string | null; readonly snoozed_until: string | null; + readonly snoozed_at: string | null; readonly may_be_live: number; readonly has_remote_tasks: number; }>` @@ -9612,6 +9614,7 @@ export const layer: Layer.Layer = ${indexedField("$.pinnedAt")} AS pinned_at, ${indexedField("$.pinOrderKey")} AS pin_order_key, ${indexedField("$.snoozedUntil")} AS snoozed_until, + ${indexedField("$.snoozedAt")} AS snoozed_at, -- A superset of isLiveSubagentShell: the sources of its run status, pending request, -- and pending background work. Each source is one list for the whole read, found -- through its partial index, so finished threads cost no lookups. @@ -9676,6 +9679,7 @@ export const layer: Layer.Layer = pinnedAt: row.pinned_at === null ? null : DateTime.makeUnsafe(row.pinned_at), pinOrderKey: row.pin_order_key, snoozedUntil: row.snoozed_until === null ? null : DateTime.makeUnsafe(row.snoozed_until), + snoozedAt: row.snoozed_at === null ? null : DateTime.makeUnsafe(row.snoozed_at), mayBeLive: row.may_be_live === 1, hasRemoteTasks: row.has_remote_tasks === 1, })); diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 5ee1005b16830..ecd3d9ab531c4 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -37,6 +37,7 @@ import * as Stream from "effect/Stream"; import type * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; import { bufferLatestLiveStream } from "./LiveStreamBudget.ts"; import type { ActiveShellIndexEntry } from "./ProjectionStore.ts"; +import { hasStoredSnooze, snoozeHolds } from "./threadSnooze.ts"; type ShellDelta = Extract; @@ -282,7 +283,7 @@ function omitOlderSettledShellsWith( (thread) => !isOlderSettledThreadShell(thread, beforeMs) || thread.pinnedAt != null || - (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs) || + snoozeHolds(thread, nowMs) || isLiveSubagentShell(thread) || ancestorIds.has(thread.id) || facts.remoteTaskParentIds.has(thread.id), @@ -397,7 +398,7 @@ function shellSubscriberThreadIds( beforeMs === undefined || !isOlderSettledThreadShell(entry, beforeMs) || entry.pinnedAt != null || - entry.snoozedUntil != null || + hasStoredSnooze(entry) || entry.mayBeLive || entry.hasRemoteTasks || ancestorIds.has(entry.id) diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 811279357d917..5f1e7472f63c6 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -68,6 +68,7 @@ import { import * as ProviderReplayHarness from "./ProviderReplayHarness.ts"; import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { automationFingerprint } from "../../issue/issueAutomation.ts"; const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); @@ -4619,6 +4620,7 @@ describe("orchestration v2 provider switching", () => { ["runtime mode", "runtime-mode"], ["worktree", "worktree"], ["provider instance", "instance"], + ["settled state", "issue-settle"], ] as const)("keeps background work alive when the %s changes on an idle thread", ([, change]) => Effect.gen(function* () { const cwd = yield* checkpointWorkspace(`settings-background-${change}`); @@ -4668,25 +4670,47 @@ describe("orchestration v2 provider switching", () => { yield* Ref.set(backgroundWork, true); const commandId = CommandId.make(`command:settings-background-${change}:change`); - yield* orchestrator - .dispatch( - change === "runtime-mode" - ? { - type: "thread.runtime-mode.set", - commandId, - threadId, - runtimeMode: "auto-accept-edits", - } - : change === "worktree" - ? { type: "thread.metadata.update", commandId, threadId, worktreePath: nextCwd } - : { - type: "thread.model-selection.set", - commandId, - threadId, - modelSelection: secondSelection, - }, - ) - .pipe(Effect.ignore); + // A rule decides at the thread's newest organizing event, here an unsettle. + const settleByRule = orchestrator + .dispatch({ + type: "thread.unsettle", + commandId: CommandId.make(`command:settings-background-${change}:organize`), + threadId, + reason: "user", + }) + .pipe( + Effect.flatMap(({ storedEvents }) => + orchestrator.dispatch({ + type: "thread.issue-automation.apply", + commandId, + threadId, + action: "settle", + expectedRevision: storedEvents.at(-1)?.sequence ?? 0, + rulesFingerprint: automationFingerprint([]), + }), + ), + ); + yield* ( + change === "issue-settle" + ? settleByRule + : orchestrator.dispatch( + change === "runtime-mode" + ? { + type: "thread.runtime-mode.set", + commandId, + threadId, + runtimeMode: "auto-accept-edits", + } + : change === "worktree" + ? { type: "thread.metadata.update", commandId, threadId, worktreePath: nextCwd } + : { + type: "thread.model-selection.set", + commandId, + threadId, + modelSelection: secondSelection, + }, + ) + ).pipe(Effect.ignore); yield* worker.drain(); const projection = yield* orchestrator.getThreadProjection(threadId); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index c7b0702dec7ca..1ea37e0a17bef 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -748,6 +748,8 @@ it.effect("shell snapshots omit idle children and older settled threads only on shell("live", "parent", "running"), ...Array.from({ length: 25 }, (_, index) => shell(`recent-${index}`, null, null, 1)), shell("old", null, null, 30), + // Snoozed with no wake time, it stays in the snoozed list however long ago it settled. + { ...shell("snoozed", null, null, 50), snoozedAt: DateTime.makeUnsafe(0) }, shell("remote-parent", null, null, 40), shell("remote-child-parent", "parent", null), ]; @@ -810,17 +812,17 @@ it.effect("shell snapshots omit idle children and older settled threads only on const withoutChildren = yield* firstSnapshot({ omitIdleSubagents: true }); assert.deepEqual( withoutChildren?.threads.map((thread) => thread.id), - ["parent", "live", ...recent, "old", "remote-parent", "remote-child-parent"], + ["parent", "live", ...recent, "old", "snoozed", "remote-parent", "remote-child-parent"], ); // A linked environment's clients nest its task under its parent, so that parent stays: an // older settled thread or an idle subagent. const withoutOld = yield* firstSnapshot({ omitIdleSubagents: true, omitOlderSettled: true }); assert.deepEqual( withoutOld?.threads.map((thread) => thread.id), - ["parent", "live", ...recent, "remote-parent", "remote-child-parent"], + ["parent", "live", ...recent, "snoozed", "remote-parent", "remote-child-parent"], ); assert.deepEqual(withoutOld?.olderSettled?.counts, [ - { projectId: ProjectId.make("project"), count: 2 }, + { projectId: ProjectId.make("project"), count: 3 }, ]); }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 4764a735a8e29..ec384985a7549 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -449,7 +449,8 @@ linked issues wakes when any of them maps to **Wake**, settles only when all of **Settle**, and otherwise snoozes. A status in no bucket, or one that could not be read, leaves the thread as it is. A snooze from a rule has no wake time; the thread shows **∞** in the Snoozed list until a status change, **Wake thread**, or a message wakes it. A thread with work -still running waits until it is idle before it snoozes or settles. +still running waits until it is idle before it snoozes or settles. A rule never settles a pinned +thread. ## GitHub stacks diff --git a/packages/client-runtime/src/state/threadUndo.test.ts b/packages/client-runtime/src/state/threadUndo.test.ts index accdc8837872f..97b0a25884d55 100644 --- a/packages/client-runtime/src/state/threadUndo.test.ts +++ b/packages/client-runtime/src/state/threadUndo.test.ts @@ -3,10 +3,22 @@ import { executeThreadUndo, planThreadUndo } from "./threadUndo.ts"; describe("planThreadUndo", () => { it("restores a snooze with no wake time after undoing a settle", async () => { - const plan = planThreadUndo("settle", { + const now = "2026-11-17T02:00:00Z"; + const snoozed = { snoozedAt: "2026-11-17T00:00:00Z", snoozedUntil: null, - }); + hasPendingApprovals: false, + hasPendingUserInput: false, + }; + // A question asked since the snooze woke the thread; Undo leaves it awake. + expect( + planThreadUndo( + "settle", + { ...snoozed, hasPendingUserInput: true, pendingUserInputAt: "2026-11-17T01:00:00Z" }, + now, + ), + ).toEqual([{ action: "unsettle", restoreUnsettledAt: null }]); + const plan = planThreadUndo("settle", snoozed, now); expect(plan).toEqual([ { action: "unsettle", restoreUnsettledAt: null }, { action: "snooze", snoozedUntil: null }, diff --git a/packages/client-runtime/src/state/threadUndo.ts b/packages/client-runtime/src/state/threadUndo.ts index 4cd62f333569e..7c2679ab8fe10 100644 --- a/packages/client-runtime/src/state/threadUndo.ts +++ b/packages/client-runtime/src/state/threadUndo.ts @@ -1,3 +1,5 @@ +import { effectiveSnoozed, type ThreadSnoozeShell } from "./threadSettled.ts"; + // Shared across hook instances so sidebar, header and menu actions invalidate each other. const currentActions = new Map(); const listeners = new Set<() => void>(); @@ -47,23 +49,26 @@ export type ThreadUndoPlan = readonly [ThreadUndoStep, ...ThreadUndoStep[]]; export function planThreadUndo( action: "settle" | "snooze" | "unpin", - thread?: { - readonly pinnedAt?: string | null; - readonly pinOrderKey?: string | null; - readonly activeOrderKey?: string | null; - readonly unsettledAt?: string | null; - readonly snoozedUntil?: string | null; - readonly snoozedAt?: string | null; - } | null, + thread?: + | (ThreadSnoozeShell & { + readonly pinnedAt?: string | null; + readonly pinOrderKey?: string | null; + readonly activeOrderKey?: string | null; + readonly unsettledAt?: string | null; + }) + | null, + // @effect-diagnostics-next-line globalDate:off + now = new Date().toISOString(), ): ThreadUndoPlan { if (action === "snooze") return [{ action: "unsnooze" }]; const pin: ThreadUndoStep = { action: "pin", ...(thread?.pinOrderKey != null ? { orderKey: thread.pinOrderKey } : {}), }; - // Pinning clears snooze on the server; restore it after restoring pin placement. + // Pinning clears snooze on the server; restore it after restoring pin placement. A snooze a + // question or failure already woke stays woken, or the restore would hide the thread again. const snooze = - thread?.snoozedUntil != null || thread?.snoozedAt != null + thread != null && effectiveSnoozed(thread, { now }) ? [{ action: "snooze" as const, snoozedUntil: thread.snoozedUntil ?? null }] : []; if (action === "unpin") return [pin, ...snooze]; diff --git a/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts b/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts index e936cbdede910..1bdee527d8092 100644 --- a/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts +++ b/packages/issue-tracker-linear/src/server/LinearIssueTracker.ts @@ -433,7 +433,7 @@ export const make: Effect.Effect + listContainers: Effect.fn("LinearIssueTracker.listContainers")(() => linear.viewer().pipe( Effect.map((data) => ({ workspace: data.workspace, @@ -443,13 +443,15 @@ export const make: Effect.Effect + ), + listStates: Effect.fn("LinearIssueTracker.listStates")(({ containerId }) => linear .getTeamStates(containerId) .pipe( Effect.map((states) => inWorkflowOrder(states).map(({ id, name }) => ({ id, name }))), ), - readStatuses: ({ containerId, keys }) => { + ), + readStatuses: Effect.fn("LinearIssueTracker.readStatuses")(({ containerId, keys }) => { const numbers = [ ...new Set( keys.flatMap((key) => { @@ -469,7 +471,7 @@ export const make: Effect.Effect ({ key: issue.identifier, stateId: issue.stateId })), ), ); - }, + }), }, // The id, not the display name: it is what the involvement filters compare against. From b50777bf0c8978e2f9d9108ad10e76b03b357dff Mon Sep 17 00:00:00 2001 From: Pixel Perfect Date: Fri, 20 Nov 2026 16:09:24 -0800 Subject: [PATCH 3/6] refactor(server): name the issue automation projection reads --- .../src/orchestration-v2/ProjectionStore.ts | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 276017a5be260..2ab296b227a68 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -9014,16 +9014,15 @@ export const layer: Layer.Layer = INDEXED BY idx_orchestration_events_thread_organization WHERE stream_id = ${threadId} AND ${sql.literal(THREAD_ORGANIZATION_EVENT_CONDITION)} )`; - const getIssueAutomationRevision: ProjectionStoreV2Shape["getIssueAutomationRevision"] = ( - threadId, - ) => - sql<{ readonly revision: number }>` - SELECT ${issueAutomationRevision(sql`${threadId}`)} AS revision - `.pipe( - Effect.map((rows) => rows[0]?.revision ?? 0), - Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })), - ); - const getIssueAutomationCandidates: ProjectionStoreV2Shape["getIssueAutomationCandidates"] = + const getIssueAutomationRevision = Effect.fn("ProjectionStore.getIssueAutomationRevision")( + function* (threadId: Parameters[0]) { + const rows = yield* sql<{ readonly revision: number }>` + SELECT ${issueAutomationRevision(sql`${threadId}`)} AS revision + `.pipe(Effect.mapError((cause) => new ProjectionStoreSetupError({ cause }))); + return rows[0]?.revision ?? 0; + }, + ); + const getIssueAutomationCandidates = Effect.fn("ProjectionStore.getIssueAutomationCandidates")( () => sql<{ readonly payload_json: string; readonly revision: number }>` SELECT t.payload_json, ${issueAutomationRevision(sql.literal("t.thread_id"))} AS revision @@ -9039,7 +9038,8 @@ export const layer: Layer.Layer = ), ), Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })), - ); + ), + ); const getOpenRemoteDelegatedTasks: ProjectionStoreV2Shape["getOpenRemoteDelegatedTasks"] = sql<{ readonly thread_id: string; From 1b854bb95c7d06e40431973d9ce151353f4eaf83 Mon Sep 17 00:00:00 2001 From: Pixel Perfect Date: Sat, 21 Nov 2026 11:17:12 -0800 Subject: [PATCH 4/6] fix(issues): status rules leave threads with auto-settle off alone A thread whose Auto-settle behavior is Never is no longer a candidate for issue status rules, so none of wake, snooze or settle applies, and the observation pruning drops an action that was waiting for the thread to go idle. The orchestrator also refuses a queued decision once auto-settle is off, which covers a switch made while a sweep is reading statuses. --- .../IssueThreadAutomationService.test.ts | 51 +++++++++--- .../src/issue/IssueThreadAutomationService.ts | 2 + .../Orchestrator.control-reads.test.ts | 79 ++++++++++--------- .../src/orchestration-v2/Orchestrator.ts | 5 +- docs/user/source-control.md | 4 +- 5 files changed, 91 insertions(+), 50 deletions(-) diff --git a/apps/server/src/issue/IssueThreadAutomationService.test.ts b/apps/server/src/issue/IssueThreadAutomationService.test.ts index 7ec0c1964ea25..9f3dacd38bfcc 100644 --- a/apps/server/src/issue/IssueThreadAutomationService.test.ts +++ b/apps/server/src/issue/IssueThreadAutomationService.test.ts @@ -94,6 +94,11 @@ function thread(issues: ReadonlyArray): OrchestrationV2AppThrea }; } +const autoSettleOff = (item: OrchestrationV2AppThread, off: boolean): OrchestrationV2AppThread => ({ + ...item, + autoSettleDisabledAt: off ? DateTime.makeUnsafe(instant) : null, +}); + function setup( rules: ReadonlyArray = [rule()], links: ReadonlyArray = [link("ENG-1")], @@ -350,23 +355,47 @@ describe("IssueThreadAutomationService", () => { }).pipe(Effect.provide(layer)); }); - it.effect("keeps an action for a busy thread and drops it after manual organizing", () => { + it.effect.each(["manual organizing", "auto-settle off"] as const)( + "keeps an action for a busy thread and drops it after %s", + (change) => { + const { state, layer } = setup(); + return Effect.gen(function* () { + const automation = yield* Automation.IssueThreadAutomationService; + const store = yield* Observations.IssueThreadAutomation; + yield* automation.sweep; + state.busy = true; + state.statuses.set("team-a", [{ key: "ENG-1", stateId: "done" }]); + yield* automation.sweep; + const pending = (yield* store.list).get(threadId)?.pending; + expect(pending?.action).toBe("settle"); + expect(pending?.commandId).not.toBe(state.attempts.at(-1)?.commandId); + if (change === "manual organizing") state.revision++; + else state.threads = state.threads.map((item) => autoSettleOff(item, true)); + state.busy = false; + yield* automation.sweep; + expect(state.commands).toHaveLength(0); + expect((yield* store.list).get(threadId)?.pending ?? null).toBeNull(); + }).pipe(Effect.provide(layer)); + }, + ); + + it.effect.each([ + { action: "wake", from: "waiting", to: "open" }, + { action: "snooze", from: "open", to: "waiting" }, + { action: "settle", from: "open", to: "done" }, + ] as const)("never applies $action to a thread with auto-settle off", ({ from, to }) => { const { state, layer } = setup(); + state.statuses.set("team-a", [{ key: "ENG-1", stateId: from }]); return Effect.gen(function* () { const automation = yield* Automation.IssueThreadAutomationService; - const store = yield* Observations.IssueThreadAutomation; yield* automation.sweep; - state.busy = true; - state.statuses.set("team-a", [{ key: "ENG-1", stateId: "done" }]); + state.threads = state.threads.map((item) => autoSettleOff(item, true)); + state.statuses.set("team-a", [{ key: "ENG-1", stateId: to }]); yield* automation.sweep; - const pending = (yield* store.list).get(threadId)?.pending; - expect(pending?.action).toBe("settle"); - expect(pending?.commandId).not.toBe(state.attempts.at(-1)?.commandId); - state.revision++; - state.busy = false; + // Turned back on, the thread starts from its issues' statuses at that time. + state.threads = state.threads.map((item) => autoSettleOff(item, false)); yield* automation.sweep; - expect(state.commands).toHaveLength(0); - expect((yield* store.list).get(threadId)?.pending).toBeNull(); + expect(state.attempts).toEqual([]); }).pipe(Effect.provide(layer)); }); diff --git a/apps/server/src/issue/IssueThreadAutomationService.ts b/apps/server/src/issue/IssueThreadAutomationService.ts index 995a1f7179a22..5c64ecf08ed9a 100644 --- a/apps/server/src/issue/IssueThreadAutomationService.ts +++ b/apps/server/src/issue/IssueThreadAutomationService.ts @@ -278,6 +278,8 @@ const make = Effect.gen(function* () { const rulesFingerprint = automationFingerprint(config.issueThreadAutomationRules); const candidates = (yield* projections.getIssueAutomationCandidates()).flatMap( ({ thread, revision }) => { + // Rules leave a thread with auto-settle off alone; pruning drops any action it waited on. + if (thread.autoSettleDisabledAt != null) return []; const links = rules.flatMap((rule) => (thread.issues ?? []) .filter((link) => matches(rule, link)) diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 2284f75c8f110..bb9e1fd4902a3 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -202,42 +202,49 @@ it.effect.each(["settle of a pinned thread", "wake of an awake thread"] as const }).pipe(Effect.provide(layerTest)), ); -it.effect.each(["same-value manual wake", "user message", "changed rules"] as const)( - "issue automation refuses a decision made before a %s", - (change) => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const projections = yield* ProjectionStore.ProjectionStoreV2; - const threadId = ThreadId.make(`thread:automation-guard:${change}`); - yield* createThread(threadId); - const expectedRevision = yield* projections.getIssueAutomationRevision(threadId); - if (change === "same-value manual wake") { - yield* orchestrator.dispatch({ - type: "thread.unsnooze", - commandId: CommandId.make(`manual-wake:${change}`), - threadId, - reason: "user", - }); - } else if (change === "user message") { - yield* queueUserMessage(threadId, `manual-work:${change}`); - } - const error = yield* orchestrator - .dispatch({ - type: "thread.issue-automation.apply", - commandId: CommandId.make(`stale:${change}`), - threadId, - action: "settle", - expectedRevision, - rulesFingerprint: change === "changed rules" ? "stale rules" : automationFingerprint([]), - }) - .pipe(Effect.flip); - assert.equal(error._tag, "OrchestratorDispatchError"); - assert.equal( - error._tag === "OrchestratorDispatchError" && error.cause, - ISSUE_AUTOMATION_STALE, - ); - assert.isNull((yield* projections.getThread(threadId)).settledAt); - }).pipe(Effect.provide(layerTest)), +it.effect.each([ + "same-value manual wake", + "user message", + "switch to auto-settle Never", + "changed rules", +] as const)("issue automation refuses a decision made before a %s", (change) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make(`thread:automation-guard:${change}`); + yield* createThread(threadId); + const expectedRevision = yield* projections.getIssueAutomationRevision(threadId); + if (change === "same-value manual wake") { + yield* orchestrator.dispatch({ + type: "thread.unsnooze", + commandId: CommandId.make(`manual-wake:${change}`), + threadId, + reason: "user", + }); + } else if (change === "user message") { + yield* queueUserMessage(threadId, `manual-work:${change}`); + } else if (change === "switch to auto-settle Never") { + yield* orchestrator.dispatch({ + type: "thread.auto-settle.set", + commandId: CommandId.make(`auto-settle-off:${change}`), + threadId, + enabled: false, + }); + } + const error = yield* orchestrator + .dispatch({ + type: "thread.issue-automation.apply", + commandId: CommandId.make(`stale:${change}`), + threadId, + action: "settle", + expectedRevision, + rulesFingerprint: change === "changed rules" ? "stale rules" : automationFingerprint([]), + }) + .pipe(Effect.flip); + assert.equal(error._tag, "OrchestratorDispatchError"); + assert.equal(error._tag === "OrchestratorDispatchError" && error.cause, ISSUE_AUTOMATION_STALE); + assert.isNull((yield* projections.getThread(threadId)).settledAt); + }).pipe(Effect.provide(layerTest)), ); it.effect("issue automation waits for queued work, then applies under a new command id", () => diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 21644b9f3863c..0b9e0700d34e1 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -15888,12 +15888,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const thread = yield* projectionStore .getThread(command.threadId) .pipe(Effect.mapError(toProjectionError)); - // Organizing the thread or changing a rule after the decision cancels it. + // Organizing the thread, turning its auto-settle off, or changing a rule cancels a decision. if ( automationFingerprint(settings.issueThreadAutomationRules) !== command.rulesFingerprint || revision !== command.expectedRevision || thread.deletedAt !== null || - thread.archivedAt !== null + thread.archivedAt !== null || + thread.autoSettleDisabledAt != null ) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, diff --git a/docs/user/source-control.md b/docs/user/source-control.md index ec384985a7549..de9f37a9e3bed 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -450,7 +450,9 @@ linked issues wakes when any of them maps to **Wake**, settles only when all of the thread as it is. A snooze from a rule has no wake time; the thread shows **∞** in the Snoozed list until a status change, **Wake thread**, or a message wakes it. A thread with work still running waits until it is idle before it snoozes or settles. A rule never settles a pinned -thread. +thread. Rules leave a thread whose **Auto-settle behavior** is **Never** alone: they do not wake, +snooze, or settle it, and an action still waiting for the thread to go idle is dropped. After you +switch it back to **Follow settings**, only later status changes count. ## GitHub stacks From 9facb8e86329e3d6f251157bbf9b947609ced135 Mon Sep 17 00:00:00 2001 From: Pixel Perfect Date: Mon, 23 Nov 2026 10:13:41 -0800 Subject: [PATCH 5/6] fix(issues): address the second round of review findings - A linked issue no rule reads is in no bucket, so the other issues can wake the thread but never snooze or settle it. - A rule saved while a sweep reads statuses no longer uses up the decision; the next sweep decides again, from a new baseline if the thread's rules changed. - The active shell index also covers $.snoozedAt, so listing active threads again parses no thread payloads. - Saving a tracker credential refreshes the teams and statuses in Settings. - The user guide says the baseline is the first check after a rule is saved. - The provider-switch test asserts that background work refused the settle. --- .../IssueThreadAutomationService.test.ts | 52 +++++++++++++------ .../src/issue/IssueThreadAutomationService.ts | 18 +++++-- .../Orchestrator.control-reads.test.ts | 2 +- .../ProviderSwitch.integration.test.ts | 39 +++++++++----- .../Migrations/111_IssueThreadAutomation.ts | 22 ++++++++ docs/user/source-control.md | 10 ++-- .../client-runtime/src/state/issueTrackers.ts | 10 +++- 7 files changed, 111 insertions(+), 42 deletions(-) diff --git a/apps/server/src/issue/IssueThreadAutomationService.test.ts b/apps/server/src/issue/IssueThreadAutomationService.test.ts index 9f3dacd38bfcc..4b537b94529aa 100644 --- a/apps/server/src/issue/IssueThreadAutomationService.test.ts +++ b/apps/server/src/issue/IssueThreadAutomationService.test.ts @@ -293,20 +293,30 @@ describe("IssueThreadAutomationService", () => { }).pipe(Effect.provide(database)); }); - it.effect("snoozes when one team's issue waits, and settles once both are done", () => { - const { state, layer } = setup([rule(), rule("team-b")], [link("ENG-1"), link("OPS-2")]); - state.statuses.set("team-b", [{ key: "OPS-2", stateId: "waiting" }]); - return Effect.gen(function* () { - const automation = yield* Automation.IssueThreadAutomationService; - yield* automation.sweep; - state.statuses.set("team-a", [{ key: "ENG-1", stateId: "done" }]); - yield* automation.sweep; - state.statuses.set("team-b", [{ key: "OPS-2", stateId: "done" }]); - yield* automation.sweep; - // OPS-2 is outside team-a, and ENG-1 outside team-b; neither counts as unread. - expect(actions(state.commands)).toEqual(["snooze", "settle"]); - }).pipe(Effect.provide(layer)); - }); + it.effect.each([ + { teams: "both teams", expected: ["snooze", "settle"] }, + { teams: "team-a only", expected: [] }, + ] as const)( + "snoozes when one team's issue waits, and settles once both are done, with rules for $teams", + ({ teams, expected }) => { + const { state, layer } = setup(teams === "both teams" ? [rule(), rule("team-b")] : [rule()], [ + link("ENG-1"), + link("OPS-2"), + ]); + state.statuses.set("team-b", [{ key: "OPS-2", stateId: "waiting" }]); + return Effect.gen(function* () { + const automation = yield* Automation.IssueThreadAutomationService; + yield* automation.sweep; + state.statuses.set("team-a", [{ key: "ENG-1", stateId: "done" }]); + yield* automation.sweep; + state.statuses.set("team-b", [{ key: "OPS-2", stateId: "done" }]); + yield* automation.sweep; + // OPS-2 is outside team-a, and ENG-1 outside team-b; neither counts as unread. With no + // team-b rule, OPS-2 is in no bucket. + expect(actions(state.commands)).toEqual(expected); + }).pipe(Effect.provide(layer)); + }, + ); it.effect.each([false, true])( "waits for an issue missing from a read, unless the thread was organized meanwhile (%s)", @@ -496,7 +506,14 @@ describe("IssueThreadAutomationService", () => { }).pipe(Effect.provide(layer)); }); - it.effect("drops a decision when its rule is removed during the status read", () => { + it.effect.each([ + { change: "its rule is removed", rules: [], expected: [] }, + { + change: "another workspace gets a rule", + rules: [rule(), rule("team-z", { workspace: "elsewhere" })], + expected: ["settle"], + }, + ])("decides again when $change during the status read", ({ rules, expected }) => { const { state, layer } = setup(); return Effect.gen(function* () { const automation = yield* Automation.IssueThreadAutomationService; @@ -510,10 +527,13 @@ describe("IssueThreadAutomationService", () => { state.statuses.set("team-a", [{ key: "ENG-1", stateId: "done" }]); const sweep = yield* automation.sweep.pipe(Effect.forkChild); yield* Deferred.await(started); - yield* settings.updateSettings({ issueThreadAutomationRules: [] }); + yield* settings.updateSettings({ issueThreadAutomationRules: rules }); yield* Deferred.succeed(finish, undefined); yield* Fiber.join(sweep); expect(state.commands).toHaveLength(0); + state.beforeRead = Effect.void; + yield* automation.sweep; + expect(actions(state.commands)).toEqual(expected); }).pipe(Effect.provide(layer)); }); }); diff --git a/apps/server/src/issue/IssueThreadAutomationService.ts b/apps/server/src/issue/IssueThreadAutomationService.ts index 5c64ecf08ed9a..d30bc34b2cb5f 100644 --- a/apps/server/src/issue/IssueThreadAutomationService.ts +++ b/apps/server/src/issue/IssueThreadAutomationService.ts @@ -342,10 +342,17 @@ const make = Effect.gen(function* () { yield* SubscriptionRef.update(refreshes, (current) => new Map(current).set(id, next)); } } - const actions = eligible.map(({ rule, link }) => { - const stateId = batchOf(rule)?.get(link.key.toUpperCase()); - return stateId === undefined ? null : (rule.mappings[stateId] ?? "unchanged"); - }); + const covered = new Set(eligible.map(({ link }) => link)); + const actions = [ + ...eligible.map(({ rule, link }) => { + const stateId = batchOf(rule)?.get(link.key.toUpperCase()); + return stateId === undefined ? null : (rule.mappings[stateId] ?? "unchanged"); + }), + // A linked issue no rule reads is in no bucket. + ...(thread.issues ?? []) + .filter((link) => !covered.has(link)) + .map(() => "unchanged" as const), + ]; const action = aggregateIssueActions(actions); const unknown = actions.includes(null); let pending = baseline?.pending ?? null; @@ -380,8 +387,9 @@ const make = Effect.gen(function* () { const waiting = yield* saveLock.withPermit( Effect.gen(function* () { const current = yield* settings.getSettings; + // The next sweep decides again, from a new baseline if this thread's rules changed. if (automationFingerprint(current.issueThreadAutomationRules) !== rulesFingerprint) - return false; + return true; return yield* orchestrator.dispatch(command).pipe( Effect.as(false), // Only a stale decision is dropped; a busy thread or a failed attempt tries again. diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index bb9e1fd4902a3..a54a5545186ad 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -247,7 +247,7 @@ it.effect.each([ }).pipe(Effect.provide(layerTest)), ); -it.effect("issue automation waits for queued work, then applies under a new command id", () => +it.effect("issue automation waits for a preparing run, then applies under a new command id", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const projections = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index 5f1e7472f63c6..92bc5320a3973 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -68,7 +68,10 @@ import { import * as ProviderReplayHarness from "./ProviderReplayHarness.ts"; import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; -import { automationFingerprint } from "../../issue/issueAutomation.ts"; +import { + automationFingerprint, + ISSUE_AUTOMATION_WAITS_FOR_IDLE, +} from "../../issue/issueAutomation.ts"; const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); @@ -4680,20 +4683,28 @@ describe("orchestration v2 provider switching", () => { }) .pipe( Effect.flatMap(({ storedEvents }) => - orchestrator.dispatch({ - type: "thread.issue-automation.apply", - commandId, - threadId, - action: "settle", - expectedRevision: storedEvents.at(-1)?.sequence ?? 0, - rulesFingerprint: automationFingerprint([]), - }), + orchestrator + .dispatch({ + type: "thread.issue-automation.apply", + commandId, + threadId, + action: "settle", + expectedRevision: storedEvents.at(-1)?.sequence ?? 0, + rulesFingerprint: automationFingerprint([]), + }) + .pipe(Effect.flip), + ), + Effect.map((error) => + assert.equal( + error._tag === "OrchestratorDispatchError" && error.cause, + ISSUE_AUTOMATION_WAITS_FOR_IDLE, + ), ), ); - yield* ( - change === "issue-settle" - ? settleByRule - : orchestrator.dispatch( + yield* change === "issue-settle" + ? settleByRule + : orchestrator + .dispatch( change === "runtime-mode" ? { type: "thread.runtime-mode.set", @@ -4710,7 +4721,7 @@ describe("orchestration v2 provider switching", () => { modelSelection: secondSelection, }, ) - ).pipe(Effect.ignore); + .pipe(Effect.ignore); yield* worker.drain(); const projection = yield* orchestrator.getThreadProjection(threadId); diff --git a/apps/server/src/persistence/Migrations/111_IssueThreadAutomation.ts b/apps/server/src/persistence/Migrations/111_IssueThreadAutomation.ts index d51f559beeef0..80f21b46c43d1 100644 --- a/apps/server/src/persistence/Migrations/111_IssueThreadAutomation.ts +++ b/apps/server/src/persistence/Migrations/111_IssueThreadAutomation.ts @@ -18,4 +18,26 @@ export default Effect.gen(function* () { ON orchestration_events(stream_id, sequence) WHERE ${THREAD_ORGANIZATION_EVENT_CONDITION} `); + // ProjectionStore.listActiveShellIndex now also reads `$.snoozedAt`, so 098's index gains it. + yield* sql`DROP INDEX IF EXISTS orchestration_v2_projection_threads_active_shell_idx`; + yield* sql` + CREATE INDEX orchestration_v2_projection_threads_active_shell_idx + ON orchestration_v2_projection_threads( + updated_at, + thread_id, + project_id, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.relationshipToParent') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.parentThreadId') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.rootThreadId') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.sideChat') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.settledOverride') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.settledAt') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.pinnedAt') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.pinOrderKey') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.snoozedUntil') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.snoozedAt') END, + CASE WHEN json_valid(payload_json) THEN json_type(payload_json, '$.pullRequests[0]') END + ) + WHERE deleted_at IS NULL AND archived_at IS NULL + `; }); diff --git a/docs/user/source-control.md b/docs/user/source-control.md index de9f37a9e3bed..b35917fc524ca 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -443,11 +443,11 @@ to one of the team's issues, in any project. It changes threads, never issues. L supported tracker. The server checks linked issues about once a minute while it runs, with or without a client -open. Only a status change counts: saving a rule records the current statuses first, and a thread -you organize by hand stays that way until one of its issues moves again. A thread with several -linked issues wakes when any of them maps to **Wake**, settles only when all of them map to -**Settle**, and otherwise snoozes. A status in no bucket, or one that could not be read, leaves -the thread as it is. A snooze from a rule has no wake time; the thread shows **∞** in the +open. Only a status change counts: the first check after you save a rule records the current +statuses, and a thread you organize by hand stays that way until one of its issues moves again. A +thread wakes when any linked issue maps to **Wake**. Short of that, it stays as it is while any +linked issue has a status in no bucket, could not be read, or belongs to a team without a rule; +it settles only when all of them map to **Settle**, and otherwise snoozes. A snooze from a rule has no wake time; the thread shows **∞** in the Snoozed list until a status change, **Wake thread**, or a message wakes it. A thread with work still running waits until it is idle before it snoozes or settles. A rule never settles a pinned thread. Rules leave a thread whose **Auto-settle behavior** is **Never** alone: they do not wake, diff --git a/packages/client-runtime/src/state/issueTrackers.ts b/packages/client-runtime/src/state/issueTrackers.ts index 5d549cd6236db..a3d28032a1009 100644 --- a/packages/client-runtime/src/state/issueTrackers.ts +++ b/packages/client-runtime/src/state/issueTrackers.ts @@ -38,9 +38,14 @@ export function createIssueTrackerEnvironmentAtoms( label: "environment-data:issue-trackers:automation", tag: WS_METHODS.issueTrackersAutomation, }); + // Bumped by each credential save, so a mounted catalog drops what the old credential could reach. + const credentialChanges = Atom.family((_environmentId: string) => + Atom.make(0).pipe(Atom.keepAlive), + ); const automationCatalog = createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:issue-trackers:automation-catalog", tag: WS_METHODS.issueTrackersAutomationCatalog, + refreshTrigger: ({ environmentId }) => credentialChanges(environmentId), }); const refresh = (environmentId: Parameters[0]["environmentId"]) => connections({ environmentId, input: {} }); @@ -74,7 +79,10 @@ export function createIssueTrackerEnvironmentAtoms( scheduler: commandScheduler, concurrency: serialPerEnvironment, onSettled: (target, registry) => - Effect.sync(() => registry.refresh(refresh(target.environmentId))), + Effect.sync(() => { + registry.refresh(refresh(target.environmentId)); + registry.update(credentialChanges(target.environmentId), (count) => count + 1); + }), }), bindProject: createEnvironmentRpcCommand(runtime, { label: "environment-data:issue-trackers:bind-project", From 43d13a3d890191966abfd1cbe5c326a52abbbc83 Mon Sep 17 00:00:00 2001 From: Pixel Perfect Date: Mon, 23 Nov 2026 10:15:50 -0800 Subject: [PATCH 6/6] fix(issues): offer status rules only on a tracker's first account Rules read statuses without naming an account, so they run as the tracker's first one. Settings showed the rules on every account's row and listed the first account's teams under the others; it now shows them on the first account only, and the user guide says which account they use. --- .../settings/SettingsSourceControlDetailRouteScreens.tsx | 5 ++++- apps/web/src/components/settings/IssueTrackerSettings.tsx | 5 ++++- docs/user/source-control.md | 3 ++- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx index 808f5972ea79b..8f2e55c058cfb 100644 --- a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx +++ b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx @@ -239,7 +239,10 @@ export function SettingsIssueTrackerRouteScreen({ /> ) : null} - {usable && tracker.automationContainer !== undefined ? ( + {/* Rules read statuses as the tracker's first account. */} + {usable && + tracker.automationContainer !== undefined && + route.params.accountId === undefined ? ( - {usable && tracker.automationContainer !== undefined ? ( + {/* Rules read statuses as the tracker's first account. */} + {usable && + tracker.automationContainer !== undefined && + tracker.accountId === undefined ? (