Skip to content

Commit c357965

Browse files
author
ben
authored
fix(automations): page shared Automations and send sharedAt as a date-time (#7547)
GET /v1/shared-automations added two API style warnings, which pushed the Spectral count past its baseline and failed API Contract on dev. The list now accepts cursor and limit (default and maximum 200, the previous cap) and returns nextCursor, with keyset paging on (sharedAt desc, id desc). The cursor time is bound with the share column's UTC encoding because the aggregate has no column of its own. sharedAt is now an RFC 3339 string instead of epoch milliseconds; no client reads it.
1 parent 4aab349 commit c357965

6 files changed

Lines changed: 61 additions & 20 deletions

File tree

‎apps/app/tests/automation-sharing.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ function shared(id: string, name: string, executionTarget: "cloud" | "desktop" =
6363
return {
6464
id, name, executionTarget,
6565
sharedBy: { memberId: "member_owner", name: "Owner" },
66-
sharedAt: 100,
66+
sharedAt: "2026-11-18T20:00:00.000Z",
6767
schedule: { kind: "daily", hour: 9, minute: 0, timezone: "UTC" },
6868
action: { kind: "agent", instructions: "Summarize recent activity", model: { providerId: "test", modelId: "test", variant: null } },
6969
}

‎ee/apps/den-api/src/automations/service.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ export class AutomationService {
374374
}
375375

376376
async copyShared(scope: OwnerScope, id: string, options: CopySharedAutomation) {
377-
const [source] = (await listSharedAutomations(scope, id)).items
377+
const [source] = (await listSharedAutomations(scope, { automationId: id, limit: 1 })).items
378378
if (!source) throw new Error("automation_not_found")
379379
const action = source.action.kind === "agent" && options.model
380380
? { ...source.action, model: options.model } : source.action

‎ee/apps/den-api/src/automations/sharing.ts‎

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
import { and, desc, eq, inArray, isNotNull, ne, or, sql } from "@openwork-ee/den-db/drizzle"
1+
import { and, desc, eq, inArray, isNotNull, lt, ne, or, sql } from "@openwork-ee/den-db/drizzle"
22
import { AuthUserTable, AutomationRevisionTable, AutomationShareTable, AutomationTable, MemberTable, TeamTable } from "@openwork-ee/den-db/schema"
33
import { createDenTypeId, isDenTypeId, normalizeDenTypeId } from "@openwork-ee/utils/typeid"
44
import type { AutomationSharing, SharedAutomation } from "@openwork/types/automations"
55
import { db } from "../db.js"
66
import { listTeamsForMember } from "../member-teams.js"
77
import { withPrimaryReads } from "../read-routing.js"
88
import { peopleMemberCondition } from "../setup-agent-members.js"
9+
import { keysetPage, type KeysetCursor } from "../list-pagination.js"
910

1011
type Scope = { organizationId: string; ownerMemberId: string }
1112
const identities = (scope: Scope) => ({
@@ -80,18 +81,31 @@ export async function replaceAutomationSharing(scope: Scope, id: string, request
8081
})
8182
}
8283

83-
/** Definition-only read: never reconciles or loads the source's runs or results. */
84-
export function listSharedAutomations(scope: Scope, automationId?: string): Promise<{ items: SharedAutomation[] }> {
85-
return withPrimaryReads(() => readSharedAutomations(scope, automationId))
84+
export const SHARED_AUTOMATION_PAGE_MAX = 200
85+
86+
type SharedAutomationQuery = { automationId?: string; cursor?: KeysetCursor; limit?: number }
87+
88+
/** Definition-only read: never reconciles or loads the source's runs or results. Newest share first. */
89+
export function listSharedAutomations(scope: Scope, query: SharedAutomationQuery = {}): Promise<{ items: SharedAutomation[]; nextCursor: string | null }> {
90+
return withPrimaryReads(() => readSharedAutomations(scope, query))
8691
}
8792

88-
async function readSharedAutomations(scope: Scope, automationId?: string): Promise<{ items: SharedAutomation[] }> {
93+
async function readSharedAutomations(scope: Scope, query: SharedAutomationQuery): Promise<{ items: SharedAutomation[]; nextCursor: string | null }> {
8994
const caller = identities(scope)
90-
if (automationId && !isDenTypeId("automation", automationId)) return { items: [] }
95+
const { automationId, cursor } = query
96+
const limit = query.limit ?? SHARED_AUTOMATION_PAGE_MAX
97+
if (automationId && !isDenTypeId("automation", automationId)) return { items: [], nextCursor: null }
98+
if (cursor && !isDenTypeId("automation", cursor.id)) return { items: [], nextCursor: null }
9199
const teams = await listTeamsForMember(caller)
100+
// The cursor time is bound with the share column's own encoding (UTC), as
101+
// the aggregate has no column to encode it.
102+
const afterCursor = (sharedAt: typeof grants.sharedAt, after: KeysetCursor) => {
103+
const at = sql.param(after.at, AutomationShareTable.created_at)
104+
return or(lt(sharedAt, at), and(eq(sharedAt, at), lt(AutomationTable.id, normalizeDenTypeId("automation", after.id))))
105+
}
92106
const grants = db.select({
93107
automationId: AutomationShareTable.automation_id,
94-
sharedAt: sql<number>`unix_timestamp(min(${AutomationShareTable.created_at})) * 1000`.mapWith(Number).as("shared_at"),
108+
sharedAt: sql<Date>`min(${AutomationShareTable.created_at})`.mapWith(AutomationShareTable.created_at).as("shared_at"),
95109
}).from(AutomationShareTable).where(and(eq(AutomationShareTable.organization_id, caller.organizationId), or(
96110
eq(AutomationShareTable.org_wide, true), eq(AutomationShareTable.org_membership_id, caller.memberId),
97111
teams.length ? inArray(AutomationShareTable.team_id, teams.map((team) => team.id)) : undefined,
@@ -109,11 +123,13 @@ async function readSharedAutomations(scope: Scope, automationId?: string): Promi
109123
.innerJoin(AuthUserTable, eq(AuthUserTable.id, MemberTable.userId))
110124
.where(and(eq(AutomationTable.organization_id, caller.organizationId), ne(AutomationTable.owner_member_id, caller.memberId),
111125
ne(AutomationTable.state, "archived"), peopleMemberCondition(),
112-
automationId ? eq(AutomationTable.id, normalizeDenTypeId("automation", automationId)) : undefined))
113-
.orderBy(desc(grants.sharedAt), desc(AutomationTable.id)).limit(200)
114-
return { items: rows.map((row) => ({
126+
automationId ? eq(AutomationTable.id, normalizeDenTypeId("automation", automationId)) : undefined,
127+
cursor ? afterCursor(grants.sharedAt, cursor) : undefined))
128+
.orderBy(desc(grants.sharedAt), desc(AutomationTable.id)).limit(limit + 1)
129+
const page = keysetPage(rows, limit, (row) => ({ at: row.sharedAt, id: row.id }))
130+
return { nextCursor: page.nextCursor, items: page.items.map((row) => ({
115131
id: row.id, name: row.name, sharedBy: { memberId: row.memberId, name: row.ownerName },
116-
sharedAt: row.sharedAt, schedule: row.schedule, executionTarget: row.executionTarget,
132+
sharedAt: row.sharedAt.toISOString(), schedule: row.schedule, executionTarget: row.executionTarget,
117133
action: row.action ?? { kind: "agent", instructions: row.instructions, model: { providerId: row.providerId, modelId: row.modelId, variant: row.variant } },
118134
})) }
119135
}

‎ee/apps/den-api/src/routes/automations/index.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ import type { AuthContextVariables } from "../../session.js"
4141
import { invalidRequestSchema, jsonResponse, notFoundSchema, unauthorizedSchema } from "../../openapi.js"
4242
import { requireFeature } from "../../features.js"
4343
import { hasPermission } from "../org/shared.js"
44-
import { getAutomationSharing, replaceAutomationSharing, listSharedAutomations } from "../../automations/sharing.js"
44+
import { getAutomationSharing, replaceAutomationSharing, listSharedAutomations, SHARED_AUTOMATION_PAGE_MAX } from "../../automations/sharing.js"
45+
import { keysetCursorQuerySchema } from "../../list-pagination.js"
4546
import { automationService, type AutomationService } from "../../automations/service.js"
4647
import { addAuditRequestResource } from "../../audit/request-capture.js"
4748
import { registerSessionRunnerRoutes } from "../session-runners/index.js"
@@ -168,6 +169,11 @@ const routeDescription = [
168169
"Deactivation stops future runs but does not cancel a run already in progress.",
169170
].join(" ")
170171

172+
const listSharedAutomationsQuerySchema = z.object({
173+
cursor: keysetCursorQuerySchema.optional(),
174+
limit: z.coerce.number().int().min(1).max(SHARED_AUTOMATION_PAGE_MAX).default(SHARED_AUTOMATION_PAGE_MAX),
175+
})
176+
171177
export function registerAutomationRoutes<T extends { Variables: RouteVariables }>(
172178
app: Hono<T>,
173179
options: {
@@ -241,11 +247,15 @@ export function registerAutomationRoutes<T extends { Variables: RouteVariables }
241247
describeMcpRoute({
242248
tags: ["Automations"], operationId: "listSharedAutomations", "x-mcp": true,
243249
summary: "List Automation definitions shared with you",
244-
description: "Returns up to 200 shared definitions, newest share first. No runs or results are exposed. To use one, add your own paused copy and review it before activating; copies use your own connections and models.",
245-
responses: { 200: jsonResponse("Shared definitions.", sharedAutomationListSchema), 404: jsonResponse("Sharing disabled.", notFoundSchema) },
250+
description: "Returns shared definitions, newest share first. Pass nextCursor from the previous page as cursor to continue; nextCursor is null on the last page. No runs or results are exposed. To use one, add your own paused copy and review it before activating; copies use your own connections and models.",
251+
responses: {
252+
200: jsonResponse("Shared definitions.", sharedAutomationListSchema),
253+
400: jsonResponse("Invalid cursor or limit.", invalidRequestSchema),
254+
404: jsonResponse("Sharing disabled.", notFoundSchema),
255+
},
246256
}),
247-
orgMemberRoute(), requireFeature("automationSharing"),
248-
async (c) => c.json(await listSharedAutomations(scope(c))),
257+
orgMemberRoute(), requireFeature("automationSharing"), queryValidator(listSharedAutomationsQuerySchema),
258+
async (c) => c.json(await listSharedAutomations(scope(c), c.req.valid("query"))),
249259
)
250260
app.post(
251261
"/v1/shared-automations/:id/copy",

‎ee/apps/den-api/test/api/automation-sharing.api.test.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ test("sharing definitions isolates owners, audiences, copies and lifecycle clean
5959
assert.ok(item)
6060
assert.equal(item.id, id)
6161
assert.equal(item.sharedBy.memberId, creator.memberId)
62-
assert.ok(item.sharedAt > 0)
62+
assert.ok(Date.parse(item.sharedAt) > 0)
6363
assert.deepEqual(Object.keys(list(field(listed.body, "items"))[0] ?? {}).sort(), ["id", "name", "sharedBy", "sharedAt", "schedule", "executionTarget", "action"].sort())
6464
assert.deepEqual(field(status(await other("GET", "/v1/shared-automations"), 200).body, "items"), [])
6565
assert.deepEqual(field(status(await create("GET", "/v1/shared-automations"), 200).body, "items"), [])
@@ -112,6 +112,20 @@ test("sharing definitions isolates owners, audiences, copies and lifecycle clean
112112
assert.equal(list(field(status(await caller("GET", "/v1/shared-automations"), 200).body, "items")).some((row) => row.id === adminId), true)
113113
}
114114
assert.deepEqual(field(status(await admin("GET", "/v1/shared-automations"), 200).body, "items"), [])
115+
status(await create("PUT", `/v1/automations/${id}/sharing`, { memberIds: [recipient.memberId] }), 200)
116+
const everyShare = sharedAutomationListSchema.parse(status(await receive("GET", "/v1/shared-automations"), 200).body)
117+
assert.equal(everyShare.nextCursor, null)
118+
assert.deepEqual(new Set(everyShare.items.map((row) => row.id)), new Set([id, adminId]))
119+
const firstPage = sharedAutomationListSchema.parse(status(await receive("GET", "/v1/shared-automations?limit=1"), 200).body)
120+
assert.deepEqual(firstPage.items.map((row) => row.id), [everyShare.items[0]?.id])
121+
assert.ok(firstPage.nextCursor)
122+
const lastPage = sharedAutomationListSchema.parse(status(await receive("GET", `/v1/shared-automations?limit=1&cursor=${firstPage.nextCursor}`), 200).body)
123+
assert.deepEqual(lastPage.items.map((row) => row.id), [everyShare.items[1]?.id])
124+
assert.equal(lastPage.nextCursor, null)
125+
error(await receive("GET", "/v1/shared-automations?cursor=not-a-cursor"), 400, "invalid_request")
126+
const foreignIdCursor = Buffer.from(JSON.stringify({ at: 1, id: "not-an-automation" })).toString("base64url")
127+
assert.deepEqual(status(await receive("GET", `/v1/shared-automations?cursor=${foreignIdCursor}`), 200).body, { items: [], nextCursor: null })
128+
status(await create("PUT", `/v1/automations/${id}/sharing`, {}), 200)
115129
status(await admin("DELETE", `/v1/automations/${adminId}`), 200)
116130
assert.deepEqual(field(status(await receive("GET", "/v1/shared-automations"), 200).body, "items"), [])
117131
error(await admin("PUT", `/v1/automations/${adminId}/sharing`, {}), 404, "automation_not_found")

‎packages/types/src/automations.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1202,7 +1202,7 @@ export const sharedAutomationSchema = z.object({
12021202
id: z.string(),
12031203
name: z.string(),
12041204
sharedBy: z.object({ memberId: z.string(), name: z.string() }),
1205-
sharedAt: z.number(),
1205+
sharedAt: z.string().datetime(),
12061206
schedule: automationScheduleSchema,
12071207
executionTarget: automationExecutionTargetSchema,
12081208
action: automationActionSchema,
@@ -1211,6 +1211,7 @@ export type SharedAutomation = z.infer<typeof sharedAutomationSchema>
12111211

12121212
export const sharedAutomationListSchema = z.object({
12131213
items: z.array(sharedAutomationSchema),
1214+
nextCursor: z.string().nullable(),
12141215
}).meta({ ref: "SharedAutomationList" })
12151216
export type SharedAutomationList = z.infer<typeof sharedAutomationListSchema>
12161217

0 commit comments

Comments
 (0)