diff --git a/apps/databases/notis-listing.json b/apps/databases/notis-listing.json index 81197d6..1168ad6 100644 --- a/apps/databases/notis-listing.json +++ b/apps/databases/notis-listing.json @@ -58,7 +58,7 @@ } ], "source_app_id": "bd97c4a6-600e-4b96-8826-2c95db1ee599", - "source_version": 2, + "source_version": 3, "submitted_by_notis_user_id": "9f9002d8-05c5-d78a-b105-b6f2422b25bc", "tagline": "Explore every database and schema in your Notis workspace.", "version_notes": "- First Store release." diff --git a/apps/databases/notis.config.ts b/apps/databases/notis.config.ts index 9b409b5..dd91a27 100644 --- a/apps/databases/notis.config.ts +++ b/apps/databases/notis.config.ts @@ -2,6 +2,7 @@ import { defineNotisApp } from '@notis/sdk/config'; export default defineNotisApp({ name: 'notis-database', + devSlug: 'notis-database', title: 'Databases', description: 'A read-only catalog and schema explorer for every database in your Notis workspace. Browse databases grouped by the app that owns them, inspect each property with its type, select options, formats, and formulas, follow relations between databases, and page through the actual records stored in any of them.', diff --git a/apps/databases/packages/sdk/src/config.ts b/apps/databases/packages/sdk/src/config.ts index effb654..9dd4d3c 100644 --- a/apps/databases/packages/sdk/src/config.ts +++ b/apps/databases/packages/sdk/src/config.ts @@ -85,7 +85,12 @@ export interface NotisAppAuthor { export interface NotisAppSkillConfig { /** Stable source-owned key used by other app declarations. */ key: string; - /** Path to the skill entrypoint, relative to notis.config.ts. */ + /** + * Path to the skill, relative to notis.config.ts. Either a Markdown file + * (`./skills/onboarding.md`) or a directory holding SKILL.md plus its + * supporting files (`./skills/onboarding/`), which are packaged on deploy + * and materialized next to SKILL.md in the sandbox. + */ path: string; /** User-facing name used for the installed skill. */ name: string; @@ -106,7 +111,13 @@ export interface NotisAppScreenshotConfig { alt: string; /** Route slug captured by `notis apps screenshot`. */ route?: string; - /** Optional fixture scenario from metadata/screenshot-fixtures.json. */ + /** + * Named scenario from metadata/screenshot-fixtures.json. Its `tools` and + * `requests` override the file-level ones key by key for this capture, and + * its `actions` run once the route has mounted -- so one route can be shown + * in several states (populated, empty, a panel opened) without the states + * leaking into each other. + */ scenario?: string; /** Optional CSS selector captured as the truthful focal region for this Store image. */ focus?: string; @@ -142,11 +153,35 @@ export interface NotisAppCapabilities { * bound to the app's own databases. */ workspaceDatabases?: 'read'; + + /** + * Read a few facts about the user's cloud computer: whether a sandbox exists + * and is running, and whether the GitHub CLI is signed in there. + * + * Without this an app has to infer them — the Workspaces app treated a + * configured repository as proof that `gh auth login` had happened, which + * cannot show an account name and cannot notice a revoked credential. + * `'read'` never creates, resumes or commands a sandbox. Read it with + * `useCloudComputer()`. + * + * `'shell'` additionally asks to command the cloud computer: it unlocks + * `LOCAL_NOTIS_RUN_SANDBOX_SHELL` and the sandbox file tools from this app's + * views (they are denied to every view otherwise), and implies the read + * facts. This is the same authority the user's own agent has on the sandbox, + * so the user is asked for it explicitly at install or in the Store grant + * step; declare it only when the app's core actions genuinely run there. + */ + cloudComputer?: 'read' | 'shell'; } export interface NotisAppConfig { /** URL-safe app slug. Existing apps may still use a display name here. */ name: string; + /** + * Stable identity used by `notis apps dev`. Set it once and keep it unchanged + * when renaming the app so local iterations keep updating one dev app. + */ + devSlug?: string; /** Human display title, Raycast-style. Falls back to `name`. */ title?: string; description?: string; diff --git a/apps/databases/packages/sdk/src/documents.ts b/apps/databases/packages/sdk/src/documents.ts index bf65550..de3ddf0 100644 --- a/apps/databases/packages/sdk/src/documents.ts +++ b/apps/databases/packages/sdk/src/documents.ts @@ -12,6 +12,7 @@ import type { DatabasePropertyType, DocumentContentType, DocumentRecord, + SecretPropertyValue, } from './runtime'; // --------------------------------------------------------------------------- @@ -45,6 +46,23 @@ export function extractRichText(value: unknown): string { .join(''); } +/** + * Reads a `secret` property value. The platform only ever sends the pointer + * ({present, reference, status, metadata}), so this rebuilds it field by field + * rather than passing the payload through — an app can never surface secret + * material through this helper, whatever the server sent. + */ +export function getSecretValue(value: unknown): SecretPropertyValue { + const record = asRecord(value); + const metadata = asRecord(record?.metadata); + return { + present: record?.present === true, + reference: optionalString(record?.reference), + status: optionalString(record?.status), + metadata, + }; +} + /** Extracts the ids of a normalized relation property value. */ export function getRelationIds(value: unknown): string[] { if (!Array.isArray(value)) return []; @@ -81,6 +99,9 @@ export function normalizePropertyValue(value: unknown): unknown { return items.map((item) => optionalString(asRecord(item)?.id) ?? item).filter(Boolean); } if (type === 'date') return optionalString(asRecord(record.date)?.start) ?? record.date ?? null; + // Before the `type in record` fallthrough: a secret value has no `secret` + // key, so passing it through would hand the caller the raw payload. + if (type === 'secret') return getSecretValue(record); if (type in record) return record[type]; return value; } diff --git a/apps/databases/packages/sdk/src/hooks/useCloudComputer.ts b/apps/databases/packages/sdk/src/hooks/useCloudComputer.ts new file mode 100644 index 0000000..96d95c1 --- /dev/null +++ b/apps/databases/packages/sdk/src/hooks/useCloudComputer.ts @@ -0,0 +1,97 @@ +'use client'; + +import { useCallback, useEffect, useRef, useState } from 'react'; +import { useNotisRuntime } from '../provider'; +import type { CloudComputerFacts } from '../runtime'; + +export interface UseCloudComputerResult { + /** + * The facts, or null while the first read is in flight. `facts.available` + * is false when this host cannot answer — render the app's own fallback. + */ + facts: CloudComputerFacts | null; + loading: boolean; + error: Error | null; + /** Re-read the facts. The platform caches them for a few minutes. */ + refresh: () => Promise; +} + +const UNAVAILABLE: CloudComputerFacts = { + available: false, + reason: 'unsupported_host', + sandbox: null, + cli_auth: { + gh: { authenticated: null, account: null, checked_at: null, reason: 'unsupported_host' }, + }, +}; + +/** + * Read-only facts about the user's cloud computer. + * + * ```tsx + * const { facts } = useCloudComputer(); + * const gh = facts?.available ? facts.cli_auth.gh : null; + * + * return gh?.authenticated + * ?

Signed in as {gh.account}

+ * : ; + * ``` + * + * Requires `capabilities.cloudComputer: 'read'` in `notis.config.ts` and the + * user's approval at install time. It answers with state the platform already + * holds: reading it never creates, resumes or commands a sandbox, and the GitHub + * probe only runs when the sandbox is already awake. `authenticated: null` + * therefore means *unknown*, not *signed out* — keep the app's own fallback for + * that case and for hosts that answer `{ available: false }` (the dev harness, + * the vite preview). + */ +export function useCloudComputer(): UseCloudComputerResult { + const runtime = useNotisRuntime(); + const [facts, setFacts] = useState(null); + // True from the first committed render: the initial read is already queued + // in an effect, and `{ loading: false, facts: null }` would flash a + // consumer's fallback branch before the answer arrives. + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const mounted = useRef(true); + + useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + }; + }, []); + + const read = useCallback(async (options?: { refresh?: boolean }) => { + if (!runtime?.cloudComputerFacts) { + setFacts(UNAVAILABLE); + setLoading(false); + return; + } + + setLoading(true); + setError(null); + try { + const next = await runtime.cloudComputerFacts(options); + if (mounted.current) setFacts(next); + } catch (err) { + const e = err instanceof Error ? err : new Error(String(err)); + if (mounted.current) { + setError(e); + // A refused or failed read is the same product state as a host that + // cannot answer: the app shows its fallback instead of an error. + setFacts(UNAVAILABLE); + } + } finally { + if (mounted.current) setLoading(false); + } + }, [runtime]); + + useEffect(() => { + void read(); + }, [read]); + + const refresh = useCallback(() => read({ refresh: true }), [read]); + + return { facts, loading, error, refresh }; +} diff --git a/apps/databases/packages/sdk/src/hooks/useDatabaseSubscription.ts b/apps/databases/packages/sdk/src/hooks/useDatabaseSubscription.ts new file mode 100644 index 0000000..50076ab --- /dev/null +++ b/apps/databases/packages/sdk/src/hooks/useDatabaseSubscription.ts @@ -0,0 +1,76 @@ +'use client'; + +import { useEffect, useRef, useState } from 'react'; +import { useNotisRuntime } from '../provider'; +import { useDocuments, type UseDocumentsOptions, type UseDocumentsResult } from './useDocuments'; +import type { DocumentRecord } from '../runtime'; + +export interface UseDatabaseSubscriptionOptions extends UseDocumentsOptions { + /** Set to false to keep the query but skip the change feed. */ + subscribe?: boolean; +} + +export interface UseDatabaseSubscriptionResult extends UseDocumentsResult { + /** Alias of `documents`, for views that think in rows. */ + rows: DocumentRecord[]; + /** True while a live change feed is attached to this database. */ + live: boolean; +} + +/** + * Query a Notis database and keep it fresh without polling. + * + * ```tsx + * const { rows, live, refetch } = useDatabaseSubscription('workspaces'); + * ``` + * + * A change on the database wakes the hook, which then refetches through the + * usual `LOCAL_NOTIS_DATABASE_QUERY` path — the change feed is a signal only + * and never carries row data. Hosts without a change feed (the dev harness, + * the screenshot stub, the vite preview) still return rows; `live` is false + * there and the app should keep offering its manual refresh. + */ +export function useDatabaseSubscription( + databaseSlug: string, + options: UseDatabaseSubscriptionOptions = {}, +): UseDatabaseSubscriptionResult { + const runtime = useNotisRuntime(); + const { subscribe = true, ...documentOptions } = options; + const { documents, loading, error, refetch } = useDocuments(databaseSlug, documentOptions); + const [live, setLive] = useState(false); + + const refetchRef = useRef(refetch); + useEffect(() => { + refetchRef.current = refetch; + }, [refetch]); + + const enabled = options.enabled !== false && subscribe; + + useEffect(() => { + if (!runtime?.subscribeDatabase || !enabled || !databaseSlug) { + setLive(false); + return; + } + + let cancelled = false; + const unsubscribe = runtime.subscribeDatabase( + databaseSlug, + () => { + refetchRef.current(); + }, + { + onStatusChange: (isLive) => { + if (!cancelled) setLive(isLive); + }, + }, + ); + + return () => { + cancelled = true; + setLive(false); + unsubscribe?.(); + }; + }, [runtime, databaseSlug, enabled]); + + return { documents, rows: documents, loading, error, refetch, live }; +} diff --git a/apps/databases/packages/sdk/src/hooks/useHandover.ts b/apps/databases/packages/sdk/src/hooks/useHandover.ts new file mode 100644 index 0000000..e8092ce --- /dev/null +++ b/apps/databases/packages/sdk/src/hooks/useHandover.ts @@ -0,0 +1,75 @@ +'use client'; + +import { useCallback, useState } from 'react'; +import { useNotisRuntime } from '../provider'; +import type { HandoverPayload, HandoverResult } from '../runtime'; + +export interface UseHandoverResult { + /** Hand the work over. Rejects when the host has no manager chat. */ + handover: (payload: HandoverPayload) => Promise; + /** True while the manager chat is being prepared. */ + pending: boolean; + error: Error | null; + /** + * False when the host cannot hand work over (dev harness, vite preview). + * Render the app's own fallback — a copyable prompt, say — when it is false. + */ + available: boolean; +} + +/** + * Hand a piece of work from app code to the Notis manager chat. + * + * An app displays work; the manager runs it. `handover` puts the message in + * the chat surface that already owns streaming progress, billing, cancellation + * and the transcript, and the app watches its own databases for the result. + * + * ```tsx + * const { handover, pending, available } = useHandover(); + * + * return available ? ( + * + * ) : ( + * + * ); + * ``` + * + * Pass `skill` to bind the work to a skill declared in `notis.config.ts`; the + * host rejects a key the app does not declare. `autoSend` is accepted for + * forward compatibility; today's hosts always return `drafted` and let the + * user press send. + */ +export function useHandover(): UseHandoverResult { + const runtime = useNotisRuntime(); + const [pending, setPending] = useState(false); + const [error, setError] = useState(null); + + const handover = useCallback( + async (payload: HandoverPayload): Promise => { + if (!runtime?.handover) { + throw new Error('This Notis host cannot hand work to the manager chat.'); + } + + setPending(true); + setError(null); + + try { + return await runtime.handover(payload); + } catch (err) { + const e = err instanceof Error ? err : new Error(String(err)); + setError(e); + throw e; + } finally { + setPending(false); + } + }, + [runtime], + ); + + return { handover, pending, error, available: Boolean(runtime?.handover) }; +} diff --git a/apps/databases/packages/sdk/src/index.ts b/apps/databases/packages/sdk/src/index.ts index 1a0af1c..05df9e0 100644 --- a/apps/databases/packages/sdk/src/index.ts +++ b/apps/databases/packages/sdk/src/index.ts @@ -13,6 +13,11 @@ export { NotisProvider, useNotisRuntime } from './provider'; export { useNotis } from './hooks/useNotis'; export { useDocuments } from './hooks/useDocuments'; export type { UseDocumentsOptions, UseDocumentsResult } from './hooks/useDocuments'; +export { useDatabaseSubscription } from './hooks/useDatabaseSubscription'; +export type { + UseDatabaseSubscriptionOptions, + UseDatabaseSubscriptionResult, +} from './hooks/useDatabaseSubscription'; export { useDocument } from './hooks/useDocument'; export type { UseDocumentOptions, UseDocumentResult } from './hooks/useDocument'; export { useUpsertDocument } from './hooks/useUpsertDocument'; @@ -22,6 +27,10 @@ export type { UseDatabaseSchemaResult } from './hooks/useDatabaseSchema'; export { useTool } from './hooks/useTool'; export type { ToolCallState, UseToolResult } from './hooks/useTool'; export { useTools } from './hooks/useTools'; +export { useHandover } from './hooks/useHandover'; +export type { UseHandoverResult } from './hooks/useHandover'; +export { useCloudComputer } from './hooks/useCloudComputer'; +export type { UseCloudComputerResult } from './hooks/useCloudComputer'; export { useNotisNavigation } from './hooks/useNotisNavigation'; export { useTopBarSearch } from './hooks/useTopBarSearch'; export { useBackend } from './hooks/useBackend'; @@ -37,6 +46,7 @@ export { extractRichText, getDocumentPreview, getRelationIds, + getSecretValue, isPresentString, markdownToPlainText, normalizeDatabaseProperty, @@ -64,6 +74,9 @@ export type { MultiSelectDragOverlayProps } from './components/MultiSelectDragOv // Types (re-exported for convenience) export type { AppDescriptor, + CloudComputerCliAuthFacts, + CloudComputerFacts, + CloudComputerSandboxFacts, CollectionItem, CollectionItemDetail, DatabaseDescriptor, @@ -72,12 +85,16 @@ export type { DatabasePropertyType, DocumentContentType, DocumentRecord, + HandoverPayload, + HandoverResult, NotisDocumentEditorProps, NotisRuntime, NotisRuntimeContext, NotisRuntimeUI, QueryFilter, RouteDescriptor, + SecretPropertyValue, + SubscribeDatabaseOptions, ToolDescriptor, ToolInputSchema, } from './runtime'; diff --git a/apps/databases/packages/sdk/src/runtime.ts b/apps/databases/packages/sdk/src/runtime.ts index 7ce8731..d7f5417 100644 --- a/apps/databases/packages/sdk/src/runtime.ts +++ b/apps/databases/packages/sdk/src/runtime.ts @@ -25,7 +25,21 @@ export type DatabasePropertyType = | 'status' | 'relation' | 'formula' - | 'files'; + | 'files' + | 'secret'; + +/** + * The value of a `secret` property. The platform stores a pointer to a + * credential held elsewhere and never the credential itself, so there is + * deliberately nothing here to read the secret material from — only whether + * one is attached, which credential it is, and its lifecycle state. + */ +export interface SecretPropertyValue { + present: boolean; + reference: string | null; + status: string | null; + metadata: Record | null; +} export interface DatabasePropertyOption { id?: string | null; @@ -188,6 +202,84 @@ export interface NotisRuntimeUI { // NotisRuntime // --------------------------------------------------------------------------- +/** + * Options for `NotisRuntime.subscribeDatabase`. + */ +export interface SubscribeDatabaseOptions { + /** + * Called with `true` once a live change feed is attached, and with `false` + * when it drops or is torn down. Hosts without a change feed (dev harness, + * screenshot stub, vite preview) never call it, so `live` stays false there. + */ + onStatusChange?: (live: boolean) => void; +} + +/** + * Work an app hands to the Notis manager chat through `NotisRuntime.handover`. + */ +export interface HandoverPayload { + /** The message the manager should act on. */ + prompt: string; + /** + * Key of a skill declared in `notis.config.ts` -> `skills[].key`. The host + * rejects a key this app does not declare. Omit to hand over plain work. + */ + skill?: string; + /** + * Accepted for forward compatibility. The portal never submits a composer on + * the user's behalf today, so every handover resolves `drafted`; `sent` is + * reserved for a host that can genuinely dispatch the run. + */ + autoSend?: boolean; +} + +export interface HandoverResult { + /** `drafted` when the user still has to press send, `sent` when it went straight through. */ + status: 'drafted' | 'sent'; +} + +/** + * The user's cloud computer, as far as an app may see it. + * + * `exists` is false when the user has never had a sandbox provisioned. A + * `status` of anything other than `'running'` means the VM is asleep; reading + * these facts never wakes it. + */ +export interface CloudComputerSandboxFacts { + exists: boolean; + status: string | null; + provider: string | null; + created_at: string | null; + updated_at: string | null; +} + +/** + * Whether a CLI inside the cloud computer is signed in. + * + * `authenticated: null` means *unknown*, never *signed out*: the sandbox was + * not running, or the probe could not answer. `reason` says which + * (`'sandbox_not_running'`, `'no_sandbox'`, `'sandbox_status_unknown'`, + * `'probe_failed'`, `'not_signed_in'`). + */ +export interface CloudComputerCliAuthFacts { + authenticated: boolean | null; + account: string | null; + checked_at: string | null; + reason: string | null; +} + +export interface CloudComputerFacts { + /** + * False when this host cannot answer at all — no cloud computer on the user's + * plan, or the platform could not resolve the facts. Render whatever the app + * did before rather than an error. + */ + available: boolean; + reason?: string | null; + sandbox: CloudComputerSandboxFacts | null; + cli_auth: { gh: CloudComputerCliAuthFacts }; +} + export interface NotisRuntime { app: AppDescriptor; route: RouteDescriptor; @@ -195,6 +287,45 @@ export interface NotisRuntime { context: NotisRuntimeContext; ui?: NotisRuntimeUI; + /** + * Subscribe to changes on an app-owned database. Returns an unsubscribe. + * + * The change notification is only a signal — it carries no rows. Consumers + * react by refetching through the normal tool path, so app scoping, + * permissions and billing are unchanged. Use the `useDatabaseSubscription` + * hook rather than calling this directly. + */ + subscribeDatabase?( + slug: string, + onChange: () => void, + options?: SubscribeDatabaseOptions, + ): () => void; + + /** + * Hand a piece of work to the Notis manager chat. The app cannot run an + * agent itself: it describes the job, and the manager surface owns progress, + * billing, cancellation and the transcript. Results come back to the app + * through its own databases (see `useDatabaseSubscription`). + * + * Use the `useHandover` hook rather than calling this directly. Hosts + * without a manager chat (the dev harness, the vite preview) leave it + * undefined, so keep whatever fallback the app already offers. + */ + handover?(payload: HandoverPayload): Promise; + + /** + * Read-only facts about the user's cloud computer. Requires + * `capabilities.cloudComputer: 'read'` in `notis.config.ts` plus the user's + * approval; resolving it never creates, resumes or commands a sandbox. + * + * Use the `useCloudComputer` hook rather than calling this directly. Hosts + * without a cloud computer (the dev harness, the vite preview) answer + * `{ available: false }`, so keep whatever fallback the app already has. + * `{ refresh: true }` bypasses the host's short answer cache — the hook's + * refresh() sends it so a just-completed sign-in becomes visible. + */ + cloudComputerFacts?(options?: { refresh?: boolean }): Promise; + navigate?: (payload: { kind: string; [key: string]: unknown }) => void; registerTopBarSearch?: (