ybelkada HF Staff commited on
Commit
4f2e92b
·
1 Parent(s): 2fee5e2

add terminal

Browse files
README.md CHANGED
@@ -37,6 +37,19 @@ description and the agent reliably breaks.
37
  A prompt inspector shows the fully assembled system prompt, attributes each
38
  section to where it came from, and diffs it against tau's default.
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  The theme control in the header cycles **System → Light → Dark**. System is the
41
  absence of a `data-theme` attribute, so the page still follows your OS with
42
  JavaScript disabled; an explicit choice is remembered per browser and applied by a
@@ -75,16 +88,27 @@ pytest
75
 
76
  ## Please read this before making the Space public
77
 
78
- **A Hugging Face Space is one container shared by every visitor, and the `bash`
79
- tool runs real commands.** Harness Studio confines each visitor to their own
80
- workspace directory, rejects file paths that resolve outside it (including via
81
- symlinks the agent writes itself), blocks an obvious denylist of commands, and
82
- caps turns, time, output, workspace size and concurrent runs. Tokens are never
83
- put in the environment, so the agent's shell cannot read them.
84
-
85
- None of that is a security boundary. It raises the cost of casual abuse and
86
- prevents accidental cross-visitor leakage; it will not stop a determined visitor.
87
- Keep the Space private or gated, treat the workspace as public, and prefer
 
 
 
 
 
 
 
 
 
 
 
88
  [Space OAuth](https://huggingface.co/docs/hub/spaces-oauth) (`hf_oauth: true`
89
  with the `inference-api` scope) over pasted tokens when you do open it up.
90
 
@@ -105,6 +129,8 @@ studio/registry.py session caps, run slots, idle GC
105
  studio/events.py bounded resumable event ring, SSE framing, redaction
106
  studio/api.py the HTTP surface
107
  static/reducer.js a port of tau's TuiEventAdapter
 
 
108
  vendor/tau/ a vendored copy of the tau source (see VENDORED_FROM)
109
  ```
110
 
 
37
  A prompt inspector shows the fully assembled system prompt, attributes each
38
  section to where it came from, and diffs it against tau's default.
39
 
40
+ **Clear chat** starts a fresh conversation while keeping the harness and the
41
+ workspace exactly as they are, so you can re-run the same prompt against the same
42
+ files without re-applying anything. Applying a harness also resets the chat, since
43
+ the prompt, tools and model are baked in when the session is built.
44
+
45
+ The workspace pane has a **Terminal** tab: one command at a time in the agent's
46
+ working directory, run through the *same* guarded bash tool the agent gets, so the
47
+ visitor has no more reach than the model does. It is not a PTY — no REPLs, no
48
+ editors — and it is disabled while the agent is running, because both would be
49
+ mutating one workspace and the post-run file sweep would then credit your changes
50
+ to the agent. Files you create this way are deliberately not badged as the
51
+ agent's work.
52
+
53
  The theme control in the header cycles **System → Light → Dark**. System is the
54
  absence of a `data-theme` attribute, so the page still follows your OS with
55
  JavaScript disabled; an explicit choice is remembered per browser and applied by a
 
88
 
89
  ## Please read this before making the Space public
90
 
91
+ **A Hugging Face Space is one container shared by every visitor, and both the
92
+ `bash` tool and the Terminal tab run real commands.** Harness Studio gives each
93
+ visitor their own workspace directory, rejects file paths that resolve outside it
94
+ (including via symlinks the agent writes itself), blocks an obvious denylist of
95
+ commands, and caps turns, time, output, workspace size and concurrent runs. Tokens
96
+ are never written to disk and never put in the environment, so no shell can read
97
+ them. Sandbox directories are named with their own random id, never the session
98
+ id — otherwise one `ls` of the sandbox root would hand a visitor every live
99
+ session, and the session id is all the `X-Studio-Session` header needs.
100
+
101
+ **What is still reachable.** A shell started by the agent or by the Terminal tab
102
+ runs as the container user with that user's full filesystem and network access. It
103
+ can read outside the workspace (`cat /etc/passwd` works), and it can read and
104
+ write another visitor's workspace if it finds the directory. The path guard applies
105
+ to the `read`/`write`/`edit` tools' arguments, not to what a shell does once it is
106
+ running; the denylist is hygiene against casual abuse, not a sandbox. Making this
107
+ safe needs real isolation (a container or VM per session), which a single Space
108
+ container cannot provide.
109
+
110
+ So: keep the Space private or gated, treat every workspace as public to other
111
+ visitors, put nothing sensitive in one, and prefer
112
  [Space OAuth](https://huggingface.co/docs/hub/spaces-oauth) (`hf_oauth: true`
113
  with the `inference-api` scope) over pasted tokens when you do open it up.
114
 
 
129
  studio/events.py bounded resumable event ring, SSE framing, redaction
130
  studio/api.py the HTTP surface
131
  static/reducer.js a port of tau's TuiEventAdapter
132
+ static/terminal.js the Terminal tab (one-shot commands, not a PTY)
133
+ static/theme.js the system/light/dark control
134
  vendor/tau/ a vendored copy of the tau source (see VENDORED_FROM)
135
  ```
136
 
static/app.js CHANGED
@@ -5,6 +5,7 @@ import { $, api, clear, el, setSessionId, tokens, withSession } from "./dom.js";
5
  import { Explorer, renderDiagnostics } from "./explorer.js";
6
  import { PromptInspector } from "./prompt-inspector.js";
7
  import { Reducer } from "./reducer.js";
 
8
  import { initTheme } from "./theme.js";
9
  import { render as renderTranscript } from "./transcript.js";
10
 
@@ -24,6 +25,28 @@ const inspector = new PromptInspector();
24
 
