Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/app/public/styles.css

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions packages/app/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export class ApiService {
listGitHubInstallations() { return this.call("flows:read", "/github/installations"); }
listTailIntegrations() { return this.call("flows:read", "/connections/cloudflare-tail"); }
listRuns(query: URLSearchParams) { return this.call("runs:read", `/v1/runs?${query}`); }
search(query: string) { return this.call("runs:read", `/v1/search?q=${encodeURIComponent(query)}`); }
getRun(runId: string) { return this.call("runs:read", `/v1/runs/${encodeURIComponent(runId)}`); }
stopRun(runId: string) { return this.call("runs:write", `/v1/runs/${encodeURIComponent(runId)}/stop`, { method: "POST" }); }
async listJobs() { return (await this.call("flows:read", "/v1/jobs") as any[]).map(value => this.publicJob(value)); }
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP
if (jobMatch && request.method === "PUT") return Response.json(await service.updateJob(decodeURIComponent(jobMatch[1]), jobInputSchema.parse(await request.json())));
if (jobMatch && request.method === "DELETE") return Response.json(await service.deleteJob(decodeURIComponent(jobMatch[1])));
if (request.method === "GET" && path === "/api/v1/runs") { const q = listRunsSchema.parse(queryInput(url)); return Response.json(await service.listRuns(queryOf(q))); }
if (request.method === "GET" && path === "/api/v1/search") return Response.json(await service.search(url.searchParams.get("q") ?? ""));
if (request.method === "GET" && path === "/api/v1/webhooks/deliveries") return Response.json(await service.listWebhookDeliveries(url.searchParams));
const webhookDeliveryMatch = path.match(/^\/api\/v1\/webhooks\/deliveries\/([^/]+)$/);
if (webhookDeliveryMatch && request.method === "GET") return Response.json(await service.getWebhookDelivery(decodeURIComponent(webhookDeliveryMatch[1])));
Expand Down
27 changes: 27 additions & 0 deletions packages/app/src/search.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
export type SearchMatch = { start: number; end: number };

/** Match a query as an ordered sequence of terms, ignoring punctuation and case. */
export function searchMatches(value: string, query: string): SearchMatch[] {
const needle = query.normalize().toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu, "");
if (!needle) return [];
const positions: number[] = [];
let cursor = 0;
for (const character of needle) {
let found = -1;
for (let index = cursor; index < value.length; index++) {
if (value[index]!.normalize().toLocaleLowerCase() === character) { found = index; break; }
}
if (found < 0) return [];
positions.push(found);
cursor = found + 1;
}
const ranges: SearchMatch[] = [];
for (const position of positions) {
const previous = ranges.at(-1);
if (previous && previous.end === position) previous.end++;
else ranges.push({ start: position, end: position + 1 });
}
return ranges;
}

