@gradio/client 2.4.0 → 2.5.1

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.
package/dist/index.js CHANGED
@@ -1428,6 +1428,307 @@ function readable_stream(input, init = {}) {
1428
1428
  return instance;
1429
1429
  }
1430
1430
  //#endregion
1431
+ //#region src/utils/run_history.ts
1432
+ var KEY_ROOT = "gradio:run-history:";
1433
+ var STORAGE_PREFIX = `${KEY_ROOT}v2:`;
1434
+ var REPLAY_PREFIX = `${KEY_ROOT}replay:v2:`;
1435
+ var MAX_RUNS = 100;
1436
+ var MAX_APPS = 8;
1437
+ /**
1438
+ * Run history is a side effect of submitting, never the point of it, so no
1439
+ * failure in here may propagate into the caller and break the app. Every
1440
+ * exported function routes through this.
1441
+ */
1442
+ function safely(operation, fallback) {
1443
+ try {
1444
+ return operation();
1445
+ } catch (error) {
1446
+ console.warn("Could not update the run history.", error);
1447
+ return fallback;
1448
+ }
1449
+ }
1450
+ /**
1451
+ * The URL of the run history page for an app. `root` never carries a trailing
1452
+ * slash, so it cannot simply be concatenated with the path.
1453
+ */
1454
+ function run_history_url(root, api_prefix = "/gradio_api") {
1455
+ return `${root.replace(/\/+$/, "")}${api_prefix}/runs`;
1456
+ }
1457
+ function storage_key(scope) {
1458
+ if (typeof window === "undefined") return null;
1459
+ const app_id = scope?.app_id;
1460
+ if (app_id === null || app_id === void 0 || app_id === "") return null;
1461
+ try {
1462
+ if (!window.localStorage) return null;
1463
+ return `${STORAGE_PREFIX}${app_id}${scope?.username ? `:user:${encodeURIComponent(scope.username)}` : ""}`;
1464
+ } catch {
1465
+ return null;
1466
+ }
1467
+ }
1468
+ function replay_key(scope) {
1469
+ const key = storage_key(scope);
1470
+ return key ? key.replace(STORAGE_PREFIX, REPLAY_PREFIX) : null;
1471
+ }
1472
+ /** When a run was most recently saved under a key, for deciding what to drop. */
1473
+ function last_saved_at(key) {
1474
+ try {
1475
+ const runs = JSON.parse(window.localStorage.getItem(key) || "[]");
1476
+ return Array.isArray(runs) && runs.length ? Date.parse(runs[0]?.started_at) || 0 : 0;
1477
+ } catch {
1478
+ return 0;
1479
+ }
1480
+ }
1481
+ /**
1482
+ * Drops the histories of long-gone app instances. Every restart mints a new app
1483
+ * id, so without this the browser would keep every history an app ever had and
1484
+ * eventually run out of room for the current one.
1485
+ */
1486
+ function prune_apps(current_key) {
1487
+ const keys = Object.keys(window.localStorage).filter((key) => key.startsWith(KEY_ROOT));
1488
+ const stale = [...keys.filter((key) => !key.startsWith(STORAGE_PREFIX) && !key.startsWith(REPLAY_PREFIX)), ...keys.filter((key) => key.startsWith(STORAGE_PREFIX) && key !== current_key).sort((a, b) => last_saved_at(b) - last_saved_at(a)).slice(MAX_APPS - 1)];
1489
+ for (const key of stale) try {
1490
+ window.localStorage.removeItem(key);
1491
+ window.sessionStorage.removeItem(key.replace(STORAGE_PREFIX, REPLAY_PREFIX));
1492
+ } catch {}
1493
+ }
1494
+ function make_id() {
1495
+ if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID();
1496
+ return `${Date.now()}-${Math.random().toString(36).slice(2)}`;
1497
+ }
1498
+ function clone_for_storage(value) {
1499
+ const seen = /* @__PURE__ */ new WeakSet();
1500
+ try {
1501
+ return JSON.parse(JSON.stringify(value, (_key, item) => {
1502
+ if (typeof item === "bigint") return item.toString();
1503
+ if (typeof item === "object" && item !== null) {
1504
+ if (seen.has(item)) return "[Circular]";
1505
+ seen.add(item);
1506
+ }
1507
+ return item;
1508
+ }));
1509
+ } catch {
1510
+ return "[Unserializable value]";
1511
+ }
1512
+ }
1513
+ function read_run_history_impl(scope) {
1514
+ const key = storage_key(scope);
1515
+ if (!key) return [];
1516
+ try {
1517
+ const value = JSON.parse(window.localStorage.getItem(key) || "[]");
1518
+ return Array.isArray(value) ? value : [];
1519
+ } catch {
1520
+ return [];
1521
+ }
1522
+ }
1523
+ function write_run_history(scope, runs) {
1524
+ const key = storage_key(scope);
1525
+ if (!key) return;
1526
+ let next = runs.slice(0, MAX_RUNS);
1527
+ let pruned = false;
1528
+ while (next.length > 0) try {
1529
+ window.localStorage.setItem(key, JSON.stringify(next));
1530
+ return;
1531
+ } catch {
1532
+ if (!pruned) {
1533
+ pruned = true;
1534
+ prune_apps(key);
1535
+ continue;
1536
+ }
1537
+ next = next.slice(0, -1);
1538
+ }
1539
+ try {
1540
+ window.localStorage.removeItem(key);
1541
+ } catch {}
1542
+ }
1543
+ function clear_run_history_impl(scope) {
1544
+ const key = storage_key(scope);
1545
+ if (!key) return;
1546
+ try {
1547
+ window.localStorage.removeItem(key);
1548
+ } catch {}
1549
+ notify_run_history_change();
1550
+ }
1551
+ function delete_run_history_impl(scope, id) {
1552
+ write_run_history(scope, read_run_history_impl(scope).filter((run) => run.id !== id));
1553
+ notify_run_history_change();
1554
+ }
1555
+ var CHANGE_EVENT = "gradio:run-history-change";
1556
+ function notify_run_history_change() {
1557
+ if (typeof window === "undefined") return;
1558
+ try {
1559
+ window.dispatchEvent(new Event(CHANGE_EVENT));
1560
+ } catch {}
1561
+ }
1562
+ /**
1563
+ * Subscribes to runs being added, deleted or cleared. `storage` covers other
1564
+ * tabs; the custom event covers this one, which `storage` never fires for.
1565
+ * Only counts change, not per-run progress, so listeners stay cheap.
1566
+ *
1567
+ * @returns a function that unsubscribes.
1568
+ */
1569
+ function on_run_history_change_impl(listener) {
1570
+ if (typeof window === "undefined") return () => {};
1571
+ window.addEventListener(CHANGE_EVENT, listener);
1572
+ window.addEventListener("storage", listener);
1573
+ return () => {
1574
+ window.removeEventListener(CHANGE_EVENT, listener);
1575
+ window.removeEventListener("storage", listener);
1576
+ };
1577
+ }
1578
+ function stage_run_history_replay_impl(scope, run) {
1579
+ const key = replay_key(scope);
1580
+ if (!key) return;
1581
+ try {
1582
+ window.sessionStorage.setItem(key, JSON.stringify(run));
1583
+ } catch {}
1584
+ }
1585
+ function consume_run_history_replay_impl(scope) {
1586
+ const key = replay_key(scope);
1587
+ if (!key) return null;
1588
+ try {
1589
+ const value = window.sessionStorage.getItem(key);
1590
+ window.sessionStorage.removeItem(key);
1591
+ return value ? JSON.parse(value) : null;
1592
+ } catch {
1593
+ return null;
1594
+ }
1595
+ }
1596
+ function restore_run_impl(config, run) {
1597
+ const dependency = config.dependencies.find((item) => item.id === run.fn_index || typeof item.api_name === "string" && `/${item.api_name.replace(/^\//, "")}` === run.api_name);
1598
+ if (!dependency) return false;
1599
+ const inputs = Array.isArray(run.inputs) ? run.inputs : Object.values(run.inputs ?? {});
1600
+ const outputs = Array.isArray(run.outputs) ? run.outputs : run.outputs === null || run.outputs === void 0 ? [] : [run.outputs];
1601
+ const restore = (ids, saved) => {
1602
+ for (const [index, id] of ids.entries()) {
1603
+ const component = config.components.find((item) => item.id === id);
1604
+ if (!component || index >= saved.length) continue;
1605
+ if (component.type === "state") continue;
1606
+ component.props.value = saved[index];
1607
+ }
1608
+ };
1609
+ restore(dependency.inputs, inputs);
1610
+ restore(dependency.outputs, outputs);
1611
+ return true;
1612
+ }
1613
+ function apply_run_history_replay_impl(config) {
1614
+ const run = consume_run_history_replay_impl(config);
1615
+ return run ? restore_run_impl(config, run) : false;
1616
+ }
1617
+ function start_run_history_impl(options) {
1618
+ const key = storage_key(options);
1619
+ if (!key) return null;
1620
+ prune_apps(key);
1621
+ const run = {
1622
+ id: make_id(),
1623
+ endpoint: options.endpoint,
1624
+ api_name: options.api_name,
1625
+ fn_index: options.fn_index,
1626
+ page: `${window.location.pathname}${window.location.search}`,
1627
+ inputs: clone_for_storage(options.inputs),
1628
+ outputs: null,
1629
+ ...options.input_components ? { input_components: clone_for_storage(options.input_components) } : {},
1630
+ ...options.output_components ? { output_components: clone_for_storage(options.output_components) } : {},
1631
+ status: "running",
1632
+ started_at: (/* @__PURE__ */ new Date()).toISOString()
1633
+ };
1634
+ write_run_history(options, [run, ...read_run_history_impl(options)]);
1635
+ notify_run_history_change();
1636
+ return run.id;
1637
+ }
1638
+ function update_run_inputs_impl(scope, id, inputs) {
1639
+ if (!id) return;
1640
+ const runs = read_run_history_impl(scope);
1641
+ const run = runs.find((item) => item.id === id);
1642
+ if (!run) return;
1643
+ run.inputs = clone_for_storage(inputs);
1644
+ write_run_history(scope, runs);
1645
+ }
1646
+ function update_run_history_impl(scope, id, event) {
1647
+ if (!id) return;
1648
+ const runs = read_run_history_impl(scope);
1649
+ const run = runs.find((item) => item.id === id);
1650
+ if (!run) return;
1651
+ let finished = false;
1652
+ if (event.type === "data") {
1653
+ run.outputs = clone_for_storage(event.data);
1654
+ deferred_outputs.set(id, run.outputs);
1655
+ } else if (event.type === "status" && event.original_msg === "process_starts") mark_process_start(run, event.time);
1656
+ else if (event.type === "status" && (event.stage === "generating" || event.stage === "streaming")) run.streamed = true;
1657
+ else if (event.type === "status" && event.stage === "complete") {
1658
+ run.status = "completed";
1659
+ mark_complete(run, event);
1660
+ finished = true;
1661
+ } else if (event.type === "status" && event.stage === "error") {
1662
+ run.status = "failed";
1663
+ run.error = typeof event.message === "string" ? event.message : JSON.stringify(event.message || "Unknown error");
1664
+ mark_complete(run, event);
1665
+ finished = true;
1666
+ } else return;
1667
+ if (finished) {
1668
+ if (deferred_outputs.has(id)) run.outputs = deferred_outputs.get(id);
1669
+ deferred_outputs.delete(id);
1670
+ last_write.delete(id);
1671
+ } else if (run.streamed) {
1672
+ if (Date.now() - (last_write.get(id) ?? 0) < STREAM_WRITE_INTERVAL_MS) return;
1673
+ last_write.set(id, Date.now());
1674
+ deferred_outputs.delete(id);
1675
+ }
1676
+ write_run_history(scope, runs);
1677
+ }
1678
+ var STREAM_WRITE_INTERVAL_MS = 500;
1679
+ /** When each in-flight streamed run was last written. */
1680
+ var last_write = /* @__PURE__ */ new Map();
1681
+ /** The newest output of a streamed run that has not been written yet. */
1682
+ var deferred_outputs = /* @__PURE__ */ new Map();
1683
+ function mark_process_start(run, time) {
1684
+ if (run.process_started_at) return;
1685
+ const started = time || /* @__PURE__ */ new Date();
1686
+ run.process_started_at = started.toISOString();
1687
+ run.queued_ms = Math.max(0, started.getTime() - Date.parse(run.started_at));
1688
+ }
1689
+ function mark_complete(run, event) {
1690
+ const completed = event.time || /* @__PURE__ */ new Date();
1691
+ run.completed_at = completed.toISOString();
1692
+ run.duration_ms = (!run.streamed && typeof event.cache_duration === "number" && event.cache_duration >= 0 ? event.cache_duration * 1e3 : null) ?? Math.max(0, completed.getTime() - Date.parse(run.process_started_at || run.started_at));
1693
+ }
1694
+ function read_run_history(scope) {
1695
+ return safely(() => read_run_history_impl(scope), []);
1696
+ }
1697
+ function clear_run_history(scope) {
1698
+ safely(() => clear_run_history_impl(scope), void 0);
1699
+ }
1700
+ function delete_run_history(scope, id) {
1701
+ safely(() => delete_run_history_impl(scope, id), void 0);
1702
+ }
1703
+ function stage_run_history_replay(scope, run) {
1704
+ safely(() => stage_run_history_replay_impl(scope, run), void 0);
1705
+ }
1706
+ function consume_run_history_replay(scope) {
1707
+ return safely(() => consume_run_history_replay_impl(scope), null);
1708
+ }
1709
+ /**
1710
+ * Applies the run staged by the history page, if this page load is the one it
1711
+ * was staged for. Every entry point that renders an app has to call this, or
1712
+ * "Load run" silently does nothing on that entry point.
1713
+ *
1714
+ * @returns whether a staged run was found and applied.
1715
+ */
1716
+ function apply_run_history_replay(config) {
1717
+ return safely(() => apply_run_history_replay_impl(config), false);
1718
+ }
1719
+ function start_run_history(options) {
1720
+ return safely(() => start_run_history_impl(options), null);
1721
+ }
1722
+ function update_run_inputs(scope, id, inputs) {
1723
+ safely(() => update_run_inputs_impl(scope, id, inputs), void 0);
1724
+ }
1725
+ function update_run_history(scope, id, event) {
1726
+ safely(() => update_run_history_impl(scope, id, event), void 0);
1727
+ }
1728
+ function on_run_history_change(listener) {
1729
+ return safely(() => on_run_history_change_impl(() => safely(listener, void 0)), () => {});
1730
+ }
1731
+ //#endregion
1431
1732
  //#region src/utils/submit.ts
