@hanzo/studio 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,6 +22,8 @@ export declare const ZEN = "zen-image";
22
22
  export declare const ASPECTS: readonly ['1:1', '4:5', '3:4', '2:3', '9:16', '16:9', '3:2', '4:3', '21:9'];
23
23
  /** Which lane a request takes: the one asked for, else Zen Image on a GPU that can run it, else the gateway. */
24
24
  export declare function lane(model: string, fleet: Fleet | null): string;
25
+ /** Which lane an edit takes: the one asked for, else Qwen Edit on a GPU that can run it, else the gateway. */
26
+ export declare function editing(model: string, fleet: Fleet | null): string;
25
27
  /** Why the gateway's image models are not answering now, or null. */
26
28
  export declare function useImageLane(): {
27
29
  model: string;
@@ -5,7 +5,9 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
5
5
  * Two lanes, chosen per request: the gateway's image models (api.hanzo.ai,
6
6
  * billed to the org) and Zen Image on the org's own GPU (Z-Image-Turbo through
7
7
  * the engine), which is offered only while a GPU advertises `image.zen`. Auto
8
- * takes the GPU when one can run it, else the gateway.
8
+ * takes the GPU when one can run it, else the gateway. An edit is the same
9
+ * choice: Qwen Edit on a GPU that advertises `edit.qwen` (the engine's fix
10
+ * lane, from the picture staged on the engine), else a gateway model.
9
11
  */
10
12
  import { SizableText, XStack, YStack } from '@hanzo/gui';
11
13
  import { Image as Picture } from '@hanzogui/lucide-icons-2';
@@ -13,7 +15,7 @@ import { useState, useSyncExternalStore } from 'react';
13
15
  import { render } from '../gpu.js';
14
16
  import { current, filename } from '../made.js';
15
17
  import { useUrl } from '../use.js';
16
- import { draw, read, Refusal } from '../wire.js';
18
+ import { draw, read, Refusal, stage } from '../wire.js';
17
19
  import { lit, num, str } from './kind.js';
18
20
  /** The gateway's image models, best first. */
