Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add community funnel analytics events (#801)

Gener32a8c949f3ed
diff --git a/src/shared/src/db/community-funnel-analytics-schema.ts b/src/shared/src/db/community-funnel-analytics-schema.ts
new file mode 100644
index 000000000..1489109f8
--- /dev/null
+++ b/src/shared/src/db/community-funnel-analytics-schema.ts
@@ -0,0 +1,48 @@
+import { index, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
+import { user } from "./schema";
+
+export const COMMUNITY_FUNNEL_EVENT_NAMES = [
+ "runtime_connected",
+ "first_agent_reply_persisted",
+ "invited_human_joined",
+] as const;
+
+export const COMMUNITY_FUNNEL_CONVERSATION_TYPES = [
+ "dm",
+ "channel",
+ "thread",
+] as const;
+
+export type CommunityFunnelEventName = typeof COMMUNITY_FUNNEL_EVENT_NAMES[number];
+export type CommunityFunnelConversationType = typeof COMMUNITY_FUNNEL_CONVERSATION_TYPES[number];
+
+export type CommunityFunnelAnalyticsEvent =
+ | {
+ event: "runtime_connected";
+ surface: "community";
+ connection_type: "local_daemon";
+ }
+ | {
+ event: "first_agent_reply_persisted";
+ surface: "community";
+ conversation_type: CommunityFunnelConversationType;
+ }
+ | {
+ event: "invited_human_joined";
+ surface: "community";
+ };
+
+export const communityFunnelAnalyticsEvent = sqliteTable("community_funnel_analytics_event", {
+ id: text("id").primaryKey(),
+ ownerUserId: text("owner_user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
+ eventName: text("event_name").notNull().$type<CommunityFunnelEventName>(),
+ conversationType: text("conversation_type").$type<CommunityFunnelConversationType>(),
+ sourceId: text("source_id").notNull(),
+ dedupeKey: text("dedupe_key").notNull(),
+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
+ claimedAt: text("claimed_at"),
+}, (t) => [
+ uniqueIndex("uq_community_funnel_analytics_dedupe").on(t.dedupeKey),
+ index("idx_community_funnel_analytics_owner_claimed_created")
+ .on(t.ownerUserId, t.claimedAt, t.createdAt),
+]);
diff --git a/src/shared/src/db/index.ts b/src/shared/src/db/index.ts
index 156cd18a0..566f2029c 100644
--- a/src/shared/src/db/index.ts
+++ b/src/shared/src/db/index.ts
@@ -4,8 +4,9 @@ import * as communitySchema from "./community-schema";
import * as communityMachineSchema from "./community-machine-schema";
import * as billingSchema from "./billing-schema";
import * as productPlanSchema from "./product-plan-schema";
+import * as communityFunnelAnalyticsSchema from "./community-funnel-analytics-schema";
-const allSchema = { ...schema, ...communitySchema, ...communityMachineSchema, ...productPlanSchema, ...billingSchema };
+const allSchema = { ...schema, ...communitySchema, ...communityMachineSchema, ...productPlanSchema, ...billingSchema, ...communityFunnelAnalyticsSchema };
export function createDb(d1: AnyD1Database) {
return drizzle(d1, { schema: allSchema });
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index 9eba6e907..32709bc23 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -68,6 +68,7 @@ export * as communityAgentInbox from "./queries/community/agent-inbox";
export * as communityBotAuditLog from "./queries/community/bot-audit-log";
export * as communityMessageTag from "./queries/community/message-tag";
export * as communityDiagnosticReport from "./queries/community/diagnostic-report";
+export * as communityFunnelAnalytics from "./queries/community/funnel-analytics";
export const nativeOauth = nativeOauthQueries;
export * as billing from "./queries/billing";
diff --git a/src/shared/src/db/queries/community/funnel-analytics.test.ts b/src/shared/src/db/queries/community/funnel-analytics.test.ts
new file mode 100644
index 000000000..c6789ea72
--- /dev/null
+++ b/src/shared/src/db/queries/community/funnel-analytics.test.ts
@@ -0,0 +1,171 @@
+import Sqlite from "better-sqlite3"
+import { readFileSync } from "node:fs"
+import { resolve } from "node:path"
+import { drizzle } from "drizzle-orm/better-sqlite3"
+import { getTableConfig } from "drizzle-orm/sqlite-core"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import * as communityFunnelAnalyticsSchema from "../../community-funnel-analytics-schema"
+import * as communityMachineSchema from "../../community-machine-schema"
+import * as communitySchema from "../../community-schema"
+import * as userSchema from "../../schema"
+import type { Database } from "../../index"
+import {
+ claimPendingEvents,
+ recordFirstAgentReplyPersisted,
+ recordInvitedHumanJoinedStatement,
+ recordRuntimeConnectedStatement,
+} from "./funnel-analytics"
+
+const migrationPath = resolve(
+ import.meta.dirname,
+ "../../../../../web/migrations/0103_community_funnel_analytics_event.sql",
+)
+
+describe("Community funnel analytics ledger", () => {
+ let sqlite: Sqlite.Database
+ let db: Database
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:")
+ sqlite.exec(`
+ CREATE TABLE user (
+ id TEXT PRIMARY KEY NOT NULL,
+ isBot INTEGER NOT NULL,
+ ownerUserId TEXT,
+ deletedAt TEXT
+ );
+ CREATE TABLE community_machine (
+ id TEXT PRIMARY KEY NOT NULL,
+ user_id TEXT NOT NULL,
+ status TEXT NOT NULL
+ );
+ CREATE TABLE community_machine_credential (
+ id TEXT PRIMARY KEY NOT NULL,
+ user_id TEXT NOT NULL,
+ machine_id TEXT NOT NULL,
+ credential_hash TEXT NOT NULL,
+ revoked_at TEXT
+ );
+ CREATE TABLE community_server_member (
+ id TEXT PRIMARY KEY NOT NULL,
+ server_id TEXT NOT NULL,
+ user_id TEXT NOT NULL
+ );
+ CREATE TABLE community_message (
+ id TEXT PRIMARY KEY NOT NULL,
+ author_id TEXT NOT NULL,
+ type TEXT NOT NULL,
+ deleted_at TEXT
+ );
+ `)
+ sqlite.exec(readFileSync(migrationPath, "utf8"))
+ sqlite.prepare("INSERT INTO user (id, isBot, ownerUserId) VALUES (?, ?, ?)").run("owner", 0, null)
+ sqlite.prepare("INSERT INTO user (id, isBot, ownerUserId) VALUES (?, ?, ?)").run("other", 0, null)
+ sqlite.prepare("INSERT INTO user (id, isBot, ownerUserId) VALUES (?, ?, ?)").run("bot", 1, "owner")
+ sqlite.prepare("INSERT INTO user (id, isBot, ownerUserId) VALUES (?, ?, ?)").run("joined", 0, null)
+ sqlite.prepare("INSERT INTO user (id, isBot, ownerUserId) VALUES (?, ?, ?)").run("joined-bot", 1, "owner")
+ sqlite.prepare("INSERT INTO community_message (id, author_id, type) VALUES (?, ?, ?)")
+ .run("message-first", "bot", "default")
+ sqlite.prepare("INSERT INTO community_message (id, author_id, type) VALUES (?, ?, ?)")
+ .run("message-later", "bot", "default")
+ db = drizzle(sqlite, {
+ schema: {
+ ...userSchema,
+ ...communitySchema,
+ ...communityMachineSchema,
+ ...communityFunnelAnalyticsSchema,
+ },
+ }) as unknown as Database
+ })
+
+ afterEach(() => sqlite.close())
+
+ it("binds ledger owners to users and supplies a runtime creation timestamp", () => {
+ const config = getTableConfig(communityFunnelAnalyticsSchema.communityFunnelAnalyticsEvent)
+ const ownerReference = config.foreignKeys[0]?.reference()
+
+ expect(ownerReference?.foreignTable).toBe(userSchema.user)
+ expect(communityFunnelAnalyticsSchema.communityFunnelAnalyticsEvent.createdAt.defaultFn?.())
+ .toEqual(expect.any(String))
+ })
+
+ it("dedupes authoritative facts, filters actors, and claims exact account payloads once", async () => {
+ sqlite.prepare("INSERT INTO community_machine (id, user_id, status) VALUES (?, ?, ?)").run("machine", "owner", "online")
+ sqlite.prepare("INSERT INTO community_machine_credential (id, user_id, machine_id, credential_hash) VALUES (?, ?, ?, ?)")
+ .run("credential", "owner", "machine", "hash")
+ sqlite.prepare("INSERT INTO community_server_member (id, server_id, user_id) VALUES (?, ?, ?)")
+ .run("membership", "server", "joined")
+ sqlite.prepare("INSERT INTO community_server_member (id, server_id, user_id) VALUES (?, ?, ?)")
+ .run("bot-membership", "server", "joined-bot")
+
+ await recordRuntimeConnectedStatement(db, {
+ ownerUserId: "owner",
+ machineId: "machine",
+ credentialHash: "hash",
+ now: "2026-09-14T00:00:00.000Z",
+ })
+ await recordRuntimeConnectedStatement(db, {
+ ownerUserId: "owner",
+ machineId: "machine",
+ credentialHash: "hash",
+ now: "2026-09-14T00:00:01.000Z",
+ })
+ await expect(recordFirstAgentReplyPersisted(db, {
+ botUserId: "bot",
+ messageId: "message-first",
+ conversationType: "thread",
+ now: "2026-09-14T00:00:02.000Z",
+ })).resolves.toBe(true)
+ await expect(recordFirstAgentReplyPersisted(db, {
+ botUserId: "bot",
+ messageId: "message-later",
+ conversationType: "dm",
+ now: "2026-09-14T00:00:03.000Z",
+ })).resolves.toBe(false)
+ await recordInvitedHumanJoinedStatement(db, {
+ ownerUserId: "owner",
+ membershipId: "membership",
+ invitedUserId: "joined",
+ now: "2026-09-14T00:00:04.000Z",
+ })
+ await recordInvitedHumanJoinedStatement(db, {
+ ownerUserId: "owner",
+ membershipId: "bot-membership",
+ invitedUserId: "joined-bot",
+ now: "2026-09-14T00:00:05.000Z",
+ })
+
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_funnel_analytics_event").get())
+ .toEqual({ count: 3 })
+ expect(sqlite.prepare("SELECT source_id FROM community_funnel_analytics_event WHERE event_name = ?").get("first_agent_reply_persisted"))
+ .toEqual({ source_id: "message-first" })
+ await expect(claimPendingEvents(db, "other")).resolves.toEqual([])
+ const events = await claimPendingEvents(db, "owner", "2026-09-14T00:01:00.000Z")
+ expect(events.sort((a, b) => a.event.localeCompare(b.event))).toEqual([
+ { event: "first_agent_reply_persisted", surface: "community", conversation_type: "thread" },
+ { event: "invited_human_joined", surface: "community" },
+ { event: "runtime_connected", surface: "community", connection_type: "local_daemon" },
+ ])
+ expect(JSON.stringify(events)).not.toMatch(/owner|machine|membership|bot|hash/)
+ await expect(claimPendingEvents(db, "owner")).resolves.toEqual([])
+ })
+
+ it("rejects invalid event and conversation combinations at the migration boundary", () => {
+ expect(() => sqlite.prepare(`
+ INSERT INTO community_funnel_analytics_event
+ (id, owner_user_id, event_name, conversation_type, source_id, dedupe_key, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ `).run("bad", "owner", "runtime_connected", "dm", "source", "bad", "2026-09-14T00:00:00.000Z"))
+ .toThrow()
+ })
+
+ it("drops an unknown stored event instead of exposing an untyped payload", async () => {
+ const returning = vi.fn().mockResolvedValue([{ eventName: "unknown", conversationType: null }])
+ const where = vi.fn(() => ({ returning }))
+ const set = vi.fn(() => ({ where }))
+ const update = vi.fn(() => ({ set }))
+
+ await expect(claimPendingEvents({ update } as unknown as Database, "owner"))
+ .resolves.toEqual([])
+ })
+})
diff --git a/src/shared/src/db/queries/community/funnel-analytics.ts b/src/shared/src/db/queries/community/funnel-analytics.ts
new file mode 100644
index 000000000..33160d888
--- /dev/null
+++ b/src/shared/src/db/queries/community/funnel-analytics.ts
@@ -0,0 +1,168 @@
+import { and, eq, exists, isNull, sql } from "drizzle-orm";
+import { alias } from "drizzle-orm/sqlite-core";
+import { nanoid } from "nanoid";
+import {
+ communityMachine,
+ communityMachineCredential,
+} from "../../community-machine-schema";
+import { communityMessage, communityServerMember } from "../../community-schema";
+import {
+ communityFunnelAnalyticsEvent,
+ type CommunityFunnelAnalyticsEvent,
+ type CommunityFunnelConversationType,
+ type CommunityFunnelEventName,
+} from "../../community-funnel-analytics-schema";
+import { user } from "../../schema";
+import type { Database } from "../../index";
+
+const inviter = alias(user, "community_funnel_inviter");
+const invitee = alias(user, "community_funnel_invitee");
+const replyingBot = alias(user, "community_funnel_replying_bot");
+const botOwner = alias(user, "community_funnel_bot_owner");
+
+function eventProjection(input: {
+ id: string;
+ ownerUserId: string;
+ eventName: CommunityFunnelEventName;
+ conversationType?: CommunityFunnelConversationType;
+ sourceId: string;
+ dedupeKey: string;
+ createdAt: string;
+}) {
+ return {
+ id: sql<string>`${input.id}`.as("id"),
+ ownerUserId: sql<string>`${input.ownerUserId}`.as("owner_user_id"),
+ eventName: sql<CommunityFunnelEventName>`${input.eventName}`.as("event_name"),
+ conversationType: sql<CommunityFunnelConversationType | null>`${input.conversationType ?? null}`.as("conversation_type"),
+ sourceId: sql<string>`${input.sourceId}`.as("source_id"),
+ dedupeKey: sql<string>`${input.dedupeKey}`.as("dedupe_key"),
+ createdAt: sql<string>`${input.createdAt}`.as("created_at"),
+ claimedAt: sql<string | null>`NULL`.as("claimed_at"),
+ };
+}
+
+export function recordRuntimeConnectedStatement(db: Database, input: {
+ ownerUserId: string;
+ machineId: string;
+ credentialHash: string;
+ now?: string;
+}) {
+ const createdAt = input.now ?? new Date().toISOString();
+ return db.insert(communityFunnelAnalyticsEvent).select(db.select(eventProjection({
+ id: nanoid(),
+ ownerUserId: input.ownerUserId,
+ eventName: "runtime_connected",
+ sourceId: input.credentialHash,
+ dedupeKey: `runtime_connected:${input.credentialHash}`,
+ createdAt,
+ })).from(user).where(and(
+ eq(user.id, input.ownerUserId),
+ eq(user.isBot, false),
+ isNull(user.deletedAt),
+ exists(db.select({ id: communityMachine.id }).from(communityMachine).where(and(
+ eq(communityMachine.id, input.machineId),
+ eq(communityMachine.userId, input.ownerUserId),
+ eq(communityMachine.status, "online"),
+ ))),
+ exists(db.select({ id: communityMachineCredential.id }).from(communityMachineCredential).where(and(
+ eq(communityMachineCredential.machineId, input.machineId),
+ eq(communityMachineCredential.userId, input.ownerUserId),
+ eq(communityMachineCredential.credentialHash, input.credentialHash),
+ isNull(communityMachineCredential.revokedAt),
+ ))),
+ ))).onConflictDoNothing();
+}
+
+export function recordFirstAgentReplyPersistedStatement(db: Database, input: {
+ botUserId: string;
+ messageId: string;
+ conversationType: CommunityFunnelConversationType;
+ now?: string;
+}) {
+ const createdAt = input.now ?? new Date().toISOString();
+ return db.insert(communityFunnelAnalyticsEvent).select(db.select({
+ id: sql<string>`${nanoid()}`.as("id"),
+ ownerUserId: botOwner.id,
+ eventName: sql<CommunityFunnelEventName>`${"first_agent_reply_persisted"}`.as("event_name"),
+ conversationType: sql<CommunityFunnelConversationType>`${input.conversationType}`.as("conversation_type"),
+ sourceId: sql<string>`${input.messageId}`.as("source_id"),
+ dedupeKey: sql<string>`${"first_agent_reply_persisted:"} || ${botOwner.id}`.as("dedupe_key"),
+ createdAt: sql<string>`${createdAt}`.as("created_at"),
+ claimedAt: sql<string | null>`NULL`.as("claimed_at"),
+ }).from(replyingBot).innerJoin(botOwner, and(
+ eq(botOwner.id, replyingBot.ownerUserId),
+ eq(botOwner.isBot, false),
+ isNull(botOwner.deletedAt),
+ )).where(and(
+ eq(replyingBot.id, input.botUserId),
+ eq(replyingBot.isBot, true),
+ isNull(replyingBot.deletedAt),
+ exists(db.select({ id: communityMessage.id }).from(communityMessage).where(and(
+ eq(communityMessage.id, input.messageId),
+ eq(communityMessage.authorId, input.botUserId),
+ eq(communityMessage.type, "default"),
+ ))),
+ ))).onConflictDoNothing();
+}
+
+export async function recordFirstAgentReplyPersisted(db: Database, input: {
+ botUserId: string;
+ messageId: string;
+ conversationType: CommunityFunnelConversationType;
+ now?: string;
+}) {
+ const rows = await recordFirstAgentReplyPersistedStatement(db, input)
+ .returning({ id: communityFunnelAnalyticsEvent.id });
+ return rows.length === 1;
+}
+
+export function recordInvitedHumanJoinedStatement(db: Database, input: {
+ ownerUserId: string;
+ membershipId: string;
+ invitedUserId: string;
+ now?: string;
+}) {
+ const createdAt = input.now ?? new Date().toISOString();
+ return db.insert(communityFunnelAnalyticsEvent).select(db.select(eventProjection({
+ id: nanoid(),
+ ownerUserId: input.ownerUserId,
+ eventName: "invited_human_joined",
+ sourceId: input.membershipId,
+ dedupeKey: `invited_human_joined:${input.membershipId}`,
+ createdAt,
+ })).from(inviter).where(and(
+ eq(inviter.id, input.ownerUserId),
+ eq(inviter.isBot, false),
+ isNull(inviter.deletedAt),
+ exists(db.select({ id: communityServerMember.id }).from(communityServerMember).innerJoin(
+ invitee,
+ and(eq(invitee.id, communityServerMember.userId), eq(invitee.isBot, false), isNull(invitee.deletedAt)),
+ ).where(and(
+ eq(communityServerMember.id, input.membershipId),
+ eq(communityServerMember.userId, input.invitedUserId),
+ ))),
+ ))).onConflictDoNothing();
+}
+
+export async function claimPendingEvents(db: Database, ownerUserId: string, now = new Date().toISOString()) {
+ const rows = await db.update(communityFunnelAnalyticsEvent).set({ claimedAt: now }).where(and(
+ eq(communityFunnelAnalyticsEvent.ownerUserId, ownerUserId),
+ isNull(communityFunnelAnalyticsEvent.claimedAt),
+ )).returning({
+ eventName: communityFunnelAnalyticsEvent.eventName,
+ conversationType: communityFunnelAnalyticsEvent.conversationType,
+ });
+
+ return rows.flatMap<CommunityFunnelAnalyticsEvent>((row) => {
+ if (row.eventName === "runtime_connected") {
+ return [{ event: "runtime_connected", surface: "community", connection_type: "local_daemon" }];
+ }
+ if (row.eventName === "first_agent_reply_persisted" && row.conversationType) {
+ return [{ event: "first_agent_reply_persisted", surface: "community", conversation_type: row.conversationType }];
+ }
+ if (row.eventName === "invited_human_joined") {
+ return [{ event: "invited_human_joined", surface: "community" }];
+ }
+ return [];
+ });
+}
diff --git a/src/shared/src/db/queries/community/invite-funnel-analytics.test.ts b/src/shared/src/db/queries/community/invite-funnel-analytics.test.ts
new file mode 100644
index 000000000..565bfd817
--- /dev/null
+++ b/src/shared/src/db/queries/community/invite-funnel-analytics.test.ts
@@ -0,0 +1,116 @@
+import Sqlite from "better-sqlite3"
+import { readFileSync } from "node:fs"
+import { resolve } from "node:path"
+import { drizzle } from "drizzle-orm/better-sqlite3"
+import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import * as communityFunnelAnalyticsSchema from "../../community-funnel-analytics-schema"
+import * as communitySchema from "../../community-schema"
+import * as userSchema from "../../schema"
+import type { Database } from "../../index"
+import { claimPendingEvents } from "./funnel-analytics"
+import { useInvite } from "./invite"
+
+const migrationPath = resolve(
+ import.meta.dirname,
+ "../../../../../web/migrations/0103_community_funnel_analytics_event.sql",
+)
+
+type BatchStatement = { all(): unknown; run(): unknown }
+
+function createTestDb(sqlite: Sqlite.Database): Database {
+ const db = drizzle(sqlite, {
+ schema: {
+ ...userSchema,
+ ...communitySchema,
+ ...communityFunnelAnalyticsSchema,
+ },
+ })
+ Object.assign(db, {
+ batch: async (statements: BatchStatement[]) => sqlite.transaction(() =>
+ statements.map((statement, index) => index === 0 ? statement.all() : statement.run()),
+ )(),
+ })
+ return db as unknown as Database
+}
+
+describe("invite membership funnel boundary", () => {
+ let sqlite: Sqlite.Database
+ let db: Database
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:")
+ sqlite.exec(`
+ CREATE TABLE user (
+ id TEXT PRIMARY KEY NOT NULL,
+ name TEXT NOT NULL,
+ email TEXT NOT NULL,
+ image TEXT,
+ avatarVersion INTEGER NOT NULL DEFAULT 0,
+ discriminator TEXT NOT NULL DEFAULT '0000',
+ isBot INTEGER NOT NULL DEFAULT 0,
+ ownerUserId TEXT,
+ deletedAt TEXT
+ );
+ CREATE TABLE community_server_invite (
+ id TEXT PRIMARY KEY NOT NULL,
+ server_id TEXT NOT NULL,
+ created_by TEXT,
+ token TEXT NOT NULL,
+ max_uses INTEGER,
+ uses INTEGER DEFAULT 0,
+ expires_at TEXT,
+ created_at TEXT NOT NULL
+ );
+ CREATE TABLE community_server_member (
+ id TEXT PRIMARY KEY NOT NULL,
+ server_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ role TEXT DEFAULT 'member',
+ rail_order INTEGER DEFAULT 0,
+ joined_at TEXT NOT NULL,
+ UNIQUE(server_id, user_id)
+ );
+ `)
+ sqlite.exec(readFileSync(migrationPath, "utf8"))
+ sqlite.prepare("INSERT INTO user (id, name, email, isBot, ownerUserId) VALUES (?, ?, ?, ?, ?)")
+ .run("owner", "Owner", "[email protected]", 0, null)
+ sqlite.prepare("INSERT INTO user (id, name, email, isBot, ownerUserId) VALUES (?, ?, ?, ?, ?)")
+ .run("human", "Human", "[email protected]", 0, null)
+ sqlite.prepare("INSERT INTO user (id, name, email, isBot, ownerUserId) VALUES (?, ?, ?, ?, ?)")
+ .run("bot", "Bot", "[email protected]", 1, "owner")
+ db = createTestDb(sqlite)
+ })
+
+ afterEach(() => sqlite.close())
+
+ function insertInvite(id: string, token: string) {
+ sqlite.prepare(`
+ INSERT INTO community_server_invite
+ (id, server_id, created_by, token, max_uses, uses, created_at)
+ VALUES (?, 'server', 'owner', ?, 10, 0, '2026-09-14T00:00:00.000Z')
+ `).run(id, token)
+ }
+
+ it("commits one inviter-owned event with a fresh human membership", async () => {
+ insertInvite("invite-human", "token-human")
+
+ await expect(useInvite(db, "token-human", "human")).resolves.toMatchObject({
+ invite: { id: "invite-human", createdBy: "owner" },
+ member: { userId: "human", userName: "Human" },
+ })
+ await expect(claimPendingEvents(db, "owner")).resolves.toEqual([
+ { event: "invited_human_joined", surface: "community" },
+ ])
+ expect(sqlite.prepare("SELECT uses FROM community_server_invite WHERE id = ?").get("invite-human"))
+ .toEqual({ uses: 1 })
+ })
+
+ it("commits a bot membership without manufacturing a human-join event", async () => {
+ insertInvite("invite-bot", "token-bot")
+
+ await expect(useInvite(db, "token-bot", "bot")).resolves.toMatchObject({
+ member: { userId: "bot" },
+ })
+ await expect(claimPendingEvents(db, "owner")).resolves.toEqual([])
+ })
+})
diff --git a/src/shared/src/db/queries/community/invite.ts b/src/shared/src/db/queries/community/invite.ts
index 19d2f0217..99343ce01 100644
--- a/src/shared/src/db/queries/community/invite.ts
+++ b/src/shared/src/db/queries/community/invite.ts
@@ -6,6 +6,7 @@ import {
} from "../../community-schema";
import { user } from "../../schema";
import type { Database } from "../../index";
+import { recordInvitedHumanJoinedStatement } from "./funnel-analytics";
export async function createInvite(
db: Database,
@@ -165,7 +166,18 @@ export async function useInvite(
),
),
);
- const batchResults = (await db.batch([insertMember, incrementUse] as any)) as any[];
+ const recordJoin = invite.createdBy
+ ? recordInvitedHumanJoinedStatement(db, {
+ ownerUserId: invite.createdBy,
+ membershipId: memberId,
+ invitedUserId: userId,
+ now,
+ })
+ : null;
+ const statements = recordJoin
+ ? [insertMember, incrementUse, recordJoin]
+ : [insertMember, incrementUse];
+ const batchResults = (await db.batch(statements as any)) as any[];
const insertedMember = (batchResults[0] as Array<typeof communityServerMember.$inferSelect>)[0];
if (!insertedMember) return null;
diff --git a/src/shared/src/db/queries/community/machine-session-epoch.ts b/src/shared/src/db/queries/community/machine-session-epoch.ts
index cde152cd9..8ef52e91b 100644
--- a/src/shared/src/db/queries/community/machine-session-epoch.ts
+++ b/src/shared/src/db/queries/community/machine-session-epoch.ts
@@ -12,6 +12,7 @@ import {
type MachineMetadataInput,
type MachineRow,
} from "./machine";
+import { recordRuntimeConnectedStatement } from "./funnel-analytics";
import { assertMachineCapacity, getMachineCapacitySummary, MachineLimitReachedError, machinesMaxForUserSql } from "../product-plan";
@@ -131,7 +132,7 @@ async function transitionLiveLease(
isNull(communityMachineCredential.revokedAt),
),
);
- const rows = await db
+ const transition = db
.update(communityMachine)
.set(values)
.where(
@@ -148,6 +149,17 @@ async function transitionLiveLease(
),
)
.returning();
+ const rows = command.type === "ready"
+ ? ((await db.batch([
+ transition,
+ recordRuntimeConnectedStatement(db, {
+ ownerUserId: epoch.userId,
+ machineId: epoch.machineId,
+ credentialHash: epoch.credentialHash,
+ now: nowIso,
+ }),
+ ] as any)) as any[])[0] as MachineRow[]
+ : await transition;
if (rows.length === 0) return { type: "stale_epoch" };
return {
diff --git a/src/shared/src/db/queries/community/machine-session-funnel-analytics.test.ts b/src/shared/src/db/queries/community/machine-session-funnel-analytics.test.ts
new file mode 100644
index 000000000..af1f59d19
--- /dev/null
+++ b/src/shared/src/db/queries/community/machine-session-funnel-analytics.test.ts
@@ -0,0 +1,143 @@
+import Sqlite from "better-sqlite3"
+import { readFileSync } from "node:fs"
+import { resolve } from "node:path"
+import { drizzle } from "drizzle-orm/better-sqlite3"
+import { afterEach, beforeEach, describe, expect, it } from "vitest"
+import * as communityFunnelAnalyticsSchema from "../../community-funnel-analytics-schema"
+import * as communityMachineSchema from "../../community-machine-schema"
+import * as productPlanSchema from "../../product-plan-schema"
+import * as userSchema from "../../schema"
+import type { Database } from "../../index"
+import { claimPendingEvents } from "./funnel-analytics"
+import { transitionMachineSessionEpoch } from "./machine-session-epoch"
+
+const migrationPath = resolve(
+ import.meta.dirname,
+ "../../../../../web/migrations/0103_community_funnel_analytics_event.sql",
+)
+
+type BatchStatement = { all(): unknown; run(): unknown }
+
+function createTestDb(sqlite: Sqlite.Database): Database {
+ const db = drizzle(sqlite, {
+ schema: {
+ ...userSchema,
+ ...communityMachineSchema,
+ ...productPlanSchema,
+ ...communityFunnelAnalyticsSchema,
+ },
+ })
+ Object.assign(db, {
+ batch: async (statements: BatchStatement[]) => sqlite.transaction(() =>
+ statements.map((statement, index) => index === 0 ? statement.all() : statement.run()),
+ )(),
+ })
+ return db as unknown as Database
+}
+
+describe("machine ready funnel boundary", () => {
+ let sqlite: Sqlite.Database
+ let db: Database
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:")
+ sqlite.exec(`
+ CREATE TABLE user (
+ id TEXT PRIMARY KEY NOT NULL,
+ isBot INTEGER NOT NULL,
+ deletedAt TEXT
+ );
+ CREATE TABLE community_machine (
+ id TEXT PRIMARY KEY NOT NULL,
+ user_id TEXT NOT NULL,
+ display_name TEXT NOT NULL DEFAULT '',
+ hostname TEXT NOT NULL DEFAULT '',
+ platform TEXT NOT NULL DEFAULT '',
+ arch TEXT NOT NULL DEFAULT '',
+ os_release TEXT NOT NULL DEFAULT '',
+ daemon_version TEXT NOT NULL DEFAULT '',
+ time_zone TEXT,
+ metadata TEXT,
+ available_runtimes TEXT NOT NULL DEFAULT '[]',
+ status TEXT NOT NULL DEFAULT 'offline',
+ last_seen_at TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+ CREATE TABLE community_machine_credential (
+ id TEXT PRIMARY KEY NOT NULL,
+ user_id TEXT NOT NULL,
+ machine_id TEXT NOT NULL,
+ credential_hash TEXT NOT NULL UNIQUE,
+ do_name TEXT NOT NULL UNIQUE,
+ created_at TEXT NOT NULL,
+ last_used_at TEXT,
+ revoked_at TEXT
+ );
+ CREATE TABLE product_plan (
+ id TEXT PRIMARY KEY NOT NULL,
+ is_default INTEGER NOT NULL,
+ is_active INTEGER NOT NULL
+ );
+ CREATE TABLE product_plan_entitlement (
+ plan_id TEXT NOT NULL,
+ entitlement_key TEXT NOT NULL,
+ value_json TEXT NOT NULL
+ );
+ CREATE TABLE user_product_plan (
+ user_id TEXT PRIMARY KEY NOT NULL,
+ plan_id TEXT NOT NULL
+ );
+ `)
+ sqlite.exec(readFileSync(migrationPath, "utf8"))
+ sqlite.prepare("INSERT INTO user (id, isBot) VALUES ('owner', 0)").run()
+ sqlite.prepare("INSERT INTO product_plan (id, is_default, is_active) VALUES ('free', 1, 1)").run()
+ sqlite.prepare("INSERT INTO product_plan_entitlement (plan_id, entitlement_key, value_json) VALUES ('free', 'machines.max', '3')").run()
+ sqlite.prepare(`
+ INSERT INTO community_machine
+ (id, user_id, display_name, hostname, platform, arch, os_release, daemon_version, available_runtimes, status, created_at, updated_at)
+ VALUES ('machine', 'owner', '', '', '', '', '', '', '[]', 'offline', '2026-09-14T00:00:00.000Z', '2026-09-14T00:00:00.000Z')
+ `).run()
+ sqlite.prepare(`
+ INSERT INTO community_machine_credential
+ (id, user_id, machine_id, credential_hash, do_name, created_at)
+ VALUES ('credential', 'owner', 'machine', 'hash', 'do-name', '2026-09-14T00:00:00.000Z')
+ `).run()
+ db = createTestDb(sqlite)
+ })
+
+ afterEach(() => sqlite.close())
+
+ it("records only the first authenticated ready transition for one credential epoch", async () => {
+ const epoch = { userId: "owner", machineId: "machine", credentialHash: "hash" }
+ const metadata = { hostname: "host", availableRuntimes: [] }
+
+ await expect(transitionMachineSessionEpoch(db, {
+ type: "ready",
+ epoch,
+ metadata,
+ })).resolves.toMatchObject({ type: "transitioned", machine: { status: "online" } })
+ await expect(transitionMachineSessionEpoch(db, {
+ type: "ready",
+ epoch,
+ metadata,
+ })).resolves.toMatchObject({ type: "transitioned" })
+ await expect(transitionMachineSessionEpoch(db, {
+ type: "renew",
+ epoch,
+ })).resolves.toMatchObject({ type: "transitioned" })
+
+ await expect(claimPendingEvents(db, "owner")).resolves.toEqual([
+ { event: "runtime_connected", surface: "community", connection_type: "local_daemon" },
+ ])
+ })
+
+ it("does not record a stale credential epoch", async () => {
+ await expect(transitionMachineSessionEpoch(db, {
+ type: "ready",
+ epoch: { userId: "owner", machineId: "machine", credentialHash: "stale" },
+ metadata: { hostname: "host" },
+ })).resolves.toEqual({ type: "stale_epoch" })
+ await expect(claimPendingEvents(db, "owner")).resolves.toEqual([])
+ })
+})
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 1bfee1e13..5c63ff30c 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -190,6 +190,11 @@ export type { NotifLevel, NotificationLevelValue, ParticipantSource, MentionKind
export * from "./provider-telemetry";
export * from "./product-entitlements";
export * from "./billing";
+export type {
+ CommunityFunnelAnalyticsEvent,
+ CommunityFunnelConversationType,
+ CommunityFunnelEventName,
+} from "./db/community-funnel-analytics-schema";
export type {
AgentStatusType,
diff --git a/src/shared/test/community-write-atomic.test.ts b/src/shared/test/community-write-atomic.test.ts
index 0a4db3b6f..bd3630050 100644
--- a/src/shared/test/community-write-atomic.test.ts
+++ b/src/shared/test/community-write-atomic.test.ts
@@ -121,7 +121,7 @@ describe("Community durable writes — real SQLite transactions", () => {
});
it("a later mention chunk failure rolls back all chunks and same nonce can retry", async () => {
- fixture.sqlite.exec(Array.from({ length: 100 }, (_, i) => `INSERT INTO user VALUES ('u${i}');`).join("\n"));
+ fixture.sqlite.exec(Array.from({ length: 100 }, (_, i) => `INSERT INTO user (id) VALUES ('u${i}');`).join("\n"));
const mentions = Array.from({ length: 100 }, (_, i) => ({ userId: `u${i}`, kind: "mention" }));
fixture.sqlite.exec("CREATE TRIGGER fail_late_mention BEFORE INSERT ON community_mention WHEN NEW.user_id = 'u85' BEGIN SELECT RAISE(ABORT, 'injected mention failure'); END");
const data = { clientNonce: "retry", mentions, extraStatements: [bump()] };
@@ -150,7 +150,7 @@ describe("Community durable writes — real SQLite transactions", () => {
expect(rows("activity")).toEqual([{ sent: 1 }]);
});
it("later participant chunk failure rolls back the send and all earlier memberships", async () => {
- fixture.sqlite.exec(Array.from({ length: 100 }, (_, i) => `INSERT INTO user VALUES ('u${i}');`).join("\n"));
+ fixture.sqlite.exec(Array.from({ length: 100 }, (_, i) => `INSERT INTO user (id) VALUES ('u${i}');`).join("\n"));
fixture.sqlite.exec("CREATE TRIGGER fail_late_participant BEFORE INSERT ON community_channel_member WHEN NEW.user_id = 'u85' BEGIN SELECT RAISE(ABORT, 'injected participant failure'); END");
const participants = Array.from({ length: 100 }, (_, i) => ({ userId: `u${i}`, source: "mention" }));
await expect(send({ participants })).rejects.toThrow("injected participant failure");
diff --git a/src/shared/test/helpers/community-write-db.ts b/src/shared/test/helpers/community-write-db.ts
index 34e67ecae..2a02445d3 100644
--- a/src/shared/test/helpers/community-write-db.ts
+++ b/src/shared/test/helpers/community-write-db.ts
@@ -6,8 +6,13 @@ export function communityWriteDb() {
const sqlite = new Sqlite(":memory:");
sqlite.pragma("foreign_keys = ON");
sqlite.exec(`
- CREATE TABLE user (id TEXT PRIMARY KEY);
- INSERT INTO user VALUES ('author'), ('peer');
+ CREATE TABLE user (
+ id TEXT PRIMARY KEY,
+ isBot INTEGER NOT NULL DEFAULT 0,
+ ownerUserId TEXT,
+ deletedAt TEXT
+ );
+ INSERT INTO user (id) VALUES ('author'), ('peer');
CREATE TABLE community_channel (
id TEXT PRIMARY KEY, server_id TEXT, category_id TEXT, name TEXT,
type TEXT NOT NULL DEFAULT 'text', topic TEXT DEFAULT '', position INTEGER DEFAULT 0,
@@ -44,6 +49,16 @@ export function communityWriteDb() {
id TEXT PRIMARY KEY, message_id TEXT NOT NULL REFERENCES community_message(id), user_id TEXT NOT NULL REFERENCES user(id),
kind TEXT NOT NULL DEFAULT 'mention', read INTEGER DEFAULT 0
);
+ CREATE TABLE community_funnel_analytics_event (
+ id TEXT PRIMARY KEY NOT NULL,
+ owner_user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ event_name TEXT NOT NULL,
+ conversation_type TEXT,
+ source_id TEXT NOT NULL,
+ dedupe_key TEXT NOT NULL UNIQUE,
+ created_at TEXT NOT NULL,
+ claimed_at TEXT
+ );
CREATE TABLE activity (sent INTEGER NOT NULL);
INSERT INTO activity VALUES (0);
INSERT INTO community_channel (id, type, created_at) VALUES ('channel', 'text', 'now');
diff --git a/src/shared/test/queries/community-invite.test.ts b/src/shared/test/queries/community-invite.test.ts
index 769374738..d104d821a 100644
--- a/src/shared/test/queries/community-invite.test.ts
+++ b/src/shared/test/queries/community-invite.test.ts
@@ -16,7 +16,10 @@ describe("community invite quota consumption", () => {
image TEXT,
avatarVersion INTEGER NOT NULL DEFAULT 0,
avatarObjectKey TEXT,
- discriminator TEXT
+ discriminator TEXT,
+ isBot INTEGER NOT NULL DEFAULT 0,
+ ownerUserId TEXT,
+ deletedAt TEXT
);
CREATE TABLE community_server_invite (
id TEXT PRIMARY KEY,
@@ -37,6 +40,16 @@ describe("community invite quota consumption", () => {
joined_at TEXT NOT NULL,
UNIQUE(server_id, user_id)
);
+ CREATE TABLE community_funnel_analytics_event (
+ id TEXT PRIMARY KEY NOT NULL,
+ owner_user_id TEXT NOT NULL,
+ event_name TEXT NOT NULL,
+ conversation_type TEXT,
+ source_id TEXT NOT NULL,
+ dedupe_key TEXT NOT NULL UNIQUE,
+ created_at TEXT NOT NULL,
+ claimed_at TEXT
+ );
`);
db = drizzle(sqlite);
// better-sqlite3's Drizzle adapter has transactions but no D1-style batch.
@@ -58,12 +71,12 @@ describe("community invite quota consumption", () => {
afterEach(() => sqlite.close());
- function seedInvite(maxUses: number | null = 1) {
+ function seedInvite(maxUses: number | null = 1, createdBy: string | null = "owner") {
sqlite.prepare(`
INSERT INTO community_server_invite
(id, server_id, created_by, token, max_uses, uses, created_at)
- VALUES ('iv1', 's1', 'owner', 'token1', ?, 0, '2026-01-01T00:00:00.000Z')
- `).run(maxUses);
+ VALUES ('iv1', 's1', ?, 'token1', ?, 0, '2026-01-01T00:00:00.000Z')
+ `).run(createdBy, maxUses);
}
it("admits only one member for the final finite use", async () => {
@@ -86,6 +99,15 @@ describe("community invite quota consumption", () => {
.toEqual({ uses: 1 });
});
+ it("admits a legacy invite without inventing a funnel owner", async () => {
+ seedInvite(1, null);
+
+ await expect(useInvite(db as never, "token1", "u1")).resolves.not.toBeNull();
+
+ expect(sqlite.prepare("SELECT COUNT(*) AS count FROM community_funnel_analytics_event").get())
+ .toEqual({ count: 0 });
+ });
+
it("enforces the active invite cap inside the insert statement", async () => {
seedInvite(null);
diff --git a/src/shared/test/queries/community-machine.test.ts b/src/shared/test/queries/community-machine.test.ts
index 8770ea44c..e5b0d9b1a 100644
--- a/src/shared/test/queries/community-machine.test.ts
+++ b/src/shared/test/queries/community-machine.test.ts
@@ -1,9 +1,13 @@
import { describe, it, expect, vi } from "vitest";
vi.mock("../../src/db/queries/product-plan", async (original) => ({ ...await original<typeof import("../../src/db/queries/product-plan")>(), assertMachineCapacity: vi.fn() }));
+vi.mock("../../src/db/queries/community/funnel-analytics", () => ({
+ recordRuntimeConnectedStatement: vi.fn(() => ({ kind: "runtime-connected-statement" })),
+}));
import * as q from "../../src/db/queries/community/machine";
import * as sessionEpoch from "../../src/db/queries/community/machine-session-epoch";
async function readyEpoch(db: any, userId: string, machineId: string, metadata: q.MachineMetadataInput, credentialHash: string) {
+ db.batch ??= vi.fn(async (statements: unknown[]) => [await statements[0], []]);
const result = await sessionEpoch.transitionMachineSessionEpoch(db, {
type: "ready",
epoch: { userId, machineId, credentialHash },
diff --git a/src/shared/test/queries/machine-plan-limits.integration.test.ts b/src/shared/test/queries/machine-plan-limits.integration.test.ts
index 8beb93397..dbf34bbc6 100644
--- a/src/shared/test/queries/machine-plan-limits.integration.test.ts
+++ b/src/shared/test/queries/machine-plan-limits.integration.test.ts
@@ -21,6 +21,7 @@ beforeEach(() => {
for (const migration of ["0098_product_plan_bot_active", "0099_billing_founder", "0101_machine_plan_limits"]) {
sqlite.exec(readFileSync(new URL(`../../../web/migrations/${migration}.sql`, import.meta.url), "utf8"));
}
+ sqlite.exec(readFileSync(new URL("../../../web/migrations/0103_community_funnel_analytics_event.sql", import.meta.url), "utf8"));
sqlite.exec("INSERT INTO user(id) VALUES('owner'),('other')");
db = drizzle(sqlite) as unknown as Database;
db.batch = (async (statements: Array<{ toSQL(): { sql: string; params: unknown[] }; all(): unknown[]; run(): unknown }>) =>
diff --git a/src/shared/test/queries/machine-session-epoch.integration.test.ts b/src/shared/test/queries/machine-session-epoch.integration.test.ts
index 676a26233..491d0c99e 100644
--- a/src/shared/test/queries/machine-session-epoch.integration.test.ts
+++ b/src/shared/test/queries/machine-session-epoch.integration.test.ts
@@ -66,6 +66,7 @@ describe("machine session epoch SQL transaction", () => {
sqlite.exec(readFileSync(new URL("../../../web/migrations/0098_product_plan_bot_active.sql", import.meta.url), "utf8"));
sqlite.exec(readFileSync(new URL("../../../web/migrations/0099_billing_founder.sql", import.meta.url), "utf8"));
sqlite.exec(readFileSync(new URL("../../../web/migrations/0101_machine_plan_limits.sql", import.meta.url), "utf8"));
+ sqlite.exec(readFileSync(new URL("../../../web/migrations/0103_community_funnel_analytics_event.sql", import.meta.url), "utf8"));
db = drizzle(sqlite);
// Match D1's all-or-nothing batch contract using real generated SQL.
(db as any).batch = (statements: Array<{ toSQL: () => { sql: string; params: unknown[] } }>) =>
diff --git a/src/web/blog/src/app/blog/layout.test.ts b/src/web/blog/src/app/blog/layout.test.ts
new file mode 100644
index 000000000..db1837181
--- /dev/null
+++ b/src/web/blog/src/app/blog/layout.test.ts
@@ -0,0 +1,36 @@
+import { createElement } from "react";
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("@/components/theme-toggle", () => ({
+ ThemeToggle: "theme-toggle",
+}));
+
+vi.mock("@/components/public-layout", () => ({
+ PublicLayout: "public-layout",
+}));
+
+vi.mock("@/components/github-outbound-link", () => ({
+ GithubOutboundBoundary: "github-outbound-boundary",
+}));
+
+import BlogLayout from "./layout";
+
+describe("BlogLayout", () => {
+ it("wraps blog content in the outbound GitHub analytics boundary", () => {
+ const child = createElement("article", null, "Post");
+ const layout = BlogLayout({ children: child });
+
+ expect(layout.type).toBe("public-layout");
+ expect(layout.props).toMatchObject({
+ zone: "blog",
+ breadcrumb: "Blog",
+ footer: "rich",
+ });
+ expect(layout.props.rightSlot.type).toBe("theme-toggle");
+ expect(layout.props.children.type).toBe("github-outbound-boundary");
+ expect(layout.props.children.props).toEqual({
+ surface: "blog",
+ children: child,
+ });
+ });
+});
diff --git a/src/web/blog/src/app/blog/layout.tsx b/src/web/blog/src/app/blog/layout.tsx
index 7f1e9758b..02d892d74 100644
--- a/src/web/blog/src/app/blog/layout.tsx
+++ b/src/web/blog/src/app/blog/layout.tsx
@@ -1,5 +1,6 @@
import { ThemeToggle } from "@/components/theme-toggle";
import { PublicLayout } from "@/components/public-layout";
+import { GithubOutboundBoundary } from "@/components/github-outbound-link";
export default function BlogLayout({
children,
@@ -8,7 +9,9 @@ export default function BlogLayout({
}) {
return (
<PublicLayout zone="blog" breadcrumb="Blog" rightSlot={<ThemeToggle />} footer="rich">
- {children}
+ <GithubOutboundBoundary surface="blog">
+ {children}
+ </GithubOutboundBoundary>
</PublicLayout>
);
}
diff --git a/src/web/migrations/0103_community_funnel_analytics_event.sql b/src/web/migrations/0103_community_funnel_analytics_event.sql
new file mode 100644
index 000000000..5fe5ec429
--- /dev/null
+++ b/src/web/migrations/0103_community_funnel_analytics_event.sql
@@ -0,0 +1,21 @@
+CREATE TABLE community_funnel_analytics_event (
+ id TEXT PRIMARY KEY NOT NULL,
+ owner_user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
+ event_name TEXT NOT NULL CONSTRAINT ck_community_funnel_analytics_event_name
+ CHECK (event_name IN ('runtime_connected', 'first_agent_reply_persisted', 'invited_human_joined')),
+ conversation_type TEXT,
+ source_id TEXT NOT NULL,
+ dedupe_key TEXT NOT NULL,
+ created_at TEXT NOT NULL,
+ claimed_at TEXT,
+ CONSTRAINT ck_community_funnel_analytics_conversation_type CHECK (
+ (event_name = 'first_agent_reply_persisted' AND conversation_type IN ('dm', 'channel', 'thread'))
+ OR (event_name != 'first_agent_reply_persisted' AND conversation_type IS NULL)
+ )
+);
+
+CREATE UNIQUE INDEX uq_community_funnel_analytics_dedupe
+ ON community_funnel_analytics_event(dedupe_key);
+
+CREATE INDEX idx_community_funnel_analytics_owner_claimed_created
+ ON community_funnel_analytics_event(owner_user_id, claimed_at, created_at);
diff --git a/src/web/src/app/api/community/analytics/funnel-events/route.test.ts b/src/web/src/app/api/community/analytics/funnel-events/route.test.ts
new file mode 100644
index 000000000..ce2e9bb53
--- /dev/null
+++ b/src/web/src/app/api/community/analytics/funnel-events/route.test.ts
@@ -0,0 +1,48 @@
+import { NextRequest } from "next/server"
+import { describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ db: { primary: true },
+ claimPendingEvents: vi.fn(),
+ withCookieHumanAuth: vi.fn(
+ (handler: (req: NextRequest, ctx: Record<string, any>) => Promise<Response>) =>
+ async (req: NextRequest) => handler(req, {
+ env: { DB: {} },
+ userId: "session-user",
+ }),
+ ),
+}))
+
+vi.mock("@/lib/db", () => ({ getPrimaryDb: () => mocks.db }))
+vi.mock("@alook/shared", () => ({
+ queries: {
+ communityFunnelAnalytics: {
+ claimPendingEvents: (...args: unknown[]) => mocks.claimPendingEvents(...args),
+ },
+ },
+}))
+vi.mock("@/lib/middleware/auth", () => ({
+ withCookieHumanAuth: mocks.withCookieHumanAuth,
+}))
+
+import { POST } from "./route"
+
+describe("POST /api/community/analytics/funnel-events", () => {
+ it("claims only the authenticated account and disables caching", async () => {
+ mocks.claimPendingEvents.mockResolvedValueOnce([
+ { event: "runtime_connected", surface: "community", connection_type: "local_daemon" },
+ ])
+
+ const response = await POST(new NextRequest(
+ "https://alook.ai/api/community/analytics/funnel-events",
+ { method: "POST", headers: { Origin: "https://alook.ai" } },
+ ))
+
+ expect(mocks.claimPendingEvents).toHaveBeenCalledWith(mocks.db, "session-user")
+ expect(response.status).toBe(200)
+ expect(response.headers.get("Cache-Control")).toBe("no-store")
+ expect(await response.json()).toEqual({ events: [
+ { event: "runtime_connected", surface: "community", connection_type: "local_daemon" },
+ ] })
+ })
+})
diff --git a/src/web/src/app/api/community/analytics/funnel-events/route.ts b/src/web/src/app/api/community/analytics/funnel-events/route.ts
new file mode 100644
index 000000000..91b98e015
--- /dev/null
+++ b/src/web/src/app/api/community/analytics/funnel-events/route.ts
@@ -0,0 +1,14 @@
+import { queries } from "@alook/shared"
+import { getPrimaryDb } from "@/lib/db"
+import { withCookieHumanAuth } from "@/lib/middleware/auth"
+import { writeJSON } from "@/lib/middleware/helpers"
+
+export const POST = withCookieHumanAuth(async (_req, ctx) => {
+ const events = await queries.communityFunnelAnalytics.claimPendingEvents(
+ getPrimaryDb(ctx.env.DB),
+ ctx.userId,
+ )
+ const response = writeJSON({ events })
+ response.headers.set("Cache-Control", "no-store")
+ return response
+})
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
index a8ee56902..a6f06675e 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
@@ -50,6 +50,7 @@ const mockListThreadParticipantUserIds = vi.fn()
const mockDeleteChannel = vi.fn()
const mockHardDeleteMessage = vi.fn()
const mockRebindPendingAttachmentsToChild = vi.fn()
+const mockRecordFirstAgentReplyPersistedStatement = vi.fn(() => ({ kind: "first-agent-reply-statement" }))
const mockFanOutToChannel = vi.fn()
const mockBroadcastToUserSafe = vi.fn()
@@ -148,6 +149,9 @@ vi.mock("@alook/shared", async () => {
communityBot: {
bumpBotDailyActivityStatement: (...a: unknown[]) => mockBumpBotDailyActivityStatement(...a),
},
+ communityFunnelAnalytics: {
+ recordFirstAgentReplyPersistedStatement: (...a: unknown[]) => mockRecordFirstAgentReplyPersistedStatement(...a),
+ },
// resolveTargetForMember (real, for the bot ref-via-query arm) resolves
// the server then channel by name, both member-scoped.
communityServer: {
diff --git a/src/web/src/components/community/social/invite-dialog.test.ts b/src/web/src/components/community/social/invite-dialog.test.ts
index af4098c93..c94fa7bc0 100644
--- a/src/web/src/components/community/social/invite-dialog.test.ts
+++ b/src/web/src/components/community/social/invite-dialog.test.ts
@@ -16,6 +16,8 @@ const mocks = vi.hoisted(() => ({
isFetching: false,
refetch: vi.fn(),
},
+ trackHumanInvitationSent: vi.fn(),
+ trackHumanInvitationCopied: vi.fn(),
}))
vi.mock("sonner", () => ({ toast: mocks.toastSpy }))
@@ -52,6 +54,10 @@ vi.mock("@/hooks/community/use-dm-message-sender", () => ({
vi.mock("@/contexts/community/current-user", () => ({
useCurrentUser: () => ({ id: "viewer", name: "Viewer", avatar: "V" }),
}))
+vi.mock("@/lib/analytics", () => ({
+ trackHumanInvitationSent: mocks.trackHumanInvitationSent,
+ trackHumanInvitationCopied: mocks.trackHumanInvitationCopied,
+}))
vi.mock("@/components/ui/dialog", async () => {
const { createElement } = await import("react")
return {
@@ -69,7 +75,13 @@ vi.mock("../people-picker", async () => {
}
})
-import { InviteDialog, InviteFriendRow, runInviteFriend } from "./invite-dialog"
+import {
+ InviteDialog,
+ InviteFriendRow,
+ awaitCommittedInvite,
+ copyInviteLink,
+ runInviteFriend,
+} from "./invite-dialog"
const friend: Friend = {
id: "friend_1",
@@ -306,3 +318,48 @@ describe("runInviteFriend", () => {
expect(inFlight).toEqual(new Set())
})
})
+
+describe("invite funnel completion boundaries", () => {
+ beforeEach(() => {
+ mocks.trackHumanInvitationSent.mockClear()
+ mocks.trackHumanInvitationCopied.mockClear()
+ })
+
+ it("reports sent only after the DM receipt commits", async () => {
+ await expect(awaitCommittedInvite({
+ accepted: true,
+ nonce: "nonce",
+ committed: Promise.resolve({ ok: true, message: { id: "message", seq: 1 } }),
+ })).resolves.toBeUndefined()
+
+ expect(mocks.trackHumanInvitationSent).toHaveBeenCalledOnce()
+ })
+
+ it.each([
+ { accepted: false } as const,
+ {
+ accepted: true,
+ nonce: "nonce",
+ committed: Promise.resolve({ ok: false, error: new Error("commit failed") }),
+ } as const,
+ ])("does not report sent for rejected or failed receipts", async (receipt) => {
+ await expect(awaitCommittedInvite(receipt)).rejects.toThrow()
+ expect(mocks.trackHumanInvitationSent).not.toHaveBeenCalled()
+ })
+
+ it("reports copied only after clipboard success", async () => {
+ const writeText = vi.fn().mockResolvedValue(undefined)
+ await copyInviteLink("https://alook.ai/c/invite/token", writeText)
+
+ expect(writeText).toHaveBeenCalledWith("https://alook.ai/c/invite/token")
+ expect(mocks.trackHumanInvitationCopied).toHaveBeenCalledOnce()
+ })
+
+ it("does not report copied when clipboard rejects", async () => {
+ await expect(copyInviteLink(
+ "https://alook.ai/c/invite/token",
+ vi.fn().mockRejectedValue(new Error("denied")),
+ )).rejects.toThrow("denied")
+ expect(mocks.trackHumanInvitationCopied).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/components/community/social/invite-dialog.tsx b/src/web/src/components/community/social/invite-dialog.tsx
index 2efd82b9d..8d46deef2 100644
--- a/src/web/src/components/community/social/invite-dialog.tsx
+++ b/src/web/src/components/community/social/invite-dialog.tsx
@@ -21,11 +21,18 @@ import {
useCreateOrGetDm,
} from "@/hooks/community/mutations"
import { useFriendsPresence } from "@/hooks/community/use-friends"
-import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"
+import {
+ useDmMessageSender,
+ type DmSendReceipt,
+} from "@/hooks/community/use-dm-message-sender"
import { useCurrentUser } from "@/contexts/community/current-user"
import type { Friend } from "@/lib/community/models/people"
import { useCommunityWsStore } from "@/stores/community/ws"
import { readCommunityProfile } from "@/lib/community/profile-read"
+import {
+ trackHumanInvitationCopied,
+ trackHumanInvitationSent,
+} from "@/lib/analytics"
const INVITE_ORIGIN =
typeof window !== "undefined" ? window.location.origin : ""
@@ -112,6 +119,25 @@ export async function runInviteFriend(
}
}
+export async function awaitCommittedInvite(
+ receipt: DmSendReceipt,
+ onCommitted: () => void = trackHumanInvitationSent,
+) {
+ if (!receipt.accepted) throw new Error("Couldn't send invite")
+ const committed = await receipt.committed
+ if (!committed.ok) throw committed.error
+ onCommitted()
+}
+
+export async function copyInviteLink(
+ url: string,
+ writeText: (value: string) => Promise<void>,
+ onCopied: () => void = trackHumanInvitationCopied,
+) {
+ await writeText(url)
+ onCopied()
+}
+
/**
* Invite dialog: friends list at the top (each with an "Invite"
* button that sends the invite URL as a DM), plus a copyable link at the
@@ -237,9 +263,7 @@ export function InviteDialog({
avatar: currentUser.avatar,
},
})
- if (!receipt.accepted) throw new Error("Couldn't send invite")
- const committed = await receipt.committed
- if (!committed.ok) throw committed.error
+ await awaitCommittedInvite(receipt)
},
(invitedUserId) => {
setInvitedUserIds((prev) => {
@@ -255,7 +279,7 @@ export function InviteDialog({
const copyLink = async () => {
if (!token) return
try {
- await navigator.clipboard.writeText(inviteUrl(token))
+ await copyInviteLink(inviteUrl(token), (value) => navigator.clipboard.writeText(value))
toast("Invite link copied")
} catch {
toast("Couldn't copy — copy manually")
diff --git a/src/web/src/components/github-outbound-link.test.ts b/src/web/src/components/github-outbound-link.test.ts
new file mode 100644
index 000000000..a9d1974bc
--- /dev/null
+++ b/src/web/src/components/github-outbound-link.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vitest"
+import {
+ ALOOK_GITHUB_REPO_URL,
+ shouldTrackGithubOutboundClick,
+} from "./github-outbound-link"
+
+describe("GitHub outbound click contract", () => {
+ it("accepts a trusted click on the exact repository URL", () => {
+ expect(shouldTrackGithubOutboundClick(true, ALOOK_GITHUB_REPO_URL)).toBe(true)
+ })
+
+ it.each([
+ [false, ALOOK_GITHUB_REPO_URL],
+ [true, `${ALOOK_GITHUB_REPO_URL}/`],
+ [true, `${ALOOK_GITHUB_REPO_URL}/issues`],
+ [true, null],
+ ])("rejects untrusted or non-exact navigation", (isTrusted, href) => {
+ expect(shouldTrackGithubOutboundClick(isTrusted, href)).toBe(false)
+ })
+})
diff --git a/src/web/src/components/github-outbound-link.tsx b/src/web/src/components/github-outbound-link.tsx
new file mode 100644
index 000000000..16c5035ca
--- /dev/null
+++ b/src/web/src/components/github-outbound-link.tsx
@@ -0,0 +1,57 @@
+"use client"
+
+import type { ComponentPropsWithoutRef, MouseEvent, ReactNode } from "react"
+import {
+ trackGithubOutboundClicked,
+ type GithubOutboundSurface,
+} from "@/lib/analytics"
+
+export const ALOOK_GITHUB_REPO_URL = "https://github.com/alookai/alook"
+
+export function shouldTrackGithubOutboundClick(
+ isTrusted: boolean,
+ href: string | null,
+) {
+ return isTrusted && href === ALOOK_GITHUB_REPO_URL
+}
+
+export function GithubOutboundLink({
+ surface,
+ onClick,
+ ...props
+}: Omit<ComponentPropsWithoutRef<"a">, "href"> & {
+ surface: GithubOutboundSurface
+}) {
+ const handleClick = (event: MouseEvent<HTMLAnchorElement>) => {
+ if (shouldTrackGithubOutboundClick(event.isTrusted, event.currentTarget.getAttribute("href"))) {
+ trackGithubOutboundClicked(surface)
+ }
+ onClick?.(event)
+ }
+
+ return (
+ <a
+ {...props}
+ href={ALOOK_GITHUB_REPO_URL}
+ onClick={handleClick}
+ />
+ )
+}
+
+export function GithubOutboundBoundary({
+ surface,
+ children,
+}: {
+ surface: GithubOutboundSurface
+ children: ReactNode
+}) {
+ const handleClickCapture = (event: MouseEvent<HTMLDivElement>) => {
+ const target = event.target
+ const anchor = target instanceof Element ? target.closest("a") : null
+ if (shouldTrackGithubOutboundClick(event.isTrusted, anchor?.getAttribute("href") ?? null)) {
+ trackGithubOutboundClicked(surface)
+ }
+ }
+
+ return <div style={{ display: "contents" }} onClickCapture={handleClickCapture}>{children}</div>
+}
diff --git a/src/web/src/components/home/hero-section.tsx b/src/web/src/components/home/hero-section.tsx
index e8c472186..8c4aa29f3 100644
--- a/src/web/src/components/home/hero-section.tsx
+++ b/src/web/src/components/home/hero-section.tsx
@@ -9,6 +9,7 @@ import { ScrollTrigger } from "gsap/ScrollTrigger";
import { SplitText } from "gsap/SplitText";
import { TypewriterVisual } from "@/components/typewriter-visual";
import { trackLandingCtaClicked } from "@/lib/analytics";
+import { GithubOutboundLink } from "@/components/github-outbound-link";
gsap.registerPlugin(ScrollTrigger, SplitText);
@@ -284,8 +285,8 @@ export function HeroSection({
{/* Community links */}
{showCommunityLinks && <div className="hero-providers mt-4 shrink-0 flex items-center justify-center gap-4" style={{ opacity: 0 }}>
- <a
- href="https://github.com/alookai/alook"
+ <GithubOutboundLink
+ surface="landing"
target="_blank"
rel="noopener noreferrer"
className="flex items-center justify-center p-2 transition-opacity hover:opacity-70"
@@ -295,7 +296,7 @@ export function HeroSection({
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
</svg>
- </a>
+ </GithubOutboundLink>
<a
href="https://discord.alook.ai"
target="_blank"
diff --git a/src/web/src/components/home/landing-content.test.ts b/src/web/src/components/home/landing-content.test.ts
index b40697dfa..65e0e4b75 100644
--- a/src/web/src/components/home/landing-content.test.ts
+++ b/src/web/src/components/home/landing-content.test.ts
@@ -305,7 +305,8 @@ describe("landing content contract", () => {
expect(landingPageSource).toContain('homeHref="/"')
expect(landingPageSource).toContain("highlightActions")
expect(landingPageSource).toContain("FooterSocialLinks")
- expect(landingPageSource).toContain("https://github.com/alookai/alook")
+ expect(landingPageSource).toContain("GithubOutboundLink")
+ expect(landingPageSource).toContain('surface="public_footer"')
expect(landingPageSource).toContain("https://discord.alook.ai")
expect(landingPageSource).toContain("https://x.com/alook_ai")
expect(landingPageSource).toContain("HeroSection")
diff --git a/src/web/src/components/home/landing-page.tsx b/src/web/src/components/home/landing-page.tsx
index be2186ea0..dd887cf47 100644
--- a/src/web/src/components/home/landing-page.tsx
+++ b/src/web/src/components/home/landing-page.tsx
@@ -24,6 +24,7 @@ import {
LANDING_TYPEWRITER_CASES,
} from "./landing-content"
import styles from "./landing-page.module.css"
+import { GithubOutboundLink } from "@/components/github-outbound-link"
function Brand() {
return (
@@ -37,11 +38,11 @@ function Brand() {
function FooterSocialLinks() {
return (
<div className={styles.footerSocials} aria-label="Alook social links">
- <a href="https://github.com/alookai/alook" target="_blank" rel="noopener noreferrer" aria-label="GitHub">
+ <GithubOutboundLink surface="public_footer" target="_blank" rel="noopener noreferrer" aria-label="GitHub">
<svg width="17" height="17" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
</svg>
- </a>
+ </GithubOutboundLink>
<a href="https://discord.alook.ai" target="_blank" rel="noopener noreferrer" aria-label="Discord">
<svg width="17" height="17" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03z" />
diff --git a/src/web/src/components/home/marketing-footer.tsx b/src/web/src/components/home/marketing-footer.tsx
index 0f59eb1a4..996f97118 100644
--- a/src/web/src/components/home/marketing-footer.tsx
+++ b/src/web/src/components/home/marketing-footer.tsx
@@ -6,6 +6,7 @@ import Image from "next/image";
import gsap from "gsap";
import { useGSAP } from "@gsap/react";
import { ScrollTrigger } from "gsap/ScrollTrigger";
+import { GithubOutboundLink } from "@/components/github-outbound-link";
gsap.registerPlugin(ScrollTrigger);
@@ -84,7 +85,18 @@ export function MarketingFooter() {
<nav className="flex items-center gap-4" aria-label="Footer navigation">
{footerLinks.map((link) =>
- link.external || link.href === "/blog" ? (
+ link.href === "https://github.com/alookai/alook" ? (
+ <GithubOutboundLink
+ key={link.label}
+ surface="public_footer"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="transition-opacity hover:opacity-70"
+ style={linkStyle}
+ >
+ {link.label}
+ </GithubOutboundLink>
+ ) : link.external || link.href === "/blog" ? (
<a
key={link.label}
href={link.href}
diff --git a/src/web/src/components/home/marketing-nav.tsx b/src/web/src/components/home/marketing-nav.tsx
index 0ebe9f2cc..49b56096c 100644
--- a/src/web/src/components/home/marketing-nav.tsx
+++ b/src/web/src/components/home/marketing-nav.tsx
@@ -3,6 +3,7 @@
import Image from "next/image";
import Link from "next/link";
import { useEffect, useState } from "react";
+import { GithubOutboundLink } from "@/components/github-outbound-link";
export function MarketingNav({
isLoggedIn,
@@ -84,8 +85,8 @@ export function MarketingNav({
>
Blog
</a>
- <a
- href="https://github.com/alookai/alook"
+ <GithubOutboundLink
+ surface="public_nav"
target="_blank"
rel="noopener noreferrer"
className={`${collapseLinksOnMobile ? "hidden sm:flex" : "flex"} items-center justify-center p-2 transition-opacity duration-150 hover:opacity-70`}
@@ -94,7 +95,7 @@ export function MarketingNav({
<svg width="16" height="16" viewBox="0 0 24 24" fill={highlightActions ? "var(--landing-accent)" : "var(--landing-text)"}>
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
</svg>
- </a>
+ </GithubOutboundLink>
<a
href="https://discord.alook.ai"
target="_blank"
@@ -142,7 +143,7 @@ export function MarketingNav({
>
{showTemplates && <Link href="/templates" className="block px-3 py-2 text-xs uppercase tracking-widest">Templates</Link>}
<a href="/blog" className="block px-3 py-2 text-xs uppercase tracking-widest">Blog</a>
- <a href="https://github.com/alookai/alook" target="_blank" rel="noopener noreferrer" className="block px-3 py-2 text-xs uppercase tracking-widest">GitHub</a>
+ <GithubOutboundLink surface="public_nav" target="_blank" rel="noopener noreferrer" className="block px-3 py-2 text-xs uppercase tracking-widest">GitHub</GithubOutboundLink>
<a href="https://discord.alook.ai" target="_blank" rel="noopener noreferrer" className="block px-3 py-2 text-xs uppercase tracking-widest">Discord</a>
<a href="https://x.com/alook_ai" target="_blank" rel="noopener noreferrer" className="block px-3 py-2 text-xs uppercase tracking-widest">X</a>
</div>
diff --git a/src/web/src/components/public-layout.tsx b/src/web/src/components/public-layout.tsx
index f9dd0e6b0..54e09a415 100644
--- a/src/web/src/components/public-layout.tsx
+++ b/src/web/src/components/public-layout.tsx
@@ -1,6 +1,7 @@
import Link from "next/link";
import Image from "next/image";
import { BRAND_SLOGAN } from "@/lib/brand-copy";
+import { GithubOutboundLink } from "@/components/github-outbound-link";
const footerLinks = [
{ href: "/templates", label: "Templates" },
@@ -129,7 +130,17 @@ export function PublicLayout({
<nav className="flex flex-wrap items-center justify-center gap-x-5 gap-y-2" aria-label="Footer navigation">
{footerLinks.map((link) =>
- link.external ? (
+ link.href === "https://github.com/alookai/alook" ? (
+ <GithubOutboundLink
+ key={link.label}
+ surface="public_footer"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-[11px] uppercase tracking-[0.15em] font-mono text-muted-foreground transition-opacity hover:opacity-70"
+ >
+ {link.label}
+ </GithubOutboundLink>
+ ) : link.external ? (
<a
key={link.label}
href={link.href}
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index aafdef74b..c102397d6 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -45,6 +45,7 @@ import {
createCommunityWsConnectionStatusController,
type CommunityWsConnectionStatusController,
} from "@/hooks/community/community-ws/connection-status"
+import { drainCommunityFunnelEvents } from "@/lib/community/funnel-analytics"
export type {
Subscription,
@@ -118,6 +119,12 @@ function deliveryInboxRefresh(
return inbox ? { inbox: true, dms } : null
}
+function hasCommunityFunnelTrigger(events: readonly CommunityWsEvent[]) {
+ return events.some((event) => event.type === "community:machine.status"
+ || event.type === "community:message.create"
+ || event.type === "community:member.join")
+}
+
function claimInboxRefreshOperation(owner: InboxRefreshOwner, key: string) {
if (owner.claimedOperationKeys.has(key)) return false
owner.claimedOperationKeys.add(key)
@@ -480,6 +487,9 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
decoded.batch.operationId,
decoded.batch.operationDigest,
)
+ if (hasCommunityFunnelTrigger(decoded.events)) {
+ void drainCommunityFunnelEvents()
+ }
return
}
@@ -497,6 +507,9 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
return
}
dispatchCommunityWsEvent(decoded.event, context("single"))
+ if (hasCommunityFunnelTrigger([decoded.event])) {
+ void drainCommunityFunnelEvents()
+ }
},
[queryClient, scheduleInboxInvalidate],
)
diff --git a/src/web/src/lib/analytics.test.ts b/src/web/src/lib/analytics.test.ts
index 2730a0c05..0b5a53e0d 100644
--- a/src/web/src/lib/analytics.test.ts
+++ b/src/web/src/lib/analytics.test.ts
@@ -26,6 +26,12 @@ import {
trackSecondAgentCreated,
trackAgentLinkCreated,
trackRuntimeConnected,
+ trackCommunityRuntimeConnected,
+ trackFirstAgentReplyPersisted,
+ trackHumanInvitationSent,
+ trackHumanInvitationCopied,
+ trackInvitedHumanJoined,
+ trackGithubOutboundClicked,
trackLandingCtaClicked,
trackTemplatesBrowsed,
trackSettingsUpdated,
@@ -218,6 +224,40 @@ describe("analytics utility", () => {
runtime_type: "desktop",
})
})
+
+ it("sends the exact Community funnel payloads", () => {
+ trackCommunityRuntimeConnected()
+ trackFirstAgentReplyPersisted("thread")
+ trackHumanInvitationSent()
+ trackHumanInvitationCopied()
+ trackInvitedHumanJoined()
+
+ expect(mockSendGTMEvent.mock.calls).toEqual([
+ [{ event: "runtime_connected", surface: "community", connection_type: "local_daemon" }],
+ [{ event: "first_agent_reply_persisted", surface: "community", conversation_type: "thread" }],
+ [{ event: "human_invitation_sent", surface: "community", invite_method: "dm" }],
+ [{ event: "human_invitation_copied", surface: "community", invite_method: "link_copy" }],
+ [{ event: "invited_human_joined", surface: "community" }],
+ ])
+ })
+
+ it("fails open when the tag manager rejects a Community funnel event", () => {
+ mockSendGTMEvent.mockImplementationOnce(() => {
+ throw new Error("tag manager unavailable")
+ })
+
+ expect(() => trackCommunityRuntimeConnected()).not.toThrow()
+ })
+
+ it("sends the exact GitHub outbound payload without URL or identifiers", () => {
+ trackGithubOutboundClicked("public_nav")
+
+ expect(mockSendGTMEvent).toHaveBeenCalledWith({
+ event: "github_outbound_clicked",
+ surface: "public_nav",
+ destination: "alook_repo",
+ })
+ })
})
describe("P3 — Page-Level Behavior", () => {
diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.ts
index 5415d7f13..875839bff 100644
--- a/src/web/src/lib/analytics.ts
+++ b/src/web/src/lib/analytics.ts
@@ -53,6 +53,14 @@ function sendCommercialEvent(payload: Record<string, unknown>) {
}
}
+function sendFunnelEvent(payload: Record<string, unknown>) {
+ try {
+ sendGTMEvent(payload)
+ } catch {
+ return
+ }
+}
+
export function trackPricingView(params: {
auth_state: AnalyticsAuthState
current_plan: AnalyticsCurrentPlan
@@ -210,6 +218,54 @@ export function trackRuntimeConnected(params: {
sendGTMEvent({ event: "runtime_connected", ...params });
}
+export type GithubOutboundSurface = "landing" | "blog" | "public_nav" | "public_footer"
+
+export function trackCommunityRuntimeConnected() {
+ sendFunnelEvent({
+ event: "runtime_connected",
+ surface: "community",
+ connection_type: "local_daemon",
+ })
+}
+
+export function trackFirstAgentReplyPersisted(
+ conversationType: "dm" | "channel" | "thread",
+) {
+ sendFunnelEvent({
+ event: "first_agent_reply_persisted",
+ surface: "community",
+ conversation_type: conversationType,
+ })
+}
+
+export function trackHumanInvitationSent() {
+ sendFunnelEvent({
+ event: "human_invitation_sent",
+ surface: "community",
+ invite_method: "dm",
+ })
+}
+
+export function trackHumanInvitationCopied() {
+ sendFunnelEvent({
+ event: "human_invitation_copied",
+ surface: "community",
+ invite_method: "link_copy",
+ })
+}
+
+export function trackInvitedHumanJoined() {
+ sendFunnelEvent({ event: "invited_human_joined", surface: "community" })
+}
+
+export function trackGithubOutboundClicked(surface: GithubOutboundSurface) {
+ sendFunnelEvent({
+ event: "github_outbound_clicked",
+ surface,
+ destination: "alook_repo",
+ })
+}
+
export type CommunityOnboardingStage =
| "harness"
| "machine"
diff --git a/src/web/src/lib/community/funnel-analytics.test.ts b/src/web/src/lib/community/funnel-analytics.test.ts
new file mode 100644
index 000000000..c79abf41f
--- /dev/null
+++ b/src/web/src/lib/community/funnel-analytics.test.ts
@@ -0,0 +1,86 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ runtime: vi.fn(),
+ reply: vi.fn(),
+ joined: vi.fn(),
+}))
+
+vi.mock("@/lib/analytics", () => ({
+ trackCommunityRuntimeConnected: mocks.runtime,
+ trackFirstAgentReplyPersisted: mocks.reply,
+ trackInvitedHumanJoined: mocks.joined,
+}))
+
+import {
+ _resetCommunityFunnelAnalyticsForTesting,
+ decodeCommunityFunnelEvents,
+ drainCommunityFunnelEvents,
+} from "./funnel-analytics"
+
+function response(payload: unknown, ok = true) {
+ return { ok, json: vi.fn().mockResolvedValue(payload) } as unknown as Response
+}
+
+describe("Community funnel analytics drain", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ _resetCommunityFunnelAnalyticsForTesting()
+ })
+
+ it("accepts only exact low-cardinality event shapes", () => {
+ expect(decodeCommunityFunnelEvents({ events: [
+ { event: "runtime_connected", surface: "community", connection_type: "local_daemon" },
+ { event: "first_agent_reply_persisted", surface: "community", conversation_type: "dm" },
+ { event: "invited_human_joined", surface: "community" },
+ { event: "runtime_connected", surface: "community", connection_type: "local_daemon", machineId: "secret" },
+ { event: "first_agent_reply_persisted", surface: "community", conversation_type: "group" },
+ { event: "unknown", surface: "community" },
+ ] })).toEqual([
+ { event: "runtime_connected", surface: "community", connection_type: "local_daemon" },
+ { event: "first_agent_reply_persisted", surface: "community", conversation_type: "dm" },
+ { event: "invited_human_joined", surface: "community" },
+ ])
+ })
+
+ it("publishes exact events and coalesces a trigger arriving in flight", async () => {
+ let resolveFirst!: (value: Response) => void
+ const first = new Promise<Response>((resolve) => { resolveFirst = resolve })
+ const fetchMock = vi.fn()
+ .mockReturnValueOnce(first)
+ .mockResolvedValueOnce(response({ events: [
+ { event: "invited_human_joined", surface: "community" },
+ ] }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ const initial = drainCommunityFunnelEvents()
+ const coalesced = drainCommunityFunnelEvents()
+ expect(coalesced).toBe(initial)
+ resolveFirst(response({ events: [
+ { event: "runtime_connected", surface: "community", connection_type: "local_daemon" },
+ { event: "first_agent_reply_persisted", surface: "community", conversation_type: "thread" },
+ ] }))
+ await initial
+
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(fetchMock).toHaveBeenNthCalledWith(1, "/api/community/analytics/funnel-events", {
+ method: "POST",
+ cache: "no-store",
+ credentials: "same-origin",
+ })
+ expect(mocks.runtime).toHaveBeenCalledOnce()
+ expect(mocks.reply).toHaveBeenCalledWith("thread")
+ expect(mocks.joined).toHaveBeenCalledOnce()
+ })
+
+ it("fails open on fetch errors and non-success responses", async () => {
+ const fetchMock = vi.fn()
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockResolvedValueOnce(response({ events: [] }, false))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(drainCommunityFunnelEvents()).resolves.toBeUndefined()
+ await expect(drainCommunityFunnelEvents()).resolves.toBeUndefined()
+ expect(mocks.runtime).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/lib/community/funnel-analytics.ts b/src/web/src/lib/community/funnel-analytics.ts
new file mode 100644
index 000000000..c945db46b
--- /dev/null
+++ b/src/web/src/lib/community/funnel-analytics.ts
@@ -0,0 +1,106 @@
+"use client"
+
+import type { CommunityFunnelAnalyticsEvent } from "@alook/shared"
+import {
+ trackCommunityRuntimeConnected,
+ trackFirstAgentReplyPersisted,
+ trackInvitedHumanJoined,
+} from "@/lib/analytics"
+
+let inFlight: Promise<void> | null = null
+let rerun = false
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value)
+}
+
+function hasOnlyKeys(value: Record<string, unknown>, keys: readonly string[]) {
+ const allowed = new Set(keys)
+ return Object.keys(value).every((key) => allowed.has(key))
+}
+
+export function decodeCommunityFunnelEvents(value: unknown): CommunityFunnelAnalyticsEvent[] {
+ if (!isRecord(value) || !Array.isArray(value.events)) return []
+ return value.events.flatMap<CommunityFunnelAnalyticsEvent>((candidate) => {
+ if (!isRecord(candidate) || candidate.surface !== "community") return []
+ if (
+ candidate.event === "runtime_connected"
+ && candidate.connection_type === "local_daemon"
+ && hasOnlyKeys(candidate, ["event", "surface", "connection_type"])
+ ) {
+ return [{
+ event: "runtime_connected",
+ surface: "community",
+ connection_type: "local_daemon",
+ }]
+ }
+ if (
+ candidate.event === "first_agent_reply_persisted"
+ && (candidate.conversation_type === "dm"
+ || candidate.conversation_type === "channel"
+ || candidate.conversation_type === "thread")
+ && hasOnlyKeys(candidate, ["event", "surface", "conversation_type"])
+ ) {
+ return [{
+ event: "first_agent_reply_persisted",
+ surface: "community",
+ conversation_type: candidate.conversation_type,
+ }]
+ }
+ if (
+ candidate.event === "invited_human_joined"
+ && hasOnlyKeys(candidate, ["event", "surface"])
+ ) {
+ return [{ event: "invited_human_joined", surface: "community" }]
+ }
+ return []
+ })
+}
+
+function publishCommunityFunnelEvent(event: CommunityFunnelAnalyticsEvent) {
+ if (event.event === "runtime_connected") {
+ trackCommunityRuntimeConnected()
+ } else if (event.event === "first_agent_reply_persisted") {
+ trackFirstAgentReplyPersisted(event.conversation_type)
+ } else {
+ trackInvitedHumanJoined()
+ }
+}
+
+async function drainOnce() {
+ const response = await fetch("/api/community/analytics/funnel-events", {
+ method: "POST",
+ cache: "no-store",
+ credentials: "same-origin",
+ })
+ if (!response.ok) return
+ const payload: unknown = await response.json()
+ for (const event of decodeCommunityFunnelEvents(payload)) {
+ publishCommunityFunnelEvent(event)
+ }
+}
+
+export function drainCommunityFunnelEvents(): Promise<void> {
+ if (inFlight) {
+ rerun = true
+ return inFlight
+ }
+ inFlight = (async () => {
+ do {
+ rerun = false
+ try {
+ await drainOnce()
+ } catch {
+ return
+ }
+ } while (rerun)
+ })().finally(() => {
+ inFlight = null
+ })
+ return inFlight
+}
+
+export function _resetCommunityFunnelAnalyticsForTesting() {
+ inFlight = null
+ rerun = false
+}
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index c97fd16f5..3205587f0 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -17,6 +17,8 @@ const mockIsChannelPrivate = vi.fn(() => false)
const mockGetPrivateChannelAudienceUserIds = vi.fn(() => [] as string[])
const mockCreateChannelMember = vi.fn()
const mockAddThreadParticipants = vi.fn()
+const firstAgentReplyStatement = { kind: "first-agent-reply-statement" }
+const mockRecordFirstAgentReplyPersistedStatement = vi.fn(() => firstAgentReplyStatement)
const mockLogError = vi.fn()
const mockLogWarn = vi.fn()
@@ -63,6 +65,9 @@ vi.mock("@alook/shared", async () => {
user: {
getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),
},
+ communityFunnelAnalytics: {
+ recordFirstAgentReplyPersistedStatement: (...a: unknown[]) => mockRecordFirstAgentReplyPersistedStatement(...a),
+ },
},
}
})
@@ -1032,3 +1037,92 @@ describe("post-commit notification registration", () => {
expect(mockFanOutToChannel).not.toHaveBeenCalled()
})
})
+
+describe("first Agent reply funnel boundary", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockCreateMessage.mockResolvedValue({ id: "msg_1" })
+ mockGetUserInternal.mockResolvedValue({ id: "bot_1", isBot: true, deletedAt: null })
+ mockGetMessage.mockResolvedValue(messageRow({ authorId: "bot_1" }))
+ mockListByMessageIds.mockResolvedValue([])
+ })
+
+ it.each([
+ [{ kind: "dm", channelId: "dm_1", otherUserId: "human_1" }, "dm"],
+ [{ kind: "channel", channelId: "channel_1", serverId: "server_1" }, "channel"],
+ [{ kind: "thread", channelId: "thread_1", parentChannelId: "forum_1", serverId: "server_1" }, "thread"],
+ [{ kind: "forum", channelId: "forum_1", serverId: "server_1" }, "thread"],
+ ] as const)("records a fresh CLI reply for %s", async (target, conversationType) => {
+ await expect(createCommunityMessage({
+ db: {} as never,
+ authorId: "bot_1",
+ authorKind: "bot",
+ target,
+ body: { content: "reply" },
+ source: "cli",
+ })).resolves.toMatchObject({ ok: true })
+
+ expect(mockRecordFirstAgentReplyPersistedStatement).toHaveBeenCalledWith({}, {
+ botUserId: "bot_1",
+ messageId: expect.any(String),
+ conversationType,
+ })
+ const input = mockCreateMessage.mock.calls[0]![1]
+ expect(input.id).toBe(mockRecordFirstAgentReplyPersistedStatement.mock.calls[0]![1].messageId)
+ expect(input.extraStatements).toContain(firstAgentReplyStatement)
+ })
+
+ it.each([
+ { authorKind: "human" as const, source: "web" as const },
+ { authorKind: "bot" as const, source: "web" as const },
+ { authorKind: "bot" as const, source: "cli" as const, messageType: "system" },
+ ])("does not record non-qualifying messages", async (input) => {
+ await createCommunityMessage({
+ db: {} as never,
+ authorId: "bot_1",
+ target: { kind: "channel", channelId: "channel_1", serverId: "server_1" },
+ body: { content: "message" },
+ ...input,
+ })
+
+ expect(mockRecordFirstAgentReplyPersistedStatement).not.toHaveBeenCalled()
+ })
+
+ it("commits the ledger statement with the message even when response read-back fails", async () => {
+ mockGetMessage.mockResolvedValueOnce(null)
+
+ await expect(createCommunityMessage({
+ db: {} as never,
+ authorId: "bot_1",
+ authorKind: "bot",
+ target: { kind: "channel", channelId: "channel_1", serverId: "server_1" },
+ body: { content: "reply" },
+ source: "daemon-http",
+ })).rejects.toThrow("message not found after insert")
+
+ expect(mockRecordFirstAgentReplyPersistedStatement).toHaveBeenCalledOnce()
+ expect(mockCreateMessage.mock.calls[0]![1].extraStatements).toContain(firstAgentReplyStatement)
+ expect(mockDispatchCommittedMessage).toHaveBeenCalledOnce()
+ })
+
+ it("does not record a same-nonce replay", async () => {
+ mockGetMessageByAuthorAndNonce.mockResolvedValueOnce(messageRow({
+ id: "msg_replay",
+ authorId: "bot_1",
+ clientNonce: "nonce",
+ }))
+
+ await expect(createCommunityMessage({
+ db: {} as never,
+ authorId: "bot_1",
+ authorKind: "bot",
+ target: { kind: "channel", channelId: "c1", serverId: "server_1" },
+ body: { content: "reply" },
+ source: "cli",
+ clientNonce: "nonce",
+ })).resolves.toMatchObject({ ok: true, deduped: true })
+
+ expect(mockCreateMessage).not.toHaveBeenCalled()
+ expect(mockRecordFirstAgentReplyPersistedStatement).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index 720ce3a35..6f7fba051 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -14,6 +14,7 @@ import {
} from "@alook/shared"
import type { MentionType } from "@alook/shared"
import type { Database } from "@alook/shared"
+import { nanoid } from "nanoid"
import { dispatchCommittedMessage } from "./message-dispatcher"
import { attachmentThumbnailUrl, attachmentUrl } from "./storage"
import { broadcastToUserSafe, fanOutToChannel } from "./fanout"
@@ -489,7 +490,24 @@ export async function createCommunityMessage(params: {
participants = rows
}
+ const qualifiesForFirstAgentReply = authorKind === "bot"
+ && (source === "cli" || source === "daemon-http")
+ && (messageType ?? "default") === "default"
+ const messageId = qualifiesForFirstAgentReply ? nanoid() : undefined
+ const conversationType = target.kind === "dm"
+ ? "dm"
+ : target.kind === "thread" || target.kind === "forum"
+ ? "thread"
+ : "channel"
+ const funnelStatements = qualifiesForFirstAgentReply && messageId
+ ? [queries.communityFunnelAnalytics.recordFirstAgentReplyPersistedStatement(db, {
+ botUserId: authorId,
+ messageId,
+ conversationType,
+ })]
+ : []
const baseMessageData: Omit<Parameters<typeof queries.communityMessage.createMessage>[1], "expectedSeq"> = {
+ ...(messageId ? { id: messageId } : {}),
authorId,
authorKind,
content,
@@ -498,7 +516,9 @@ export async function createCommunityMessage(params: {
mentionType,
type: messageType,
clientNonce,
- extraStatements,
+ ...(extraStatements?.length || funnelStatements.length
+ ? { extraStatements: [...(extraStatements ?? []), ...funnelStatements] }
+ : {}),
attachmentIds,
participants,
mentions: [