Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat(pipes): add Linear issue triggers (#6843)

Louis Beaumont9de574ca0937
diff --git a/apps/screenpipe-app-tauri/components/settings/__tests__/pipe-trigger-picker.test.tsx b/apps/screenpipe-app-tauri/components/settings/__tests__/pipe-trigger-picker.test.tsx
index cdf4c73ea..637fb8a3d 100644
--- a/apps/screenpipe-app-tauri/components/settings/__tests__/pipe-trigger-picker.test.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/__tests__/pipe-trigger-picker.test.tsx
@@ -79,6 +79,9 @@ describe("PipeTriggerPicker app trigger catalog", () => {
"calendar event starts",
"new issue",
"new pull request",
+ "new Linear issue",
+ "Linear issue assigned to me",
+ "Linear issue status changed",
"new task",
]) {
expect(screen.getByText(label)).toBeInTheDocument();
@@ -162,4 +165,48 @@ describe("PipeTriggerPicker app trigger catalog", () => {
}],
});
});
+
+ it("stores a team-scoped Linear status-change trigger", async () => {
+ fetchMock.mockImplementation(async (url, init) => {
+ if (String(url) === "/connections/linear/proxy/graphql") {
+ const after = JSON.parse(String(init?.body)).variables.after;
+ return response({
+ data: {
+ teams: {
+ nodes: after
+ ? [{ id: "team-product", name: "Product", key: "PROD" }]
+ : [{ id: "team-eng", name: "Engineering", key: "ENG" }],
+ pageInfo: after
+ ? { hasNextPage: false, endCursor: null }
+ : { hasNextPage: true, endCursor: "page-2" },
+ },
+ },
+ });
+ }
+ return response({});
+ });
+ const { applyOptimistic } = renderPicker([
+ { id: "linear", name: "Linear", icon: "linear", connected: true },
+ ]);
+
+ chooseOption(/^Linear issue status changed/i);
+ fireEvent.click(await screen.findByRole("button", { name: /Product PROD/i }));
+ clickDetailAdd();
+
+ expect(applyOptimistic).toHaveBeenCalledWith({
+ sources: [{
+ app: "linear",
+ kind: "issue_status_changed",
+ filter: { team_id: "team-product", team_name: "Product" },
+ }],
+ });
+ const requests = fetchMock.mock.calls.filter(([url]) => String(url) === "/connections/linear/proxy/graphql");
+ expect(requests).toHaveLength(2);
+ const request = requests[0];
+ expect(request?.[1]?.method).toBe("POST");
+ expect(JSON.parse(String(request?.[1]?.body))).toMatchObject({
+ query: expect.stringContaining("teams(first: 100, after: $after)"),
+ variables: { after: null },
+ });
+ });
});
diff --git a/apps/screenpipe-app-tauri/components/settings/pipe-trigger-picker.tsx b/apps/screenpipe-app-tauri/components/settings/pipe-trigger-picker.tsx
index d9893a1a5..15bea0b5f 100644
--- a/apps/screenpipe-app-tauri/components/settings/pipe-trigger-picker.tsx
+++ b/apps/screenpipe-app-tauri/components/settings/pipe-trigger-picker.tsx
@@ -60,6 +60,7 @@ type SourceApp =
| "google-calendar"
| "outlook-email"
| "github"
+ | "linear"
| "todoist";
type OptionId =
@@ -75,6 +76,9 @@ type OptionId =
| "notion"
| "github_issue"
| "github_pull_request"
+ | "linear_issue_created"
+ | "linear_issue_assigned"
+ | "linear_issue_status_changed"
| "todoist_task"
| "obsidian"
| "pipe";
@@ -104,11 +108,14 @@ const OPTIONS: Option[] = [
{ id: "notion", group: "notion", label: "page created or edited", sub: "workspace or a database", app: "notion" },
{ id: "github_issue", group: "github", label: "new issue", sub: "in a repository you pick", app: "github", kind: "issue" },
{ id: "github_pull_request", group: "github", label: "new pull request", sub: "in a repository you pick", app: "github", kind: "pull_request" },
+ { id: "linear_issue_created", group: "linear", label: "new Linear issue", sub: "in a team you pick", app: "linear", kind: "issue_created" },
+ { id: "linear_issue_assigned", group: "linear", label: "Linear issue assigned to me", sub: "in a team you pick", app: "linear", kind: "issue_assigned" },
+ { id: "linear_issue_status_changed", group: "linear", label: "Linear issue status changed", sub: "in a team you pick", app: "linear", kind: "issue_status_changed" },
{ id: "todoist_task", group: "todoist", label: "new task", sub: "added to Todoist", app: "todoist", kind: "task" },
{ id: "obsidian", group: "obsidian", label: "new note", sub: "in a vault folder", app: "obsidian" },
{ id: "pipe", group: "pipes", label: "after a scheduled task finishes", sub: "chain off another scheduled task" },
];
-const GROUP_ORDER = ["recurring", "meetings", "email", "calendar", "slack", "notion", "github", "todoist", "obsidian", "pipes"];
+const GROUP_ORDER = ["recurring", "meetings", "email", "calendar", "slack", "notion", "github", "linear", "todoist", "obsidian", "pipes"];
function optionIcon(o: Option) {
if (o.app) return <IntegrationIcon icon={o.icon || o.app} className="w-4 h-4 flex items-center justify-center" fallbackClassName="h-4 w-4 text-muted-foreground" />;
@@ -134,6 +141,14 @@ function sourceLabel(s: TriggerSource): string {
if (s.app === "google-calendar") return `google calendar${acct} · event starts`;
if (s.app === "outlook-email") return `outlook${acct} · ${s.kind === "sent_message" ? "email sent" : "new email"}`;
if (s.app === "github") return `github${acct} · new ${s.kind === "pull_request" ? "pull request" : "issue"} in ${s.filter?.repository || "repository"}`;
+ if (s.app === "linear") {
+ const action = s.kind === "issue_assigned"
+ ? "issue assigned to me"
+ : s.kind === "issue_status_changed"
+ ? "issue status changed"
+ : "new issue";
+ return `linear · ${action} in ${s.filter?.team_name || "team"}`;
+ }
if (s.app === "todoist") return "todoist · new task";
return `${s.app} · ${s.kind || "new item"}`;
}
@@ -398,6 +413,9 @@ function detailTitle(id: OptionId): string {
case "notion": return "Notion page created or edited";
case "github_issue": return "new GitHub issue in…";
case "github_pull_request": return "new GitHub pull request in…";
+ case "linear_issue_created": return "new Linear issue in…";
+ case "linear_issue_assigned": return "Linear issue assigned to me in…";
+ case "linear_issue_status_changed": return "Linear issue status changed in…";
case "todoist_task": return "new Todoist task";
case "obsidian": return "new Obsidian note in…";
case "pipe": return "after a scheduled task finishes";
@@ -441,6 +459,7 @@ function PipeDetail({ pipes, onAdd }: { pipes: { name: string }[]; onAdd: (name:
interface SlackChannel { id: string; name: string; is_private?: boolean }
interface NotionDb { id: string; name: string }
interface GithubRepo { id: number; full_name: string; private?: boolean }
+interface LinearTeam { id: string; name: string; key?: string }
/** Accounts for an app: [] = single/default, else one per connected workspace. */
function accountsFor(conns: AvailableConnection[], app: string): { value: string; label: string }[] {
@@ -546,6 +565,7 @@ function SourceDetail({
/>
)}
{app === "github" && <GithubPicker key={`${inst ?? ""}:${kind}`} instance={inst} kind={kind || "issue"} onAdd={onAdd} />}
+ {app === "linear" && <LinearPicker kind={kind || "issue_created"} onAdd={onAdd} />}
{app === "todoist" && (
<SimpleSourceDetail
text="Runs when a new active task is added to Todoist."
@@ -564,6 +584,7 @@ const APP_META: Record<string, { name: string; blurb: string; examples: string[]
"google-calendar": { name: "Google Calendar", blurb: "Connect Google Calendar with read-only access to run tasks when timed events start.", examples: ["customer call", "focus block"] },
"outlook-email": { name: "Outlook", blurb: "Connect Outlook to watch your Inbox or Sent Items.", examples: ["Inbox", "Sent Items"] },
github: { name: "GitHub", blurb: "Connect GitHub and choose a repository to watch for issues or pull requests.", examples: ["issues", "pull requests"] },
+ linear: { name: "Linear", blurb: "Connect Linear and choose a team to watch for issue activity.", examples: ["created", "assigned", "status"] },
todoist: { name: "Todoist", blurb: "Connect Todoist to run a task whenever a new active task is added.", examples: ["new task"] },
};
@@ -848,6 +869,86 @@ function GithubPicker({ instance, kind, onAdd }: { instance?: string; kind: stri
);
}
+function LinearPicker({ kind, onAdd }: { kind: string; onAdd: (s: TriggerSource) => void }) {
+ const [teams, setTeams] = useState<LinearTeam[] | null>(null);
+ const [picked, setPicked] = useState<LinearTeam | null>(null);
+ const [q, setQ] = useState("");
+ const [err, setErr] = useState<string | null>(null);
+
+ useEffect(() => {
+ (async () => {
+ try {
+ const list: LinearTeam[] = [];
+ let after: string | null = null;
+ for (let page = 0; page < 5; page += 1) {
+ const r = await localFetch("/connections/linear/proxy/graphql", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ query: "query PipeLinearTeams($after: String) { teams(first: 100, after: $after) { nodes { id name key } pageInfo { hasNextPage endCursor } } }",
+ variables: { after },
+ }),
+ });
+ const j = await r.json();
+ if (Array.isArray(j?.errors) && j.errors.length > 0) throw new Error("Linear GraphQL error");
+ if (!Array.isArray(j?.data?.teams?.nodes)) throw new Error("Invalid Linear response");
+ list.push(...j.data.teams.nodes.filter((team: LinearTeam) => team.id && team.name));
+ const pageInfo = j.data.teams.pageInfo;
+ if (!pageInfo?.hasNextPage || !pageInfo?.endCursor) break;
+ after = pageInfo.endCursor;
+ }
+ list.sort((a, b) => a.name.localeCompare(b.name));
+ setTeams(list);
+ if (!list.length) setErr("no Linear teams found for this account.");
+ } catch {
+ setTeams([]);
+ setErr("couldn't reach Linear.");
+ }
+ })();
+ }, []);
+
+ const shown = (teams ?? []).filter((team) => !q || team.name.toLowerCase().includes(q.toLowerCase()) || team.key?.toLowerCase().includes(q.toLowerCase()));
+ const description = kind === "issue_assigned"
+ ? "Runs when an issue in this team is assigned to you."
+ : kind === "issue_status_changed"
+ ? "Runs only when an issue in this team moves between workflow statuses."
+ : "Runs when a new issue is created in this team.";
+
+ return (
+ <div>
+ <p className="text-xs text-muted-foreground mb-3">{description}</p>
+ <label className={LABEL}>team</label>
+ <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="search teams…" className={`${INPUT} mt-1 mb-2`} />
+ <div className="border rounded-none max-h-[220px] overflow-y-auto">
+ {teams === null ? (
+ <div className="flex items-center gap-2 text-xs text-muted-foreground px-3 py-4"><Loader2 className="h-3.5 w-3.5 animate-spin" /> loading teams…</div>
+ ) : err ? (
+ <div className="text-xs text-muted-foreground px-3 py-3">{err}</div>
+ ) : shown.length === 0 ? (
+ <div className="text-xs text-muted-foreground px-3 py-3">no match.</div>
+ ) : (
+ shown.map((team) => (
+ <button
+ key={team.id}
+ onClick={() => setPicked(team)}
+ className={`w-full flex items-center gap-2 px-3 py-1.5 text-left text-xs transition-colors ${picked?.id === team.id ? "bg-accent" : "hover:bg-accent/60"}`}
+ >
+ <IntegrationIcon icon="linear" className="w-3.5 h-3.5 flex items-center justify-center" fallbackClassName="h-3.5 w-3.5 text-muted-foreground" />
+ <span className="flex-1 truncate">{team.name}</span>
+ {team.key && <span className="text-[10px] text-muted-foreground font-mono">{team.key}</span>}
+ {picked?.id === team.id && <Check className="h-3.5 w-3.5" />}
+ </button>
+ ))
+ )}
+ </div>
+ <PrimaryAdd
+ disabled={!picked}
+ onClick={() => picked && onAdd({ app: "linear", kind, filter: { team_id: picked.id, team_name: picked.name } })}
+ />
+ </div>
+ );
+}
+
function ObsidianPicker({ onAdd }: { onAdd: (s: TriggerSource) => void }) {
const [vault, setVault] = useState<string | null>(null);
const [folder, setFolder] = useState<string>("");
diff --git a/crates/screenpipe-core/src/pipes/connection_triggers.rs b/crates/screenpipe-core/src/pipes/connection_triggers.rs
index 3fecd1816..a188889e9 100644
--- a/crates/screenpipe-core/src/pipes/connection_triggers.rs
+++ b/crates/screenpipe-core/src/pipes/connection_triggers.rs
@@ -11,7 +11,7 @@
//!
//! Three ingestion classes, one cursor model:
//! - **file** (Obsidian): scan a vault folder for new/changed `.md` files.
-//! - **api poll** (Slack, Notion, email, Calendar, GitHub, Todoist): page the local connection proxy
+//! - **api poll** (Slack, Notion, email, Calendar, GitHub, Linear, Todoist): page the local connection proxy
//! (`/connections/<id>/...`, which injects auth server-side) and diff the
//! response against an opaque, source-specific cursor token.
//!
@@ -80,6 +80,7 @@ const SUPPORTED_APPS: &[&str] = &[
"google-calendar",
"outlook-email",
"github",
+ "linear",
"todoist",
];
@@ -220,6 +221,13 @@ fn token_cmp(app: &str, a: &str, b: &str) -> Ordering {
(Err(_), Ok(_)) => Ordering::Less,
(Err(_), Err(_)) => a.cmp(b),
}
+ } else if app == "linear" {
+ match (linear_token_parts(a), linear_token_parts(b)) {
+ (Some((at, ai)), Some((bt, bi))) => at.cmp(&bt).then_with(|| ai.cmp(bi)),
+ (Some(_), None) => Ordering::Greater,
+ (None, Some(_)) => Ordering::Less,
+ (None, None) => a.cmp(b),
+ }
} else {
let pa = a.parse::<f64>().unwrap_or(f64::MIN);
let pb = b.parse::<f64>().unwrap_or(f64::MIN);
@@ -246,6 +254,7 @@ fn now_token(app: &str) -> String {
"google-calendar" | "outlook-email" | "github" | "todoist" => {
system_time_ms(SystemTime::now()).unwrap_or(0).to_string()
}
+ "linear" => format!("{}:", chrono::Utc::now().timestamp_micros()),
_ => String::new(),
}
}
@@ -302,6 +311,7 @@ fn default_kind(app: &str) -> &str {
"imap" | "outlook-email" => "message",
"google-calendar" => "event_started",
"github" => "issue",
+ "linear" => "issue_created",
"todoist" => "task",
_ => "item",
}
@@ -332,6 +342,37 @@ fn rfc3339_millis(value: &str) -> Option<String> {
.map(|dt| dt.timestamp_millis().to_string())
}
+fn rfc3339_micros(value: &str) -> Option<i64> {
+ chrono::DateTime::parse_from_rfc3339(value)
+ .ok()
+ .map(|dt| dt.timestamp_micros())
+}
+
+fn linear_token(timestamp: &str, event_id: &str) -> Option<String> {
+ Some(format!("{}:{}", rfc3339_micros(timestamp)?, event_id))
+}
+
+fn linear_token_parts(value: &str) -> Option<(i64, &str)> {
+ let (timestamp, event_id) = value.split_once(':')?;
+ Some((timestamp.parse().ok()?, event_id))
+}
+
+fn linear_cursor_rfc3339(value: &str) -> Option<String> {
+ let raw = value
+ .split_once(':')
+ .map(|(timestamp, _)| timestamp)
+ .unwrap_or(value);
+ let parsed = raw.parse::<i64>().ok()?;
+ // Accept millisecond cursors if an older development build wrote one.
+ let micros = if parsed.abs() < 10_000_000_000_000 {
+ parsed.checked_mul(1_000)?
+ } else {
+ parsed
+ };
+ chrono::DateTime::<chrono::Utc>::from_timestamp_micros(micros)
+ .map(|dt| dt.to_rfc3339_opts(chrono::SecondsFormat::Micros, true))
+}
+
fn millis_as_rfc3339(value: &str) -> Option<String> {
let millis = value.parse::<i64>().ok()?;
chrono::DateTime::<chrono::Utc>::from_timestamp_millis(millis)
@@ -370,6 +411,7 @@ async fn fetch_items(
"google-calendar" => fetch_google_calendar(ctx, src, since).await,
"outlook-email" => fetch_outlook_email(ctx, src).await,
"github" => fetch_github(ctx, src, since).await,
+ "linear" => fetch_linear(ctx, src, since).await,
"todoist" => fetch_todoist(ctx, since).await,
_ => None,
}
@@ -682,6 +724,132 @@ async fn fetch_github(
Some(all)
}
+const LINEAR_CREATED_QUERY: &str = r#"
+query PipeLinearCreatedIssues($teamId: ID!, $since: DateTimeOrDuration!, $after: String) {
+ issues(
+ first: 100
+ after: $after
+ orderBy: createdAt
+ filter: { team: { id: { eq: $teamId } }, createdAt: { gte: $since } }
+ ) {
+ nodes { id identifier title url createdAt }
+ pageInfo { hasNextPage endCursor }
+ }
+}
+"#;
+
+const LINEAR_ACTIVITY_QUERY: &str = r#"
+query PipeLinearIssueActivity($teamId: ID!, $since: DateTimeOrDuration!, $after: String) {
+ viewer { id }
+ issues(
+ first: 100
+ after: $after
+ orderBy: updatedAt
+ filter: { team: { id: { eq: $teamId } }, updatedAt: { gte: $since } }
+ ) {
+ nodes {
+ id
+ identifier
+ title
+ url
+ history(last: 50) {
+ nodes {
+ id
+ createdAt
+ fromAssigneeId
+ toAssigneeId
+ toAssignee { id name }
+ fromStateId
+ toStateId
+ fromState { id name }
+ toState { id name }
+ }
+ }
+ }
+ pageInfo { hasNextPage endCursor }
+ }
+}
+"#;
+
+async fn fetch_linear(
+ ctx: &SourceCtx<'_>,
+ src: &SourceTrigger,
+ since: &str,
+) -> Option<Vec<DetectedItem>> {
+ let team_id = src
+ .filter
+ .get("team_id")
+ .map(String::as_str)
+ .filter(|id| !id.is_empty())?;
+ let kind = effective_kind(src);
+ if !matches!(
+ kind,
+ "issue_created" | "issue_assigned" | "issue_status_changed"
+ ) {
+ return None;
+ }
+
+ let since_at = linear_cursor_rfc3339(since)
+ .unwrap_or_else(|| (chrono::Utc::now() - chrono::Duration::days(30)).to_rfc3339());
+ let query = if kind == "issue_created" {
+ LINEAR_CREATED_QUERY
+ } else {
+ LINEAR_ACTIVITY_QUERY
+ };
+ let url = format!("{}/connections/linear/proxy/graphql", ctx.api_base);
+ let mut after: Option<String> = None;
+ let mut all = Vec::new();
+
+ for _ in 0..MAX_PAGES {
+ let value = ctx
+ .post_json(
+ &url,
+ serde_json::json!({
+ "query": query,
+ "variables": {
+ "teamId": team_id,
+ "since": since_at,
+ "after": after,
+ }
+ }),
+ )
+ .await?;
+ if value
+ .get("errors")
+ .and_then(Value::as_array)
+ .is_some_and(|errors| !errors.is_empty())
+ {
+ debug!("connection trigger: Linear GraphQL returned errors");
+ return None;
+ }
+ value.pointer("/data/issues/nodes")?.as_array()?;
+ all.extend(parse_linear_issues(&value, kind));
+
+ let page_info = value.pointer("/data/issues/pageInfo");
+ let has_next = page_info
+ .and_then(|info| info.get("hasNextPage"))
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ after = page_info
+ .and_then(|info| info.get("endCursor"))
+ .and_then(Value::as_str)
+ .filter(|cursor| !cursor.is_empty())
+ .map(String::from);
+ // Initialization only proves the connection and establishes a "now"
+ // watermark; it must never walk or replay the existing issue history.
+ if since.is_empty() || !has_next || after.is_none() {
+ break;
+ }
+ }
+
+ all.sort_by(|a, b| token_cmp("linear", &a.ts, &b.ts));
+ all.dedup_by(|a, b| a.id == b.id);
+ if !since.is_empty() {
+ all.retain(|item| token_gt("linear", &item.ts, since));
+ }
+ Some(all)
+}
+
async fn fetch_todoist(ctx: &SourceCtx<'_>, since: &str) -> Option<Vec<DetectedItem>> {
let url = format!("{}/connections/todoist/proxy/api/v1/tasks", ctx.api_base);
let limit = "200";
@@ -999,6 +1167,137 @@ pub fn parse_todoist_tasks(value: &Value) -> Vec<DetectedItem> {
out
}
+pub fn parse_linear_issues(value: &Value, kind: &str) -> Vec<DetectedItem> {
+ if !matches!(
+ kind,
+ "issue_created" | "issue_assigned" | "issue_status_changed"
+ ) {
+ return Vec::new();
+ }
+ let issues = value
+ .pointer("/data/issues/nodes")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten();
+ let viewer_id = value.pointer("/data/viewer/id").and_then(Value::as_str);
+ let mut out = Vec::new();
+
+ for issue in issues {
+ let issue_id = match issue.get("id").and_then(Value::as_str) {
+ Some(id) => id,
+ None => continue,
+ };
+ let identifier = issue
+ .get("identifier")
+ .and_then(Value::as_str)
+ .unwrap_or("issue");
+ let issue_title = issue
+ .get("title")
+ .and_then(Value::as_str)
+ .filter(|title| !title.trim().is_empty())
+ .unwrap_or("issue");
+ let title = first_line(&format!("{identifier} · {issue_title}"), 120);
+ let url = issue.get("url").and_then(Value::as_str).unwrap_or("");
+
+ if kind == "issue_created" {
+ let Some(created_at) = issue.get("createdAt").and_then(Value::as_str) else {
+ continue;
+ };
+ let Some(token) = linear_token(created_at, issue_id) else {
+ continue;
+ };
+ out.push(DetectedItem {
+ id: issue_id.to_string(),
+ title,
+ preview: url.to_string(),
+ ts: token,
+ });
+ continue;
+ }
+
+ let histories = issue
+ .pointer("/history/nodes")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten();
+ for history in histories {
+ let Some(history_id) = history.get("id").and_then(Value::as_str) else {
+ continue;
+ };
+ let Some(created_at) = history.get("createdAt").and_then(Value::as_str) else {
+ continue;
+ };
+ let Some(token) = linear_token(created_at, history_id) else {
+ continue;
+ };
+
+ if kind == "issue_assigned" {
+ let to_assignee = history
+ .get("toAssigneeId")
+ .and_then(Value::as_str)
+ .or_else(|| history.pointer("/toAssignee/id").and_then(Value::as_str));
+ if to_assignee.is_none() || to_assignee != viewer_id {
+ continue;
+ }
+ let from_assignee = history.get("fromAssigneeId").and_then(Value::as_str);
+ if from_assignee == to_assignee {
+ continue;
+ }
+ let assignee = history
+ .pointer("/toAssignee/name")
+ .and_then(Value::as_str)
+ .unwrap_or("you");
+ let preview = if url.is_empty() {
+ format!("assigned to {assignee}")
+ } else {
+ format!("assigned to {assignee} · {url}")
+ };
+ out.push(DetectedItem {
+ id: history_id.to_string(),
+ title: title.clone(),
+ preview,
+ ts: token,
+ });
+ continue;
+ }
+
+ let from_state_id = history
+ .get("fromStateId")
+ .and_then(Value::as_str)
+ .or_else(|| history.pointer("/fromState/id").and_then(Value::as_str));
+ let to_state_id = history
+ .get("toStateId")
+ .and_then(Value::as_str)
+ .or_else(|| history.pointer("/toState/id").and_then(Value::as_str));
+ if from_state_id.is_none() || to_state_id.is_none() || from_state_id == to_state_id {
+ continue;
+ }
+ let from_state = history
+ .pointer("/fromState/name")
+ .and_then(Value::as_str)
+ .unwrap_or("previous status");
+ let to_state = history
+ .pointer("/toState/name")
+ .and_then(Value::as_str)
+ .unwrap_or("new status");
+ let preview = if url.is_empty() {
+ format!("{from_state} → {to_state}")
+ } else {
+ format!("{from_state} → {to_state} · {url}")
+ };
+ out.push(DetectedItem {
+ id: history_id.to_string(),
+ title: title.clone(),
+ preview,
+ ts: token,
+ });
+ }
+ }
+
+ out.sort_by(|a, b| token_cmp("linear", &a.ts, &b.ts));
+ out
+}
+
/// Best-effort title from a Notion page/database object.
pub fn extract_notion_title(obj: &Value) -> String {
if let Some(s) = rich_text_plain(obj.get("title")) {
@@ -1604,6 +1903,146 @@ mod tests {
);
}
+ #[test]
+ fn parse_linear_created_issues_uses_stable_composite_cursors() {
+ let payload = serde_json::json!({
+ "data": {
+ "issues": {
+ "nodes": [
+ {
+ "id": "issue-b",
+ "identifier": "ENG-2",
+ "title": "Second",
+ "url": "https://linear.app/acme/issue/ENG-2",
+ "createdAt": "2026-09-02T17:00:00.123456Z"
+ },
+ {
+ "id": "issue-a",
+ "identifier": "ENG-1",
+ "title": "First",
+ "createdAt": "2026-09-02T17:00:00.123456Z"
+ }
+ ]
+ }
+ }
+ });
+ let issues = parse_linear_issues(&payload, "issue_created");
+ assert_eq!(
+ issues
+ .iter()
+ .map(|item| item.id.as_str())
+ .collect::<Vec<_>>(),
+ ["issue-a", "issue-b"]
+ );
+ assert_eq!(issues[0].title, "ENG-1 · First");
+ assert_eq!(issues[1].preview, "https://linear.app/acme/issue/ENG-2");
+ assert!(token_gt("linear", &issues[1].ts, &issues[0].ts));
+ }
+
+ #[test]
+ fn parse_linear_assignment_only_fires_for_a_real_assignment_to_viewer() {
+ let payload = serde_json::json!({
+ "data": {
+ "viewer": { "id": "me" },
+ "issues": {
+ "nodes": [{
+ "id": "issue-1",
+ "identifier": "ENG-1",
+ "title": "Fix capture",
+ "url": "https://linear.app/acme/issue/ENG-1",
+ "history": { "nodes": [
+ {
+ "id": "assigned-me",
+ "createdAt": "2026-09-02T17:00:01Z",
+ "fromAssigneeId": null,
+ "toAssigneeId": "me",
+ "toAssignee": { "id": "me", "name": "Louis" }
+ },
+ {
+ "id": "assigned-other",
+ "createdAt": "2026-09-02T17:00:02Z",
+ "fromAssigneeId": "me",
+ "toAssigneeId": "other",
+ "toAssignee": { "id": "other", "name": "Ezra" }
+ },
+ {
+ "id": "unchanged",
+ "createdAt": "2026-09-02T17:00:03Z",
+ "fromAssigneeId": "me",
+ "toAssigneeId": "me",
+ "toAssignee": { "id": "me", "name": "Louis" }
+ }
+ ] }
+ }]
+ }
+ }
+ });
+ let assignments = parse_linear_issues(&payload, "issue_assigned");
+ assert_eq!(assignments.len(), 1);
+ assert_eq!(assignments[0].id, "assigned-me");
+ assert_eq!(
+ assignments[0].preview,
+ "assigned to Louis · https://linear.app/acme/issue/ENG-1"
+ );
+ }
+
+ #[test]
+ fn parse_linear_status_only_fires_for_explicit_state_transitions() {
+ let payload = serde_json::json!({
+ "data": {
+ "viewer": { "id": "me" },
+ "issues": {
+ "nodes": [{
+ "id": "issue-1",
+ "identifier": "ENG-1",
+ "title": "Fix capture",
+ "history": { "nodes": [
+ {
+ "id": "transition",
+ "createdAt": "2026-09-02T17:00:01Z",
+ "fromStateId": "todo",
+ "toStateId": "started",
+ "fromState": { "id": "todo", "name": "Todo" },
+ "toState": { "id": "started", "name": "In Progress" }
+ },
+ {
+ "id": "initial-state",
+ "createdAt": "2026-09-02T17:00:02Z",
+ "fromStateId": null,
+ "toStateId": "todo",
+ "toState": { "id": "todo", "name": "Todo" }
+ },
+ {
+ "id": "unrelated-edit",
+ "createdAt": "2026-09-02T17:00:03Z",
+ "fromStateId": null,
+ "toStateId": null
+ }
+ ] }
+ }]
+ }
+ }
+ });
+ let transitions = parse_linear_issues(&payload, "issue_status_changed");
+ assert_eq!(transitions.len(), 1);
+ assert_eq!(transitions[0].id, "transition");
+ assert_eq!(transitions[0].preview, "Todo → In Progress");
+ }
+
+ #[test]
+ fn linear_cursor_supports_microseconds_and_legacy_milliseconds() {
+ let micros = linear_token("2026-09-02T17:00:00.123456Z", "event").unwrap();
+ assert_eq!(micros, "1788368400123456:event");
+ assert_eq!(
+ linear_cursor_rfc3339(&micros).as_deref(),
+ Some("2026-09-02T17:00:00.123456Z")
+ );
+ assert_eq!(
+ linear_cursor_rfc3339("1788368400123:legacy").as_deref(),
+ Some("2026-09-02T17:00:00.123000Z")
+ );
+ }
+
#[test]
fn github_repository_rejects_proxy_path_injection() {
let mut valid = source("github", "issue");
@@ -1797,6 +2236,108 @@ mod tests {
assert_eq!(items[0].title, "Follow up");
}
+ #[tokio::test]
+ async fn linear_fetch_scopes_status_history_to_the_selected_team() {
+ use wiremock::matchers::{header, method, path};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/connections/linear/proxy/graphql"))
+ .and(header("authorization", "Bearer local-key"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "data": {
+ "viewer": { "id": "me" },
+ "issues": {
+ "nodes": [{
+ "id": "issue-1",
+ "identifier": "ENG-1",
+ "title": "Fix capture",
+ "history": { "nodes": [
+ {
+ "id": "history-a",
+ "createdAt": "2026-09-02T17:00:00Z",
+ "fromStateId": "todo",
+ "toStateId": "started",
+ "fromState": { "id": "todo", "name": "Todo" },
+ "toState": { "id": "started", "name": "In Progress" }
+ },
+ {
+ "id": "history-b",
+ "createdAt": "2026-09-02T17:00:00Z",
+ "fromStateId": "started",
+ "toStateId": "done",
+ "fromState": { "id": "started", "name": "In Progress" },
+ "toState": { "id": "done", "name": "Done" }
+ }
+ ] }
+ }],
+ "pageInfo": { "hasNextPage": false, "endCursor": null }
+ }
+ }
+ })))
+ .mount(&server)
+ .await;
+
+ let client = reqwest::Client::new();
+ let ctx = SourceCtx {
+ http: &client,
+ api_base: &server.uri(),
+ api_key: Some("local-key"),
+ };
+ let mut src = source("linear", "issue_status_changed");
+ src.filter.insert("team_id".into(), "team-eng".into());
+ let since = linear_token("2026-09-02T17:00:00Z", "history-a").unwrap();
+ let items = fetch_items(&ctx, &src, &since).await.unwrap();
+ assert_eq!(
+ items
+ .iter()
+ .map(|item| item.id.as_str())
+ .collect::<Vec<_>>(),
+ ["history-b"]
+ );
+
+ let requests = server.received_requests().await.unwrap();
+ assert_eq!(requests.len(), 1);
+ let body: Value = serde_json::from_slice(&requests[0].body).unwrap();
+ assert_eq!(
+ body.pointer("/variables/teamId").and_then(Value::as_str),
+ Some("team-eng")
+ );
+ assert_eq!(
+ body.pointer("/variables/since").and_then(Value::as_str),
+ Some("2026-09-02T17:00:00.000000Z")
+ );
+ let query = body.get("query").and_then(Value::as_str).unwrap();
+ assert!(query.contains("history(last: 50)"));
+ assert!(query.contains("updatedAt: { gte: $since }"));
+ }
+
+ #[tokio::test]
+ async fn linear_graphql_errors_do_not_advance_the_trigger() {
+ use wiremock::matchers::{method, path};
+ use wiremock::{Mock, MockServer, ResponseTemplate};
+
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/connections/linear/proxy/graphql"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "errors": [{ "message": "rate limited" }]
+ })))
+ .mount(&server)
+ .await;
+
+ let client = reqwest::Client::new();
+ let ctx = SourceCtx {
+ http: &client,
+ api_base: &server.uri(),
+ api_key: None,
+ };
+ let mut src = source("linear", "issue_created");
+ src.filter.insert("team_id".into(), "team-eng".into());
+ assert!(fetch_items(&ctx, &src, "").await.is_none());
+ }
+
#[test]
fn notion_title_falls_back_to_url() {
let bare = serde_json::json!({ "id": "abc", "url": "https://notion.so/abc" });