Skip to content
Closed
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 apps/databases/notis-listing.json
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down
1 change: 1 addition & 0 deletions apps/databases/notis.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
Expand Down
39 changes: 37 additions & 2 deletions apps/databases/packages/sdk/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
21 changes: 21 additions & 0 deletions apps/databases/packages/sdk/src/documents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
DatabasePropertyType,
DocumentContentType,
DocumentRecord,
SecretPropertyValue,
} from './runtime';

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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 [];
Expand Down Expand Up @@ -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;
}
Expand Down
97 changes: 97 additions & 0 deletions apps/databases/packages/sdk/src/hooks/useCloudComputer.ts
Original file line number Diff line number Diff line change
@@ -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<void>;
}

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
* ? <p>Signed in as {gh.account}</p>
* : <GithubConnect />;
* ```
*
* 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<CloudComputerFacts | null>(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<Error | null>(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 };
}
Original file line number Diff line number Diff line change
@@ -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 };
}
75 changes: 75 additions & 0 deletions apps/databases/packages/sdk/src/hooks/useHandover.ts
Original file line number Diff line number Diff line change
@@ -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<HandoverResult>;
/** 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 ? (
* <Button
* disabled={pending}
* onClick={() => { void handover({ prompt: 'Create a workspace on notis to ...' }); }}
* >
* Send to Notis
* </Button>
* ) : (
* <CopyablePrompt prompt="Create a workspace on notis to ..." />
* );
* ```
*
* 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<Error | null>(null);

const handover = useCallback(
async (payload: HandoverPayload): Promise<HandoverResult> => {
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) };
}
Loading
Loading