1432
1733
  function submit(endpoint, data = {}, event_data, trigger_id, all_events, additional_headers) {
1433
1734
  try {
@@ -1439,9 +1740,35 @@ function submit(endpoint, data = {}, event_data, trigger_id, all_events, additio
1439
1740
  if (!config) throw new Error("Could not resolve app config");
1440
1741
  let { fn_index, endpoint_info, dependency } = get_endpoint_info(api_info, endpoint, api_map, config);
1441
1742
  let resolved_data = map_data_to_params(data, endpoint_info);
1442
- let stream;
1443
1743
  let protocol = config.protocol ?? "ws";
1444
1744
  if (protocol === "ws") throw new Error(WS_PROTOCOL_MSG);
1745
+ const history_endpoint = typeof dependency.api_name === "string" ? `/${dependency.api_name}` : endpoint;
1746
+ const history_api_name = typeof dependency.api_name === "string" ? `/${dependency.api_name}` : `Function ${fn_index}`;
1747
+ const component_metadata = (id) => {
1748
+ const component = config.components.find((item) => item.id === id);
1749
+ if (!component) return null;
1750
+ return {
1751
+ type: component.type,
1752
+ component_class_id: component.component_class_id,
1753
+ props: component.props
1754
+ };
1755
+ };
1756
+ const is_documented_endpoint = dependency.api_visibility === "public";
1757
+ const history_enabled = config.run_history !== false && this.options.record_history !== false;
1758
+ const history_scope = {
1759
+ app_id: config.app_id,
1760
+ username: config.username
1761
+ };
1762
+ const history_run_id = !history_enabled || !is_documented_endpoint ? null : start_run_history({
1763
+ ...history_scope,
1764
+ endpoint: history_endpoint,
1765
+ api_name: history_api_name,
1766
+ fn_index,
1767
+ inputs: handle_payload(resolved_data, dependency, config.components, "input", true),
1768
+ input_components: dependency.inputs.map(component_metadata),
1769
+ output_components: dependency.outputs.map(component_metadata)
1770
+ });
1771
+ let stream;
1445
1772
  let event_id_final = "";
1446
1773
  const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
1447
1774
  let payload;
@@ -1454,6 +1781,7 @@ function submit(endpoint, data = {}, event_data, trigger_id, all_events, additio
1454
1781
  return acc;
1455
1782
  }, {}) || {};
1456
1783
  function fire_event(event) {
1784
+ update_run_history(history_scope, history_run_id, event);
1457
1785
  if (all_events || events_to_publish[event.type]) push_event(event);
1458
1786
  }
1459
1787
  async function cancel() {
@@ -1501,8 +1829,10 @@ function submit(endpoint, data = {}, event_data, trigger_id, all_events, additio
1501
1829
  });
1502
1830
  }
1503
1831
  const job = this.handle_blob(config.root, resolved_data, endpoint_info).then(async (_payload) => {
1832
+ let input_data = handle_payload(_payload, dependency, config.components, "input", true);
1833
+ update_run_inputs(history_scope, history_run_id, input_data || []);
1504
1834
  payload = {
1505
- data: handle_payload(_payload, dependency, config.components, "input", true) || [],
1835
+ data: input_data || [],
1506
1836
  event_data,
1507
1837
  fn_index,
1508
1838
  trigger_id,
@@ -2153,6 +2483,10 @@ var Client = class {
2153
2483
  async config_success(_config) {
2154
2484
  this.config = _config;
2155
2485
  this.api_prefix = _config.api_prefix || "";
2486
+ if (_config.run_history === false) clear_run_history({
2487
+ app_id: _config.app_id,
2488
+ username: _config.username
2489
+ });
2156
2490
  if (this.config.auth_required) return this.prepare_return_obj();
2157
2491
  try {
2158
2492
  this.api_info = await this.view_api();
@@ -2260,4 +2594,4 @@ async function duplicate_space(app_reference, options) {
2260
2594
  return await Client.duplicate(app_reference, options);
2261
2595
  }
2262
2596
  //#endregion
2263
- export { Client, FileData, MISSING_CREDENTIALS_MSG, client, duplicate_space as duplicate, handle_file, predict, prepare_files, submit, upload, upload_files };
2597
+ export { Client, FileData, MISSING_CREDENTIALS_MSG, apply_run_history_replay, clear_run_history, client, consume_run_history_replay, delete_run_history, duplicate_space as duplicate, handle_file, on_run_history_change, predict, prepare_files, read_run_history, run_history_url, stage_run_history_replay, submit, upload, upload_files };