pi-studio 0.11.8 → 0.11.9

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/CHANGELOG.md CHANGED
@@ -4,6 +4,15 @@ All notable changes to `pi-studio` are documented here.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.11.9] — 2026-11-03
8
+
9
+ ### Added
10
+ - The REPL pane shows the images and PDFs a record entry's code saved, such as a plot, as agent-markdown-preview's REPL page does. An image shows under the entry's output; click it to open Studio's image viewer. A PDF is a link that opens it in a new tab. A file shows when the entry's code or output names it (a path ending in `.png`, `.jpg`, `.gif`, `.webp`, `.svg` or `.pdf`, relative paths taken from the REPL's current directory) and it was written while the entry ran. A file saved again by a later entry shows under that entry instead. Up to six files show for each of a session's latest 12 entries. Studio serves only those files.
11
+
12
+ ### Changed
13
+ - The REPL pane's record has no description line under its heading.
14
+ - A PDF's header, on its card and in its enlarged view, shows **Auto-refresh** and **More**. More holds **Refresh now**, **Browser tab**, **System viewer**, **Show in folder** and **Copy path**, so the header fits on one line. The card's Enlarge is its icon alone, with Enlarge as its tooltip.
15
+
7
16
  ## [0.11.8] — 2026-11-03
8
17
 
9
18
  ### Changed
