feat(issues): wake, snooze and settle threads from Linear team statuses #39940
OpenPixPMusic(GitHub profile, opens in a new tab)wants to merge 6 commits into
main fromrefs/pull/39940/headopened View on GitHubtanstack-source added labelsfeature
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -0,0 +311,21 @@311+ yield* automation.sweep;312+ state.statuses.set("team-a", [{ key: "ENG-1", stateId: "done" }]);313+ yield* automation.sweep;314+ expect(state.commands).toHaveLength(0);315+ if (manual) state.revision++;316+ state.statuses.set("team-a", [317+ { key: "ENG-1", stateId: "done" },318+ { key: "ENG-2", stateId: "waiting" },319+ ]);320+ yield* automation.sweep;321+ expect(state.commands).toMatchObject(322+ manual ? [] : [{ action: "snooze", expectedRevision: 1 }],323+ );324+ }).pipe(Effect.provide(layer));325+ },326+ );327+328+ it.effect("ignores the same issue key in another workspace", () => {329+ const { state, layer } = setup(330+ [rule()],331+ [link("ENG-1"), link("ENG-1", { url: "https://linear.app/another/issue/ENG-1" })],@@ -0,0 +159,21 @@159+ const existing = (yield* settings.getSettings).issueThreadAutomationRules.find(160+ (candidate) => candidate.id === requested.id,161+ );162+ const read = yield* catalog({163+ tracker: requested.tracker,164+ containerId: requested.containerId,165+ }).pipe(Effect.result);166+ const reachable =167+ read._tag === "Success" &&168+ sameWorkspace(read.success.workspace, requested.workspace) &&169+ (existing === undefined || sameWorkspace(existing.workspace, requested.workspace));170+ if (!reachable) {171+ // A rule the current connection cannot reach can still be switched off.172+ if (requested.enabled || existing === undefined)173+ return yield* read._tag === "Failure"174+ ? read.failure175+ : new IssueAutomationError({176+ operation: "save",177+ detail: "The connected account is in another workspace.",178+ });179+ rule = { ...existing, enabled: false };@@ -0,0 +364,21 @@364+ type: "thread.issue-automation.apply" as const,365+ commandId: pending.commandId,366+ threadId: thread.id,367+ action: pending.action,368+ expectedRevision: pending.revision,369+ rulesFingerprint,370+ };371+ const waiting = yield* saveLock.withPermit(372+ Effect.gen(function* () {373+ const current = yield* settings.getSettings;374+ if (automationFingerprint(current.issueThreadAutomationRules) !== rulesFingerprint)375+ return false;376+ return yield* orchestrator.dispatch(command).pipe(377+ Effect.as(false),378+ // A busy thread keeps the action for the next sweep; any other refusal drops it.379+ Effect.catch((error) =>380+ Effect.succeed(381+ error._tag === "OrchestratorCommandPreviouslyRejectedError" ||382+ (error._tag === "OrchestratorDispatchError" &&383+ error.cause === ISSUE_AUTOMATION_WAITS_FOR_IDLE),384+ ),@@ -15446,0 +15461,21 @@15461+ if (15462+ automationFingerprint(settings.issueThreadAutomationRules) !== command.rulesFingerprint ||15463+ revision !== command.expectedRevision ||15464+ thread.deletedAt !== null ||15465+ thread.archivedAt !== null15466+ ) {15467+ return yield* new OrchestratorDispatchError({15468+ commandId: command.commandId,15469+ commandType: command.type,15470+ cause: ISSUE_AUTOMATION_STALE,15471+ });15472+ }15473+ const now = yield* DateTime.now;15474+ const nowMs = DateTime.toEpochMillis(now);15475+ const unsettled =15476+ thread.settledOverride === "settled"15477+ ? { settledOverride: "active" as const, settledAt: null, unsettledAt: now }15478+ : {};15479+ if (command.action === "wake") {15480+ const snoozed = snoozeHolds(thread, nowMs);15481+ if (!snoozed && thread.settledOverride !== "settled") break;@@ -15446,0 +15487,21 @@15487+ type: snoozed ? "thread.unsnoozed" : "thread.unsettled",15488+ threadId: thread.id,15489+ providerInstanceId: thread.providerInstanceId,15490+ occurredAt: now,15491+ payload: {15492+ ...thread,15493+ ...unsettled,15494+ ...(snoozed ? { snoozedUntil: now, lastSnoozeWakeAt: now } : {}),15495+ updatedAt: now,15496+ },15497+ });15498+ break;15499+ }15500+ const { runs, runtimeRequests } = yield* projectionStore15501+ .getThreadRecords(command.threadId, ["runs", "runtimeRequests"])15502+ .pipe(Effect.mapError(toProjectionError));15503+ if (15504+ runs.some((run) =>15505+ ["queued", "preparing", "starting", "running", "waiting"].includes(run.status),15506+ ) ||15507+ runtimeRequests.some((request) => request.status === "pending")@@ -4968,4 +4980,7 @@49684980 AND json_extract(t.payload_json, '$.limitRecovery.autoResume') = 149694981 AND julianday(json_extract(item.payload_json, '$.failure.resetAt')) <= julianday(${DateTime.formatIso(options.now)})49704982 AND (4971- json_extract(t.payload_json, '$.snoozedUntil') IS NULL4983+ (4984+ json_extract(t.payload_json, '$.snoozedUntil') IS NULL4985+ AND json_extract(t.payload_json, '$.snoozedAt') IS NULL4986+ )@@ -8857,3 +8873,5 @@88578873 )88588874 .pipe(Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })));885988758876+ // Pruning old events can only move a revision, which drops a waiting action rather than8877+ // applying one that is stale. Without the hint, SQLite walks every event of the thread.@@ -124,4 +124,5 @@124124 }125125126126 export interface SnoozeThreadInput extends ThreadCommandInput {127- readonly snoozedUntil: string;127+ /** Null snoozes until the thread is woken. */128+ readonly snoozedUntil: string | null;@@ -61,5 +63,5 @@6163 };6264 // Pinning clears snooze on the server; restore it after restoring pin placement.6365 const snooze =64- thread?.snoozedUntil != null65- ? [{ action: "snooze" as const, snoozedUntil: thread.snoozedUntil }]66+ thread?.snoozedUntil != null || thread?.snoozedAt != null67+ ? [{ action: "snooze" as const, snoozedUntil: thread.snoozedUntil ?? null }]@@ -649,0 +701,21 @@701+ Schema.Struct({702+ ruleId: TrimmedNonEmptyString,703+ checkedAt: Schema.NullOr(IsoDateTime),704+ error: Schema.NullOr(Schema.String),705+ }),706+ ),707+});708+export type IssueAutomationOverview = typeof IssueAutomationOverview.Type;709+710+/** A null rule removes the rule with that id. */711+export const IssueAutomationSaveInput = Schema.Struct({712+ id: TrimmedNonEmptyString,713+ rule: Schema.NullOr(IssueAutomationRule),714+});715+export type IssueAutomationSaveInput = typeof IssueAutomationSaveInput.Type;716+717+export class IssueAutomationError extends Schema.TaggedError<IssueAutomationError>()(718+ "IssueAutomationError",719+ {720+ operation: Schema.String,721+ detail: Schema.optional(TrimmedNonEmptyString),@@ -427,3 +431,6 @@427431 })),428432 ),429433434+ // Team ids are unique across workspaces, so another workspace's credential finds none.435+ automation: {436+ listContainers: () =>
Pusheda0837fe
Pushedd99e0b7
- @@ -0,0 +54,21 @@54+ /** Reads every linked issue's status once and organizes the threads whose issues moved. */55+ readonly sweep: Effect.Effect<void, IssueAutomationError>;56+ /** Rises each time a sweep sees the issue's status change; 0 until it does. */57+ readonly subscribeStatusRefreshes: (input: {58+ readonly tracker: IssueTrackerKind;59+ readonly key: string;60+ }) => Stream.Stream<number>;61+ }62+>()("t3/issue/IssueThreadAutomationService") {}63+64+type RuntimeStatus = IssueAutomationOverview["status"][number];65+66+const RETRY_AFTER_MS = 60_000;67+const isIssueTrackerError = Schema.is(IssueTrackerError);68+const isIssueAutomationError = Schema.is(IssueAutomationError);69+const wrap = (operation: string) => (cause: unknown) =>70+ isIssueAutomationError(cause)71+ ? cause72+ : new IssueAutomationError({73+ operation,74+ ...(isIssueTrackerError(cause) && cause.detail.trim() ? { detail: cause.detail } : {}),@@ -0,0 +286,21 @@286+ .map((link) => ({ rule, link, key: observationKey(rule, link) })),287+ );288+ return links.length === 0 ? [] : [{ thread, revision, links }];289+ },290+ );291+ const previous = yield* observations.list;292+ const now = yield* Clock.currentTimeMillis;293+ // Null for a rule whose statuses could not be read this sweep.294+ const batches = new Map<string, ReadonlyMap<string, string> | null>();295+ for (const rule of rules) {296+ const keys = [297+ ...new Set(298+ candidates.flatMap(({ links }) =>299+ links.filter((entry) => entry.rule === rule).map(({ link }) => link.key),300+ ),301+ ),302+ ];303+ if (keys.length === 0) continue;304+ batches.set(305+ rule.id,306+ (retryAt.get(rule.id) ?? 0) > now ? null : yield* readStatuses(rule, keys, now),@@ -0,0 +299,21 @@299+ links.filter((entry) => entry.rule === rule).map(({ link }) => link.key),300+ ),301+ ),302+ ];303+ if (keys.length === 0) continue;304+ batches.set(305+ rule.id,306+ (retryAt.get(rule.id) ?? 0) > now ? null : yield* readStatuses(rule, keys, now),307+ );308+ }309+ const refreshed = new Set<string>();310+ for (const { thread, revision, links } of candidates) {311+ const batchOf = (rule: IssueAutomationRule) => batches.get(rule.id) ?? null;312+ const old = previous.get(thread.id);313+ // A link the read left out is outside the rule's container, unless it was seen there before.314+ const eligible = links.filter(315+ ({ rule, link, key }) =>316+ batchOf(rule) === null ||317+ batchOf(rule)?.has(link.key.toUpperCase()) === true ||318+ old?.statuses[key] != null,319+ );@@ -0,0 +364,21 @@364+ threadId: thread.id,365+ fingerprint,366+ statuses,367+ pending,368+ };369+ if (old === undefined || automationFingerprint(old) !== automationFingerprint(observation))370+ yield* observations.save(observation);371+ if (pending === null || pending.action === "unchanged" || pending.action !== action) continue;372+ const command = {373+ type: "thread.issue-automation.apply" as const,374+ commandId: pending.commandId,375+ threadId: thread.id,376+ action: pending.action,377+ expectedRevision: pending.revision,378+ rulesFingerprint,379+ };380+ const waiting = yield* saveLock.withPermit(381+ Effect.gen(function* () {382+ const current = yield* settings.getSettings;383+ if (automationFingerprint(current.issueThreadAutomationRules) !== rulesFingerprint)384+ return false;@@ -79,0 +233,21 @@233+ type: "thread.issue-automation.apply",234+ commandId: CommandId.make(`stale:${change}`),235+ threadId,236+ action: "settle",237+ expectedRevision,238+ rulesFingerprint: change === "changed rules" ? "stale rules" : automationFingerprint([]),239+ })240+ .pipe(Effect.flip);241+ assert.equal(error._tag, "OrchestratorDispatchError");242+ assert.equal(error._tag === "OrchestratorDispatchError" && error.cause, ISSUE_AUTOMATION_STALE);243+ assert.isNull((yield* projections.getThread(threadId)).settledAt);244+ }).pipe(Effect.provide(layerTest)),245+);246+247+it.effect("issue automation waits for queued work, then applies under a new command id", () =>248+ Effect.gen(function* () {249+ const orchestrator = yield* Orchestrator.OrchestratorV2;250+ const projections = yield* ProjectionStore.ProjectionStoreV2;251+ const threadId = ThreadId.make("thread:automation-busy");252+ yield* createThread(threadId);253+ yield* queueUserMessage(threadId, "automation:queued");@@ -9507,3 +9559,4 @@95079559 ${indexedField("$.pinnedAt")} AS pinned_at,95089560 ${indexedField("$.pinOrderKey")} AS pin_order_key,95099561 ${indexedField("$.snoozedUntil")} AS snoozed_until,9562+ ${indexedField("$.snoozedAt")} AS snoozed_at,@@ -4564,0 +4568,21 @@4568+ yield* (4569+ change === "issue-settle"4570+ ? settleByRule4571+ : orchestrator.dispatch(4572+ change === "runtime-mode"4573+ ? {4574+ type: "thread.runtime-mode.set",4575+ commandId,4576+ threadId,4577+ runtimeMode: "auto-accept-edits",4578+ }4579+ : change === "worktree"4580+ ? { type: "thread.metadata.update", commandId, threadId, worktreePath: nextCwd }4581+ : {4582+ type: "thread.model-selection.set",4583+ commandId,4584+ threadId,4585+ modelSelection: secondSelection,4586+ },4587+ )4588+ ).pipe(Effect.ignore);@@ -428,3 +428,14 @@428428429429 Writing to a tracker over a remote connection requires the `source-control:write` scope.430430431+### Organize threads by issue status432+433+Threads can follow the status of the issues linked to them. Open the connected tracker under434+**Settings → Source control & issues**, choose **Add team**, and use the **+** buttons to put the435+team's statuses in **Wake**, **Snooze**, or **Settle**. The rule applies to every thread linked436+to one of the team's issues, in any project. It changes threads, never issues. Linear is the437+supported tracker.438+439+The server checks linked issues about once a minute while it runs, with or without a client440+open. Only a status change counts: saving a rule records the current statuses first, and a thread441+you organize by hand stays that way until one of its issues moves again. A thread with several@@ -33,3 +33,11 @@3333 label: "environment-data:issue-trackers:connections",3434 tag: WS_METHODS.issueTrackersList,3535 });36+ const automation = createEnvironmentRpcQueryAtomFamily(runtime, {37+ label: "environment-data:issue-trackers:automation",38+ tag: WS_METHODS.issueTrackersAutomation,39+ });40+ const automationCatalog = createEnvironmentRpcQueryAtomFamily(runtime, {41+ label: "environment-data:issue-trackers:automation-catalog",42+ tag: WS_METHODS.issueTrackersAutomationCatalog,43+ });
Pushed43d13a3
juliusmarminge closed this
juliusmarminge reopened this
Sign in to join this conversation.






This PR changes the test suite by +23 test cases (browser 0, unit +3, server +20).
Keep tests that would fail for a real reason, and test logic below the UI where it can be. See Testing.