Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): add loop deep links and copy link button (#76393)

Charles Vien99d723e71ef9
diff --git a/products/desktop/apps/code/src/main/di/bindings.ts b/products/desktop/apps/code/src/main/di/bindings.ts
index 6cc67ecbf520..2cf27f8c0732 100644
--- a/products/desktop/apps/code/src/main/di/bindings.ts
+++ b/products/desktop/apps/code/src/main/di/bindings.ts
@@ -54,12 +54,14 @@ import type {
CANVAS_LINK_SERVICE,
CHANNEL_LINK_SERVICE,
INBOX_LINK_SERVICE,
+ LOOP_LINK_SERVICE,
NEW_TASK_LINK_SERVICE,
OPEN_TARGET_LINK_SERVICE,
SCOUT_LINK_SERVICE,
TASK_LINK_SERVICE,
} from "@posthog/core/links/identifiers";
import type { InboxLinkService } from "@posthog/core/links/inbox-link";
+import type { LoopLinkService } from "@posthog/core/links/loop-link";
import type { NewTaskLinkService } from "@posthog/core/links/new-task-link";
import type { OpenTargetLinkService } from "@posthog/core/links/open-target-link";
import type { ScoutLinkService } from "@posthog/core/links/scout-link";
@@ -292,6 +294,7 @@ import type {
FS_SERVICE as MAIN_FS_SERVICE,
INBOX_LINK_SERVICE as MAIN_INBOX_LINK_SERVICE,
LLM_GATEWAY_SERVICE as MAIN_LLM_GATEWAY_SERVICE,
+ LOOP_LINK_SERVICE as MAIN_LOOP_LINK_SERVICE,
MCP_APPS_SERVICE as MAIN_MCP_APPS_SERVICE,
NEW_TASK_LINK_SERVICE as MAIN_NEW_TASK_LINK_SERVICE,
OPEN_TARGET_LINK_SERVICE as MAIN_OPEN_TARGET_LINK_SERVICE,
@@ -456,6 +459,7 @@ export interface MainBindings {
[MAIN_OPEN_TARGET_LINK_SERVICE]: OpenTargetLinkService;
[MAIN_CANVAS_LINK_SERVICE]: CanvasLinkService;
[MAIN_CHANNEL_LINK_SERVICE]: ChannelLinkService;
+ [MAIN_LOOP_LINK_SERVICE]: LoopLinkService;
[TASK_LINK_SERVICE]: TaskLinkService;
[INBOX_LINK_SERVICE]: InboxLinkService;
[SCOUT_LINK_SERVICE]: ScoutLinkService;
@@ -464,6 +468,7 @@ export interface MainBindings {
[OPEN_TARGET_LINK_SERVICE]: OpenTargetLinkService;
[CANVAS_LINK_SERVICE]: CanvasLinkService;
[CHANNEL_LINK_SERVICE]: ChannelLinkService;
+ [LOOP_LINK_SERVICE]: LoopLinkService;
// Watcher registry
[MAIN_WATCHER_REGISTRY_SERVICE]: WatcherRegistryService;
diff --git a/products/desktop/apps/code/src/main/di/container.ts b/products/desktop/apps/code/src/main/di/container.ts
index 04c245598f61..f56129ebd653 100644
--- a/products/desktop/apps/code/src/main/di/container.ts
+++ b/products/desktop/apps/code/src/main/di/container.ts
@@ -54,12 +54,14 @@ import {
CANVAS_LINK_SERVICE,
CHANNEL_LINK_SERVICE,
INBOX_LINK_SERVICE,
+ LOOP_LINK_SERVICE,
NEW_TASK_LINK_SERVICE,
OPEN_TARGET_LINK_SERVICE,
SCOUT_LINK_SERVICE,
TASK_LINK_SERVICE,
} from "@posthog/core/links/identifiers";
import { InboxLinkService } from "@posthog/core/links/inbox-link";
+import { LoopLinkService } from "@posthog/core/links/loop-link";
import { NewTaskLinkService } from "@posthog/core/links/new-task-link";
import { OpenTargetLinkService } from "@posthog/core/links/open-target-link";
import { ScoutLinkService } from "@posthog/core/links/scout-link";
@@ -303,6 +305,7 @@ import {
FS_SERVICE as MAIN_FS_SERVICE,
INBOX_LINK_SERVICE as MAIN_INBOX_LINK_SERVICE,
LLM_GATEWAY_SERVICE as MAIN_LLM_GATEWAY_SERVICE,
+ LOOP_LINK_SERVICE as MAIN_LOOP_LINK_SERVICE,
MCP_APPS_SERVICE as MAIN_MCP_APPS_SERVICE,
NEW_TASK_LINK_SERVICE as MAIN_NEW_TASK_LINK_SERVICE,
OPEN_TARGET_LINK_SERVICE as MAIN_OPEN_TARGET_LINK_SERVICE,
@@ -711,6 +714,8 @@ container.bind(MAIN_CANVAS_LINK_SERVICE).to(CanvasLinkService);
container.bind(CANVAS_LINK_SERVICE).toService(MAIN_CANVAS_LINK_SERVICE);
container.bind(MAIN_CHANNEL_LINK_SERVICE).to(ChannelLinkService);
container.bind(CHANNEL_LINK_SERVICE).toService(MAIN_CHANNEL_LINK_SERVICE);
+container.bind(MAIN_LOOP_LINK_SERVICE).to(LoopLinkService);
+container.bind(LOOP_LINK_SERVICE).toService(MAIN_LOOP_LINK_SERVICE);
container.load(watcherRegistryModule);
container
.bind(MAIN_WATCHER_REGISTRY_SERVICE)
diff --git a/products/desktop/apps/code/src/main/di/tokens.ts b/products/desktop/apps/code/src/main/di/tokens.ts
index 51ec3fac579d..21683b869cec 100644
--- a/products/desktop/apps/code/src/main/di/tokens.ts
+++ b/products/desktop/apps/code/src/main/di/tokens.ts
@@ -115,6 +115,9 @@ export const CANVAS_LINK_SERVICE = Symbol.for(
export const CHANNEL_LINK_SERVICE = Symbol.for(
"posthog.host.main.channel-link.service",
);
+export const LOOP_LINK_SERVICE = Symbol.for(
+ "posthog.host.main.loop-link.service",
+);
export const WATCHER_REGISTRY_SERVICE = Symbol.for(
"posthog.host.main.watcher-registry.service",
);
diff --git a/products/desktop/apps/code/src/main/index.ts b/products/desktop/apps/code/src/main/index.ts
index 4ef7e467ce66..38545ed82693 100644
--- a/products/desktop/apps/code/src/main/index.ts
+++ b/products/desktop/apps/code/src/main/index.ts
@@ -26,6 +26,7 @@ import type { ApprovalLinkService } from "@posthog/core/links/approval-link";
import type { CanvasLinkService } from "@posthog/core/links/canvas-link";
import type { ChannelLinkService } from "@posthog/core/links/channel-link";
import type { InboxLinkService } from "@posthog/core/links/inbox-link";
+import type { LoopLinkService } from "@posthog/core/links/loop-link";
import type { NewTaskLinkService } from "@posthog/core/links/new-task-link";
import type { ScoutLinkService } from "@posthog/core/links/scout-link";
import type { TaskLinkService } from "@posthog/core/links/task-link";
@@ -62,6 +63,7 @@ import {
EXTERNAL_APPS_SERVICE,
FILE_WATCHER_SERVICE,
INBOX_LINK_SERVICE,
+ LOOP_LINK_SERVICE,
FS_SERVICE as MAIN_FS_SERVICE,
NEW_TASK_LINK_SERVICE,
POSTHOG_PLUGIN_SERVICE,
@@ -277,10 +279,11 @@ async function initializeServices(): Promise<void> {
container.get<ScoutLinkService>(SCOUT_LINK_SERVICE);
container.get<NewTaskLinkService>(NEW_TASK_LINK_SERVICE);
container.get<ApprovalLinkService>(APPROVAL_LINK_SERVICE);
- // Eagerly resolved so their constructors register the `canvas` / `channel`
- // deep-link handlers at boot, before any link arrives.
+ // Eagerly resolved so their constructors register the `canvas` / `channel` /
+ // `loop` deep-link handlers at boot, before any link arrives.
container.get<CanvasLinkService>(CANVAS_LINK_SERVICE);
container.get<ChannelLinkService>(CHANNEL_LINK_SERVICE);
+ container.get<LoopLinkService>(LOOP_LINK_SERVICE);
container.get<GitHubIntegrationService>(GITHUB_INTEGRATION_SERVICE);
container.get<SlackIntegrationService>(SLACK_INTEGRATION_SERVICE);
container.get<ExternalAppsService>(EXTERNAL_APPS_SERVICE);
diff --git a/products/desktop/apps/web/src/web-host-router.ts b/products/desktop/apps/web/src/web-host-router.ts
index fb2ac0a73a71..73158a341fc4 100644
--- a/products/desktop/apps/web/src/web-host-router.ts
+++ b/products/desktop/apps/web/src/web-host-router.ts
@@ -65,6 +65,7 @@ const deepLinkStubRouter = router({
getPendingOpenTarget: publicProcedure.query(() => null),
getPendingCanvasLink: publicProcedure.query(() => null),
getPendingChannelLink: publicProcedure.query(() => null),
+ getPendingLoopLink: publicProcedure.query(() => null),
onOpenTask: neverEmit,
onOpenReport: neverEmit,
onOpenScout: neverEmit,
@@ -73,6 +74,7 @@ const deepLinkStubRouter = router({
onOpenTarget: neverEmit,
onOpenCanvas: neverEmit,
onOpenChannel: neverEmit,
+ onOpenLoop: neverEmit,
});
// Slack/GitHub connect. Desktop opens the PostHog integration authorize URL in
diff --git a/products/desktop/docs/DEEP-LINKS.md b/products/desktop/docs/DEEP-LINKS.md
index bc9b0ad61087..dd28357ac4af 100644
--- a/products/desktop/docs/DEEP-LINKS.md
+++ b/products/desktop/docs/DEEP-LINKS.md
@@ -10,7 +10,7 @@ PostHog registers custom URL schemes so the desktop app can be opened with conte
| Development | `posthog-code-dev://` |
| Legacy (production only) | `twig://`, `array://` |
-All schemes route through the same dispatcher. The host portion of the URL selects the handler (`task`, `inbox`, `scout`, `approval`, `canvas`, `channel`, `new`, `plan`, `issue`, `callback`, `integration`, `slack-integration`, `mcp-oauth-complete`).
+All schemes route through the same dispatcher. The host portion of the URL selects the handler (`task`, `inbox`, `scout`, `loop`, `approval`, `canvas`, `channel`, `new`, `plan`, `issue`, `callback`, `integration`, `slack-integration`, `mcp-oauth-complete`).
If the app is not running, the OS launches it and the link is queued until the renderer is ready. If the app is minimised, it is restored and focused before the link is handled.
@@ -116,6 +116,19 @@ posthog-code://scout/error-tracking
posthog-code://scout/error-tracking?finding=abc123
```
+### `posthog-code://loop/<loopId>`
+
+Open a loop's detail page. This is the link copied by the "Copy link" button on
+a loop's detail page.
+
+| Segment | Required | Description |
+|---|---|---|
+| `<loopId>` | Yes | Loop ID |
+
+```
+posthog-code://loop/abc123
+```
+
### `posthog-code://approval/<requestId>`
Open the agent fleet approvals inbox focused on a specific tool-approval request.
@@ -233,6 +246,7 @@ In development the same payload is delivered to `http://localhost:8238/mcp-oauth
| `task` | [packages/core/src/links/task-link.ts](../packages/core/src/links/task-link.ts) |
| `inbox` | [packages/core/src/links/inbox-link.ts](../packages/core/src/links/inbox-link.ts) |
| `scout` | [packages/core/src/links/scout-link.ts](../packages/core/src/links/scout-link.ts) |
+| `loop` | [packages/core/src/links/loop-link.ts](../packages/core/src/links/loop-link.ts) |
| `approval` | [packages/core/src/links/approval-link.ts](../packages/core/src/links/approval-link.ts) |
| `canvas` | [packages/core/src/links/canvas-link.ts](../packages/core/src/links/canvas-link.ts) |
| `channel` | [packages/core/src/links/channel-link.ts](../packages/core/src/links/channel-link.ts) |
diff --git a/products/desktop/packages/core/src/links/identifiers.ts b/products/desktop/packages/core/src/links/identifiers.ts
index 043a0b3ed0fe..69a3d1fda43e 100644
--- a/products/desktop/packages/core/src/links/identifiers.ts
+++ b/products/desktop/packages/core/src/links/identifiers.ts
@@ -24,3 +24,4 @@ export const CANVAS_LINK_SERVICE = Symbol.for("posthog.core.canvasLinkService");
export const CHANNEL_LINK_SERVICE = Symbol.for(
"posthog.core.channelLinkService",
);
+export const LOOP_LINK_SERVICE = Symbol.for("posthog.core.loopLinkService");
diff --git a/products/desktop/packages/core/src/links/loop-link.test.ts b/products/desktop/packages/core/src/links/loop-link.test.ts
new file mode 100644
index 000000000000..eea2037a5bcc
--- /dev/null
+++ b/products/desktop/packages/core/src/links/loop-link.test.ts
@@ -0,0 +1,140 @@
+import type {
+ DeepLinkHandler,
+ IDeepLinkRegistry,
+} from "@posthog/platform/deep-link";
+import type { IMainWindow } from "@posthog/platform/main-window";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ LoopLinkEvent,
+ type LoopLinkPayload,
+ LoopLinkService,
+} from "./loop-link";
+
+function makeLogger() {
+ const logger = {
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ debug: vi.fn(),
+ scope: vi.fn(() => logger),
+ };
+ return logger;
+}
+
+function makeDeepLinkService() {
+ const handlers = new Map<string, DeepLinkHandler>();
+ const service = {
+ registerHandler: vi.fn((key: string, handler: DeepLinkHandler) => {
+ handlers.set(key, handler);
+ }),
+ trigger: (key: string, path: string, search = "") => {
+ const handler = handlers.get(key);
+ if (!handler) throw new Error(`No handler for ${key}`);
+ return handler(path, new URLSearchParams(search));
+ },
+ };
+ return service as unknown as IDeepLinkRegistry & {
+ trigger: (key: string, path: string, search?: string) => boolean;
+ };
+}
+
+function makeMainWindow() {
+ return {
+ focus: vi.fn(),
+ restore: vi.fn(),
+ isMinimized: vi.fn().mockReturnValue(false),
+ } as unknown as IMainWindow & {
+ focus: ReturnType<typeof vi.fn>;
+ restore: ReturnType<typeof vi.fn>;
+ isMinimized: ReturnType<typeof vi.fn>;
+ };
+}
+
+describe("LoopLinkService", () => {
+ let deepLinkService: ReturnType<typeof makeDeepLinkService>;
+ let mainWindow: ReturnType<typeof makeMainWindow>;
+ let service: LoopLinkService;
+
+ beforeEach(() => {
+ deepLinkService = makeDeepLinkService();
+ mainWindow = makeMainWindow();
+ service = new LoopLinkService(deepLinkService, mainWindow, makeLogger());
+ });
+
+ it("registers a 'loop' handler on the DeepLinkService", () => {
+ expect(deepLinkService.registerHandler).toHaveBeenCalledWith(
+ "loop",
+ expect.any(Function),
+ );
+ });
+
+ it.each<{ name: string; path: string; expected: LoopLinkPayload }>([
+ {
+ name: "emits OpenLoop with the loop id",
+ path: "loop-abc-123",
+ expected: { loopId: "loop-abc-123" },
+ },
+ {
+ name: "takes only the first path segment as the loop id",
+ path: "loop-abc-123/extra/segments",
+ expected: { loopId: "loop-abc-123" },
+ },
+ {
+ name: "decodes a percent-encoded loop id",
+ path: "loop%2Dabc",
+ expected: { loopId: "loop-abc" },
+ },
+ ])("$name", ({ path, expected }) => {
+ const listener = vi.fn();
+ service.on(LoopLinkEvent.OpenLoop, listener);
+
+ const result = deepLinkService.trigger("loop", path);
+
+ expect(result).toBe(true);
+ expect(listener).toHaveBeenCalledWith(expected);
+ });
+
+ it("queues a pending deep link when no listener is attached", () => {
+ deepLinkService.trigger("loop", "loop-abc-123");
+
+ const pending = service.consumePendingDeepLink();
+ expect(pending).toEqual({ loopId: "loop-abc-123" });
+
+ // Draining clears it
+ expect(service.consumePendingDeepLink()).toBeNull();
+ });
+
+ it("returns false and does not emit when the path is empty", () => {
+ const listener = vi.fn();
+ service.on(LoopLinkEvent.OpenLoop, listener);
+
+ const result = deepLinkService.trigger("loop", "");
+
+ expect(result).toBe(false);
+ expect(listener).not.toHaveBeenCalled();
+ });
+
+ it.each<{ name: string; minimized: boolean; expectRestore: boolean }>([
+ {
+ name: "focuses the main window on link arrival",
+ minimized: false,
+ expectRestore: false,
+ },
+ {
+ name: "restores then focuses the main window when it is minimized",
+ minimized: true,
+ expectRestore: true,
+ },
+ ])("$name", ({ minimized, expectRestore }) => {
+ mainWindow.isMinimized.mockReturnValue(minimized);
+
+ deepLinkService.trigger("loop", "loop-abc-123");
+
+ expect(mainWindow.focus).toHaveBeenCalledTimes(1);
+ if (expectRestore) {
+ expect(mainWindow.restore).toHaveBeenCalledTimes(1);
+ } else {
+ expect(mainWindow.restore).not.toHaveBeenCalled();
+ }
+ });
+});
diff --git a/products/desktop/packages/core/src/links/loop-link.ts b/products/desktop/packages/core/src/links/loop-link.ts
new file mode 100644
index 000000000000..6327778a671b
--- /dev/null
+++ b/products/desktop/packages/core/src/links/loop-link.ts
@@ -0,0 +1,96 @@
+import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";
+import {
+ DEEP_LINK_SERVICE,
+ type IDeepLinkRegistry,
+} from "@posthog/platform/deep-link";
+import {
+ type IMainWindow,
+ MAIN_WINDOW_SERVICE,
+} from "@posthog/platform/main-window";
+import { TypedEventEmitter } from "@posthog/shared";
+import { inject, injectable } from "inversify";
+import type { LinkLogger } from "./identifiers";
+
+export const LoopLinkEvent = {
+ OpenLoop: "openLoop",
+} as const;
+
+export interface LoopLinkPayload {
+ /** Loop id, matching the `/code/loops/$loopId` route param. */
+ loopId: string;
+}
+
+export interface LoopLinkEvents {
+ [LoopLinkEvent.OpenLoop]: LoopLinkPayload;
+}
+
+@injectable()
+export class LoopLinkService extends TypedEventEmitter<LoopLinkEvents> {
+ private pendingDeepLink: LoopLinkPayload | null = null;
+ private readonly log: LinkLogger;
+
+ constructor(
+ @inject(DEEP_LINK_SERVICE)
+ private readonly deepLinkService: IDeepLinkRegistry,
+ @inject(MAIN_WINDOW_SERVICE)
+ private readonly mainWindow: IMainWindow,
+ @inject(ROOT_LOGGER)
+ rootLogger: RootLogger,
+ ) {
+ super();
+ this.log = rootLogger.scope("loop-link-service");
+
+ this.deepLinkService.registerHandler("loop", (path) =>
+ this.handleLoopLink(path),
+ );
+ }
+
+ private handleLoopLink(path: string): boolean {
+ const loopId = decodeSegment(path.split("/")[0]);
+
+ if (!loopId) {
+ this.log.warn("Loop link missing loop id");
+ return false;
+ }
+
+ const payload: LoopLinkPayload = { loopId };
+
+ const hasListeners = this.listenerCount(LoopLinkEvent.OpenLoop) > 0;
+
+ if (hasListeners) {
+ this.log.info(`Emitting loop link event: loopId=${loopId}`);
+ this.emit(LoopLinkEvent.OpenLoop, payload);
+ } else {
+ this.log.info(
+ `Queueing loop link (renderer not ready): loopId=${loopId}`,
+ );
+ this.pendingDeepLink = payload;
+ }
+
+ this.log.info("Deep link focusing window", { loopId });
+ if (this.mainWindow.isMinimized()) {
+ this.mainWindow.restore();
+ }
+ this.mainWindow.focus();
+
+ return true;
+ }
+
+ public consumePendingDeepLink(): LoopLinkPayload | null {
+ const pending = this.pendingDeepLink;
+ this.pendingDeepLink = null;
+ if (pending) {
+ this.log.info(`Consumed pending loop link: loopId=${pending.loopId}`);
+ }
+ return pending;
+ }
+}
+
+function decodeSegment(segment: string | undefined): string {
+ if (!segment) return "";
+ try {
+ return decodeURIComponent(segment);
+ } catch {
+ return segment;
+ }
+}
diff --git a/products/desktop/packages/host-router/src/routers/deep-link.router.ts b/products/desktop/packages/host-router/src/routers/deep-link.router.ts
index 0bd1c0cb9b5c..9d8703565e88 100644
--- a/products/desktop/packages/host-router/src/routers/deep-link.router.ts
+++ b/products/desktop/packages/host-router/src/routers/deep-link.router.ts
@@ -18,6 +18,7 @@ import {
CANVAS_LINK_SERVICE,
CHANNEL_LINK_SERVICE,
INBOX_LINK_SERVICE,
+ LOOP_LINK_SERVICE,
NEW_TASK_LINK_SERVICE,
OPEN_TARGET_LINK_SERVICE,
SCOUT_LINK_SERVICE,
@@ -28,6 +29,11 @@ import {
type InboxLinkService,
type PendingInboxDeepLink,
} from "@posthog/core/links/inbox-link";
+import {
+ LoopLinkEvent,
+ type LoopLinkPayload,
+ type LoopLinkService,
+} from "@posthog/core/links/loop-link";
import {
NewTaskLinkEvent,
type NewTaskLinkPayload,
@@ -206,4 +212,22 @@ export const deepLinkRouter = router({
.consumePendingDeepLink();
},
),
+
+ onOpenLoop: publicProcedure.subscription(async function* (opts) {
+ const service = opts.ctx.container.get<LoopLinkService>(LOOP_LINK_SERVICE);
+ const iterable = service.toIterable(LoopLinkEvent.OpenLoop, {
+ signal: opts.signal,
+ });
+ for await (const data of iterable) {
+ yield data;
+ }
+ }),
+
+ getPendingLoopLink: publicProcedure.query(
+ ({ ctx }): LoopLinkPayload | null => {
+ return ctx.container
+ .get<LoopLinkService>(LOOP_LINK_SERVICE)
+ .consumePendingDeepLink();
+ },
+ ),
});
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 82bdd241b73a..2d56353f4059 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -1267,6 +1267,11 @@ export interface LoopRunViewedProperties {
is_manual_run: boolean;
}
+export interface LoopLinkCopiedProperties {
+ loop_id: string;
+ visibility: "personal" | "team";
+}
+
// Event names as constants
export const ANALYTICS_EVENTS = {
// App lifecycle
@@ -1451,6 +1456,7 @@ export const ANALYTICS_EVENTS = {
LOOP_RUN_STARTED: "Loop run started",
LOOP_RUN_BLOCKED: "Loop run blocked",
LOOP_RUN_VIEWED: "Loop run viewed",
+ LOOP_LINK_COPIED: "Loop link copied",
} as const;
// Event property mapping
@@ -1629,6 +1635,7 @@ export type EventPropertyMap = {
[ANALYTICS_EVENTS.LOOP_RUN_STARTED]: LoopRunStartedProperties;
[ANALYTICS_EVENTS.LOOP_RUN_BLOCKED]: LoopRunBlockedProperties;
[ANALYTICS_EVENTS.LOOP_RUN_VIEWED]: LoopRunViewedProperties;
+ [ANALYTICS_EVENTS.LOOP_LINK_COPIED]: LoopLinkCopiedProperties;
};
/**
diff --git a/products/desktop/packages/shared/src/deep-links.test.ts b/products/desktop/packages/shared/src/deep-links.test.ts
index 8952b4628a68..25be1853fe1b 100644
--- a/products/desktop/packages/shared/src/deep-links.test.ts
+++ b/products/desktop/packages/shared/src/deep-links.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
buildInboxDeeplink,
+ buildLoopDeeplink,
buildScoutDeeplink,
decodePlanBase64,
getDeeplinkProtocol,
@@ -97,6 +98,36 @@ describe("buildInboxDeeplink", () => {
});
});
+describe("buildLoopDeeplink", () => {
+ it.each<{
+ name: string;
+ loopId: string;
+ isDevBuild: boolean;
+ expected: string;
+ }>([
+ {
+ name: "builds a production loop link",
+ loopId: "loop-abc-123",
+ isDevBuild: false,
+ expected: "posthog-code://loop/loop-abc-123",
+ },
+ {
+ name: "uses the dev scheme for dev builds",
+ loopId: "loop-abc-123",
+ isDevBuild: true,
+ expected: "posthog-code-dev://loop/loop-abc-123",
+ },
+ {
+ name: "encodes special characters in the loop id",
+ loopId: "id with spaces/&",
+ isDevBuild: false,
+ expected: "posthog-code://loop/id%20with%20spaces%2F%26",
+ },
+ ])("$name", ({ loopId, isDevBuild, expected }) => {
+ expect(buildLoopDeeplink(loopId, { isDevBuild })).toBe(expected);
+ });
+});
+
describe("buildScoutDeeplink", () => {
it.each<{
name: string;
diff --git a/products/desktop/packages/shared/src/deep-links.ts b/products/desktop/packages/shared/src/deep-links.ts
index 5a4801af4b9f..5455e1b39e51 100644
--- a/products/desktop/packages/shared/src/deep-links.ts
+++ b/products/desktop/packages/shared/src/deep-links.ts
@@ -42,6 +42,18 @@ export function buildInboxDeeplink(
return slug ? `${base}/${slug}` : base;
}
+/**
+ * Build a canonical deep link to a loop's detail page
+ * (`<scheme>://loop/<loopId>`). The inbound side lives in the `loop` handler
+ * (`LoopLinkService`), which routes to `/code/loops/<loopId>`.
+ */
+export function buildLoopDeeplink(
+ loopId: string,
+ { isDevBuild }: { isDevBuild: boolean },
+): string {
+ return `${getDeeplinkProtocol(isDevBuild)}://loop/${encodeURIComponent(loopId)}`;
+}
+
/**
* Build a canonical deep link to a scout's detail page, optionally focused on a
* specific finding (`<scheme>://scout/<skillSlug>?finding=<id>`).
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index 56ce3353c34c..45fb5b0e27d6 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -100,6 +100,7 @@ export {
} from "./cloud-task-models";
export {
buildInboxDeeplink,
+ buildLoopDeeplink,
buildScoutDeeplink,
DEEPLINK_PROTOCOL_DEVELOPMENT,
DEEPLINK_PROTOCOL_PRODUCTION,
diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopDetailView.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopDetailView.tsx
index b274013e43b8..b48fffc1243c 100644
--- a/products/desktop/packages/ui/src/features/loops/components/LoopDetailView.tsx
+++ b/products/desktop/packages/ui/src/features/loops/components/LoopDetailView.tsx
@@ -1,4 +1,4 @@
-import { ArrowLeftIcon } from "@phosphor-icons/react";
+import { ArrowLeftIcon, LinkIcon } from "@phosphor-icons/react";
import type { LoopSchemas } from "@posthog/api-client/loops";
import { isUploadableSkillSource } from "@posthog/core/message-editor/skillTags";
import { useHostTRPC } from "@posthog/host-router/react";
@@ -62,6 +62,7 @@ import {
} from "../loopDisplay";
import { formatLoopModel } from "../loopModels";
import { loopSkillBundles, primaryLoopSkillBundle } from "../loopSkill";
+import { copyLoopLink } from "../utils/copyLoopLink";
import { LoopLoadError } from "./LoopFallbacks";
import { LoopHeaderTitle } from "./LoopHeaderTitle";
import { LoopRunRow } from "./LoopRunRow";
@@ -256,6 +257,14 @@ export function LoopDetailView({ loopId }: { loopId: string }) {
aria-label={loop.enabled ? "Pause loop" : "Enable loop"}
onCheckedChange={handleToggleEnabled}
/>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => copyLoopLink(loop)}
+ >
+ <LinkIcon size={14} />
+ Copy link
+ </Button>
<Button
variant="outline"
size="sm"
diff --git a/products/desktop/packages/ui/src/features/loops/hooks/useLoopDeepLink.ts b/products/desktop/packages/ui/src/features/loops/hooks/useLoopDeepLink.ts
new file mode 100644
index 000000000000..f79ca9235de6
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/loops/hooks/useLoopDeepLink.ts
@@ -0,0 +1,36 @@
+import { useHostTRPC } from "@posthog/host-router/react";
+import { useAuthStateValue } from "@posthog/ui/features/auth/store";
+import { navigateToLoopDetail } from "@posthog/ui/router/navigationBridge";
+import { useQuery } from "@tanstack/react-query";
+import { useSubscription } from "@trpc/tanstack-react-query";
+import { useEffect } from "react";
+
+export function useLoopDeepLink() {
+ const trpcReact = useHostTRPC();
+ const isAuthenticated = useAuthStateValue(
+ (s) => s.status === "authenticated",
+ );
+
+ const pendingDeepLink = useQuery(
+ trpcReact.deepLink.getPendingLoopLink.queryOptions(undefined, {
+ enabled: isAuthenticated,
+ staleTime: Number.POSITIVE_INFINITY,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ }),
+ );
+
+ useEffect(() => {
+ if (pendingDeepLink.data?.loopId) {
+ navigateToLoopDetail(pendingDeepLink.data.loopId);
+ }
+ }, [pendingDeepLink.data]);
+
+ useSubscription(
+ trpcReact.deepLink.onOpenLoop.subscriptionOptions(undefined, {
+ onData: (data) => {
+ if (data?.loopId) navigateToLoopDetail(data.loopId);
+ },
+ }),
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/loops/utils/copyLoopLink.ts b/products/desktop/packages/ui/src/features/loops/utils/copyLoopLink.ts
new file mode 100644
index 000000000000..eed6b733ca49
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/loops/utils/copyLoopLink.ts
@@ -0,0 +1,26 @@
+import type { LoopSchemas } from "@posthog/api-client/loops";
+import { ANALYTICS_EVENTS, buildLoopDeeplink } from "@posthog/shared";
+import { toast } from "@posthog/ui/primitives/toast";
+import { track } from "@posthog/ui/shell/analytics";
+
+/**
+ * Copy a deep link (`<scheme>://loop/{loopId}`) for a loop to the clipboard,
+ * toasting success or failure. The inbound side lives in `useLoopDeepLink`.
+ */
+export function copyLoopLink(
+ loop: Pick<LoopSchemas.Loop, "id" | "visibility">,
+): void {
+ const url = buildLoopDeeplink(loop.id, {
+ isDevBuild: import.meta.env.DEV,
+ });
+ navigator.clipboard
+ .writeText(url)
+ .then(() => {
+ toast.success("Link copied");
+ track(ANALYTICS_EVENTS.LOOP_LINK_COPIED, {
+ loop_id: loop.id,
+ visibility: loop.visibility,
+ });
+ })
+ .catch(() => toast.error("Couldn't copy link"));
+}
diff --git a/products/desktop/packages/ui/src/router/routes/__root.tsx b/products/desktop/packages/ui/src/router/routes/__root.tsx
index fe2122fdadfd..9ca6ca2279e6 100644
--- a/products/desktop/packages/ui/src/router/routes/__root.tsx
+++ b/products/desktop/packages/ui/src/router/routes/__root.tsx
@@ -44,6 +44,7 @@ import { useTaskDeepLink } from "@posthog/ui/features/deep-links/useTaskDeepLink
import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import { useInboxDeepLink } from "@posthog/ui/features/inbox/hooks/useInboxDeepLink";
import { useIntegrations } from "@posthog/ui/features/integrations/useIntegrations";
+import { useLoopDeepLink } from "@posthog/ui/features/loops/hooks/useLoopDeepLink";
import { useScoutDeepLink } from "@posthog/ui/features/scouts/hooks/useScoutDeepLink";
import { useSetupDiscovery } from "@posthog/ui/features/setup/useSetupDiscovery";
import {
@@ -222,6 +223,7 @@ function RootLayout() {
useScoutDeepLink();
useCanvasDeepLink();
useChannelDeepLink();
+ useLoopDeepLink();
const approvalDeepLink = useApprovalDeepLink();
useSetupDiscovery();
useNewTaskDeepLink();