package/README.md CHANGED
@@ -136,7 +136,7 @@ Icons in exported PDFs need Mermaid CLI 11.12+ (`npm install -g @mermaid-js/merm
136
136
 
137
137
  ### REPL
138
138
 
139
- The REPL pane runs code in tmux sessions. It can start its own, and it shares a record of submissions and output with [pi-repl](https://github.com/omaclaren/pi-repl) when both use the same session. Pane echo sets how much submitted code goes into the raw tmux history, as in pi-repl: up to 20 lines with Summary, the default, up to 40 with Full, and none with Off. Your sends and notes are recorded under your name (**Sending as**, under Quick send). The agent is told of record entries it hasn't seen, such as your sends, other clients' sends and late output, when a run starts and with its REPL tools' results. The record format is in [`shared/REPL_SESSION_RECORD_PROTOCOL.md`](./shared/REPL_SESSION_RECORD_PROTOCOL.md).
139
+ The REPL pane runs code in tmux sessions. It can start its own, and it shares a record of submissions and output with [pi-repl](https://github.com/omaclaren/pi-repl) when both use the same session. Pane echo sets how much submitted code goes into the raw tmux history, as in pi-repl: up to 20 lines with Summary, the default, up to 40 with Full, and none with Off. Your sends and notes are recorded under your name (**Sending as**, under Quick send). An image or PDF an entry's code saved while it ran, such as a plot, shows under it when the code or output names it. The agent is told of record entries it hasn't seen, such as your sends, other clients' sends and late output, when a run starts and with its REPL tools' results. The record format is in [`shared/REPL_SESSION_RECORD_PROTOCOL.md`](./shared/REPL_SESSION_RECORD_PROTOCOL.md).
140
140
 
141
141
  ### Side questions
142
142
 
package/ROADMAP.md CHANGED
@@ -2,9 +2,18 @@
2
2
 
3
3
  This is the current planning source of truth for Studio work. `NEXT-STAGE.md` is historical; `TODO.md` tracks smaller backlog items that are not yet assigned to a release.
4
4
 
5
- ## Current status (14 Oct 2026)
5
+ ## Current status (3 Nov 2026)
6
6
 
7
- `0.10.0` ships the buffer-first workspace as **dual editor mode** (Prompt and Document), on by default, with **single editor mode** one switch away (footer button, `/studio --single`). It went through real course use as private alpha candidates 49–69. The `PI_STUDIO_*` flags described further down are now development overrides only: when any is set it decides, and the mode switch is hidden. Fixes follow in `0.10.x`. The sections below are the history up to this point.
7
+ `0.11.9` is the current release, and Studio is in a feature freeze from it, for use in normal work. Before the freeze, `0.11.9` added the images and PDFs a REPL entry's code saved, shown under the entry, and a PDF header that fits on one line. During the freeze, changes are limited to fixes for failures in normal use, lost data, effects on other people's processes or files, and security. [TODO.md](TODO.md) lists the known limits and what comes after the freeze.
8
+
9
+ `0.10.0` (14 Oct) made the buffer-first workspace the default, as **dual editor mode** (Prompt and Document), with **single editor mode** one switch away (footer button, `/studio --single`). It went through real course use as private alpha candidates 49–69. The `PI_STUDIO_*` flags described further down are development overrides only: when any is set it decides, and the mode switch is hidden.
10
+
11
+ The `0.11` releases brought the REPL pane up to pi-repl `0.11.7`: Ruby, Java, Octave, MATLAB, gnuplot and C++; sends and notes recorded under the sender's name; the record-directory key; and telling the agent what's new in the record. They also brought Working closer to agent-markdown-preview's. The [changelog](CHANGELOG.md) has each release. The sections below are the history up to `0.10.0`.
12
+
13
+ ### Parity at the freeze
14
+
15
+ - **pi-repl `0.11.7` and agent-repl `0.5.0`.** Studio's copies of the shared record, names, protocol, control-file, display, C++, gnuplot and M-language helpers are byte-identical to pi-repl's, and agent-repl carries the same record, names and protocol files. Two helpers differ: pi-repl generalised `repl-session-stop.js` and `repl-gnuplot-processes.js` for LFortran. Studio doesn't run LFortran, and won't paste into pi-repl's LFortran session ("This session takes code only through pi-repl").
16
+ - **pi-markdown-preview `0.26.2` and agent-markdown-preview `0.13.2`.** Their REPL page reads the same records with the same record-directory check. Both show the images and PDFs an entry's code saved, by the same rules: a file shows when the entry names it and it was written in that entry's turn. Studio has them from `0.11.9`; the preview packages' REPL page has its latest rules on an unreleased branch.
8
17
 
9
18
  ## Release approach
10
19
 
@@ -688,8 +688,6 @@
688
688
  error: "",
689
689
  };
690
690
  let replTmuxAvailable = null;
691
- // Whether the agent is told of new record entries ("on", "send" or "off"), from Studio's server.
692
- let replRecordActivity = "off";
693
691
  // The name this page's sends and notes are recorded under: chosen here and kept in this
694
692
  // browser, else the default from Studio's server (PI_REPL_USER_NAME, then pi-repl's saved
695
693
  // name, then "User"). Read once, so another tab choosing a name later leaves this page alone.
@@ -807,10 +805,20 @@
807
805
  beforeTranscript: "",
808
806
  status: typeof entry.status === "string" ? entry.status : "sent",
809
807
  skippedChunks: Math.max(0, Math.floor(Number(entry.skippedChunks) || 0)),
808
+ // Image and PDF files the entry names, as Studio found them when it sent it; not kept.
809
+ files: normalizeReplEntryFiles(entry.files),
810
810
  };
811
811
  return (normalized.code.trim() || normalized.prose.trim() || normalized.output.trim()) ? normalized : null;
812
812
  }
813
813
 
814
+ function normalizeReplEntryFiles(files) {
815
+ if (!Array.isArray(files)) return [];
816
+ return files.filter((file) => file && typeof file === "object" && typeof file.id === "string" && /^[0-9a-f]{64}$/.test(file.id)
817
+ && typeof file.written === "string" && file.written && typeof file.v === "string" && /^[0-9a-f]{16}$/.test(file.v))
818
+ .slice(0, 6)
819
+ .map((file) => ({ id: file.id, written: file.written.slice(0, 1024), image: file.image === true, v: file.v }));
820
+ }
821
+
814
822
  function loadPersistedReplJournalEntries() {
815
823
  try {
816
824
  const raw = window.localStorage ? window.localStorage.getItem("piStudio.replStudioEntries.v1") : null;
@@ -896,6 +904,8 @@
896
904
  let replJournalEntries = loadPersistedReplJournalEntries();
897
905
  let activeReplJournalEntryId = "";
898
906
  const replJournalImportPendingSessions = new Set();
907
+ // Whether the REPL view is kept at its bottom, as of its last draw or scroll, for thumbnails that load later.
908
+ let replViewStuckToBottom = false;
899
909
  let replJournalCollapsed = (() => {
900
910
  try {
901
911
  const stored = window.localStorage ? window.localStorage.getItem("piStudio.replStudioCollapsed") : null;
@@ -9686,7 +9696,6 @@
9686
9696
  event.preventDefault();
9687
9697
  event.stopPropagation();
9688
9698
  });
9689
- actions.appendChild(openLink);
9690
9699
 
9691
9700
  const systemViewerBtn = document.createElement("button");
9692
9701
  systemViewerBtn.type = "button";
@@ -9696,7 +9705,6 @@
9696
9705
  systemViewerBtn.addEventListener("click", () => {
9697
9706
  void runStudioPdfLocalAction("system-viewer", studioPdfFocusResourceQuery, systemViewerBtn, { isCurrent: studioPdfFocusIsCurrent });
9698
9707
  });
9699
- actions.appendChild(systemViewerBtn);
9700
9708
 
9701
9709
  const revealBtn = document.createElement("button");
9702
9710
  revealBtn.type = "button";
@@ -9706,7 +9714,6 @@
9706
9714
  revealBtn.addEventListener("click", () => {
9707
9715
  void runStudioPdfLocalAction("reveal", studioPdfFocusResourceQuery, revealBtn, { isCurrent: studioPdfFocusIsCurrent });
9708
9716
  });
9709
- actions.appendChild(revealBtn);
9710
9717
 
9711
9718
  const copyPathBtn = document.createElement("button");
9712
9719
  copyPathBtn.type = "button";
@@ -9716,16 +9723,14 @@
9716
9723
  copyPathBtn.addEventListener("click", () => {
9717
9724
  void copyStudioPdfResourcePath(studioPdfFocusResourceQuery, copyPathBtn, { isCurrent: studioPdfFocusIsCurrent });
9718
9725
  });
9719
- actions.appendChild(copyPathBtn);
9720
9726
 
9721
9727
  const refreshBtn = document.createElement("button");
9722
9728
  refreshBtn.type = "button";
9723
9729
  refreshBtn.className = "studio-pdf-focus-btn studio-pdf-focus-refresh";
9724
- refreshBtn.textContent = "Refresh";
9730
+ refreshBtn.textContent = "Refresh now";
9725
9731
  refreshBtn.title = "Reload this PDF preview from disk. Shortcut: Cmd/Ctrl+Option/Alt+Shift+R.";
9726
9732
  refreshBtn.setAttribute("aria-label", "Refresh PDF preview from disk");
9727
9733
  refreshBtn.addEventListener("click", () => refreshStudioPdfFocusViewer());
9728
- actions.appendChild(refreshBtn);
9729
9734
 
9730
9735
  const autoRefreshBtn = document.createElement("button");
9731
9736
  autoRefreshBtn.type = "button";
@@ -9736,6 +9741,7 @@
9736
9741
  autoRefreshBtn.setAttribute("aria-pressed", "false");
9737
9742
  autoRefreshBtn.addEventListener("click", () => toggleStudioPdfFocusAutoRefresh());
9738
9743
  actions.appendChild(autoRefreshBtn);
9744
+ actions.appendChild(createStudioPdfMoreMenu("focus", [refreshBtn, openLink, systemViewerBtn, revealBtn, copyPathBtn]));
9739
9745
 
9740
9746
  const fullscreenBtn = document.createElement("button");
9741
9747
  fullscreenBtn.type = "button";
@@ -9818,6 +9824,7 @@
9818
9824
  if (studioPdfFocusOpenLinkEl) studioPdfFocusOpenLinkEl.href = src;
9819
9825
  setStudioPdfFocusFrameSource(src, title, sourceFrame);
9820
9826
  if (document.body) document.body.classList.add("studio-pdf-focus-open");
9827
+ closeStudioPdfFocusMoreMenus();
9821
9828
  if (studioPdfFocusOverlayEl) studioPdfFocusOverlayEl.hidden = false;
9822
9829
  syncStudioBufferOpenOperation();
9823
9830
  syncStudioPdfFocusFullscreenButton();
@@ -9839,6 +9846,7 @@
9839
9846
  if (exitResult && typeof exitResult.catch === "function") exitResult.catch(() => {});
9840
9847
  } catch {}
9841
9848
  }
9849
+ closeStudioPdfFocusMoreMenus();
9842
9850
  if (studioPdfFocusOverlayEl) studioPdfFocusOverlayEl.hidden = true;
9843
9851
  restoreStudioPdfFocusMovedFrame();
9844
9852
  if (studioPdfFocusFrameEl) studioPdfFocusFrameEl.src = "about:blank";
@@ -9888,6 +9896,64 @@
9888
9896
  return query;
9889
9897
  }
9890
9898
 
9899
+ // A PDF's less frequent actions, under More as in the REPL pane: a manual refresh beside
9900
+ // Auto-refresh, and the one-off ways to take the PDF elsewhere (Oliver, candidate 117).
9901
+ function createStudioPdfMoreMenu(kind, items) {
9902
+ const details = document.createElement("details");
9903
+ details.className = "studio-pdf-more studio-pdf-" + kind + "-more";
9904
+ const summary = document.createElement("summary");
9905
+ summary.textContent = "More";
9906
+ summary.title = "More ways to refresh or open this PDF.";
9907
+ details.appendChild(summary);
9908
+ const menu = document.createElement("div");
9909
+ menu.className = "studio-pdf-more-menu";
9910
+ items.forEach((item) => {
9911
+ item.classList.add("studio-pdf-more-item");
9912
+ menu.appendChild(item);
9913
+ });
9914
+ // A chosen item closes the menu once its own click has run. The items stop their clicks
9915
+ // from bubbling, so this listens on the way down; the card's items are handled first, on
9916
+ // the document, by handleStudioPreviewMediaActivation, which closes their menu itself.
9917
+ menu.addEventListener("click", (event) => {
9918
+ if (event.target instanceof Element) dismissStudioPdfMoreMenuAfterChoice(event.target);
9919
+ }, true);
9920
+ // Keyboard focus leaving the menu, such as Tab past its last item, closes it, so an open
9921
+ // menu never sits behind a focused control whose Escape belongs to the view (Sol, c117).
9922
+ details.addEventListener("focusout", (event) => {
9923
+ if (details.open && event.relatedTarget instanceof Node && !details.contains(event.relatedTarget)) details.open = false;
9924
+ });
9925
+ // Escape closes the menu, not the view it's in.
9926
+ details.addEventListener("keydown", (event) => {
9927
+ if (event.key !== "Escape" || !details.open) return;
9928
+ event.preventDefault();
9929
+ event.stopPropagation();
9930
+ details.open = false;
9931
+ summary.focus();
9932
+ });
9933
+ details.appendChild(menu);
9934
+ return details;
9935
+ }
9936
+
9937
+ // A chosen item's menu closes once its click has been handled.
9938
+ function dismissStudioPdfMoreMenuAfterChoice(element) {
9939
+ const item = element && typeof element.closest === "function" ? element.closest(".studio-pdf-more-item") : null;
9940
+ const details = item ? item.closest("details.studio-pdf-more") : null;
9941
+ if (details) window.setTimeout(() => { details.open = false; }, 0);
9942
+ }
9943
+
9944
+ // The enlarged view starts and ends with its menu closed.
9945
+ function closeStudioPdfFocusMoreMenus() {
9946
+ if (!studioPdfFocusOverlayEl) return;
9947
+ studioPdfFocusOverlayEl.querySelectorAll("details.studio-pdf-more[open]").forEach((details) => { details.open = false; });
9948
+ }
9949
+
9950
+ // A press outside an open PDF menu closes it.
9951
+ document.addEventListener("pointerdown", (event) => {
9952
+ document.querySelectorAll("details.studio-pdf-more[open]").forEach((details) => {
9953
+ if (!(event.target instanceof Node) || !details.contains(event.target)) details.open = false;
9954
+ });
9955
+ }, true);
9956
+
9891
9957
  function syncStudioPdfAutoRefreshButton(button, enabled, available) {
9892
9958
  if (!button) return;
9893
9959
  const active = Boolean(enabled && available);
@@ -10477,6 +10543,8 @@
10477
10543
  const card = actionBtn.closest(".studio-pdf-card");
10478
10544
  if (!card) return;
10479
10545
  consumeStudioPreviewMediaEvent(event);
10546
+ // The card's More menu would never see this click, which ends here (Sol, Astra, c117).
10547
+ dismissStudioPdfMoreMenuAfterChoice(actionBtn);
10480
10548
  if (!studioPreviewNodeOwnerIsCurrent(actionBtn)) return;
10481
10549
  const interactionContext = buildStudioPreviewInteractionContext(actionBtn);
10482
10550
  if (!studioPreviewInteractionIsCurrent(interactionContext)) return;
@@ -11036,14 +11104,13 @@
11036
11104
  const focusBtn = document.createElement("button");
11037
11105
  focusBtn.type = "button";
11038
11106
  focusBtn.className = "studio-pdf-card-action studio-pdf-card-focus";
11039
- focusBtn.title = "Open this PDF in a larger Studio overlay.";
11107
+ focusBtn.title = "Enlarge";
11040
11108
  focusBtn.setAttribute("aria-label", "Enlarge PDF");
11041
11109
  if (focusBtn.dataset) {
11042
11110
  focusBtn.dataset.studioPdfViewerUrl = viewerUrl;
11043
11111
  focusBtn.dataset.studioPdfTitle = title;
11044
11112
  }
11045
11113
  focusBtn.appendChild(makeStudioUiRefreshIcon("focus"));
11046
- focusBtn.appendChild(document.createTextNode("Enlarge"));
11047
11114
  focusBtn.addEventListener("click", handleStudioPdfFocusButtonClick);
11048
11115
  titleGroup.appendChild(focusBtn);
11049
11116
  }
@@ -11069,7 +11136,6 @@
11069
11136
  event.preventDefault();
11070
11137
  event.stopPropagation();
11071
11138
  });
11072
- actions.appendChild(openLink);
11073
11139
 
11074
11140
  const systemViewerBtn = document.createElement("button");
11075
11141
  systemViewerBtn.type = "button";
@@ -11081,7 +11147,6 @@
11081
11147
  event.stopPropagation();
11082
11148
  void runStudioPdfLocalAction("system-viewer", resourceQuery, systemViewerBtn, { isCurrent });
11083
11149
  });
11084
- actions.appendChild(systemViewerBtn);
11085
11150
 
11086
11151
  const revealBtn = document.createElement("button");
11087
11152
  revealBtn.type = "button";
@@ -11093,7 +11158,6 @@
11093
11158
  event.stopPropagation();
11094
11159
  void runStudioPdfLocalAction("reveal", resourceQuery, revealBtn, { isCurrent });
11095
11160
  });
11096
- actions.appendChild(revealBtn);
11097
11161
 
11098
11162
  const copyPathBtn = document.createElement("button");
11099
11163
  copyPathBtn.type = "button";
@@ -11105,12 +11169,11 @@
11105
11169
  event.stopPropagation();
11106
11170
  void copyStudioPdfResourcePath(resourceQuery, copyPathBtn, { isCurrent });
11107
11171
  });
11108
- actions.appendChild(copyPathBtn);
11109
11172
 
11110
11173
  const refreshBtn = document.createElement("button");
11111
11174
  refreshBtn.type = "button";
11112
11175
  refreshBtn.className = "studio-pdf-card-action studio-pdf-card-refresh";
11113
- refreshBtn.textContent = "Refresh";
11176
+ refreshBtn.textContent = "Refresh now";
11114
11177
  refreshBtn.title = "Reload this PDF preview from disk. Shortcut: Cmd/Ctrl+Option/Alt+Shift+R.";
11115
11178
  refreshBtn.addEventListener("click", (event) => {
11116
11179
  event.preventDefault();
@@ -11118,7 +11181,6 @@
11118
11181
  if (!isCurrent()) return;
11119
11182
  if (!refreshStudioPdfCard(card)) setStatus("Could not refresh this PDF preview.", "warning");
11120
11183
  });
11121
- actions.appendChild(refreshBtn);
11122
11184
 
11123
11185
  const autoRefreshBtn = document.createElement("button");
11124
11186
  autoRefreshBtn.type = "button";
@@ -11139,6 +11201,7 @@
11139
11201
  setStudioPdfCardAutoRefresh(card, !state.enabled);
11140
11202
  });
11141
11203
  actions.appendChild(autoRefreshBtn);
11204
+ actions.appendChild(createStudioPdfMoreMenu("card", [refreshBtn, openLink, systemViewerBtn, revealBtn, copyPathBtn]));
11142
11205
 
11143
11206
  header.appendChild(actions);
11144
11207
  }
@@ -12167,6 +12230,21 @@
12167
12230
  if (!actionBtn) return;
12168
12231
  event.preventDefault();
12169
12232
  const action = actionBtn.getAttribute("data-repl-action") || "";
12233
+ // Looking at a file changes nothing, whichever session the pane was drawn for.
12234
+ if (action === "file-view" || action === "file-open") {
12235
+ const url = actionBtn.getAttribute("data-repl-file-url") || "";
12236
+ if (!/^\/repl-file\?/.test(url)) return;
12237
+ if (action === "file-view") {
12238
+ openStudioImageFocusViewer(url, actionBtn.getAttribute("data-repl-file-name") || "Image");
12239
+ return;
12240
+ }
12241
+ try {
12242
+ openStudioTabDirect(url);
12243
+ } catch (error) {
12244
+ setStatus(error instanceof Error ? error.message : String(error), "warning");
12245
+ }
12246
+ return;
12247
+ }
12170
12248
  // The name isn't the session's, so a pane drawn for another session can still change it.
12171
12249
  if (action === "sender-edit") {
12172
12250
  replSenderEditing = true;
@@ -12478,6 +12556,8 @@
12478
12556
  critiqueViewEl.addEventListener("toggle", handleReplMoreToggle, true);
12479
12557
  critiqueViewEl.addEventListener("click", handleTracePaneClick);
12480
12558
  critiqueViewEl.addEventListener("click", handleReplPaneClick);
12559
+ critiqueViewEl.addEventListener("load", handleReplFileImageLoad, true);
12560
+ critiqueViewEl.addEventListener("scroll", handleReplViewScroll, { passive: true });
12481
12561
  critiqueViewEl.addEventListener("click", handleFilesPaneClick);
12482
12562
  critiqueViewEl.addEventListener("click", handleGitChangesPaneClick);
12483
12563
  critiqueViewEl.addEventListener("click", handleStudioQuartoPreviewClick);
@@ -14514,6 +14594,7 @@
14514
14594
  + prose
14515
14595
  + code
14516
14596
  + output
14597
+ + buildReplEntryFilesHtml(entry)
14517
14598
  + pending
14518
14599
  + "</article>";
14519
14600
  }).join("");
@@ -14526,9 +14607,6 @@
14526
14607
  + (hasEntries ? cards : (recordRefusal ? "" : "<div class='repl-studio-empty'>" + escapeHtml(emptyText) + "</div>"));
14527
14608
  return "<section class='repl-journal'>"
14528
14609
  + "<div class='repl-journal-header'><h3>Shared REPL Record</h3>" + toggleActions + "</div>"
14529
- + "<p class='repl-journal-description'>What Studio and pi-repl have sent to this session."
14530
- + (replRecordActivity === "off" ? "" : " New entries here go to the agent and its model provider.")
14531
- + "</p>"
14532
14610
  + (recordRefusal ? "<p class='repl-journal-omitted'>" + escapeHtml("Not shown: " + recordRefusal) + "</p>" : "")
14533
14611
  + (!recordRefusal && recordState.unverified ? "<p class='repl-journal-omitted'>Record directory not verified: this session has no record-directory key yet, so the record here may not be the one other clients use.</p>" : "")
14534
14612
  + (omitted ? "<div class='repl-journal-omitted'>Showing latest 12 entries for this session; " + escapeHtml(String(omitted)) + " older entries remain in export.</div>" : "")
@@ -14537,6 +14615,69 @@
14537
14615
  + "</section>";
14538
14616
  }
14539
14617
 
14618
+ function getReplFileUrl(file) {
14619
+ return "/repl-file?" + new URLSearchParams({ token: getToken(), id: file.id, v: file.v }).toString();
14620
+ }
14621
+
14622
+ // Image and PDF files an entry names, such as a saved plot, as pi-markdown-preview's REPL
14623
+ // page shows them: one tile each, images first, named inside the tile, the path as written
14624
+ // in its tooltip. An image opens in Studio's image viewer, a PDF in a new tab.
14625
+ function buildReplEntryFilesHtml(entry) {
14626
+ const files = Array.isArray(entry.files) ? entry.files : [];
14627
+ if (!files.length) return "";
14628
+ const name = (written) => written.split(/[\\/]/).pop() || written;
14629
+ const tiles = [...files.filter((file) => file.image), ...files.filter((file) => !file.image)].map((file) => {
14630
+ const url = getReplFileUrl(file);
14631
+ const attrs = " data-repl-file-url='" + escapeHtml(url) + "' data-repl-file-name='" + escapeHtml(name(file.written)) + "' title='" + escapeHtml(file.written) + "'";
14632
+ if (file.image) {
14633
+ return "<button type='button' class='repl-studio-file' data-repl-action='file-view'" + attrs + ">"
14634
+ + "<img class='repl-studio-file-img' src='" + escapeHtml(url) + "' alt='" + escapeHtml(file.written) + "' data-repl-file-key='" + escapeHtml(url) + "'>"
14635
+ + "<span class='repl-studio-file-name'>" + escapeHtml(name(file.written)) + "</span></button>";
14636
+ }
14637
+ const format = (/\.([^.]+)$/.exec(name(file.written)) || ["", ""])[1].toUpperCase();
14638
+ return "<button type='button' class='repl-studio-file repl-studio-file-other' data-repl-action='file-open'" + attrs + ">"
14639
+ + "<span class='repl-studio-file-format'>" + escapeHtml(format) + "</span>"
14640
+ + "<span class='repl-studio-file-name'>" + escapeHtml(name(file.written)) + "</span></button>";
14641
+ }).join("");
14642
+ return "<div class='repl-studio-files'>" + tiles + "</div>";
14643
+ }
14644
+
14645
+ // A redraw keeps the images already loaded, so a thumbnail doesn't flicker or change
14646
+ // the pane's height each time the record is drawn again.
14647
+ function captureReplFileImages() {
14648
+ const loaded = new Map();
14649
+ if (!critiqueViewEl) return loaded;
14650
+ critiqueViewEl.querySelectorAll("img[data-repl-file-key]").forEach((img) => {
14651
+ const key = img.getAttribute("data-repl-file-key") || "";
14652
+ if (key && img.complete && img.naturalWidth > 0 && !loaded.has(key)) loaded.set(key, img);
14653
+ });
14654
+ return loaded;
14655
+ }
14656
+
14657
+ function restoreReplFileImages(loaded) {
14658
+ if (!critiqueViewEl || !loaded.size) return;
14659
+ critiqueViewEl.querySelectorAll("img[data-repl-file-key]").forEach((img) => {
14660
+ const key = img.getAttribute("data-repl-file-key") || "";
14661
+ const kept = loaded.get(key);
14662
+ if (!kept) return;
14663
+ loaded.delete(key);
14664
+ img.replaceWith(kept);
14665
+ });
14666
+ }
14667
+
14668
+ // A thumbnail that loads while the pane is kept at its bottom keeps it there. Scrolling
14669
+ // decides that as a redraw does, so a load after the person scrolled up leaves them be (Sol).
14670
+ function handleReplViewScroll() {
14671
+ if (rightView === "repl") replViewStuckToBottom = shouldAutoStickReplView();
14672
+ }
14673
+
14674
+ function handleReplFileImageLoad(event) {
14675
+ if (rightView !== "repl" || !replViewStuckToBottom || !critiqueViewEl) return;
14676
+ const target = event.target;
14677
+ if (!(target instanceof Element) || !target.matches("img[data-repl-file-key]")) return;
14678
+ critiqueViewEl.scrollTop = critiqueViewEl.scrollHeight;
14679
+ }
14680
+
14540
14681
  function buildReplMirrorHtml(body, transcript) {
14541
14682
  const hasTranscript = Boolean(String(transcript || "").trim());
14542
14683
  const summary = hasTranscript
@@ -14965,10 +15106,13 @@
14965
15106
  function renderReplView() {
14966
15107
  if (!critiqueViewEl) return;
14967
15108
  const shouldStick = shouldAutoStickReplView();
15109
+ replViewStuckToBottom = shouldStick;
14968
15110
  const previousScrollTop = critiqueViewEl.scrollTop;
14969
15111
  const senderCursor = captureReplSenderCursor();
15112
+ const loadedFiles = captureReplFileImages();
14970
15113
  finishPreviewRender(critiqueViewEl);
14971
15114
  critiqueViewEl.innerHTML = buildReplPanelHtml();
15115
+ restoreReplFileImages(loadedFiles);
14972
15116
  restoreReplSenderCursor(senderCursor);
14973
15117
  critiqueViewEl.classList.remove("response-scroll-resetting");
14974
15118
  if (shouldStick) {
@@ -21143,7 +21287,7 @@
21143
21287
  if (!raw || raw.charAt(0) === "#") return false;
21144
21288
  if (/^\/\//.test(raw)) return false;
21145
21289
  if (/^(?:https?|mailto|tel|data|blob|javascript|about):/i.test(raw)) return false;
21146
- if (/^\/(?:pdf-resource|html-preview-resource|export-pdf|export-html|render-preview|render-math|import-file-copy|resource-grants|local-preview-link|reveal-local-resource|open-local-resource)(?:[?#/]|$)/i.test(raw)) return false;
21290
+ if (/^\/(?:repl-file|pdf-resource|html-preview-resource|export-pdf|export-html|render-preview|render-math|import-file-copy|resource-grants|local-preview-link|reveal-local-resource|open-local-resource)(?:[?#/]|$)/i.test(raw)) return false;
21147
21291
  return true;
21148
21292
  }
21149
21293
 
@@ -29491,7 +29635,6 @@
29491
29635
  noteReplChoiceAnswer(message);
29492
29636
  const present = !isReplChoicePending();
29493
29637
  replTmuxAvailable = typeof message.tmuxAvailable === "boolean" ? message.tmuxAvailable : replTmuxAvailable;
29494
- if (message.recordActivity === "on" || message.recordActivity === "send" || message.recordActivity === "off") replRecordActivity = message.recordActivity;
29495
29638
  const defaultName = validateReplPersonName(message.personName);
29496
29639
  if (!defaultName.error) replPersonNameDefault = defaultName.name;
29497
29640
  if (message.personNameSource === "environment" || message.personNameSource === "setting" || message.personNameSource === "default") replPersonNameSource = message.personNameSource;
package/client/studio.css CHANGED
@@ -2198,6 +2198,91 @@
2198
2198
  height: 15px;
2199
2199
  }
2200
2200
 
2201
+ /* A PDF's More menu, on its card and in its enlarged view, as the REPL pane's (candidate 117). */
2202
+ .studio-pdf-more {
2203
+ position: relative;
2204
+ flex: 0 0 auto;
2205
+ }
2206
+
2207
+ .studio-pdf-more > summary {
2208
+ display: inline-flex;
2209
+ align-items: center;
2210
+ cursor: pointer;
2211
+ user-select: none;
2212
+ list-style: none;
2213
+ padding: 3px 7px;
2214
+ border: 1px solid transparent;
2215
+ border-radius: 7px;
2216
+ color: var(--studio-info-text, var(--muted));
2217
+ font-size: 12px;
2218
+ font-weight: 600;
2219
+ line-height: 1.2;
2220
+ white-space: nowrap;
2221
+ }
2222
+
2223
+ .studio-pdf-more > summary::-webkit-details-marker {
2224
+ display: none;
2225
+ }
2226
+
2227
+ .studio-pdf-more > summary::after {
2228
+ content: "⌄";
2229
+ margin-left: 4px;
2230
+ font-size: 11px;
2231
+ }
2232
+
2233
+ .studio-pdf-more > summary:hover,
2234
+ .studio-pdf-more > summary:focus-visible,
2235
+ .studio-pdf-more[open] > summary {
2236
+ background: var(--panel);
2237
+ border-color: var(--control-border);
2238
+ color: var(--text);
2239
+ outline: none;
2240
+ }
2241
+
2242
+ .studio-pdf-more-menu {
2243
+ position: absolute;
2244
+ top: calc(100% + 6px);
2245
+ right: 0;
2246
+ z-index: 30;
2247
+ display: flex;
2248
+ flex-direction: column;
2249
+ align-items: stretch;
2250
+ gap: 2px;
2251
+ width: max-content;
2252
+ min-width: 160px;
2253
+ padding: 6px;
2254
+ border: 1px solid var(--panel-border);
2255
+ border-radius: 10px;
2256
+ background: var(--panel);
2257
+ box-shadow: 0 12px 30px rgba(0, 0, 0, 0.22);
2258
+ }
2259
+
2260
+ .studio-pdf-more .studio-pdf-more-menu > .studio-pdf-more-item {
2261
+ display: flex;
2262
+ width: 100%;
2263
+ min-height: 0;
2264
+ justify-content: flex-start;
2265
+ padding: 5px 8px;
2266
+ border: 1px solid transparent;
2267
+ border-radius: 6px;
2268
+ background: transparent;
2269
+ color: var(--text);
2270
+ font-size: 12px;
2271
+ font-weight: 500;
2272
+ line-height: 1.3;
2273
+ text-align: left;
2274
+ text-decoration: none;
2275
+ white-space: nowrap;
2276
+ }
2277
+
2278
+ .studio-pdf-more .studio-pdf-more-menu > .studio-pdf-more-item:not(:disabled):hover,
2279
+ .studio-pdf-more .studio-pdf-more-menu > .studio-pdf-more-item:not(:disabled):focus-visible {
2280
+ background: var(--studio-header-action-hover-bg, var(--panel-2));
2281
+ border-color: transparent;
2282
+ color: var(--text);
2283
+ text-decoration: none;
2284
+ }
2285
+
2201
2286
  .rendered-markdown .studio-pdf-card-caption {
2202
2287
  padding: 8px 10px 0;
2203
2288
  color: var(--studio-info-text, var(--muted));
@@ -4950,7 +5035,6 @@
4950
5035
  }
4951
5036
 
4952
5037
  .repl-journal-header p,
4953
- .repl-journal-description,
4954
5038
  .repl-journal-omitted {
4955
5039
  margin: 1px 0 0;
4956
5040
  color: var(--muted);
@@ -5122,6 +5206,68 @@
5122
5206
  font-style: italic;
5123
5207
  }
5124
5208
 
5209
+ /* Image and PDF files an entry names, such as a saved plot, as pi-markdown-preview's REPL
5210
+ page shows them: one tile a row, up to 640 by 420 px, named inside the tile. */
5211
+ .repl-studio-files {
5212
+ display: flex;
5213
+ flex-direction: column;
5214
+ align-items: flex-start;
5215
+ gap: 8px;
5216
+ margin: 6px 0 2px calc(var(--repl-studio-prompt-width) + var(--repl-studio-column-gap));
5217
+ }
5218
+
5219
+ .repl-journal-list .repl-studio-file {
5220
+ display: flex;
5221
+ flex-direction: column;
5222
+ gap: 6px;
5223
+ max-width: min(100%, 640px);
5224
+ padding: 8px;
5225
+ border: 1px solid var(--panel-border);
5226
+ border-radius: 8px;
5227
+ background: var(--panel);
5228
+ color: inherit;
5229
+ font-size: 12px;
5230
+ text-align: left;
5231
+ }
5232
+
5233
+ .repl-journal-list .repl-studio-file:not(:disabled):hover {
5234
+ background: var(--panel-2);
5235
+ }
5236
+
5237
+ .repl-studio-file-img {
5238
+ display: block;
5239
+ max-width: 100%;
5240
+ max-height: 420px;
5241
+ object-fit: contain;
5242
+ border-radius: 4px;
5243
+ background: #fff;
5244
+ }
5245
+
5246
+ .repl-studio-file-name {
5247
+ color: var(--muted);
5248
+ overflow-wrap: anywhere;
5249
+ }
5250
+
5251
+ .repl-journal-list .repl-studio-file-other {
5252
+ flex-direction: row;
5253
+ align-items: center;
5254
+ gap: 8px;
5255
+ padding: 8px 10px;
5256
+ }
5257
+
5258
+ .repl-studio-file-other .repl-studio-file-name {
5259
+ color: var(--accent);
5260
+ text-decoration: underline;
5261
+ }
5262
+
5263
+ .repl-studio-file-format {
5264
+ padding: 1px 5px;
5265
+ border: 1px solid var(--panel-border);
5266
+ border-radius: 4px;
5267
+ color: var(--muted);
5268
+ font: 600 11px/1.4 var(--font-ui);
5269
+ }
5270
+
5125
5271
  .repl-journal-card-header,
5126
5272
  .repl-journal-section,
5127
5273
  .repl-journal-label,
package/index.ts CHANGED
@@ -62,6 +62,8 @@ import {
62
62
  buildStudioReplDeadPaneCloseArgs,
63
63
  isStudioGnuplotSession,
64
64
  isStudioReplReadyLine,
65
+ parseStudioReplPaneCwd,
66
+ STUDIO_REPL_PANE_CWD_FORMAT,
65
67
  STUDIO_REPL_PANE_FORMAT,
66
68
  STUDIO_REPL_SESSION_NAME,
67
69
  studioReplSessionTarget,
@@ -100,6 +102,13 @@ import {
100
102
  replEntryVersion,
101
103
  resetReplActivityState,
102
104
  } from "./shared/studio-repl-activity.js";
105
+ import {
106
+ createStudioReplFileRoutes,
107
+ openStudioReplFileRoute,
108
+ resolveStudioReplFiles,
109
+ STUDIO_REPL_FILE_ENTRIES,
110
+ studioReplSessionRunBounds,
111
+ } from "./shared/studio-repl-files.js";
103
112
  import {
104
113
  createReplSubmissionDisplay,
105
114
  normalizeReplSubmissionEchoMode,
@@ -8246,6 +8255,19 @@ function respondStudioDirectoryGrantRequiredJson(res: ServerResponse, error: Stu
8246
8255
  });
8247
8256
  }
8248
8257
 
8258
+ // An inline Content-Disposition for any file name: an ASCII fallback, and the name itself as
8259
+ // UTF-8 (RFC 6266), since Node refuses a header with characters such as Δ or 測 (Sol, Astra, c116).
8260
+ function studioInlineContentDisposition(name: string, fallback: string): string {
8261
+ const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/[;"\\]/g, "_").trim() || fallback;
8262
+ let encoded = "";
8263
+ try {
8264
+ encoded = encodeURIComponent(name).replace(/['()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
8265
+ } catch {
8266
+ // A name that isn't well-formed Unicode keeps only its fallback.
8267
+ }
8268
+ return encoded && encoded !== ascii ? `inline; filename="${ascii}"; filename*=UTF-8''${encoded}` : `inline; filename="${ascii}"`;
8269
+ }
8270
+
8249
8271
  function respondPdfFile(req: IncomingMessage, res: ServerResponse, filePath: string): void {
8250
8272
  const method = (req.method ?? "GET").toUpperCase();
8251
8273
  if (method !== "GET" && method !== "HEAD") {
@@ -8263,7 +8285,7 @@ function respondPdfFile(req: IncomingMessage, res: ServerResponse, filePath: str
8263
8285
  ].map((value) => Number(value).toString(16)).join("-")}"`;
8264
8286
  const commonHeaders = {
8265
8287
  "Content-Type": "application/pdf",
8266
- "Content-Disposition": `inline; filename="${basename(filePath).replace(/["\\]/g, "") || "document.pdf"}"`,
8288
+ "Content-Disposition": studioInlineContentDisposition(basename(filePath), "document.pdf"),
8267
8289
  "Referrer-Policy": "no-referrer",
8268
8290
  "Cache-Control": "no-store",
8269
8291
  "X-Content-Type-Options": "nosniff",
@@ -8299,6 +8321,24 @@ function respondHtmlPreviewResourceJson(req: IncomingMessage, res: ServerRespons
8299
8321
  });
8300
8322
  }