19
21
  export const MODELS = [
@@ -44,6 +46,16 @@ export function lane(model, fleet) {
44
46
  return model;
45
47
  return lit(fleet, 'image.zen') ? ZEN : MODELS[0].id;
46
48
  }
49
+ /** Which lane an edit takes: the one asked for, else Qwen Edit on a GPU that can run it, else the gateway. */
50
+ export function editing(model, fleet) {
51
+ if (MODELS.some((m) => m.id === model))
52
+ return model;
53
+ if (lit(fleet, 'edit.qwen'))
54
+ return ZEN;
55
+ if (model === ZEN)
56
+ throw new Error('Editing on your GPU needs one that runs Qwen Edit; connect it with hanzo link, or edit with a gateway model.');
57
+ return MODELS[0].id;
58
+ }
47
59
  async function size(blob) {
48
60
  try {
49
61
  const bmp = await createImageBitmap(blob);
@@ -74,11 +86,19 @@ export function useImageLane() {
74
86
  }
75
87
  /** Make pictures from words (and, for an edit, the pictures they start from), and keep them. */
76
88
  export async function picture(w, o) {
77
- const use = lane(o.model, w.fleet);
89
+ const use = o.from?.length ? editing(o.model, w.fleet) : lane(o.model, w.fleet);
78
90
  const files = [];
91
+ if (use === ZEN && o.from?.length) {
92
+ for (const f of o.from) {
93
+ w.doing('Sending the picture to your GPU');
94
+ const upload = await stage(w.wire, await read(w.wire, f.key), f.name);
95
+ const got = await render(w.wire, 'fix', { upload, instruction: o.prompt.slice(0, 500) }, w.doing, w.signal);
96
+ for (const g of got)
97
+ files.push(await w.keep(`edit-${files.length + 1}.png`, g.blob, await size(g.blob)));
98
+ }
99
+ return { files, by: 'Qwen Edit (your GPU)' };
100
+ }
79
101
  if (use === ZEN) {
80
- if (o.from?.length)
81
- throw new Error('Zen Image draws from words only; edit with a gateway model.');
82
102
  const [width, height] = PIXELS[o.aspect] ?? PIXELS['1:1'];
83
103
  for (let i = 0; i < (o.count ?? 1); i++) {
84
104
  const got = await render(w.wire, 'image', { prompt: o.prompt, width, height }, w.doing, w.signal);
package/lib/live.d.ts CHANGED
@@ -34,11 +34,9 @@ export declare function useChats(w: Wire): {
34
34
  rows: Listed[];
35
35
  error: string;
36
36
  };
37
- /** The words that say where work is kept, while the Library does not answer. */
38
- export declare const KEPT = "Kept in this browser \u00B7 Saving to Library when it\u2019s available";
39
37
  /**
40
38
  * Whether the person's Library answers: asked once, and on the first yes
41
- * whatever was kept only in this browser is carried up to it.
39
+ * every made file this browser still holds is carried up to it and dropped here.
42
40
  */
43
41
  export declare function useLibrary(w: Wire): boolean | null;
44
42
  export type { Fleet };
package/lib/live.js CHANGED
@@ -100,13 +100,11 @@ export function useChats(w) {
100
100
  }, [w]);
101
101
  return { rows, error: rowsError };
102
102
  }
103
- /** The words that say where work is kept, while the Library does not answer. */
104
- export const KEPT = 'Kept in this browser · Saving to Library when it’s available';
105
103
  let shelf = null;
106
104
  const shelfListeners = new Set();
107
105
  /**
108
106
  * Whether the person's Library answers: asked once, and on the first yes
109
- * whatever was kept only in this browser is carried up to it.
107
+ * every made file this browser still holds is carried up to it and dropped here.
110
108
  */
111
109
  export function useLibrary(w) {
112
110
  const [, bump] = useState(0);
package/lib/made.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  export type KindId = 'image' | 'poster' | 'document' | 'slides' | 'type' | 'mesh' | 'video' | 'voice' | 'music' | 'ad';
2
- export declare const KINDS: readonly KindId[];
3
2
  export interface Stored {
4
3
  /** The full key in the bucket. */
5
4
  key: string;
@@ -61,15 +60,3 @@ export declare const current: (m: Made) => Version;
61
60
  export declare const dir: (chat: string, m: Pick<Made, 'id' | 'kind'>, version: string) => string;
62
61
  /** A file name a person reads: the title, slugged, and the extension. */
63
62
  export declare function filename(title: string, ext: string): string;
64
- /** A library entry, read from a key under files/. */
65
- export interface Shelved {
66
- kind: KindId;
67
- chat: string;
68
- made: string;
69
- version: string;
70
- name: string;
71
- key: string;
72
- modified: number;
73
- size: number;
74
- }
75
- export declare function shelved(key: string, modified: number, size: number): Shelved | null;
package/lib/made.js CHANGED
@@ -12,7 +12,6 @@
12
12
  * the conversation that made it.
13
13
  */
14
14
  import { fresh } from './route.js';
15
- export const KINDS = ['image', 'poster', 'document', 'slides', 'type', 'mesh', 'video', 'voice', 'music', 'ad'];
16
15
  export const blank = (id = fresh()) => ({ id, title: 'New creation', created: Date.now(), updated: Date.now(), turns: [], made: [] });
17
16
  /** The version a made thing shows. */
18
17
  export const current = (m) => m.versions[Math.min(Math.max(0, m.at), m.versions.length - 1)];
@@ -27,10 +26,3 @@ export function filename(title, ext) {
27
26
  .slice(0, 60);
28
27
  return `${base || 'untitled'}.${ext}`;
29
28
  }
30
- export function shelved(key, modified, size) {
31
- const [kind, chat, made, version, ...rest] = key.split('/');
32
- const name = rest.join('/');
33
- if (!kind || !chat || !made || !version || !name || !KINDS.includes(kind))
34
- return null;
35
- return { kind: kind, chat, made, version, name, key: `files/${key}`, modified, size };
36
- }
package/lib/places.js CHANGED
@@ -9,13 +9,11 @@ import { Download, Search, Trash2 } from '@hanzogui/lucide-icons-2';
9
9
  import { useEffect, useMemo, useState } from 'react';
10
10
  import { useHost } from './host.js';
11
11
  import { ALL, kind } from './kinds/index.js';
12
- import { KEPT, useAvailable, useChats, useLibrary, useWire } from './live.js';
13
- import { shelved } from './made.js';
12
+ import { useAvailable, useChats, useLibrary, useWire } from './live.js';
14
13
  import { path } from './route.js';
15
14
  import { CATEGORIES, RUNTIME, STARTERS } from './starters.js';
16
15
  import { Act, download, Pill } from './ui.js';
17
- import { useUrl } from './use.js';
18
- import { ask, list, read, remove } from './wire.js';
16
+ import { ask, discard, shelf } from './wire.js';
19
17
  /** A starter handed from Explore to the conversation it starts. */
20
18
  let queued = null;
21
19
  export const queue = (s) => {
@@ -29,6 +27,9 @@ export const take = () => {
29
27
  function Page({ title, children, right }) {
30
28
  return (_jsx(YStack, { flex: 1, minH: 0, overflow: "scroll", bg: "var(--pane-fill, var(--sheet-1))", rounded: "var(--pane-round, var(--radius-xl))", borderWidth: 1, borderColor: "var(--pane-edge, var(--white-08))", children: _jsxs(YStack, { width: "100%", maxW: 1160, mx: "auto", p: "$4", gap: "$4", children: [_jsxs(XStack, { items: "center", gap: "$3", flexWrap: "wrap", children: [_jsx(SizableText, { render: "h1", size: "$7", fontWeight: "600", flex: 1, children: title }), right] }), children] }) }));
31
29
  }
30
+ /* ----------------------------------------------------------------- library */
31
+ /** The Studio kind whose mark a Library kind wears. */
32
+ const MARK = { image: 'image', video: 'video', audio: 'voice', document: 'document', slides: 'slides', type: 'type', model: 'mesh' };
32
33
  export function Library() {
33
34
  const host = useHost();
34
35
  const wire = useWire(host);
@@ -36,48 +37,29 @@ export function Library() {
36
37
  const [error, setError] = useState('');
37
38
  const [only, setOnly] = useState('all');
38
39
  const [q, setQ] = useState('');
39
- const shelf = useLibrary(wire);
40
+ useLibrary(wire);
40
41
  const reload = () => {
41
42
  setError('');
42
- list(wire, 'files/').then((entries) => {
43
- const by = new Map();
44
- for (const e of entries) {
45
- const s = shelved(e.key, e.modified, e.size);
46
- if (!s || s.made === 'attached')
47
- continue;
48
- const id = `${s.chat}/${s.made}`;
49
- const it = by.get(id) ?? { kind: s.kind, chat: s.chat, made: s.made, files: [], modified: 0 };
50
- // The newest version's files stand for the thing.
51
- const newest = it.files[0]?.version;
52
- if (!newest || s.version > newest)
53
- it.files = [s, ...it.files.filter((f) => f.version === s.version)];
54
- else if (s.version === newest)
55
- it.files.push(s);
56
- it.modified = Math.max(it.modified, s.modified);
57
- by.set(id, it);
58
- }
59
- setItems([...by.values()].sort((a, b) => b.modified - a.modified));
60
- }, (e) => setError(e instanceof Error ? e.message : String(e)));
43
+ shelf(wire).then(setItems, (e) => setError(e instanceof Error ? e.message : String(e)));
61
44
  };
62
45
  useEffect(reload, [wire]);
63
46
  const kinds = useMemo(() => [...new Set((items ?? []).map((i) => i.kind))], [items]);
64
- const shown = (items ?? []).filter((i) => (only === 'all' || i.kind === only) && (!q || i.files.some((f) => f.name.toLowerCase().includes(q.toLowerCase()))));
65
- return (_jsxs(Page, { title: "Library", right: _jsxs(XStack, { items: "center", gap: "$2", height: 34, px: "$3", rounded: 999, borderWidth: 1, borderColor: "$borderColor", minW: 220, children: [_jsx(Search, { size: 14 }), _jsx("input", { "aria-label": "Search the library", placeholder: "Search", value: q, onChange: (e) => setQ(e.currentTarget.value), style: { flex: 1, border: 0, background: 'transparent', color: 'inherit', font: 'inherit', outline: 'none' } })] }), children: [_jsx(SizableText, { size: "$2", color: "$soft", children: shelf ? 'Saved to your Library, private to you until you share it.' : KEPT }), _jsxs(XStack, { gap: "$2", flexWrap: "wrap", role: "toolbar", "aria-label": "Kinds", children: [_jsx(Pill, { on: only === 'all', onPress: () => setOnly('all'), children: "All" }), kinds.map((k) => (_jsx(Pill, { on: only === k, onPress: () => setOnly(k), children: kind(k).label }, k)))] }), error ? _jsx(SizableText, { color: "$red10", children: error }) : null, items === null && !error ? _jsx(SizableText, { color: "$soft", children: "Reading\u2026" }) : null, items && !shown.length ? _jsx(SizableText, { color: "$soft", children: items.length ? 'Nothing matches.' : 'Nothing made yet. Start on the home page.' }) : null, _jsx(XStack, { flexWrap: "wrap", gap: 12, role: "list", "aria-label": "Made", children: shown.map((i) => (_jsx(Thing, { wire: wire, item: i, onOpen: () => host.go(path({ kind: 'chat', id: i.chat })), onGone: reload }, `${i.chat}/${i.made}`))) })] }));
47
+ const shown = (items ?? []).filter((i) => (only === 'all' || i.kind === only) && (!q || i.name.toLowerCase().includes(q.toLowerCase())));
48
+ return (_jsxs(Page, { title: "Library", right: _jsxs(XStack, { items: "center", gap: "$2", height: 34, px: "$3", rounded: 999, borderWidth: 1, borderColor: "$borderColor", minW: 220, children: [_jsx(Search, { size: 14 }), _jsx("input", { "aria-label": "Search the library", placeholder: "Search", value: q, onChange: (e) => setQ(e.currentTarget.value), style: { flex: 1, border: 0, background: 'transparent', color: 'inherit', font: 'inherit', outline: 'none' } })] }), children: [_jsx(SizableText, { size: "$2", color: "$soft", children: "Saved to your Library, private to you until you share it." }), _jsxs(XStack, { gap: "$2", flexWrap: "wrap", role: "toolbar", "aria-label": "Kinds", children: [_jsx(Pill, { on: only === 'all', onPress: () => setOnly('all'), children: "All" }), kinds.map((k) => (_jsx(Pill, { on: only === k, onPress: () => setOnly(k), children: MARK[k] ? kind(MARK[k]).label : k }, k)))] }), error ? _jsx(SizableText, { color: "$red10", children: error }) : null, items === null && !error ? _jsx(SizableText, { color: "$soft", children: "Reading\u2026" }) : null, items && !shown.length ? _jsx(SizableText, { color: "$soft", children: items.length ? 'Nothing matches.' : 'Nothing made yet. Start on the home page.' }) : null, _jsx(XStack, { flexWrap: "wrap", gap: 12, role: "list", "aria-label": "Made", children: shown.map((i) => (_jsx(Thing, { wire: wire, item: i, onOpen: () => host.go(path({ kind: 'chat', id: i.ref })), onGone: reload }, i.id))) })] }));
66
49
  }
67
50
  function Thing({ wire, item, onOpen, onGone }) {
68
- const k = kind(item.kind);
69
- const Icon = k.icon;
70
- const pic = item.files.find((f) => /\.(png|jpe?g|webp)$/i.test(f.name));
71
- const { src } = useUrl(wire, pic?.key);
51
+ const Icon = kind(MARK[item.kind] ?? 'image').icon;
52
+ const pic = item.mime.startsWith('image/') ? item.url : '';
72
53
  const [busy, setBusy] = useState(false);
73
- const first = item.files.find((f) => !f.name.endsWith('.json')) ?? item.files[0];
74
- const name = first.name;
75
- return (_jsxs(YStack, { role: "listitem", width: "calc(50% - 6px)", $sm: { width: 'calc(25% - 9px)' }, gap: "$1.5", children: [_jsxs(YStack, { render: "button", "aria-label": `Open ${name} in its conversation`, onPress: onOpen, rounded: 16, overflow: "hidden", bg: "$hover", cursor: "pointer", style: { aspectRatio: '4 / 5' }, items: "center", justify: "center", position: "relative", children: [src ? _jsx("img", { src: src, alt: "", style: { position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' } }) : _jsx(Icon, { size: 28 }), _jsx(XStack, { position: "absolute", t: 8, l: 8, width: 26, height: 26, rounded: 99, bg: "rgba(0,0,0,0.55)", items: "center", justify: "center", children: _jsx(Icon, { size: 13 }) })] }), _jsxs(XStack, { items: "center", gap: "$1", children: [_jsx(SizableText, { size: "$2", fontWeight: "600", numberOfLines: 1, flex: 1, children: name.replace(/\.[a-z0-9.]+$/i, '').replace(/-/g, ' ') }), _jsx(Act, { label: `Download ${name}`, onPress: () => void read(wire, first.key).then((b) => download(name, b)), children: _jsx(Download, { size: 13 }) }), _jsx(Act, { label: `Delete ${name}`, disabled: busy, onPress: () => {
76
- if (!window.confirm(`Delete ${name} from the library? Its conversation keeps the record.`))
54
+ const name = item.name;
55
+ return (_jsxs(YStack, { role: "listitem", width: "calc(50% - 6px)", $sm: { width: 'calc(25% - 9px)' }, gap: "$1.5", children: [_jsxs(YStack, { render: "button", "aria-label": `Open ${name} in its conversation`, onPress: onOpen, rounded: 16, overflow: "hidden", bg: "$hover", cursor: "pointer", style: { aspectRatio: '4 / 5' }, items: "center", justify: "center", position: "relative", children: [pic ? _jsx("img", { src: pic, alt: "", style: { position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' } }) : _jsx(Icon, { size: 28 }), _jsx(XStack, { position: "absolute", t: 8, l: 8, width: 26, height: 26, rounded: 99, bg: "rgba(0,0,0,0.55)", items: "center", justify: "center", children: _jsx(Icon, { size: 13 }) })] }), _jsxs(XStack, { items: "center", gap: "$1", children: [_jsx(SizableText, { size: "$2", fontWeight: "600", numberOfLines: 1, flex: 1, children: name.replace(/\.[a-z0-9.]+$/i, '').replace(/-/g, ' ') }), _jsx(Act, { label: `Download ${name}`, onPress: () => void fetch(item.download || item.url, { credentials: 'omit' })
56
+ .then((r) => r.blob())
57
+ .then((b) => download(name, b)), children: _jsx(Download, { size: 13 }) }), _jsx(Act, { label: `Delete ${name}`, disabled: busy, onPress: () => {
58
+ if (!window.confirm(`Delete ${name} from your Library? Its conversation keeps the record.`))
77
59
  return;
78
60
  setBusy(true);
79
- void Promise.all(item.files.map((f) => remove(wire, f.key))).finally(onGone);
80
- }, children: _jsx(Trash2, { size: 13 }) })] }), _jsx(SizableText, { size: "$1", color: "$soft", mt: -4, children: `${k.label} · ${new Date(item.modified).toLocaleDateString()}` })] }));
61
+ void discard(wire, item.id).finally(onGone);
62
+ }, children: _jsx(Trash2, { size: 13 }) })] }), _jsx(SizableText, { size: "$1", color: "$soft", mt: -4, children: `${MARK[item.kind] ? kind(MARK[item.kind]).label : item.kind} · ${new Date(item.created).toLocaleDateString()}` })] }));
81
63
  }
82
64
  /* ----------------------------------------------------------------- explore */
83
65
  export function Explore() {
package/lib/talk.js CHANGED
@@ -24,7 +24,7 @@ import { MODELS, useImageLane, ZEN } from './kinds/image.js';
24
24
  import { ALL, kind } from './kinds/index.js';
25
25
  import { lit } from './kinds/kind.js';
26
26
  import { PRESETS } from './kinds/type/system.js';
27
- import { BRAIN, KEPT, touch, useAvailable, useLibrary, useWire, WRITER } from './live.js';
27
+ import { BRAIN, touch, useAvailable, useLibrary, useWire, WRITER } from './live.js';
28
28
  import { blank, current } from './made.js';
29
29
  import { take } from './places.js';
30
30
  import { path } from './route.js';
@@ -96,7 +96,7 @@ function Conversation({ start, host, wire, available }) {
96
96
  const [editing, setEditing] = useState({});
97
97
  const [editFailed, setEditFailed] = useState({});
98
98
  const wide = useMedia().md;
99
- const shelf = useLibrary(wire);
99
+ useLibrary(wire);
100
100
  const imaging = useImageLane();
101
101
  const [desk, setDesk] = usePanel('studio', true, wide);
102
102
  useKey(() => setDesk(!desk));
@@ -337,7 +337,7 @@ function Conversation({ start, host, wire, available }) {
337
337
  tools,
338
338
  mind: null,
339
339
  narrow: !wide,
340
- note: imaging ? `Image models are not answering (${imaging.reason}). Posters and ads are set in type until they are back.` : shelf === false ? KEPT : undefined,
340
+ note: imaging ? `Image models are not answering (${imaging.reason}). Posters and ads are set in type until they are back.` : undefined,
341
341
  });
342
342
  const deskPane = (sheet) => (_jsx(Panel, { side: deck, kinds: tabs, onHide: () => setDesk(false), sheet: sheet, label: "What this conversation made" }));
343
343
  return (_jsxs(XStack, { "data-slot": "studio-split", flex: 1, minH: 0, minW: 0, width: "100%", children: [_jsxs(YStack, { "data-slot": "studio-talk", ...pane, flex: 1, minH: 0, minW: 0, width: "100%", overflow: "hidden", children: [_jsxs(XStack, { px: "$4", pt: "$3", pb: "$2", gap: "$2", items: "center", minH: 44, children: [_jsx(SizableText, { render: "h1", size: "$5", color: "$ink", numberOfLines: 1, flex: 1, minW: 0, children: empty ? 'Studio' : chat.title }), chat.made.length ? _jsx(PanelToggle, { open: desk, onToggle: () => setDesk(!desk) }) : null] }), _jsx(Thread, { messages: messages, streaming: busy, send: (text) => void send(text), stop: working ? () => working.abort() : undefined, body: body, center: true, onFiles: (files) => void upload(files), empty: _jsx(Opening, {}), composer: { ...composer, foot: empty ? _jsx(Home, { available: available, onStart: begin }) : undefined } })] }), desk && chat.made.length && !wide ? deskPane(true) : null, desk && chat.made.length && wide ? (_jsxs(YStack, { "data-slot": "studio-desk", ref: (el) => {
package/lib/wire.d.ts CHANGED
@@ -132,13 +132,16 @@ export declare function draw(w: Wire, model: string, prompt: string, o?: {
132
132
  export declare function speak(w: Wire, input: string, voice: string, model: string, signal?: AbortSignal): Promise<Blob>;
133
133
  /** Whether api.hanzo.ai/v1/library answers for this person. */
134
134
  export declare function libraryLive(w: Wire): Promise<boolean>;
135
- /** Keep bytes at a key. Answers the key. */
135
+ /** Keep bytes at a key: a made file in the Library, anything else in this browser. Answers the key. */
136
136
  export declare function put(w: Wire, key: string, blob: Blob): Promise<string>;
137
- /** Carry up to the Library whatever is kept only here. Answers how many went. */
137
+ /**
138
+ * Carry up to the Library every made file this browser still holds the bytes
139
+ * of, and drop them here once the Library has them. Answers how many went.
140
+ */
138
141
  export declare function sync(w: Wire): Promise<number>;
139
142
  /** An address a page can draw a kept file at. */
140
143
  export declare function url(w: Wire, key: string): Promise<string>;
141
- /** A kept file's bytes. */
144
+ /** A kept file's bytes: from this page, this browser, or the Library. */
142
145
  export declare function read(w: Wire, key: string): Promise<Blob>;
143
146
  export interface Entry {
144
147
  /** Relative to the prefix listed. */
@@ -146,15 +149,32 @@ export interface Entry {
146
149
  size: number;
147
150
  /** Unix milliseconds. */
148
151
  modified: number;
149
- /** Whether it is saved in the Library too. */
150
- shelved: boolean;
151
152
  }
152
153
  /** What is kept under a prefix (one that ends in '/'), keys relative to it. */
153
154
  export declare function list(w: Wire, prefix: string): Promise<Entry[]>;
155
+ /** Delete a kept file: its Library item and bytes first, then this browser's record. */
154
156
  export declare function remove(w: Wire, key: string): Promise<void>;
155
157
  /** A kept JSON document, or null when there is none. */
156
158
  export declare function load<T>(w: Wire, key: string): Promise<T | null>;
157
159
  export declare const save: (w: Wire, key: string, value: unknown) => Promise<string>;
160
+ export interface Shelf {
161
+ id: string;
162
+ kind: string;
163
+ name: string;
164
+ mime: string;
165
+ bytes: number;
166
+ ref: string;
167
+ origin: string;
168
+ url: string;
169
+ download: string;
170
+ preview: string;
171
+ created: string;
172
+ shared: boolean;
173
+ }
174
+ /** Every Studio item in the person's Library, read a page at a time. */
175
+ export declare function shelf(w: Wire, signal?: AbortSignal): Promise<Shelf[]>;
176
+ /** Delete one item from the Library, and this browser's record of it. */
177
+ export declare function discard(w: Wire, id: string): Promise<void>;
158
178
  export interface Node {
159
179
  identity: string;
160
180
  name?: string;
package/lib/wire.js CHANGED
@@ -304,6 +304,8 @@ function tx(d, mode, run) {
304
304
  });
305
305
  }
306
306
  const get = async (w, key) => (await tx(await db(w), 'readonly', (s) => s.get(key))) ?? null;
307
+ const keep = async (w, r) => void (await tx(await db(w), 'readwrite', (s) => s.put(r)));
308
+ const all = async (w) => tx(await db(w), 'readonly', (s) => s.getAll());
307
309
  /* The Library: answered or not, asked once per page. */
308
310
  let library = null;
309
311
  /** Whether api.hanzo.ai/v1/library answers for this person. */
@@ -314,7 +316,11 @@ export function libraryLive(w) {
314
316
  });
315
317
  return library.catch(() => false);
316
318
  }
319
+ /** The most a browser may send the Library in one save (its inline limit). */
320
+ const INLINE = 10 * 1024 * 1024;
317
321
  const KINDS_LIB = { image: 'image', poster: 'image', ad: 'image', video: 'video', voice: 'audio', music: 'audio', document: 'document', slides: 'slides', type: 'type', mesh: 'model' };
322
+ /** Whether a key and its bytes belong in the Library: a made file the Library can take from a browser. */
323
+ const shelvable = (key, blob) => key.startsWith('files/') && key.split('/').length > 3 && blob.size <= INLINE;
318
324
  const base64 = async (b) => {
319
325
  const buf = new Uint8Array(await b.arrayBuffer());
320
326
  let bin = '';
@@ -322,97 +328,127 @@ const base64 = async (b) => {
322
328
  bin += String.fromCharCode(...buf.subarray(i, i + 0x8000));
323
329
  return btoa(bin);
324
330
  };
325
- /** Save one kept file to the Library, idempotently (its key is the idempotency key). */
326
- async function shelve(w, r) {
327
- const [, kind, chat] = r.key.split('/');
328
- if (!r.key.startsWith('files/') || !kind || !chat || r.blob.size > 10 * 1024 * 1024)
329
- return undefined;
331
+ /** Save one made file to the Library. Answers its item; the key makes a repeat the same item. */
332
+ async function shelve(w, key, blob) {
333
+ const [, kind, chat] = key.split('/');
330
334
  const item = await ask(w, 'api', '/v1/library', {
331
335
  body: {
332
- name: r.key.split('/').pop(),
333
- mime: r.mime,
334
- data: await base64(r.blob),
336
+ name: key.split('/').pop(),
337
+ mime: blob.type || 'application/octet-stream',
338
+ data: await base64(blob),
335
339
  source: 'studio',
336
340
  kind: KINDS_LIB[kind] ?? 'file',
337
341
  ref: chat,
338
342
  origin: `/studio/c/${chat}`,
339
- key: r.key,
343
+ key,
340
344
  },
341
345
  });
346
+ if (!item.id)
347
+ throw new Refusal(502, 'The Library took the file and named no item.');
342
348
  return item.id;
343
349
  }
344
- /** Keep bytes at a key. Answers the key. */
350
+ /** What this page made or read, held for its life: a file is never fetched twice. */
351
+ const held = new Map();
352
+ /** Keep bytes at a key: a made file in the Library, anything else in this browser. Answers the key. */
345
353
  export async function put(w, key, blob) {
346
- const r = { key, blob, mime: blob.type || 'application/octet-stream', modified: Date.now() };
347
- if (key.startsWith('files/') && (await libraryLive(w)))
348
- r.lib = await shelve(w, r).catch(() => undefined);
349
- await tx(await db(w), 'readwrite', (s) => s.put(r));
350
- shown.delete(key);
354
+ const r = { key, mime: blob.type || 'application/octet-stream', size: blob.size, modified: Date.now() };
355
+ const lib = shelvable(key, blob) && (await libraryLive(w)) ? await shelve(w, key, blob).catch(() => undefined) : undefined;
356
+ await keep(w, lib ? { ...r, lib } : { ...r, blob });
357
+ held.set(key, blob);
358
+ forget(key);
351
359
  return key;
352
360
  }
353
- /** Carry up to the Library whatever is kept only here. Answers how many went. */
361
+ /**
362
+ * Carry up to the Library every made file this browser still holds the bytes
363
+ * of, and drop them here once the Library has them. Answers how many went.
364
+ */
354
365
  export async function sync(w) {
355
366
  if (!(await libraryLive(w)))
356
367
  return 0;
357
- const all = await tx(await db(w), 'readonly', (s) => s.getAll());
358
368
  let n = 0;
359
- for (const r of all.filter((x) => x.key.startsWith('files/') && !x.lib)) {
360
- const lib = await shelve(w, r).catch(() => undefined);
369
+ for (const r of await all(w)) {
370
+ if (!r.blob || !shelvable(r.key, r.blob))
371
+ continue;
372
+ const lib = r.lib ?? (await shelve(w, r.key, r.blob).catch(() => undefined));
361
373
  if (!lib)
362
374
  continue;
363
- await tx(await db(w), 'readwrite', (s) => s.put({ ...r, lib }));
375
+ const { blob, ...rest } = r;
376
+ await keep(w, { ...rest, size: blob.size, lib });
364
377
  n++;
365
378
  }
366
379
  return n;
367
380
  }
368
381
  /** Addresses handed out, kept while they work: an object URL for the page's life, a Library URL until it expires. */
369
382
  const shown = new Map();
383
+ function forget(key) {
384
+ const hit = shown.get(key);
385
+ if (hit?.url.startsWith('blob:'))
386
+ URL.revokeObjectURL(hit.url);
387
+ shown.delete(key);
388
+ }
370
389
  /** An address a page can draw a kept file at. */
371
390
  export async function url(w, key) {
372
391
  const hit = shown.get(key);
373
392
  if (hit && hit.until > Date.now())
374
393
  return hit.url;
375
- const r = await get(w, key);
376
- if (!r)
377
- throw new Refusal(404, 'This file is not kept in this browser.');
378
- if (r.lib) {
379
- const item = await ask(w, 'api', `/v1/library/${enc(r.lib)}`).catch(() => null);
380
- if (item?.url) {
381
- shown.set(key, { url: item.url, until: item.expires ? Date.parse(item.expires) - 60_000 : Date.now() + 240_000 });
382
- return item.url;
383
- }
394
+ const local = held.get(key) ?? (await get(w, key))?.blob;
395
+ if (local) {
396
+ const made = URL.createObjectURL(local);
397
+ shown.set(key, { url: made, until: Number.POSITIVE_INFINITY });
398
+ return made;
384
399
  }
385
- const made = URL.createObjectURL(r.blob);
386
- shown.set(key, { url: made, until: Number.POSITIVE_INFINITY });
387
- return made;
400
+ const r = await get(w, key);
401
+ if (!r?.lib)
402
+ throw new Refusal(404, 'This file is not in your Library.');
403
+ const item = await ask(w, 'api', `/v1/library/${enc(r.lib)}`);
404
+ if (!item.url)
405
+ throw new Refusal(502, 'The Library named no address for the file.');
406
+ shown.set(key, { url: item.url, until: item.expires ? Date.parse(item.expires) - 60_000 : Date.now() + 240_000 });
407
+ return item.url;
388
408
  }
389
- /** A kept file's bytes. */
409
+ /** A kept file's bytes: from this page, this browser, or the Library. */
390
410
  export async function read(w, key) {
411
+ const hit = held.get(key);
412
+ if (hit)
413
+ return hit;
391
414
  const r = await get(w, key);
392
415
  if (!r)
393
- throw new Refusal(404, 'This file is not kept in this browser.');
394
- return r.blob;
416
+ throw new Refusal(404, 'This file is not in your Library.');
417
+ if (r.blob)
418
+ return r.blob;
419
+ const res = await fetch(await url(w, key), { cache: 'no-store', credentials: 'omit' });
420
+ if (!res.ok)
421
+ throw new Refusal(res.status, 'The Library would not hand the file back.');
422
+ const b = await res.blob();
423
+ held.set(key, b);
424
+ return b;
395
425
  }
396
426
  /** What is kept under a prefix (one that ends in '/'), keys relative to it. */
397
427
  export async function list(w, prefix) {
398
428
  const range = IDBKeyRange.bound(prefix, `${prefix}￿`);
399
- const all = await tx(await db(w), 'readonly', (s) => s.getAll(range));
400
- return all.map((r) => ({ key: r.key.slice(prefix.length), size: r.blob.size, modified: r.modified, shelved: Boolean(r.lib) }));
429
+ const rows = await tx(await db(w), 'readonly', (s) => s.getAll(range));
430
+ return rows.map((r) => ({ key: r.key.slice(prefix.length), size: r.size ?? r.blob?.size ?? 0, modified: r.modified }));
401
431
  }
432
+ /** Delete a kept file: its Library item and bytes first, then this browser's record. */
402
433
  export async function remove(w, key) {
403
434
  const r = await get(w, key);
404
435
  if (r?.lib)
405
- await ask(w, 'api', `/v1/library/${enc(r.lib)}`, { method: 'DELETE' }).catch(() => undefined);
436
+ await unshelve(w, r.lib);
406
437
  await tx(await db(w), 'readwrite', (s) => s.delete(key));
407
- const hit = shown.get(key);
408
- if (hit?.url.startsWith('blob:'))
409
- URL.revokeObjectURL(hit.url);
410
- shown.delete(key);
438
+ held.delete(key);
439
+ forget(key);
440
+ }
441
+ /** Delete one Library item. One already gone is gone. */
442
+ async function unshelve(w, id) {
443
+ await ask(w, 'api', `/v1/library/${enc(id)}`, { method: 'DELETE' }).catch((e) => {
444
+ if (!(e instanceof Refusal && e.status === 404))
445
+ throw e;
446
+ });
411
447
  }
412
448
  /** A kept JSON document, or null when there is none. */
413
449
  export async function load(w, key) {
414
450
  const r = await get(w, key);
415
- if (!r)
451
+ if (!r?.blob)
416
452
  return null;
417
453
  try {
418
454
  return JSON.parse(await r.blob.text());
@@ -422,6 +458,24 @@ export async function load(w, key) {
422
458
  }
423
459
  }
424
460
  export const save = (w, key, value) => put(w, key, new Blob([JSON.stringify(value)], { type: 'application/json' }));
461
+ /** Every Studio item in the person's Library, read a page at a time. */
462
+ export async function shelf(w, signal) {
463
+ const out = [];
464
+ let cursor = '';
465
+ do {
466
+ const page = await ask(w, 'api', `/v1/library${query({ source: 'studio', scope: 'mine', limit: 200, cursor })}`, { signal });
467
+ out.push(...(page.data ?? []));
468
+ cursor = page.next ?? '';
469
+ } while (cursor);
470
+ return out;
471
+ }
472
+ /** Delete one item from the Library, and this browser's record of it. */
473
+ export async function discard(w, id) {
474
+ await unshelve(w, id);
475
+ for (const r of await all(w))
476
+ if (r.lib === id)
477
+ await tx(await db(w), 'readwrite', (s) => s.delete(r.key));
478
+ }
425
479
  /** The org's GPUs and what each can run. A fleet the engine cannot read is an error, never an empty fleet. */
426
480
  export const gpus = (w, signal) => ask(w, 'engine', '/v1/gpu-status', { signal });
427
481
  /** Dispatch a lane to the org's GPUs (the engine's one funnel). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hanzo/studio",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "type": "module",
5
5
  "license": "BSD-3-Clause",
6
6
  "description": "Hanzo Studio: a chat that makes images, posters, documents, slides, type systems, 3D, video and sound, with every result open in a tab beside it. Mounted by the Hanzo app at hanzo.ai/studio and served whole at studio.hanzo.ai.",