export function matchesSearch(value: string, query: string): boolean { return searchMatches(value, query).length > 0; }
29 changes: 29 additions & 0 deletions packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { adaptWebhook, publicWebhookConfig, validateWebhookHandler, type Webhook
import { reflectTriggerContext } from "./trigger-context";
import { installedTriggerAvailability, sameProviderReference } from "./trigger-availability";
import { clickUpJson, matchingClickUpTask } from "./clickup";
import { matchesSearch } from "./search";

export { DEFAULT_CONTEXT_TEMPLATE, linearTicketPrompt, renderContextTemplate } from "./linear-source";

Expand Down Expand Up @@ -201,6 +202,7 @@ export class TenantV2 extends DurableObject<Env> {
const url = new URL(request.url);
try {
if (request.method === "GET" && url.pathname === "/v1/runs") return this.listRuns(url);
if (request.method === "GET" && url.pathname === "/v1/search") return this.search(url.searchParams.get("q") ?? "");
if (request.method === "GET" && url.pathname === "/v1/webhooks/deliveries") return this.listWebhookDeliveries(url);
const webhookDeliveryMatch = url.pathname.match(/^\/v1\/webhooks\/deliveries\/([^/]+)$/);
if (request.method === "GET" && webhookDeliveryMatch) return this.getWebhookDelivery(decodeURIComponent(webhookDeliveryMatch[1]));
Expand Down Expand Up @@ -1008,6 +1010,33 @@ export class TenantV2 extends DurableObject<Env> {
return json({ items, nextCursor: hasMore ? this.nextCursor(items.at(-1), "created_at") : null });
}

private search(query: string): Response {
const needle = query.trim();
if (!needle) return json({ items: [] });
const items: Array<Record<string, unknown>> = [];
const add = (kind: string, id: unknown, title: unknown, subtitle: unknown, url: string, haystack: unknown[]) => {
const searchable = haystack.map(value => String(value ?? "")).join("\n");
if (matchesSearch(searchable, needle)) items.push({ kind, id: String(id), title: String(title || id), subtitle: String(subtitle || ""), url });
};
for (const job of this.rows("SELECT id,name,slug,execution_target,enabled,created_at,updated_at FROM jobs ORDER BY created_at DESC")) {
add("job", job.id, job.name, `${job.slug} · ${job.enabled ? "Enabled" : "Disabled"}`, `/jobs/${encodeURIComponent(String(job.id))}`, Object.values(job));
for (const trigger of this.rows("SELECT id,slug,kind,config,enabled,created_at,updated_at FROM triggers WHERE job_id=? ORDER BY position,created_at,id", job.id)) {
add("trigger", trigger.id, `${job.name} · ${trigger.slug}`, `${trigger.kind} trigger`, `/jobs/${encodeURIComponent(String(job.id))}/edit`, Object.values(trigger).concat(Object.values(job)));
}
}
for (const run of this.rows(`SELECT r.id,r.pipe_id,r.issue_id,r.issue_title,r.run_name,r.agent_name,r.workspace_name,r.agent_kind,r.state,r.provider,r.execution_backend_kind,r.execution_handle,r.execution_capabilities,r.destination_url,r.created_at,r.updated_at,r.herdr_server_namespace,r.worktree_path,r.ownership_lease,r.herdr_workspace_id,r.herdr_pane_id,r.herdr_terminal_id,r.agent_session_source,r.agent_session_kind,r.agent_session_value,r.herdr_cwd,r.last_agent_status,r.recovery_reason,r.recovery_last_action FROM runs r ORDER BY r.created_at DESC LIMIT 1000`)) {
const title = String(run.run_name || run.issue_title || `Run ${String(run.id).slice(0, 8)}`);
add("run", run.id, title, `${run.state} · ${run.agent_name || run.agent_kind || run.provider || "run"}`, `/job-runs/${encodeURIComponent(String(run.id))}`, Object.values(run));
}
for (const event of this.rows("SELECT id,job_id,provider,delivery_id,outcome,detail,received_at FROM job_events ORDER BY received_at DESC LIMIT 1000")) {
add("event", event.id, `${event.provider} event · ${event.outcome}`, String(event.detail), `/jobs/${encodeURIComponent(String(event.job_id))}`, Object.values(event));
}
for (const activity of this.rows("SELECT id,run_id,action,detail,created_at FROM run_activity ORDER BY created_at DESC LIMIT 1000")) {
add("activity", activity.id, `${activity.action} · run ${String(activity.run_id).slice(0, 8)}`, String(activity.detail), `/job-runs/${encodeURIComponent(String(activity.run_id))}`, Object.values(activity));
}
return json({ items: items.slice(0, 100) });
}

private async getRun(runId: string): Promise<Response> {
const run = this.one(`SELECT r.id, r.pipe_id AS job_id, r.issue_id, r.issue_url, r.issue_title, r.run_name, r.agent_name, r.workspace_name, r.agent_kind, r.state, r.provider, r.execution_backend_kind AS backend_kind, r.execution_handle, r.execution_capabilities AS capabilities, r.destination_url, r.prompt AS encrypted_prompt, r.result, r.exec_status, r.exec_exit_code, r.recovery_last_action, r.created_at, r.updated_at,
i.id AS invocation_id, i.job_id AS invocation_job_id, i.source AS invocation_source, i.claim_key AS invocation_claim_key, i.trigger_id AS invocation_trigger_id, i.context, i.occurrence AS invocation_occurrence, i.created_at AS invocation_created_at
Expand Down
11 changes: 9 additions & 2 deletions packages/app/src/ui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ themeToggle.addEventListener('click',()=>{const dark=!document.documentElement.c
document.addEventListener('click',event=>{if(!(event.target instanceof Element))return;document.querySelectorAll('details[open]').forEach(menu=>{if(!menu.contains(event.target))menu.open=false})});
const activeNavigation=location.pathname.startsWith('/settings')?'settings':location.pathname.startsWith('/jobs')?'jobs':'';
if(activeNavigation){const link=document.querySelector('[data-navigation="'+activeNavigation+'"]');link?.setAttribute('aria-current','page')}
const searchDialog=document.querySelector('#search-dialog'),searchInput=document.querySelector('#search-input'),searchResults=document.querySelector('#search-results'),searchStatus=document.querySelector('#search-status');
const searchEsc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const searchHighlight=(value,query)=>{const normalized=String(query||'').toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu,'');let cursor=0,html='';for(const character of normalized){let found=-1;for(let i=cursor;i<value.length;i++){if(value[i].normalize().toLocaleLowerCase()===character){found=i;break}}if(found<0)return searchEsc(value);if(found>cursor)html+=searchEsc(value.slice(cursor,found));html+='<mark class="rounded bg-factorize-200 text-slate-950 dark:bg-factorize-500/50 dark:text-white">'+searchEsc(value[found])+'</mark>';cursor=found+1}return html+searchEsc(value.slice(cursor))};
let searchTimer,searchItems=[],searchIndex=0;const renderSearch=()=>{if(!searchResults)return;searchResults.innerHTML=searchItems.length?searchItems.map((item,index)=>'<a data-search-result="'+index+'" href="'+searchEsc(item.url)+'" class="block rounded-lg px-3 py-3 '+(index===searchIndex?'bg-stone-100 dark:bg-slate-800':'hover:bg-stone-50 dark:hover:bg-slate-800')+'"><span class="block font-medium">'+searchHighlight(item.title,searchInput.value)+'</span><span class="mt-1 block truncate text-xs text-slate-500">'+searchHighlight(item.subtitle,searchInput.value)+'</span></a>').join(''):'<p class="px-3 py-8 text-center text-sm text-slate-500">'+(searchInput?.value?'No matches.':'Type to search jobs, runs, and metadata.')+'</p>';if(searchStatus)searchStatus.textContent=searchItems.length?searchItems.length+' results':'No search results'};
const runSearch=async()=>{const query=searchInput?.value.trim()||'';if(!query){searchItems=[];renderSearch();return}if(searchStatus)searchStatus.textContent='Searching…';try{const response=await fetch('/api/v1/search?q='+encodeURIComponent(query));if(!response.ok)throw new Error('Search failed');searchItems=(await response.json()).items||[];searchIndex=0;renderSearch()}catch{searchItems=[];if(searchStatus)searchStatus.textContent='Search is unavailable. Try again.';renderSearch()}};
const openSearch=()=>{if(!searchDialog)return;searchDialog.showModal();searchInput.focus();renderSearch()};const closeSearch=()=>searchDialog?.close();
document.querySelector('#search-button')?.addEventListener('click',openSearch);document.querySelector('#search-close')?.addEventListener('click',closeSearch);searchDialog?.addEventListener('click',event=>{if(event.target===searchDialog)closeSearch()});searchInput?.addEventListener('input',()=>{clearTimeout(searchTimer);searchTimer=setTimeout(runSearch,120)});searchInput?.addEventListener('keydown',event=>{if(event.key==='ArrowDown'){event.preventDefault();searchIndex=Math.min(searchIndex+1,Math.max(0,searchItems.length-1));renderSearch()}else if(event.key==='ArrowUp'){event.preventDefault();searchIndex=Math.max(searchIndex-1,0);renderSearch()}else if(event.key==='Enter'&&searchItems[searchIndex]){event.preventDefault();location.href=searchItems[searchIndex].url}else if(event.key==='Escape')closeSearch()});document.addEventListener('keydown',event=>{if(event.key==='/'&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!(event.target instanceof HTMLInputElement)&&!(event.target instanceof HTMLTextAreaElement)&&!(event.target instanceof HTMLSelectElement)){event.preventDefault();openSearch()}else if(event.key==='Escape'&&searchDialog?.open)closeSearch()});
`;

const shell = (title: string, viewer: Viewer, body: string, script = "") => `<!doctype html>
Expand All @@ -37,7 +44,7 @@ const shell = (title: string, viewer: Viewer, body: string, script = "") => `<!d
<a href="https://factorize.sh" class="flex items-center gap-2 text-lg font-bold tracking-tight"><img src="/bee-mark-monochrome.png" alt="" class="navbar-bee h-8 w-8 object-contain">Factorize</a>
<div class="flex items-center gap-2 text-sm font-medium sm:gap-4">
${viewer ? `<a href="/jobs" data-navigation="jobs" class="inline-flex min-h-11 items-center rounded-lg px-2 text-slate-600 hover:text-slate-950 aria-[current=page]:text-slate-950 aria-[current=page]:underline aria-[current=page]:underline-offset-8 dark:text-slate-300 dark:hover:text-white dark:aria-[current=page]:text-white">Jobs</a><details class="relative"><summary aria-label="Open profile menu" class="grid h-11 w-11 cursor-pointer list-none items-center justify-center rounded-full bg-slate-900 text-sm font-semibold text-white outline-none focus-visible:ring-2 focus-visible:ring-factorize-600 focus-visible:ring-offset-2 dark:bg-white dark:text-slate-950 dark:focus-visible:ring-offset-slate-950">${escapeHtml(viewer.email.slice(0, 1).toUpperCase())}</summary><div class="absolute right-0 z-20 mt-2 w-56 rounded-xl border border-stone-200 bg-white p-2 shadow-xl dark:border-slate-700 dark:bg-slate-900"><p class="truncate px-3 py-2 text-xs font-normal text-slate-500 dark:text-slate-400">${escapeHtml(viewer.email)}</p><a href="/settings" data-navigation="settings" class="flex min-h-11 items-center rounded-lg px-3 py-2 text-sm hover:bg-stone-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-factorize-600 aria-[current=page]:bg-stone-100 aria-[current=page]:font-semibold dark:hover:bg-slate-800 dark:aria-[current=page]:bg-slate-800">Settings</a><form action="/auth/logout" method="post" class="mt-1 border-t border-stone-200 pt-1 dark:border-slate-700"><button type="submit" class="min-h-11 w-full rounded-lg px-3 py-2 text-left text-sm hover:bg-stone-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-factorize-600 dark:hover:bg-slate-800">Log out</button></form></div></details>` : `<a href="/auth/login" class="text-slate-600 hover:text-slate-950 dark:text-slate-300 dark:hover:text-white">Log in</a>`}
<button id="theme-toggle" type="button" class="grid h-9 w-9 place-items-center rounded-lg border border-stone-200 bg-white text-lg text-slate-700 hover:bg-stone-100 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800"><span id="theme-icon" aria-hidden="true">☾</span></button>
${viewer ? `<button id="search-button" type="button" title="Search (/)" aria-label="Search (/)" class="inline-flex min-h-11 items-center gap-2 rounded-lg px-2 text-slate-600 hover:bg-stone-100 hover:text-slate-950 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-white"><span aria-hidden="true">⌕</span><span class="hidden sm:inline">Search</span><kbd class="hidden rounded border border-stone-300 px-1.5 py-0.5 text-[10px] font-normal sm:inline dark:border-slate-700">/</kbd></button>` : ""}<button id="theme-toggle" type="button" class="grid h-9 w-9 place-items-center rounded-lg border border-stone-200 bg-white text-lg text-slate-700 hover:bg-stone-100 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:bg-slate-800"><span id="theme-icon" aria-hidden="true">☾</span></button>
</div>
</nav></header>${body}<footer class="border-t border-stone-200 bg-white dark:border-slate-800 dark:bg-slate-950"><div class="mx-auto flex w-full max-w-6xl flex-wrap items-center justify-between gap-3 px-5 py-6 text-sm text-slate-500 lg:px-8 dark:text-slate-400"><p>Open-source software factories for everybody.</p><a href="https://github.com/GenerationSoftware/factorize" target="_blank" rel="noreferrer" class="inline-flex items-center gap-2 font-medium text-slate-600 transition hover:text-slate-950 dark:text-slate-300 dark:hover:text-white"><svg aria-hidden="true" viewBox="0 0 16 16" fill="currentColor" class="h-5 w-5"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82A7.66 7.66 0 0 1 8 4.73c.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8Z"/></svg>View on GitHub</a></div></footer><script>${themeScript}${script}</script></body></html>`;

Expand All @@ -61,7 +68,7 @@ export const landingPage = (viewer: Viewer) => shell("Factorize: Software Factor
</section>
</div></main>`);

const dashboardHead = (title: string, description: string, action = "") => `<div class="flex flex-col items-stretch gap-3 sm:flex-row sm:items-end sm:justify-between sm:gap-4"><div class="min-w-0"><h1 class="text-3xl font-bold tracking-tight">${title}</h1>${description ? `<p class="mt-2 text-slate-600 dark:text-slate-400">${description}</p>` : ""}</div>${action}</div>`;
const dashboardHead = (title: string, description: string, action = "") => `<div class="flex flex-col items-stretch gap-3 sm:flex-row sm:items-end sm:justify-between sm:gap-4"><div class="min-w-0"><h1 class="text-3xl font-bold tracking-tight">${title}</h1>${description ? `<p class="mt-2 text-slate-600 dark:text-slate-400">${description}</p>` : ""}</div>${action}</div><dialog id="search-dialog" aria-labelledby="search-title" class="m-auto w-[min(42rem,calc(100vw-2rem))] rounded-2xl border border-stone-200 bg-white p-0 text-slate-950 shadow-2xl backdrop:bg-slate-950/50 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100"><div class="border-b border-stone-200 p-4 dark:border-slate-700"><div class="flex items-center justify-between gap-4"><h2 id="search-title" class="font-semibold">Search Factorize</h2><button id="search-close" type="button" class="rounded-lg px-2 py-1 text-sm text-slate-500 hover:bg-stone-100 dark:hover:bg-slate-800">Esc</button></div><input id="search-input" type="search" autocomplete="off" placeholder="Search jobs, runs, and metadata…" class="field mt-4 w-full" aria-describedby="search-status"><p id="search-status" class="sr-only" role="status"></p></div><div id="search-results" class="max-h-[min(60vh,32rem)] overflow-y-auto p-2"></div></dialog>`;
const card = "rounded-2xl border border-stone-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900";
const uiHelpers = `
const $=s=>document.querySelector(s),esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
Expand Down