8301
8323
 
8324
+ // An image a REPL record entry names, as itself, for the pane's thumbnail and the image viewer.
8325
+ // Opened on its own, an SVG can't run scripts or load other files: the page is sandboxed.
8326
+ function respondStudioReplFileImage(req: IncomingMessage, res: ServerResponse, filePath: string, mimeType: string): void {
8327
+ const method = (req.method ?? "GET").toUpperCase();
8328
+ if (method !== "GET" && method !== "HEAD") { res.setHeader("Allow", "GET, HEAD"); respondText(res, 405, "Use GET or HEAD."); return; }
8329
+ const image = method === "HEAD" ? undefined : readFileSync(filePath);
8330
+ res.writeHead(200, {
8331
+ "Content-Type": mimeType,
8332
+ "Content-Length": String(image ? image.length : statSync(filePath).size),
8333
+ "Cache-Control": "no-store",
8334
+ "X-Content-Type-Options": "nosniff",
8335
+ "Referrer-Policy": "no-referrer",
8336
+ "Cross-Origin-Resource-Policy": "same-origin",
8337
+ "Content-Security-Policy": "sandbox; default-src 'none'; img-src data:; style-src 'unsafe-inline'",
8338
+ });
8339
+ res.end(image);
8340
+ }
8341
+
8302
8342
  function respondStudioReadOnlyImage(req: IncomingMessage, res: ServerResponse, filePath: string, mimeType: string): void {
8303
8343
  const method = (req.method ?? "GET").toUpperCase();
8304
8344
  if (method !== "GET" && method !== "HEAD") { res.setHeader("Allow", "GET, HEAD"); respondText(res, 405, "Use GET or HEAD."); return; }
@@ -12756,6 +12796,11 @@ function recordStudioReplJournalEntry(
12756
12796
  }
12757
12797
 
12758
12798
  function getStudioReplJournalEntries(sessionName: string | null | undefined): StudioReplJournalEntry[] {
12799
+ return readStudioReplJournal(sessionName).entries;
12800
+ }
12801
+
12802
+ /** A session's record entries, or every session's, with the sessions they were read from. */
12803
+ function readStudioReplJournal(sessionName: string | null | undefined): { entries: StudioReplJournalEntry[]; sessions: StudioReplSessionInfo[] } {
12759
12804
  const normalizedSessionName = String(sessionName || "").trim();
12760
12805
  const sessions = normalizedSessionName
12761
12806
  ? [inspectStudioReplSession(normalizedSessionName)].filter((session): session is StudioReplSessionInfo => Boolean(session))
@@ -12788,10 +12833,60 @@ function getStudioReplJournalEntries(sessionName: string | null | undefined): St
12788
12833
  const entries = (normalizedSessionName
12789
12834
  ? studioReplJournalEntries.filter((entry) => entry.sessionName === normalizedSessionName)
12790
12835
  : studioReplJournalEntries).filter((entry) => !refused.has(entry.sessionName));
12791
- return entries.slice(-STUDIO_REPL_JOURNAL_MAX_ENTRIES).map((entry) => ({
12792
- ...entry,
12793
- sharedSynced: !studioReplUnsyncedJournalEntryIds.has(entry.id) && entry.sharedSynced === true,
12794
- }));
12836
+ return {
12837
+ entries: entries.slice(-STUDIO_REPL_JOURNAL_MAX_ENTRIES).map((entry) => ({
12838
+ ...entry,
12839
+ sharedSynced: !studioReplUnsyncedJournalEntryIds.has(entry.id) && entry.sharedSynced === true,
12840
+ })),
12841
+ sessions,
12842
+ };
12843
+ }
12844
+
12845
+ type StudioReplFileRoutes = ReturnType<typeof createStudioReplFileRoutes>;
12846
+
12847
+ // A pane's current directory, asked of tmux by pane ID (studio-repl-tmux.js says why not in the listing).
12848
+ function readStudioReplPaneCwd(paneId: string): string | undefined {
12849
+ if (!/^%\d+$/.test(paneId)) return undefined;
12850
+ const result = runStudioTmux(["display-message", "-p", "-t", paneId, STUDIO_REPL_PANE_CWD_FORMAT], { timeout: 3_000 });
12851
+ return result.ok ? parseStudioReplPaneCwd(result.stdout) || undefined : undefined;
12852
+ }
12853
+
12854
+ /**
12855
+ * Entries for the page, each of a session's latest STUDIO_REPL_FILE_ENTRIES with the image and
12856
+ * PDF files it names (studio-repl-files.js): `{ id, written, image, v }`, `id` naming its route
12857
+ * and `v` the file's version. A relative path resolves against the session's first pane's
12858
+ * current directory, asked of tmux once a session and only when an entry needs it.
12859
+ */
12860
+ function attachStudioReplEntryFiles(entries: StudioReplJournalEntry[], sessions: StudioReplSessionInfo[], routes: StudioReplFileRoutes | undefined) {
12861
+ if (!routes) return entries;
12862
+ const panes = new Map(sessions.map((session) => [session.sessionName, session.target]));
12863
+ const cwds = new Map<string, string | undefined>();
12864
+ const cwdOf = (sessionName: string) => () => {
12865
+ if (!cwds.has(sessionName)) {
12866
+ const paneId = panes.get(sessionName);
12867
+ cwds.set(sessionName, paneId ? readStudioReplPaneCwd(paneId) : undefined);
12868
+ }
12869
+ return cwds.get(sessionName);
12870
+ };
12871
+ // Each entry's own turn in its session, so a file the next one wrote isn't this one's.
12872
+ const bounds = studioReplSessionRunBounds(entries);
12873
+ const looked = new Set<string>();
12874
+ const counts = new Map<string, number>();
12875
+ for (let index = entries.length - 1; index >= 0; index--) {
12876
+ const sessionName = entries[index].sessionName;
12877
+ const count = counts.get(sessionName) ?? 0;
12878
+ if (count >= STUDIO_REPL_FILE_ENTRIES) continue;
12879
+ counts.set(sessionName, count + 1);
12880
+ looked.add(entries[index].id);
12881
+ }
12882
+ return entries.map((entry) => {
12883
+ if (!looked.has(entry.id)) return entry;
12884
+ const files = resolveStudioReplFiles(entry, cwdOf(entry.sessionName), { bounds: bounds.get(entry.id) });
12885
+ return files.length ? {
12886
+ ...entry,
12887
+ files: files.map((file) => ({ id: routes.add(file), written: file.written, image: file.contentType !== "application/pdf", v: file.version })),
12888
+ } : entry;
12889
+ });
12795
12890
  }
12796
12891
 
12797
12892
  function updateStudioReplJournalEntryOutput(
@@ -14096,6 +14191,19 @@ ${cssVarsBlock}
14096
14191
 
14097
14192
  export default function (pi: ExtensionAPI) {
14098
14193
  let serverState: StudioServerState | null = null;
14194
+ // Routes for the files the REPL pane shows, made anew for each server's token.
14195
+ let studioReplFiles: { token: string; routes: StudioReplFileRoutes } | null = null;
14196
+ const getStudioReplFileRoutes = (): StudioReplFileRoutes | undefined => {
14197
+ const token = serverState?.token;
14198
+ if (!token) return undefined;
14199
+ if (studioReplFiles?.token !== token) studioReplFiles = { token, routes: createStudioReplFileRoutes(token) };
14200
+ return studioReplFiles.routes;
14201
+ };
14202
+ // Record entries as the page gets them, with the files they name.
14203
+ const getStudioReplPageEntries = (sessionName: string | null | undefined): StudioReplJournalEntry[] => {
14204
+ const { entries, sessions } = readStudioReplJournal(sessionName);
14205
+ return attachStudioReplEntryFiles(entries, sessions, getStudioReplFileRoutes());
14206
+ };
14099
14207
  const studioWorkspaceStateStore = createStudioWorkspaceStateStore();
14100
14208
  // Hosting-capable unless the env flags turned hosting off; single editor mode doesn't use it.
14101
14209
  const studioBufferStateStore = createStudioBufferServerStore({ legacyState: (id: string) => studioWorkspaceStateStore.get(id),
@@ -14570,7 +14678,7 @@ export default function (pi: ExtensionAPI) {
14570
14678
  sharedSynced: journalEntry.sharedSynced === true,
14571
14679
  completed,
14572
14680
  timedOut: Boolean(sent.controlFiles?.doneFile && !completed),
14573
- journalEntries: getStudioReplJournalEntries(selected.session.sessionName),
14681
+ journalEntries: getStudioReplPageEntries(selected.session.sessionName),
14574
14682
  select,
14575
14683
  ...(select ? {
14576
14684
  session: currentSession,
@@ -15448,7 +15556,7 @@ export default function (pi: ExtensionAPI) {
15448
15556
  activeSessionName: active?.sessionName ?? null,
15449
15557
  activeRuntime: studioReplSelection.runtime,
15450
15558
  shown: studioReplSelection.shown,
15451
- journalEntries: getStudioReplJournalEntries(active?.sessionName ?? null),
15559
+ journalEntries: getStudioReplPageEntries(active?.sessionName ?? null),
15452
15560
  recordActivity: replActivityMode,
15453
15561
  // What the page sends as when it hasn't chosen a name.
15454
15562
  personName: person.name,
@@ -15484,7 +15592,7 @@ export default function (pi: ExtensionAPI) {
15484
15592
  shown: studioReplSelection.shown,
15485
15593
  transcript: captured.transcript,
15486
15594
  capturedAt: Date.now(),
15487
- journalEntries: getStudioReplJournalEntries(captured.session.sessionName),
15595
+ journalEntries: getStudioReplPageEntries(captured.session.sessionName),
15488
15596
  ...extra,
15489
15597
  });
15490
15598
  };
@@ -15499,13 +15607,13 @@ export default function (pi: ExtensionAPI) {
15499
15607
  session: captured.session,
15500
15608
  transcript: captured.transcript,
15501
15609
  capturedAt: Date.now(),
15502
- journalEntries: getStudioReplJournalEntries(captured.session.sessionName),
15610
+ journalEntries: getStudioReplPageEntries(captured.session.sessionName),
15503
15611
  } : {
15504
15612
  type: "repl_capture",
15505
15613
  observation: true,
15506
15614
  sessionName,
15507
15615
  captureError: captured.message,
15508
- journalEntries: getStudioReplJournalEntries(sessionName),
15616
+ journalEntries: getStudioReplPageEntries(sessionName),
15509
15617
  });
15510
15618
  };
15511
15619
 
@@ -15521,7 +15629,7 @@ export default function (pi: ExtensionAPI) {
15521
15629
  sendReplSelectionToClient(client, extra);
15522
15630
  return;
15523
15631
  }
15524
- sendReplStateToClient(client, { journalEntries: getStudioReplJournalEntries(sessionName), ...extra });
15632
+ sendReplStateToClient(client, { journalEntries: getStudioReplPageEntries(sessionName), ...extra });
15525
15633
  };
15526
15634
 
15527
15635
  const emitDebugEvent = (event: string, details?: Record<string, unknown>) => {
@@ -17787,7 +17895,7 @@ export default function (pi: ExtensionAPI) {
17787
17895
  requestId: msg.requestId,
17788
17896
  sessionName: msg.sessionName,
17789
17897
  message: sent.message,
17790
- journalEntries: getStudioReplJournalEntries(msg.sessionName),
17898
+ journalEntries: getStudioReplPageEntries(msg.sessionName),
17791
17899
  });
17792
17900
  const timeoutMs = STUDIO_REPL_SEND_DEFAULT_TIMEOUT_MS;
17793
17901
  let completed = false;
@@ -17874,7 +17982,7 @@ export default function (pi: ExtensionAPI) {
17874
17982
  type: "repl_journal_ack",
17875
17983
  requestId: msg.requestId,
17876
17984
  sessionName: msg.sessionName,
17877
- journalEntries: getStudioReplJournalEntries(msg.sessionName),
17985
+ journalEntries: getStudioReplPageEntries(msg.sessionName),
17878
17986
  });
17879
17987
  } catch (error) {
17880
17988
  sendToClient(client, { type: "error", requestId: msg.requestId, message: error instanceof Error ? error.message : String(error) });
@@ -17904,7 +18012,7 @@ export default function (pi: ExtensionAPI) {
17904
18012
  type: "repl_journal_ack",
17905
18013
  requestId: msg.requestId,
17906
18014
  sessionName: msg.sessionName,
17907
- journalEntries: getStudioReplJournalEntries(msg.sessionName),
18015
+ journalEntries: getStudioReplPageEntries(msg.sessionName),
17908
18016
  });
17909
18017
  } catch (error) {
17910
18018
  sendToClient(client, { type: "error", requestId: msg.requestId, message: error instanceof Error ? error.message : String(error) });
@@ -19930,6 +20038,27 @@ export default function (pi: ExtensionAPI) {
19930
20038
  return;
19931
20039
  }
19932
20040
 
20041
+ // A file a REPL record entry names, by the route the page was given for it.
20042
+ if (requestUrl.pathname === "/repl-file") {
20043
+ const token = requestUrl.searchParams.get("token") ?? "";
20044
+ if (token !== serverState.token) {
20045
+ respondText(res, 403, "Invalid or expired studio token. Re-run /studio.");
20046
+ return;
20047
+ }
20048
+ const opened = openStudioReplFileRoute(getStudioReplFileRoutes()?.get(requestUrl.searchParams.get("id") ?? ""));
20049
+ if (!opened.ok) {
20050
+ respondText(res, opened.status, opened.message);
20051
+ return;
20052
+ }
20053
+ try {
20054
+ if (opened.contentType === "application/pdf") respondPdfFile(req, res, opened.filePath);
20055
+ else respondStudioReplFileImage(req, res, opened.filePath, opened.contentType);
20056
+ } catch {
20057
+ if (!res.headersSent) respondText(res, 404, "Studio couldn't read this file.");
20058
+ }
20059
+ return;
20060
+ }
20061
+
19933
20062
  if (requestUrl.pathname === "/pdf-resource") {
19934
20063
  const token = requestUrl.searchParams.get("token") ?? "";
19935
20064
  if (token !== serverState.token) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-studio",
3
- "version": "0.11.8",
3
+ "version": "0.11.9",
4
4
  "description": "Two-pane browser workspace for pi with prompt/response editing, annotations, critiques, active quiz, prompt/response history, live previews, and tmux-backed REPL/literate REPL workflows",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,273 @@
1
+ import { createHash, createHmac } from "node:crypto";
2
+ import { realpathSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { extname, isAbsolute, resolve } from "node:path";
5
+
6
+ /*
7
+ * Image and PDF files a REPL record entry's code saved, such as a plot, so the REPL pane can show
8
+ * them, as pi-markdown-preview's REPL page does (its repl-files.js). A file counts only if the
9
+ * entry's code or output names it and it was written while the entry ran: reading names from
10
+ * text can't be made exact across languages and prose, so the time it was written decides
11
+ * whether a name found there is shown (Sol, Astra, candidate 116). The page gets each file
12
+ * through an opaque route that only this list makes; nothing else is served.
13
+ */
14
+
15
+ export const STUDIO_REPL_FILE_CONTENT_TYPES = new Map([
16
+ [".png", "image/png"], [".jpg", "image/jpeg"], [".jpeg", "image/jpeg"], [".gif", "image/gif"],
17
+ [".webp", "image/webp"], [".svg", "image/svg+xml"], [".pdf", "application/pdf"],
18
+ ]);
19
+ const EXTENSIONS = "png|jpe?g|gif|webp|svg|pdf";
20
+ // A quoted path, as code writes one: savefig("out/fit.png"), png('plot.png'), `fit 2.png`.
21
+ const QUOTES = new Set(['"', "'", "`"]);
22
+ const QUOTED_PATH = new RegExp(`^[^\\r\\n\\0]{1,1024}\\.(?:${EXTENSIONS})$`, "i");
23
+ // A bare path, as output prints one: "Saved to /tmp/fit.png." (a sentence's full stop isn't part of it).
24
+ const BARE = new RegExp(`(?:^|[\\s(=:,\\[])((?:~|\\.{1,2})?\\/?(?:[\\w@%+.,~-]+\\/)*[\\w@%+.,~-]+\\.(?:${EXTENSIONS}))(?=$|[\\s)\\]:;,'"]|\\.(?:\\s|$))`, "gim");
25
+ const CANDIDATES_PER_ENTRY = 20;
26
+ // How long after an entry finished a file it names may still have been written by its code,
27
+ // such as by a plotting process that flushes after the prompt returns.
28
+ export const STUDIO_REPL_FILE_WRITE_GRACE_MS = 2_000;
29
+ export const STUDIO_REPL_FILES_PER_ENTRY = 6;
30
+ // The pane shows a session's latest 12 entries; only they are looked at.
31
+ export const STUDIO_REPL_FILE_ENTRIES = 12;
32
+ const STUDIO_REPL_FILE_ROUTES = 500;
33
+ // Versions of one file a route serves: those the page has been shown, the latest few.
34
+ const STUDIO_REPL_FILE_ROUTE_VERSIONS = 8;
35
+ export const STUDIO_REPL_FILE_MAX_BYTES = 64 * 1024 * 1024;
36
+
37
+ /**
38
+ * A text's quoted spans, each closed by its own delimiter on the same line, and the text with
39
+ * them blanked. Inside a span a backslash escapes the next character and a doubled delimiter
40
+ * stands for one (MATLAB's 'O''Brien'), so neither ends it; a span holding either isn't a name
41
+ * as written, so it names nothing (`plain: false`). A quote with no close on its line, such as
42
+ * an apostrophe in prose, starts no span, and nor do later copies of it on that line, so the
43
+ * scan stays linear however many there are (agent-markdown-preview's rule).
44
+ */
45
+ function quotedSpans(text) {
46
+ const spans = [];
47
+ let unquoted = "";
48
+ // Where each quote last found no close: the end of that line.
49
+ const unclosedUntil = new Map();
50
+ let index = 0;
51
+ while (index < text.length) {
52
+ const quote = text[index];
53
+ let end = index + 1;
54
+ let closed = false;
55
+ let plain = true;
56
+ if (QUOTES.has(quote) && !(unclosedUntil.get(quote) > index)) {
57
+ while (end < text.length && text[end] !== "\n" && text[end] !== "\r") {
58
+ if (text[end] === "\\" && end + 1 < text.length && text[end + 1] !== "\n" && text[end + 1] !== "\r") { plain = false; end += 2; continue; }
59
+ if (text[end] === quote) {
60
+ if (text[end + 1] === quote) { plain = false; end += 2; continue; }
61
+ closed = true;
62
+ break;
63
+ }
64
+ end += 1;
65
+ }
66
+ if (!closed) unclosedUntil.set(quote, end);
67
+ }
68
+ if (closed) {
69
+ spans.push({ text: text.slice(index + 1, end), plain });
70
+ unquoted += " ".repeat(end + 1 - index);
71
+ index = end + 1;
72
+ } else {
73
+ unquoted += quote;
74
+ index += 1;
75
+ }
76
+ }
77
+ return { spans, unquoted };
78
+ }
79
+
80
+ /**
81
+ * The image and PDF paths an entry names, output first, as written, in order and without repeats.
82
+ * A quoted path is taken whole, and nothing inside quotes is searched again for bare paths, so
83
+ * "fit 2.png" and "O'Brien fit.png" can't name 2.png or fit.png (Sol, Astra, candidate 116).
84
+ * A quoted name that isn't a supported path as written names nothing. Prose and other
85
+ * languages' quoting can still mislead this; resolveStudioReplFiles's time check decides.
86
+ */
87
+ export function studioReplFilePaths(entry) {
88
+ const found = new Set();
89
+ for (const text of [entry?.output, entry?.code]) {
90
+ if (typeof text !== "string") continue;
91
+ const { spans, unquoted } = quotedSpans(text);
92
+ for (const span of spans) if (span.plain && QUOTED_PATH.test(span.text)) found.add(span.text);
93
+ for (const match of unquoted.matchAll(BARE)) found.add(match[1]);
94
+ }
95
+ return [...found].slice(0, CANDIDATES_PER_ENTRY);
96
+ }
97
+
98
+ /** A written path made absolute: against home for `~/`, else against the session's directory, if it has one. */
99
+ function resolveWritten(written, cwd) {
100
+ if (written.startsWith("~/")) return resolve(homedir(), written.slice(2));
101
+ if (isAbsolute(written)) return resolve(written);
102
+ const directory = cwd();
103
+ return typeof directory === "string" && isAbsolute(directory) ? resolve(directory, written) : undefined;
104
+ }
105
+
106
+ /**
107
+ * A file's version: it changes when the file is written or replaced, even by a copy that keeps
108
+ * its modification time (cp -p), which changes its inode or change time (Sol, candidate 116).
109
+ */
110
+ function studioReplFileVersion(info) {
111
+ return createHash("sha256").update([info.dev, info.ino, info.size, info.mtimeMs, info.ctimeMs].join(":")).digest("hex").slice(0, 16);
112
+ }
113
+
114
+ /**
115
+ * When an entry's code could have written a file: from when the entry was recorded, before its
116
+ * code was sent, to a little after it finished, or after now while it runs (a file's time is
117
+ * finer than Date.now()'s). Undefined for an entry without a usable start time, which then
118
+ * shows no files.
119
+ */
120
+ function studioReplEntryWriteWindow(entry, now) {
121
+ const start = Number(entry?.createdAt);
122
+ if (!Number.isFinite(start) || start <= 0) return undefined;
123
+ if (entry.status === "sending" || entry.status === "sent") return { start, end: now + STUDIO_REPL_FILE_WRITE_GRACE_MS };
124
+ const finished = Number.isFinite(Number(entry.completedAt)) && Number(entry.completedAt) > 0 ? Number(entry.completedAt) : Number(entry.updatedAt);
125
+ return { start, end: (Number.isFinite(finished) && finished >= start ? finished : start) + STUDIO_REPL_FILE_WRITE_GRACE_MS };
126
+ }
127
+
128
+ /**
129
+ * When an entry finished: its completion, or for a finished status without one its last update.
130
+ * Undefined while it's sending or sent, or without a usable time.
131
+ */
132
+ function studioReplEntryFinish(entry) {
133
+ const completed = Number(entry.completedAt);
134
+ if (Number.isFinite(completed) && completed > 0) return completed;
135
+ if (entry.status === "sending" || entry.status === "sent") return undefined;
136
+ const updated = Number(entry.updatedAt);
137
+ return Number.isFinite(updated) && updated > 0 ? updated : undefined;
138
+ }
139
+
140
+ /**
141
+ * When each entry with code had its session to itself. Sends to a session take turns under its
142
+ * lease, but not in the order they were recorded: a page's send is recorded before it waits for
143
+ * the lease, an agent's once it has it (Sol, candidate 116 round 5). So the order is the order
144
+ * they finished in. An entry's turn starts when it was recorded or when the one before it
145
+ * finished, whichever is later, and a file written once the next one started is the next one's.
146
+ * `start` and `before` bound the time a file was written.
147
+ * - While entries are still running, the last to finish keeps no grace after it: one of them
148
+ * may have started then. Each running entry starts at the last finish or its recording.
149
+ * - Notes have no code and don't count; an entry without a usable time has no bounds.
150
+ *
151
+ * @returns {Map<string, { start: number, before: number }>} by entry ID
152
+ */
153
+ export function studioReplSessionRunBounds(entries) {
154
+ const sessions = new Map();
155
+ for (const entry of entries ?? []) {
156
+ if (!entry || entry.status === "note" || typeof entry.code !== "string" || !entry.code.trim()) continue;
157
+ if (!Number.isFinite(Number(entry.createdAt)) || Number(entry.createdAt) <= 0) continue;
158
+ const list = sessions.get(entry.sessionName) ?? [];
159
+ list.push(entry);
160
+ sessions.set(entry.sessionName, list);
161
+ }
162
+ const bounds = new Map();
163
+ for (const list of sessions.values()) {
164
+ const finished = [];
165
+ const running = [];
166
+ for (const entry of list) {
167
+ const finish = studioReplEntryFinish(entry);
168
+ if (finish !== undefined) finished.push({ entry, finish });
169
+ else if (entry.status === "sending" || entry.status === "sent") running.push(entry);
170
+ }
171
+ finished.sort((a, b) => a.finish - b.finish);
172
+ let lastFinish = -Infinity;
173
+ const starts = finished.map(({ entry, finish }) => {
174
+ const start = Math.max(Number(entry.createdAt), lastFinish);
175
+ lastFinish = finish;
176
+ return start;
177
+ });
178
+ finished.forEach(({ entry, finish }, index) => {
179
+ const before = index + 1 < finished.length ? starts[index + 1] : running.length ? finish : Infinity;
180
+ bounds.set(entry.id, { start: starts[index], before });
181
+ });
182
+ for (const entry of running) bounds.set(entry.id, { start: Math.max(Number(entry.createdAt), lastFinish), before: Infinity });
183
+ }
184
+ return bounds;
185
+ }
186
+
187
+ /**
188
+ * The files an entry names that its code wrote: up to STUDIO_REPL_FILES_PER_ENTRY of
189
+ * `{ written, path, contentType, version }`, each a regular file last modified while the entry
190
+ * ran (studioReplEntryWriteWindow). A file written before it, such as one whose name merely
191
+ * shares a tail with the name the code wrote, or rewritten since by a later entry, isn't
192
+ * shown. `bounds` (studioReplSessionRunBounds) narrows that to the entry's own turn in its
193
+ * session. `cwd` gives the session's working directory, for relative paths: a string, or a
194
+ * function asked at most once, and only for a relative path. Without it only absolute and
195
+ * `~/` paths resolve.
196
+ *
197
+ * @param {any} entry
198
+ * @param {string | (() => string | undefined) | undefined} cwd
199
+ * @param {{ statFile?: (path: string) => import("node:fs").Stats, now?: number, bounds?: { start: number, before: number } }} [options]
200
+ */
201
+ export function resolveStudioReplFiles(entry, cwd, { statFile = statSync, now = Date.now(), bounds } = {}) {
202
+ const window = studioReplEntryWriteWindow(entry, now);
203
+ if (!window) return [];
204
+ const start = Math.max(window.start, Number.isFinite(bounds?.start) ? bounds.start : -Infinity);
205
+ const before = typeof bounds?.before === "number" ? bounds.before : Infinity;
206
+ let directory;
207
+ let asked = false;
208
+ const directoryOnce = () => {
209
+ if (!asked) { asked = true; directory = typeof cwd === "function" ? cwd() : cwd; }
210
+ return directory;
211
+ };
212
+ const files = [];
213
+ for (const written of studioReplFilePaths(entry)) {
214
+ if (files.length >= STUDIO_REPL_FILES_PER_ENTRY) break;
215
+ const contentType = STUDIO_REPL_FILE_CONTENT_TYPES.get(extname(written).toLowerCase());
216
+ if (!contentType) continue;
217
+ const path = resolveWritten(written, directoryOnce);
218
+ if (!path || files.some((file) => file.path === path)) continue;
219
+ let info;
220
+ try { info = statFile(path); } catch { continue; }
221
+ if (!info?.isFile() || !(info.mtimeMs >= start && info.mtimeMs <= window.end && info.mtimeMs < before)) continue;
222
+ files.push({ written, path, contentType, version: studioReplFileVersion(info) });
223
+ }
224
+ return files;
225
+ }
226
+
227
+ /**
228
+ * Routes for the files the page has been shown: an opaque ID per path, keyed to this Studio
229
+ * server's token, kept for the most recent STUDIO_REPL_FILE_ROUTES files. A route serves only
230
+ * the versions of its file the page was shown (Sol, candidate 116 round 4), so a file replaced
231
+ * since, by anything, isn't served until an entry shows that version.
232
+ */
233
+ export function createStudioReplFileRoutes(secret) {
234
+ const routes = new Map();
235
+ return {
236
+ add(file) {
237
+ const id = createHmac("sha256", secret).update("repl-file\0").update(file.path).digest("hex");
238
+ const known = routes.get(id);
239
+ const versions = known?.contentType === file.contentType ? known.versions.filter((version) => version !== file.version) : [];
240
+ versions.push(file.version);
241
+ routes.delete(id);
242
+ routes.set(id, { path: file.path, contentType: file.contentType, versions: versions.slice(-STUDIO_REPL_FILE_ROUTE_VERSIONS) });
243
+ while (routes.size > STUDIO_REPL_FILE_ROUTES) routes.delete(routes.keys().next().value);
244
+ return id;
245
+ },
246
+ get(id) {
247
+ return typeof id === "string" && /^[0-9a-f]{64}$/.test(id) ? routes.get(id) : undefined;
248
+ },
249
+ get size() { return routes.size; },
250
+ };
251
+ }
252
+
253
+ /**
254
+ * The file a route serves now, or why not: it must still be a regular file, within the size
255
+ * limit, whose real path has an extension of the same type as when it was shown, in a version
256
+ * the page was shown.
257
+ *
258
+ * @returns {{ ok: true, filePath: string, contentType: string } | { ok: false, status: number, message: string }}
259
+ */
260
+ export function openStudioReplFileRoute(route, { realpath = realpathSync, statFile = statSync } = {}) {
261
+ if (!route) return { ok: false, status: 404, message: "This file is no longer shown in the REPL pane." };
262
+ let filePath;
263
+ try { filePath = realpath(route.path); } catch { return { ok: false, status: 404, message: "This file no longer exists." }; }
264
+ if (STUDIO_REPL_FILE_CONTENT_TYPES.get(extname(filePath).toLowerCase()) !== route.contentType) {
265
+ return { ok: false, status: 404, message: "This file is no longer the file that was shown." };
266
+ }
267
+ let info;
268
+ try { info = statFile(filePath); } catch { return { ok: false, status: 404, message: "This file no longer exists." }; }
269
+ if (!info.isFile()) return { ok: false, status: 404, message: "This file is no longer the file that was shown." };
270
+ if (info.size > STUDIO_REPL_FILE_MAX_BYTES) return { ok: false, status: 413, message: "This file is too large to show here." };
271
+ if (!route.versions?.includes(studioReplFileVersion(info))) return { ok: false, status: 404, message: "This file is no longer the file that was shown." };
272
+ return { ok: true, filePath, contentType: route.contentType };
273
+ }
@@ -127,6 +127,25 @@ export function firstStudioReplPanes(stdout) {
127
127
  return [...first.values()];
128
128
  }
129
129
 
130
+ /**
131
+ * A pane's current directory, read on its own by pane ID with display-message, for the relative
132
+ * paths of files a record entry names. It isn't in STUDIO_REPL_PANE_FORMAT: a directory's name
133
+ * can hold a newline, which there could forge another pane's row (Sol, candidate 116).
134
+ */
135
+ export const STUDIO_REPL_PANE_CWD_FORMAT = "#{pane_current_path}";
136
+
137
+ /**
138
+ * The directory from display-message's output, or "" unless it's one absolute path of at most
139
+ * 4,096 characters with no line break or NUL.
140
+ *
141
+ * @param {string} stdout
142
+ * @returns {string}
143
+ */
144
+ export function parseStudioReplPaneCwd(stdout) {
145
+ const path = String(stdout ?? "").replace(/\n$/, "");
146
+ return path.startsWith("/") && path.length <= 4096 && !/[\r\n\0]/.test(path) ? path : "";
147
+ }
148
+
130
149
  const STUDIO_REPL_READY_PROMPTS = {
131
150
  python: /^>>>[ \t]*$/,
132
151
  ipython: /^In \[\d+\]:[ \t]*$/,