25
  const explorer = new Explorer({ onNotice: (message) => notice(message) });
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  const panel = new ConfigPanel({
28
  onChange: (preset) => {
29
  state.dirty = true;
@@ -147,6 +170,29 @@ $("apply-config").addEventListener("click", async () => {
147
  }
148
  });
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  $("reset-config").addEventListener("click", () => {
151
  panel.setConfig(state.session.config);
152
  state.dirty = false;
@@ -259,6 +305,14 @@ function paint() {
259
  $("cancel-run").hidden = !reduced.running;
260
  $("apply-config").disabled = reduced.running;
261
  $("reset-workspace").disabled = reduced.running;
 
 
 
 
 
 
 
 
262
 
263
  const queued = (reduced.queue.steering || 0) + (reduced.queue.followUp || 0);
264
  $("composer-hint").textContent = queued
 
5
  import { Explorer, renderDiagnostics } from "./explorer.js";
6
  import { PromptInspector } from "./prompt-inspector.js";
7
  import { Reducer } from "./reducer.js";
8
+ import { Terminal } from "./terminal.js";
9
  import { initTheme } from "./theme.js";
10
  import { render as renderTranscript } from "./transcript.js";
11
 
 
25
 
26
  const explorer = new Explorer({ onNotice: (message) => notice(message) });
27
 
28
+ // A manual command can create or change files, so the tree re-reads afterwards.
29
+ const terminal = new Terminal({
30
+ onAfterCommand: () => explorer.refresh().catch(() => {}),
31
+ });
32
+
33
+ // Workspace tabs. The views are separate elements rather than one re-rendered
34
+ // container so the terminal's scrollback survives a trip to the file tree.
35
+ for (const tab of document.querySelectorAll("[data-ws]")) {
36
+ tab.addEventListener("click", () => {
37
+ const want = tab.dataset.ws;
38
+ for (const other of document.querySelectorAll("[data-ws]")) {
39
+ other.classList.toggle("active", other === tab);
40
+ }
41
+ $("files-view").hidden = want !== "files";
42
+ $("terminal-view").hidden = want !== "terminal";
43
+ $("files-actions").hidden = want !== "files";
44
+ $("terminal-actions").hidden = want !== "terminal";
45
+ if (want === "terminal") terminal.focus();
46
+ else explorer.refresh().catch(() => {});
47
+ });
48
+ }
49
+
50
  const panel = new ConfigPanel({
51
  onChange: (preset) => {
52
  state.dirty = true;
 
170
  }
171
  });
172
 
173
+ $("clear-conversation").addEventListener("click", async () => {
174
+ if (!state.reducer.state.items.length) {
175
+ notice("The conversation is already empty.");
176
+ return;
177
+ }
178
+ if (!confirm("Clear the conversation? The harness and the workspace are kept.")) return;
179
+ const button = $("clear-conversation");
180
+ button.disabled = true;
181
+ try {
182
+ const payload = await api("/api/session/clear-conversation", { method: "POST" });
183
+ state.session = payload;
184
+ state.reducer.reset();
185
+ inspector.update(payload.prompt);
186
+ restartStream();
187
+ notice("Conversation cleared. The harness and the workspace are unchanged.");
188
+ } catch (failure) {
189
+ notice(failure.message);
190
+ } finally {
191
+ button.disabled = false;
192
+ paint();
193
+ }
194
+ });
195
+
196
  $("reset-config").addEventListener("click", () => {
197
  panel.setConfig(state.session.config);
198
  state.dirty = false;
 
305
  $("cancel-run").hidden = !reduced.running;
306
  $("apply-config").disabled = reduced.running;
307
  $("reset-workspace").disabled = reduced.running;
308
+ $("clear-conversation").disabled = reduced.running;
309
+ // The agent and the visitor would otherwise be mutating one workspace at once,
310
+ // and the post-run file sweep would credit manual changes to the agent.
311
+ $("term-run").disabled = reduced.running || terminal.busy;
312
+ $("term-command").disabled = reduced.running;
313
+ $("term-command").placeholder = reduced.running
314
+ ? "waiting for the agent to finish…"
315
+ : "ls -la";
316
 
317
  const queued = (reduced.queue.steering || 0) + (reduced.queue.followUp || 0);
318
  $("composer-hint").textContent = queued
static/index.html CHANGED
@@ -98,36 +98,65 @@
98
  aria-label="Prompt"></textarea>
99
  <div class="composer-actions">
100
  <span class="composer-hint" id="composer-hint"></span>
 
 
 
101
  <button type="button" id="cancel-run" class="ghost" hidden>Stop</button>
102
  <button type="submit" id="send-run" class="primary">Send</button>
103
  </div>
104
  </form>
105
  </section>
106
 
107
- <!-- ── Right: the workspace ─────────────────────────────────── -->
108
  <section class="pane pane-workspace">
109
  <div class="pane-head">
110
- <h2>Workspace</h2>
 
 
 
111
  <div class="head-actions">
112
- <button id="new-file" class="ghost small">New file</button>
113
- <button id="reset-workspace" class="ghost small">Clear</button>
 
 
 
 
 
114
  </div>
115
  </div>
116
- <div class="quota" id="quota"></div>
117
- <div class="tree" id="tree"></div>
118
- <div class="editor" id="editor" hidden>
119
- <div class="editor-head">
120
- <span class="editor-path" id="editor-path"></span>
121
- <div class="head-actions">
122
- <button id="save-file" class="primary small">Save</button>
123
- <button id="delete-file" class="ghost small danger">Delete</button>
124
- <button id="close-file" class="ghost small">Close</button>
 
 
 
125
  </div>
 
 
126
  </div>
127
- <textarea id="editor-text" spellcheck="false" aria-label="File contents"></textarea>
128
- <p class="editor-note" id="editor-note"></p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  </div>
130
- <div class="diagnostics" id="diagnostics"></div>
131
  </section>
132
  </main>
133
 
 
98
  aria-label="Prompt"></textarea>
99
  <div class="composer-actions">
100
  <span class="composer-hint" id="composer-hint"></span>
101
+ <button type="button" id="clear-conversation" class="ghost"
102
+ title="Start a fresh conversation, keeping the harness and the workspace"
103
+ >Clear chat</button>
104
  <button type="button" id="cancel-run" class="ghost" hidden>Stop</button>
105
  <button type="submit" id="send-run" class="primary">Send</button>
106
  </div>
107
  </form>
108
  </section>
109
 
110
+ <!-- ── Right: the workspace, as files or a terminal ──────────── -->
111
  <section class="pane pane-workspace">
112
  <div class="pane-head">
113
+ <div class="tabs" role="tablist">
114
+ <button class="tab active" data-ws="files" role="tab" id="ws-tab-files">Files</button>
115
+ <button class="tab" data-ws="terminal" role="tab" id="ws-tab-terminal">Terminal</button>
116
+ </div>
117
  <div class="head-actions">
118
+ <span class="head-actions" id="files-actions">
119
+ <button id="new-file" class="ghost small">New file</button>
120
+ <button id="reset-workspace" class="ghost small">Clear</button>
121
+ </span>
122
+ <span class="head-actions" id="terminal-actions" hidden>
123
+ <button id="term-clear" class="ghost small">Clear output</button>
124
+ </span>
125
  </div>
126
  </div>
127
+
128
+ <div class="ws-view" id="files-view">
129
+ <div class="quota" id="quota"></div>
130
+ <div class="tree" id="tree"></div>
131
+ <div class="editor" id="editor" hidden>
132
+ <div class="editor-head">
133
+ <span class="editor-path" id="editor-path"></span>
134
+ <div class="head-actions">
135
+ <button id="save-file" class="primary small">Save</button>
136
+ <button id="delete-file" class="ghost small danger">Delete</button>
137
+ <button id="close-file" class="ghost small">Close</button>
138
+ </div>
139
  </div>
140
+ <textarea id="editor-text" spellcheck="false" aria-label="File contents"></textarea>
141
+ <p class="editor-note" id="editor-note"></p>
142
  </div>
143
+ <div class="diagnostics" id="diagnostics"></div>
144
+ </div>
145
+
146
+ <div class="ws-view" id="terminal-view" hidden>
147
+ <p class="term-note">
148
+ One command at a time in the agent's workspace, behind the same guards the
149
+ agent's <code>bash</code> tool gets. Not an interactive shell — no REPLs or
150
+ editors.
151
+ </p>
152
+ <div class="term-scroll" id="term-scroll" role="log" aria-live="polite"></div>
153
+ <form class="term-form" id="term-form" autocomplete="off">
154
+ <span class="term-sigil" aria-hidden="true">$</span>
155
+ <input id="term-command" type="text" spellcheck="false" autocapitalize="off"
156
+ placeholder="ls -la" aria-label="Terminal command">
157
+ <button type="submit" class="primary small" id="term-run">Run</button>
158
+ </form>
159
  </div>
 
160
  </section>
161
  </main>
162
 
static/styles.css CHANGED
@@ -311,6 +311,9 @@ label { display: block; font-size: 12px; color: var(--text-dim);
311
  .node .badge.modified { background: var(--modified); }
312
  .node .size { margin-left: auto; color: var(--text-faint); font-size: 11px; }
313
 
 
 
 
314
  .editor { flex: 1 1 auto; display: flex; flex-direction: column; min-height: 0;
315
  border-top: 1px solid var(--border); }
316
  .editor-head { display: flex; align-items: center; gap: 8px; padding: 7px 10px;
@@ -330,6 +333,30 @@ label { display: block; font-size: 12px; color: var(--text-dim);
330
  .diag.warning { color: var(--warn); }
331
  .diag.error { color: var(--error); }
332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
  /* ── prompt drawer ───────────────────────────────────────── */
334
 
335
  /* A row of its own rather than an overlay: as a flex child of body it shortens
 
311
  .node .badge.modified { background: var(--modified); }
312
  .node .size { margin-left: auto; color: var(--text-faint); font-size: 11px; }
313
 
314
+ /* Only one workspace view is mounted at a time; both need to fill the pane. */
315
+ .ws-view { flex: 1 1 auto; display: flex; flex-direction: column; min-height: 0; }
316
+
317
  .editor { flex: 1 1 auto; display: flex; flex-direction: column; min-height: 0;
318
  border-top: 1px solid var(--border); }
319
  .editor-head { display: flex; align-items: center; gap: 8px; padding: 7px 10px;
 
333
  .diag.warning { color: var(--warn); }
334
  .diag.error { color: var(--error); }
335
 
336
+ /* ── terminal ────────────────────────────────────────────── */
337
+
338
+ .term-note { flex: 0 0 auto; margin: 0; padding: 8px 12px; font-size: 11.5px;
339
+ color: var(--text-faint); border-bottom: 1px solid var(--border);
340
+ background: var(--bg-raised); }
341
+ .term-note code { color: var(--text-dim); }
342
+ .term-scroll { flex: 1 1 auto; overflow-y: auto; padding: 8px 12px;
343
+ background: var(--bg-sunken); font-family: var(--mono); font-size: 12px;
344
+ line-height: 1.5; min-height: 80px; }
345
+ .term-empty { color: var(--text-faint); font-style: italic; }
346
+ .term-entry { margin-bottom: 10px; }
347
+ .term-echo { color: var(--accent); overflow-wrap: anywhere; }
348
+ .term-echo .term-sigil { color: var(--text-faint); margin-right: 6px; }
349
+ .term-out { margin: 3px 0 0; white-space: pre-wrap; overflow-wrap: anywhere;
350
+ color: var(--text-dim); max-height: 340px; overflow-y: auto; }
351
+ .term-entry.failed .term-out { color: var(--error); }
352
+ .term-entry.blocked .term-out { color: var(--warn); }
353
+ .term-meta { font-size: 10.5px; color: var(--text-faint); margin-top: 2px; }
354
+ .term-form { flex: 0 0 auto; display: flex; align-items: center; gap: 8px;
355
+ padding: 9px 12px; border-top: 1px solid var(--border);
356
+ background: var(--bg-raised); }
357
+ .term-form .term-sigil { color: var(--accent); font-family: var(--mono); }
358
+ .term-form input { flex: 1; min-width: 0; font-family: var(--mono); font-size: 12.5px; }
359
+
360
  /* ── prompt drawer ───────────────────────────────────────── */
361
 
362
  /* A row of its own rather than an overlay: as a flex child of body it shortens
static/terminal.js ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // The visitor's own terminal: one command at a time in the agent's workspace.
2
+ //
3
+ // Not a PTY. A real interactive shell would mean a websocket, a pty pair and an
4
+ // emulator bundle, and would hand every visitor of a shared container a live
5
+ // shell. A one-shot runner covers what this app is actually for -- looking at what
6
+ // the agent did, running the tests yourself -- and it reaches the server through
7
+ // the very same guarded bash tool the agent uses, so there is one containment
8
+ // story rather than two.
9
+
10
+ import { $, api, clear, el } from "./dom.js";
11
+
12
+ const MAX_ENTRIES = 80;
13
+ const MAX_HISTORY = 50;
14
+
15
+ export class Terminal {
16
+ constructor({ onAfterCommand }) {
17
+ this.scroll = $("term-scroll");
18
+ this.input = $("term-command");
19
+ this.onAfterCommand = onAfterCommand;
20
+ this.entries = [];
21
+ this.history = [];
22
+ this.historyIndex = -1;
23
+ this.busy = false;
24
+
25
+ $("term-form").addEventListener("submit", (event) => {
26
+ event.preventDefault();
27
+ this.run(this.input.value);
28
+ });
29
+ $("term-clear").addEventListener("click", () => {
30
+ this.entries = [];
31
+ this.render();
32
+ });
33
+ this.input.addEventListener("keydown", (event) => this._onKey(event));
34
+ this.render();
35
+ }
36
+
37
+ focus() {
38
+ this.input.focus();
39
+ }
40
+
41
+ _onKey(event) {
42
+ if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
43
+ if (!this.history.length) return;
44
+ event.preventDefault();
45
+ if (event.key === "ArrowUp") {
46
+ this.historyIndex = this.historyIndex < 0
47
+ ? this.history.length - 1
48
+ : Math.max(0, this.historyIndex - 1);
49
+ } else if (this.historyIndex < 0) {
50
+ return;
51
+ } else if (this.historyIndex >= this.history.length - 1) {
52
+ this.historyIndex = -1;
53
+ this.input.value = "";
54
+ return;
55
+ } else {
56
+ this.historyIndex += 1;
57
+ }
58
+ this.input.value = this.history[this.historyIndex] ?? "";
59
+ // Put the caret at the end, where you would expect it after recall.
60
+ requestAnimationFrame(() => {
61
+ this.input.setSelectionRange(this.input.value.length, this.input.value.length);
62
+ });
63
+ }
64
+
65
+ async run(raw) {
66
+ const command = raw.trim();
67
+ if (!command || this.busy) return;
68
+
69
+ this.busy = true;
70
+ $("term-run").disabled = true;
71
+ this.input.value = "";
72
+ if (this.history[this.history.length - 1] !== command) this.history.push(command);
73
+ if (this.history.length > MAX_HISTORY) this.history.shift();
74
+ this.historyIndex = -1;
75
+
76
+ const entry = { command, output: "", state: "running", meta: "" };
77
+ this._push(entry);
78
+
79
+ try {
80
+ const result = await api("/api/terminal", { method: "POST", body: { command } });
81
+ entry.output = result.output || "";
82
+ if (result.blocked) {
83
+ entry.state = "blocked";
84
+ } else if (result.timedOut) {
85
+ entry.state = "failed";
86
+ entry.output = `${entry.output}\n(timed out)`.trim();
87
+ } else {
88
+ entry.state = result.exitCode === 0 ? "ok" : "failed";
89
+ }
90
+ entry.meta = [
91
+ result.exitCode === null || result.exitCode === undefined
92
+ ? null
93
+ : `exit ${result.exitCode}`,
94
+ result.durationSeconds ? `${result.durationSeconds}s` : null,
95
+ result.truncated ? "output truncated" : null,
96
+ ]
97
+ .filter(Boolean)
98
+ .join(" · ");
99
+ } catch (failure) {
100
+ entry.state = failure.status === 409 ? "blocked" : "failed";
101
+ entry.output = failure.message;
102
+ } finally {
103
+ this.busy = false;
104
+ $("term-run").disabled = false;
105
+ this.render();
106
+ this.focus();
107
+ // A command can create or change files, so let the file tree catch up.
108
+ this.onAfterCommand?.();
109
+ }
110
+ }
111
+
112
+ _push(entry) {
113
+ this.entries.push(entry);
114
+ if (this.entries.length > MAX_ENTRIES) this.entries.shift();
115
+ this.render();
116
+ }
117
+
118
+ render() {
119
+ const host = clear(this.scroll);
120
+ if (!this.entries.length) {
121
+ host.append(el("p", { class: "term-empty", text:
122
+ "Nothing run yet. Try `ls -la`, `cat fizz.py`, or `python3 -m pytest -q`." }));
123
+ return;
124
+ }
125
+ for (const entry of this.entries) {
126
+ const node = el("div", { class: `term-entry ${entry.state}` }, [
127
+ el("div", { class: "term-echo" }, [
128
+ el("span", { class: "term-sigil", text: "$" }),
129
+ entry.command,
130
+ ]),
131
+ ]);
132
+ if (entry.state === "running") {
133
+ node.append(el("p", { class: "term-out", text: "running…" }));
134
+ } else {
135
+ node.append(el("p", { class: "term-out", text: entry.output || "(no output)" }));
136
+ if (entry.meta) node.append(el("div", { class: "term-meta", text: entry.meta }));
137
+ }
138
+ host.append(node);
139
+ }
140
+ this.scroll.scrollTop = this.scroll.scrollHeight;
141
+ }
142
+ }
studio/api.py CHANGED
@@ -88,6 +88,10 @@ class PathBody(BaseModel):
88
  path: str = Field(min_length=1, max_length=1024)
89
 
90
 
 
 
 
 
91
  # -- session ------------------------------------------------------------
92
 
93
 
@@ -217,6 +221,30 @@ async def reset_workspace(session: Annotated[StudioSession, Depends(current)]) -
217
  return Response(status_code=204)
218
 
219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  @router.get("/session/export", response_class=HTMLResponse)
221
  async def export_session(session: Annotated[StudioSession, Depends(current)]) -> HTMLResponse:
222
  """A standalone HTML transcript, using tau's own session exporter."""
 
88
  path: str = Field(min_length=1, max_length=1024)
89
 
90
 
91
+ class CommandBody(BaseModel):
92
+ command: str = Field(min_length=1, max_length=4000)
93
+
94
+
95
  # -- session ------------------------------------------------------------
96
 
97
 
 
221
  return Response(status_code=204)
222
 
223
 
224
+ @router.post("/session/clear-conversation")
225
+ async def clear_conversation(
226
+ session: Annotated[StudioSession, Depends(current)],
227
+ ) -> dict[str, Any]:
228
+ """Start a fresh conversation without touching the harness or the workspace."""
229
+ try:
230
+ await session.clear_conversation()
231
+ except RunInProgress as exc:
232
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
233
+ return {**session.describe(), "prompt": prompt_mod.inspection_payload(session.session)}
234
+
235
+
236
+ @router.post("/terminal")
237
+ async def run_terminal(
238
+ session: Annotated[StudioSession, Depends(current)],
239
+ body: CommandBody,
240
+ ) -> dict[str, Any]:
241
+ """Run one command in the visitor's workspace, behind the agent's own guards."""
242
+ try:
243
+ return await session.run_terminal(body.command)
244
+ except RunInProgress as exc:
245
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
246
+
247
+
248
  @router.get("/session/export", response_class=HTMLResponse)
249
  async def export_session(session: Annotated[StudioSession, Depends(current)]) -> HTMLResponse:
250
  """A standalone HTML transcript, using tau's own session exporter."""
studio/sandbox.py CHANGED
@@ -9,6 +9,7 @@ Each visitor gets a directory tree under ``HS_ROOT`` and an explicit
9
  from __future__ import annotations
10
 
11
  import os
 
12
  import shutil
13
  from dataclasses import dataclass
14
  from pathlib import Path
@@ -42,7 +43,17 @@ class Sandbox:
42
 
43
  @classmethod
44
  def create(cls, sid: str, *, root: Path | None = None) -> Sandbox:
45
- base = (root or LIMITS.root) / sid
 
 
 
 
 
 
 
 
 
 
46
  sandbox = cls(sid=sid, root=base)
47
  for path in (sandbox.workspace, sandbox.tau_home, sandbox.agents_home):
48
  path.mkdir(parents=True, exist_ok=True)
 
9
  from __future__ import annotations
10
 
11
  import os
12
+ import secrets
13
  import shutil
14
  from dataclasses import dataclass
15
  from pathlib import Path
 
43
 
44
  @classmethod
45
  def create(cls, sid: str, *, root: Path | None = None) -> Sandbox:
46
+ """Create a visitor's directories under a name unrelated to their sid.
47
+
48
+ The directory must NOT be named after the session id. Every visitor's bash
49
+ tool -- and the Studio's own terminal -- can list the sandbox root, since
50
+ all sandboxes belong to the one container user. If the names were sids, a
51
+ single ``ls`` would hand over every live session: the sid is all the
52
+ ``X-Studio-Session`` header needs, so that is session takeover, with
53
+ inference billed to someone else's token. A separate random name means an
54
+ attacker learns only that other sessions exist.
55
+ """
56
+ base = (root or LIMITS.root) / secrets.token_urlsafe(12)
57
  sandbox = cls(sid=sid, root=base)
58
  for path in (sandbox.workspace, sandbox.tau_home, sandbox.agents_home):
59
  path.mkdir(parents=True, exist_ok=True)
studio/session.py CHANGED
@@ -17,6 +17,7 @@ from tau_coding.paths import TauPaths
17
  from tau_coding.resources import TauResourcePaths
18
  from tau_coding.session import CodingSession, CodingSessionConfig
19
  from tau_coding.session_preparation import prepare_coding_session
 
20
 
21
  from studio import prompt as prompt_mod
22
  from studio.catalog import PROVIDER_NAME, hf_settings
@@ -24,7 +25,7 @@ from studio.config import LIMITS, HarnessConfig
24
  from studio.events import EventRing
25
  from studio.provider import build_provider
26
  from studio.sandbox import Sandbox
27
- from studio.tools import RunBudget, TouchedFiles, build_tools
28
 
29
  BASH_PREFIX = "set -o pipefail"
30
 
@@ -56,6 +57,7 @@ class StudioSession:
56
  self._touched = TouchedFiles()
57
  self._budget = RunBudget()
58
  self._run_lock = asyncio.Lock()
 
59
  self._run_task: asyncio.Task[None] | None = None
60
 
61
  # -- lifecycle ------------------------------------------------------
@@ -168,6 +170,71 @@ class StudioSession:
168
  await _close_quietly(self._session)
169
  self._session = None
170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  # -- running --------------------------------------------------------
172
 
173
  def start_run(self, text: str) -> int:
 
17
  from tau_coding.resources import TauResourcePaths
18
  from tau_coding.session import CodingSession, CodingSessionConfig
19
  from tau_coding.session_preparation import prepare_coding_session
20
+ from tau_coding.tools import ToolInputError
21
 
22
  from studio import prompt as prompt_mod
23
  from studio.catalog import PROVIDER_NAME, hf_settings
 
25
  from studio.events import EventRing
26
  from studio.provider import build_provider
27
  from studio.sandbox import Sandbox
28
+ from studio.tools import RunBudget, TouchedFiles, build_terminal_tool, build_tools
29
 
30
  BASH_PREFIX = "set -o pipefail"
31
 
 
57
  self._touched = TouchedFiles()
58
  self._budget = RunBudget()
59
  self._run_lock = asyncio.Lock()
60
+ self._terminal: object | None = None
61
  self._run_task: asyncio.Task[None] | None = None
62
 
63
  # -- lifecycle ------------------------------------------------------
 
170
  await _close_quietly(self._session)
171
  self._session = None
172
 
173
+ async def clear_conversation(self) -> None:
174
+ """Start a fresh conversation, keeping the harness exactly as it is.
175
+
176
+ tau's own ``new_session`` needs a ``SessionManager``, which the Studio
177
+ deliberately does not use (transcripts stay in memory), so a clean slate
178
+ means rebuilding the session from the same config. The workspace is left
179
+ alone: files are a separate axis, with their own Clear.
180
+ """
181
+ if self.running:
182
+ raise RunInProgress("cannot clear the conversation while a run is active")
183
+ await self.apply(self.config)
184
+ self.last_run_touched = {}
185
+
186
+ # -- terminal -------------------------------------------------------
187
+
188
+ async def run_terminal(self, command: str) -> dict[str, Any]:
189
+ """Run one command in the workspace on the visitor's behalf.
190
+
191
+ Refused while the agent is running: both would be mutating the same
192
+ workspace, and the post-run mtime sweep would then credit the visitor's
193
+ changes to the agent. A clear refusal beats a transcript that lies.
194
+ """
195
+ if self.running:
196
+ raise RunInProgress(
197
+ "the agent is working in this workspace; wait for the run to finish"
198
+ )
199
+ if self._terminal is None:
200
+ self._terminal = build_terminal_tool(
201
+ cwd=self.sandbox.workspace,
202
+ sandbox=self.sandbox,
203
+ shell_command_prefix=BASH_PREFIX,
204
+ )
205
+ self.touch()
206
+
207
+ tool = self._terminal
208
+ try:
209
+ result = await tool.execute( # type: ignore[attr-defined]
210
+ "terminal", {"command": command, "description": "visitor terminal command"}
211
+ )
212
+ except ToolInputError as exc:
213
+ # Guard rejections are the expected failure here, not a server error:
214
+ # show them where the visitor typed the command.
215
+ return {"output": str(exc), "exitCode": None, "blocked": True}
216
+ except Exception as exc:
217
+ return {
218
+ "output": f"{exc.__class__.__name__}: {exc}",
219
+ "exitCode": None,
220
+ "blocked": False,
221
+ }
222
+ finally:
223
+ self.sandbox.invalidate()
224
+
225
+ details = result.details if isinstance(result.details, dict) else {}
226
+ truncation = details.get("truncation")
227
+ return {
228
+ "output": "".join(
229
+ block.text for block in result.content if getattr(block, "type", "") == "text"
230
+ ),
231
+ "exitCode": details.get("exit_code"),
232
+ "timedOut": bool(details.get("timed_out")),
233
+ "durationSeconds": details.get("duration_seconds"),
234
+ "truncated": bool(truncation) and truncation != {},
235
+ "blocked": False,
236
+ }
237
+
238
  # -- running --------------------------------------------------------
239
 
240
  def start_run(self, text: str) -> int:
studio/tools.py CHANGED
@@ -157,6 +157,34 @@ def build_tools(
157
  return tools
158
 
159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  def _guard(
161
  name: str,
162
  inner: Any,
 
157
  return tools
158
 
159
 
160
+ def build_terminal_tool(
161
+ *,
162
+ cwd: Path,
163
+ sandbox: Sandbox,
164
+ shell_command_prefix: str | None = None,
165
+ ) -> AgentTool:
166
+ """A bash tool for the visitor's own terminal.
167
+
168
+ Deliberately the same executor behind the same guards as the agent's bash
169
+ tool: the visitor gets no more reach than the model does, so there is one
170
+ containment story to reason about rather than two. It keeps its own budget so
171
+ manual commands never consume the agent's per-run allowance, and a throwaway
172
+ tracker so manual edits are not badged as the agent's work.
173
+ """
174
+ definition = create_bash_tool_definition(cwd=cwd, shell_command_prefix=shell_command_prefix)
175
+ tool = definition.to_agent_tool()
176
+ return dataclasses.replace(
177
+ tool,
178
+ execute_fn=_guard(
179
+ "bash",
180
+ tool.execute_fn,
181
+ sandbox=sandbox,
182
+ touched=TouchedFiles(),
183
+ budget=RunBudget(limit=10**9),
184
+ ),
185
+ )
186
+
187
+
188
  def _guard(
189
  name: str,
190
  inner: Any,
tests/js/ui.test.mjs CHANGED
@@ -74,6 +74,32 @@ check("the close button is wired", /"drawer-close"\)\.addEventListener/.test(js)
74
  check("entering the studio hides the gate", /\$\("gate"\)\.hidden = true/.test(js));
75
  check("entering the studio shows the layout", /\$\("layout"\)\.hidden = false/.test(js));
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  if (failures.length) {
78
  console.error(`FAILED:\n- ${failures.join("\n- ")}`);
79
  process.exit(1);
 
74
  check("entering the studio hides the gate", /\$\("gate"\)\.hidden = true/.test(js));
75
  check("entering the studio shows the layout", /\$\("layout"\)\.hidden = false/.test(js));
76
 
77
+ // 6. The workspace is tabbed. Both views must be real elements that can be hidden,
78
+ // so the terminal's scrollback survives a trip to the file tree.
79
+ for (const id of ["files-view", "terminal-view", "files-actions", "terminal-actions"]) {
80
+ check(`#${id} exists`, html.includes(`id="${id}"`));
81
+ }
82
+ check("the tab switch toggles both views",
83
+ /\$\("files-view"\)\.hidden/.test(js) && /\$\("terminal-view"\)\.hidden/.test(js));
84
+ check("only one workspace view starts visible",
85
+ /id="terminal-view"[^>]*\shidden/.test(html) && !/id="files-view"[^>]*\shidden/.test(html));
86
+ check("the .ws-view rule lets a view fill the pane",
87
+ /\.ws-view\s*\{[^}]*flex:\s*1 1 auto/.test(css));
88
+
89
+ // 7. Clear-chat must be static markup, not rebuilt by paintRunbar -- a handler
90
+ // attached once would otherwise be discarded on the next repaint.
91
+ check("#clear-conversation is in the markup", html.includes('id="clear-conversation"'));
92
+ check("#clear-conversation is not rebuilt by the run bar",
93
+ !/paintRunbar[\s\S]*?id: "clear-conversation"/.test(js));
94
+
95
+ // 8. The terminal must be disabled while the agent runs, or both would mutate the
96
+ // same workspace and the file sweep would misattribute the visitor's changes.
97
+ check("the terminal is disabled during a run", /\$\("term-run"\)\.disabled = reduced\.running/.test(js));
98
+ check("terminal controls exist",
99
+ ["term-scroll", "term-command", "term-run", "term-form", "term-clear"]
100
+ .every((id) => html.includes(`id="${id}"`)));
101
+ check("the terminal says it is not a real shell", /not an interactive shell/i.test(html));
102
+
103
  if (failures.length) {
104
  console.error(`FAILED:\n- ${failures.join("\n- ")}`);
105
  process.exit(1);
tests/test_api.py CHANGED
@@ -147,3 +147,51 @@ def test_prompt_inspection_is_attributed(client: TestClient) -> None:
147
  kinds = [s["kind"] for s in payload["sources"]]
148
  assert "default" in kinds
149
  assert payload["text"].startswith("You are an expert coding assistant")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  kinds = [s["kind"] for s in payload["sources"]]
148
  assert "default" in kinds
149
  assert payload["text"].startswith("You are an expert coding assistant")
150
+
151
+
152
+ def test_terminal_endpoint_runs_commands(client: TestClient) -> None:
153
+ client.post("/api/session", json={"token": "hf_good"})
154
+ client.put("/api/files/content", json={"path": "note.txt", "content": "hello\n"})
155
+
156
+ ran = client.post("/api/terminal", json={"command": "cat note.txt"})
157
+ assert ran.status_code == 200
158
+ body = ran.json()
159
+ assert body["exitCode"] == 0
160
+ assert "hello" in body["output"]
161
+
162
+
163
+ def test_terminal_endpoint_reports_blocks_as_output(client: TestClient) -> None:
164
+ """A guard rejection is expected input, not a server error."""
165
+ client.post("/api/session", json={"token": "hf_good"})
166
+ blocked = client.post("/api/terminal", json={"command": "wget http://example.com"})
167
+ assert blocked.status_code == 200
168
+ assert blocked.json()["blocked"] is True
169
+
170
+
171
+ def test_terminal_endpoint_validates_its_input(client: TestClient) -> None:
172
+ client.post("/api/session", json={"token": "hf_good"})
173
+ assert client.post("/api/terminal", json={"command": ""}).status_code == 422
174
+ assert client.post("/api/terminal", json={"command": "x" * 5000}).status_code == 422
175
+
176
+
177
+ def test_terminal_endpoint_needs_a_session(client: TestClient) -> None:
178
+ assert client.post("/api/terminal", json={"command": "ls"}).status_code == 401
179
+
180
+
181
+ def test_clear_conversation_endpoint(client: TestClient) -> None:
182
+ client.post("/api/session", json={"token": "hf_good"})
183
+ config = HarnessConfig(prompt_mode="override", system_prompt="You are a teapot.")
184
+ client.put("/api/session/config", json=config.model_dump(mode="json"))
185
+ client.put("/api/files/content", json={"path": "keep.txt", "content": "x"})
186
+
187
+ cleared = client.post("/api/session/clear-conversation")
188
+ assert cleared.status_code == 200
189
+ body = cleared.json()
190
+ # The harness and the workspace both survive; only the chat is gone.
191
+ assert body["config"]["system_prompt"] == "You are a teapot."
192
+ assert body["prompt"]["text"].startswith("You are a teapot.")
193
+ assert [e["path"] for e in client.get("/api/files").json()["entries"]] == ["keep.txt"]
194
+
195
+
196
+ def test_clear_conversation_needs_a_session(client: TestClient) -> None:
197
+ assert client.post("/api/session/clear-conversation").status_code == 401
tests/test_sandbox.py CHANGED
@@ -81,3 +81,24 @@ def test_destroy_and_sweep(tmp_path: Path) -> None:
81
 
82
  assert sweep_orphans(root) == 1
83
  assert (root / "_tmp").exists(), "the shared TMPDIR must survive a sweep"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  assert sweep_orphans(root) == 1
83
  assert (root / "_tmp").exists(), "the shared TMPDIR must survive a sweep"
84
+
85
+
86
+ def test_the_directory_name_is_not_the_session_id(tmp_path: Path) -> None:
87
+ """Every sandbox lives under one container user, so any visitor's shell can
88
+ list the sandbox root. If the directory names were session ids, one `ls` would
89
+ be session takeover -- the sid is all the X-Studio-Session header needs."""
90
+ root = tmp_path / "root"
91
+ sid = "a-very-recognisable-session-id"
92
+ sandbox = Sandbox.create(sid, root=root)
93
+
94
+ assert sandbox.sid == sid, "the session still knows its own id"
95
+ names = [child.name for child in root.iterdir()]
96
+ assert sid not in names
97
+ assert not any(sid in name for name in names)
98
+ assert sid not in str(sandbox.root)
99
+
100
+
101
+ def test_two_sandboxes_never_collide(tmp_path: Path) -> None:
102
+ root = tmp_path / "root"
103
+ roots = {Sandbox.create(f"sid-{i}", root=root).root for i in range(25)}
104
+ assert len(roots) == 25
tests/test_terminal.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The visitor's terminal, and clearing the conversation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+
7
+ import pytest
8
+ from tau_agent.messages import AssistantMessage, TextContent
9
+ from tau_ai.events import AssistantDoneEvent, AssistantStartEvent
10
+ from tau_ai.fake import FakeProvider
11
+
12
+ from studio.config import HarnessConfig
13
+ from studio.sandbox import Sandbox
14
+ from studio.session import RunInProgress, StudioSession
15
+
16
+
17
+ def _text_turn(text: str) -> list:
18
+ message = AssistantMessage(model="fake", content=[TextContent(text=text)], stop_reason="stop")
19
+ return [
20
+ AssistantStartEvent(partial=AssistantMessage(model="fake")),
21
+ AssistantDoneEvent(reason="stop", message=message),
22
+ ]
23
+
24
+
25
+ @pytest.fixture
26
+ def studio(tmp_path, monkeypatch) -> StudioSession:
27
+ provider = FakeProvider([_text_turn("Hi."), _text_turn("Again."), _text_turn("Third.")])
28
+ monkeypatch.setattr("studio.session.build_provider", lambda *a, **k: provider)
29
+ return StudioSession(
30
+ sid="t",
31
+ token="hf_token_value_long",
32
+ user="tester",
33
+ sandbox=Sandbox.create("t", root=tmp_path / "sb"),
34
+ client=None, # type: ignore[arg-type]
35
+ )
36
+
37
+
38
+ # -- terminal ----------------------------------------------------------
39
+
40
+
41
+ @pytest.mark.anyio
42
+ async def test_a_command_runs_in_the_workspace(studio: StudioSession) -> None:
43
+ await studio.apply(HarnessConfig())
44
+ (studio.sandbox.workspace / "hello.txt").write_text("contents\n")
45
+
46
+ result = await studio.run_terminal("cat hello.txt")
47
+ assert result["exitCode"] == 0
48
+ assert "contents" in result["output"]
49
+ assert result["blocked"] is False
50
+
51
+
52
+ @pytest.mark.anyio
53
+ async def test_a_failing_command_reports_its_exit_code(studio: StudioSession) -> None:
54
+ await studio.apply(HarnessConfig())
55
+ result = await studio.run_terminal("exit 3")
56
+ assert result["exitCode"] == 3
57
+
58
+
59
+ @pytest.mark.anyio
60
+ async def test_the_terminal_runs_under_bash(studio: StudioSession) -> None:
61
+ """Same prefix as the agent's tool, so bashisms behave the same way."""
62
+ await studio.apply(HarnessConfig())
63
+ result = await studio.run_terminal('if [[ -n "$BASH_VERSION" ]]; then echo yes; fi')
64
+ assert "yes" in result["output"]
65
+
66
+
67
+ @pytest.mark.anyio
68
+ async def test_the_terminal_starts_in_the_workspace(studio: StudioSession) -> None:
69
+ await studio.apply(HarnessConfig())
70
+ result = await studio.run_terminal("pwd")
71
+ assert studio.sandbox.relative(studio.sandbox.workspace) == "."
72
+ assert result["output"].strip().endswith("workspace")
73
+
74
+
75
+ @pytest.mark.anyio
76
+ async def test_the_terminal_obeys_the_same_denylist(studio: StudioSession) -> None:
77
+ """The visitor must get no more reach than the model does."""
78
+ await studio.apply(HarnessConfig())
79
+ result = await studio.run_terminal("curl http://example.com")
80
+ assert result["blocked"] is True
81
+ assert "network egress" in result["output"]
82
+ assert result["exitCode"] is None
83
+
84
+
85
+ @pytest.mark.anyio
86
+ async def test_a_blocked_command_does_not_raise(studio: StudioSession) -> None:
87
+ """It renders where the visitor typed it, not as a 500."""
88
+ await studio.apply(HarnessConfig())
89
+ for command in ("sudo id", "pip install requests", "printenv"):
90
+ result = await studio.run_terminal(command)
91
+ assert result["blocked"] is True, command
92
+
93
+
94
+ @pytest.mark.anyio
95
+ async def test_the_terminal_has_its_own_budget(studio: StudioSession) -> None:
96
+ """Manual commands must not consume the agent's per-run tool allowance."""
97
+ await studio.apply(HarnessConfig())
98
+ for _ in range(5):
99
+ assert (await studio.run_terminal("true"))["exitCode"] == 0
100
+ assert studio._budget.used == 0 # noqa: SLF001
101
+
102
+
103
+ @pytest.mark.anyio
104
+ async def test_the_terminal_does_not_badge_files_as_the_agents(studio: StudioSession) -> None:
105
+ await studio.apply(HarnessConfig())
106
+ await studio.run_terminal("echo hi > mine.txt")
107
+ assert (studio.sandbox.workspace / "mine.txt").exists()
108
+ assert studio.last_run_touched == {}
109
+
110
+
111
+ @pytest.mark.anyio
112
+ async def test_the_terminal_is_refused_during_a_run(studio: StudioSession) -> None:
113
+ await studio.apply(HarnessConfig())
114
+ gate = asyncio.Event()
115
+
116
+ async def blocked() -> None:
117
+ await gate.wait()
118
+
119
+ studio._run_task = asyncio.create_task(blocked()) # noqa: SLF001
120
+ with pytest.raises(RunInProgress, match="wait for the run to finish"):
121
+ await studio.run_terminal("ls")
122
+
123
+ gate.set()
124
+ await studio._run_task # noqa: SLF001
125
+ assert (await studio.run_terminal("true"))["exitCode"] == 0
126
+
127
+
128
+ @pytest.mark.anyio
129
+ async def test_the_terminal_refreshes_the_quota(studio: StudioSession) -> None:
130
+ await studio.apply(HarnessConfig())
131
+ studio.sandbox.usage(refresh=True)
132
+ await studio.run_terminal("printf 'xxxxxxxxxx' > big.txt")
133
+ assert studio.sandbox.usage(refresh=True).files == 1
134
+
135
+
136
+ # -- clearing the conversation -----------------------------------------
137
+
138
+
139
+ async def _run(studio: StudioSession, text: str) -> None:
140
+ studio.start_run(text)
141
+ await studio._run_task # noqa: SLF001
142
+
143
+
144
+ @pytest.mark.anyio
145
+ async def test_clearing_keeps_the_harness_and_the_workspace(studio: StudioSession) -> None:
146
+ config = HarnessConfig(prompt_mode="override", system_prompt="You are a teapot.")
147
+ await studio.apply(config)
148
+ (studio.sandbox.workspace / "keep.txt").write_text("still here\n")
149
+ await _run(studio, "hello")
150
+
151
+ assert studio.session.messages, "the run should have left a transcript"
152
+ before = studio.session.system_prompt
153
+
154
+ await studio.clear_conversation()
155
+
156
+ assert studio.session.messages == (), "the transcript should be empty"
157
+ assert studio.config == config, "the harness must be untouched"
158
+ assert studio.session.system_prompt == before
159
+ assert (studio.sandbox.workspace / "keep.txt").read_text() == "still here\n"
160
+ assert studio.last_run_touched == {}
161
+
162
+
163
+ @pytest.mark.anyio
164
+ async def test_clearing_resets_the_event_stream_without_reusing_ids(
165
+ studio: StudioSession,
166
+ ) -> None:
167
+ """Ids stay monotonic so a reconnecting reader never replays the old chat."""
168
+ await studio.apply(HarnessConfig())
169
+ await _run(studio, "hello")
170
+ last = studio.ring.since(0)[-1].seq
171
+
172
+ await studio.clear_conversation()
173
+ assert studio.ring.since(0) == []
174
+
175
+ studio.ring.push_studio("tick")
176
+ assert studio.ring.since(0)[0].seq > last
177
+
178
+
179
+ @pytest.mark.anyio
180
+ async def test_a_new_conversation_can_be_run_after_clearing(studio: StudioSession) -> None:
181
+ await studio.apply(HarnessConfig())
182
+ await _run(studio, "hello")
183
+ await studio.clear_conversation()
184
+ await _run(studio, "again")
185
+ roles = [message.role for message in studio.session.messages]
186
+ assert roles == ["user", "assistant"], roles
187
+
188
+
189
+ @pytest.mark.anyio
190
+ async def test_clearing_is_refused_during_a_run(studio: StudioSession) -> None:
191
+ await studio.apply(HarnessConfig())
192
+ gate = asyncio.Event()
193
+
194
+ async def blocked() -> None:
195
+ await gate.wait()
196
+
197
+ studio._run_task = asyncio.create_task(blocked()) # noqa: SLF001
198
+ with pytest.raises(RunInProgress):
199
+ await studio.clear_conversation()
200
+ gate.set()
201
+ await studio._run_task # noqa: SLF001