From 2349c125eb0ded80483784b8965b166ea9da52bd Mon Sep 17 00:00:00 2001 From: Abhishek Anand Date: Wed, 2 Dec 2026 05:18:36 +0530 Subject: [PATCH 1/5] Save a file a task made to Downloads when it is clicked Clicked, a file in the outputs folder is copied to Downloads like a browser download, then opened there, or shown in Finder when it could run or is an archive. The same file clicked again finds the copy saved before; a different file of that name gets a numbered name. The answer can link it, and the app says where it went. --- coderunner/agent/loop.py | 2 +- coderunner/files/attached.py | 25 ++++++++++++++++++++++++ coderunner/server/gateway.py | 13 ++++++++++--- coderunner/server/web/app/app.js | 6 ++++-- tests/test_gateway.py | 33 ++++++++++++++++++++------------ tests/test_parallel.py | 12 ++++++++++-- 6 files changed, 71 insertions(+), 20 deletions(-) diff --git a/coderunner/agent/loop.py b/coderunner/agent/loop.py index e95c3c4..523be62 100644 --- a/coderunner/agent/loop.py +++ b/coderunner/agent/loop.py @@ -46,7 +46,7 @@ - For a long task (more than about five steps), first write a short plan with plan_update, once, and keep to it: mark steps done as they finish; rewrite it only when the approach must change. Short tasks need no plan. - The owner's shared folders are searchable with files_search (text, code, documents, images, audio, video). Link a file you used by its name and full path, as [Lease.pdf](/Users/me/Documents/Lease.pdf), or in angle brackets when the path has spaces, as [Lease.pdf](); {owner} opens it from the answer. - Save lasting preferences and facts with memory_save. Never store secrets. -- Save files you make for {owner} in /app/uploads/outputs: {owner} can open only those. +- Save files you make for {owner} in /app/uploads/outputs and link them: a click saves one to {owner}'s Downloads. {owner} can open only those. - Only your final message reaches {owner}, as a chat reply. A call's say field may carry a few words on what you are doing ("Checking Skyscanner for the 12th"), shown briefly as a status line; leave it out when there is nothing new. Never mention tools, clicks, element numbers, errors, timeouts or retries. - tell_owner keeps a finding you will want in the answer (a price, a choice you made), when you have no tool call to write beside. Your final message still holds everything. - When a site will not show what you need, get it from another site that has it before deciding it cannot be done. When only part can be found, answer with that part in the form asked (a table with the rows you have) and say in one sentence what is missing. diff --git a/coderunner/files/attached.py b/coderunner/files/attached.py index 3ea1631..ae9641a 100644 --- a/coderunner/files/attached.py +++ b/coderunner/files/attached.py @@ -254,3 +254,28 @@ async def for_the_model(ids: list[str], media, vision: bool, sandbox: bool) -> t if sandbox: note += f"\nCode in the sandbox finds each one under {SANDBOX_DIR}//." return note, images, shown + + +def to_downloads(copy: pathlib.Path, folder: pathlib.Path | None = None) -> pathlib.Path: + """A file a task made, saved where a browser saves a download: the owner's Downloads folder, under its own + name, or "name (2).ext" beside a different file of that name. Clicking the same file again finds the one saved + before rather than making another. Never executable, whatever the sandbox made it.""" + import filecmp + folder = folder or pathlib.Path.home() / "Downloads" + folder.mkdir(parents=True, exist_ok=True) + stem, suffix = copy.stem, copy.suffix + for n in range(1, 1000): + target = folder / (copy.name if n == 1 else f"{stem} ({n}){suffix}") + if target.is_symlink(): + continue + if target.is_file() and filecmp.cmp(copy, target, shallow=False): + return target + if not target.exists(): + try: + with open(target, "xb") as out, open(copy, "rb") as src: + shutil.copyfileobj(src, out) + except FileExistsError: + continue + os.chmod(target, 0o644) + return target + raise OSError("no free name in Downloads") diff --git a/coderunner/server/gateway.py b/coderunner/server/gateway.py index dadd289..fd359a9 100644 --- a/coderunner/server/gateway.py +++ b/coderunner/server/gateway.py @@ -578,7 +578,7 @@ async def call_tool(request: Request): async def open_file(request: Request): """A file an answer links to, or the search box found, opened on this computer when the owner clicks it: - only a file in the shared folders. Documents, pictures, sound and video open in their usual app; anything + a file in the shared folders, or one a task made (saved to Downloads first). Documents, pictures, sound and video open in their usual app; anything that could run (an app, a script, code) is shown in Finder instead, so a link written by a model never starts a program. A folder (search finds those too) is shown in Finder: an app is a folder as well.""" from ..files import attached @@ -605,7 +605,11 @@ async def open_file(request: Request): copy = await asyncio.to_thread(attached.snapshot_output, relative) if copy is None: return JSONResponse({"error": "That file is not in the assistant's outputs folder."}, status_code=404) - path, made = copy, True + # Clicked, it is the owner's: saved to Downloads like a browser download, then opened or shown there. + try: + path, made = await asyncio.to_thread(attached.to_downloads, copy), True + except OSError: + return JSONResponse({"error": "It could not be saved to your Downloads folder."}, status_code=500) shared = not made and index is not None and (path.is_file() or path.is_dir()) and \ index.folders.inside(str(path)) if not (made or shared): @@ -622,9 +626,12 @@ async def open_file(request: Request): argv = ["xdg-open", str(path if opens else path.parent)] done = await asyncio.to_thread(subprocess.run, argv, capture_output=True, timeout=20) svc.audit.write("file.opened", path=str(path), shown=not opens, origin=principal(request)) + saved = {"saved": str(path)} if made else {} if done.returncode: + if made: + return JSONResponse({"opened": False, "shown": False, **saved}) return JSONResponse({"error": "It could not be opened."}, status_code=500) - return JSONResponse({"opened": opens, "shown": not opens}) + return JSONResponse({"opened": opens, "shown": not opens, **saved}) async def files(request: Request): """GET without `q`: the index's status. GET with `q`: the files that answer it, best first (`kind` keeps diff --git a/coderunner/server/web/app/app.js b/coderunner/server/web/app/app.js index fafc448..642268d 100644 --- a/coderunner/server/web/app/app.js +++ b/coderunner/server/web/app/app.js @@ -1200,8 +1200,10 @@ function showEvent(e) { // A file an answer links to: opened on this computer by the assistant (only from the shared folders). document.addEventListener("open-file", async (event) => { - try { await api("/api/files/open", {method: "POST", body: JSON.stringify({path: event.detail.path})}); } - catch (err) { notice(err.message); } + try { + const done = await api("/api/files/open", {method: "POST", body: JSON.stringify({path: event.detail.path})}); + if (done?.saved) notice(`Saved to Downloads: ${done.saved.split("/").pop()}`); + } catch (err) { notice(err.message); } }); function listen() { diff --git a/tests/test_gateway.py b/tests/test_gateway.py index ab4ee97..e9c5f0c 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -248,7 +248,7 @@ def run(argv, **kwargs): self.assertEqual(ran, [["open", str(shared / "Lease.pdf")], ["open", "-R", str(shared / "run.command")], ["open", "-R", str(shared / "tool.py")]]) - async def test_a_file_a_task_made_opens_by_its_path_here_or_in_the_sandbox(self): + async def test_a_file_a_task_made_is_saved_to_downloads_and_opened_there_by_its_path_here_or_in_the_sandbox(self): import os import subprocess import tempfile @@ -261,6 +261,10 @@ async def test_a_file_a_task_made_opens_by_its_path_here_or_in_the_sandbox(self) (elsewhere / "private.pdf").write_bytes(b"%PDF") (outputs / "link.pdf").symlink_to(elsewhere / "private.pdf") home = pathlib.Path(tempfile.mkdtemp()).resolve() + user = pathlib.Path(tempfile.mkdtemp()).resolve() + downloads = user / "Downloads" + downloads.mkdir() + (downloads / "setup.sh").write_text("someone else's") self.svc.files = None ran = [] @@ -271,27 +275,32 @@ def run(argv, **kwargs): with mock.patch("coderunner.server.gateway.subprocess.run", run), \ mock.patch("coderunner.server.gateway.sys.platform", "darwin"), \ mock.patch("coderunner.files.attached.outputs_dir", return_value=outputs), \ - mock.patch("coderunner.core.paths.home", return_value=home): + mock.patch("coderunner.core.paths.home", return_value=home), \ + mock.patch("pathlib.Path.home", return_value=user): async with self.client() as client: post = lambda path: client.post("/api/files/open", json={"path": str(path)}, headers=admin) # noqa: E731 + pdf = str(downloads / "regional-restaurants-india.pdf") self.assertEqual((await post("/app/uploads/outputs/regional-restaurants-india.pdf")).json(), - {"opened": True, "shown": False}) + {"opened": True, "shown": False, "saved": pdf}) + # Clicked again, by its path here: the copy saved before, not a second one. self.assertEqual((await post(outputs / "regional-restaurants-india.pdf")).json(), - {"opened": True, "shown": False}) - self.assertEqual((await post("/app/uploads/outputs/setup.sh")).json(), {"opened": False, "shown": True}) + {"opened": True, "shown": False, "saved": pdf}) + # A different file of that name is left alone; what could run is shown in Finder, not run. + self.assertEqual((await post("/app/uploads/outputs/setup.sh")).json(), + {"opened": False, "shown": True, "saved": str(downloads / "setup (2).sh")}) # A link the sandbox left there leads nowhere outside it. self.assertEqual((await post("/app/uploads/outputs/link.pdf")).status_code, 404) self.assertEqual((await post("/app/uploads/outputs/../../../etc/hosts")).status_code, 404) gone = await post("/workspace/report.pdf") self.assertEqual(gone.status_code, 404) self.assertIn("inside the assistant's computer", gone.json()["error"]) - # What was opened is a copy outside the folder the sandbox writes, never the file there. - self.assertEqual([argv[:-1] for argv in ran], [["open"], ["open"], ["open", "-R"]]) - copies = [pathlib.Path(argv[-1]) for argv in ran] - self.assertTrue(all(home in copy.parents and outputs not in copy.parents for copy in copies)) - self.assertEqual([copy.name for copy in copies], ["regional-restaurants-india.pdf"] * 2 + ["setup.sh"]) - self.assertEqual(copies[0].read_bytes(), b"%PDF") - self.assertFalse(os.access(copies[2], os.X_OK)) + # What was opened is the copy in Downloads, never the file in the folder the sandbox writes. + self.assertEqual(ran, [["open", pdf], ["open", pdf], ["open", "-R", str(downloads / "setup (2).sh")]]) + self.assertEqual(sorted(p.name for p in downloads.iterdir()), + ["regional-restaurants-india.pdf", "setup (2).sh", "setup.sh"]) + self.assertEqual((downloads / "regional-restaurants-india.pdf").read_bytes(), b"%PDF") + self.assertEqual((downloads / "setup.sh").read_text(), "someone else's") + self.assertFalse(os.access(downloads / "setup (2).sh", os.X_OK)) def test_a_copy_is_taken_without_following_a_link_at_any_step(self): import os diff --git a/tests/test_parallel.py b/tests/test_parallel.py index a2b8cd3..56dd8c4 100644 --- a/tests/test_parallel.py +++ b/tests/test_parallel.py @@ -397,8 +397,16 @@ async def looked(args, ctx): fake.script = [step(n) for n in range(24)] + [{"role": "assistant", "content": "The Sony WH-CH720N, from two sites."}] # No summary to be had (agent.compaction), and results too short for the trim to let go of. fake.summary = lambda body: {"_status": 500, "error": "Compute error."} - rooms = iter([100000] * 24 + [6000] * 5) - with mock.patch.object(agent, "_room", side_effect=lambda context, conversation: next(rooms)): + # Full after 24 steps: a room that holds the instructions and request twice over and a little more, so + # what makes way is the steps, however long the instructions grow. + calls = [] + + def room(context, conversation): + calls.append(1) + if len(calls) <= 24: + return 100000 + return 2 * agent._size(fake.requests[0]["messages"][:3], [0, 0]) + 1000 + with mock.patch.object(agent, "_room", side_effect=room): ctx = RunContext(conversation="app:full") reply = await agent.run(ctx, "Best headphones?") self.assertEqual(reply, "The Sony WH-CH720N, from two sites.") From 27d0fdc45215919c7195e8bda7cba5f002dbb1b1 Mon Sep 17 00:00:00 2001 From: Abhishek Anand Date: Wed, 2 Dec 2026 21:08:01 +0530 Subject: [PATCH 2/5] Save a download with the umask's mode instead of a world-readable chmod --- coderunner/files/attached.py | 2 +- tests/test_gateway.py | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/coderunner/files/attached.py b/coderunner/files/attached.py index ae9641a..dd28f1d 100644 --- a/coderunner/files/attached.py +++ b/coderunner/files/attached.py @@ -272,10 +272,10 @@ def to_downloads(copy: pathlib.Path, folder: pathlib.Path | None = None) -> path return target if not target.exists(): try: + # A new file, as a browser saves one: read-write under the umask, never executable. with open(target, "xb") as out, open(copy, "rb") as src: shutil.copyfileobj(src, out) except FileExistsError: continue - os.chmod(target, 0o644) return target raise OSError("no free name in Downloads") diff --git a/tests/test_gateway.py b/tests/test_gateway.py index e9c5f0c..08ca9e2 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -298,6 +298,8 @@ def run(argv, **kwargs): self.assertEqual(ran, [["open", pdf], ["open", pdf], ["open", "-R", str(downloads / "setup (2).sh")]]) self.assertEqual(sorted(p.name for p in downloads.iterdir()), ["regional-restaurants-india.pdf", "setup (2).sh", "setup.sh"]) + # The sandbox made the script executable; the copy in Downloads is not. + self.assertFalse(os.stat(downloads / "setup (2).sh").st_mode & 0o111) self.assertEqual((downloads / "regional-restaurants-india.pdf").read_bytes(), b"%PDF") self.assertEqual((downloads / "setup.sh").read_text(), "someone else's") self.assertFalse(os.access(downloads / "setup (2).sh", os.X_OK)) From 1993415f6215de3e777b56bfbdf335cee1cd076f Mon Sep 17 00:00:00 2001 From: Abhishek Anand Date: Wed, 2 Dec 2026 22:41:16 +0530 Subject: [PATCH 3/5] Save a download under its name only once the whole file is there, and never hand back an executable copy The file is copied to a hidden temp file in Downloads first and then linked to its name without overwriting, so a failed copy leaves nothing behind. A same-name file with the same bytes is reused only if it is not executable. --- coderunner/files/attached.py | 65 ++++++++++++++++++++++----- tests/test_attached.py | 85 ++++++++++++++++++++++++++++++++++++ 2 files changed, 139 insertions(+), 11 deletions(-) diff --git a/coderunner/files/attached.py b/coderunner/files/attached.py index dd28f1d..f7863cd 100644 --- a/coderunner/files/attached.py +++ b/coderunner/files/attached.py @@ -259,23 +259,66 @@ async def for_the_model(ids: list[str], media, vision: bool, sandbox: bool) -> t def to_downloads(copy: pathlib.Path, folder: pathlib.Path | None = None) -> pathlib.Path: """A file a task made, saved where a browser saves a download: the owner's Downloads folder, under its own name, or "name (2).ext" beside a different file of that name. Clicking the same file again finds the one saved - before rather than making another. Never executable, whatever the sandbox made it.""" + before rather than making another. Never executable, whatever the sandbox made it, and never half-written: + the name is taken only once the whole file is there.""" import filecmp folder = folder or pathlib.Path.home() / "Downloads" folder.mkdir(parents=True, exist_ok=True) stem, suffix = copy.stem, copy.suffix - for n in range(1, 1000): - target = folder / (copy.name if n == 1 else f"{stem} ({n}){suffix}") - if target.is_symlink(): - continue - if target.is_file() and filecmp.cmp(copy, target, shallow=False): - return target - if not target.exists(): + tmp = None + try: + for n in range(1, 1000): + target = folder / (copy.name if n == 1 else f"{stem} ({n}){suffix}") + if target.is_symlink(): + continue + if target.is_file(): + # The same file saved before, unless that one could run. + if not target.stat().st_mode & 0o111 and filecmp.cmp(copy, target, shallow=False): + return target + continue + if target.exists(): + continue + if tmp is None: + tmp = _hidden_copy(copy, folder) try: - # A new file, as a browser saves one: read-write under the umask, never executable. - with open(target, "xb") as out, open(copy, "rb") as src: - shutil.copyfileobj(src, out) + _claim(tmp, target) except FileExistsError: continue return target + finally: + if tmp is not None: + with contextlib.suppress(FileNotFoundError): + os.unlink(tmp) raise OSError("no free name in Downloads") + + +def _hidden_copy(copy: pathlib.Path, folder: pathlib.Path) -> pathlib.Path: + """The whole file, copied under a hidden name in the folder it is saved to: owner read-write only.""" + fd, name = tempfile.mkstemp(dir=folder, prefix=".coderunner-", suffix=".part") + try: + with os.fdopen(fd, "wb") as out, open(copy, "rb") as src: + shutil.copyfileobj(src, out) + except BaseException: + with contextlib.suppress(FileNotFoundError): + os.unlink(name) + raise + return pathlib.Path(name) + + +def _claim(tmp: pathlib.Path, target: pathlib.Path) -> None: + """Give the finished copy its name, never over a file already there (FileExistsError).""" + try: + os.link(tmp, target) + return + except FileExistsError: + raise + except OSError: # a disk without hard links: hold the name, then put the copy in its place + pass + with open(target, "xb"): + pass + try: + os.replace(tmp, target) + except BaseException: + with contextlib.suppress(FileNotFoundError): + os.unlink(target) + raise diff --git a/tests/test_attached.py b/tests/test_attached.py index bf8a42f..e9f0713 100644 --- a/tests/test_attached.py +++ b/tests/test_attached.py @@ -395,5 +395,90 @@ async def test_a_file_too_large_is_refused_and_a_task_names_its_files(self): self.assertEqual(empty.status_code, 400) +class DownloadsTests(unittest.TestCase): + """A file a task made, saved into a Downloads folder (a temporary one here).""" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + root = pathlib.Path(tmp.name).resolve() + self.made, self.folder = root / "outputs", root / "Downloads" + self.made.mkdir() + self.folder.mkdir() + + def make(self, name, data, mode=0o644): + path = self.made / name + path.write_bytes(data) + os.chmod(path, mode) + return path + + def names(self): + return sorted(p.name for p in self.folder.iterdir()) + + def test_a_failed_copy_leaves_nothing_behind_and_a_retry_takes_the_name(self): + report = self.make("report.txt", b"hello world, the whole report") + real = attached.shutil.copyfileobj + + def half(src, out, *args): + out.write(src.read(5)) + out.flush() + raise OSError(28, "No space left on device") + with mock.patch.object(attached.shutil, "copyfileobj", half): + with self.assertRaises(OSError): + attached.to_downloads(report, self.folder) + self.assertEqual(self.names(), []) + with mock.patch.object(attached.shutil, "copyfileobj", real): + saved = attached.to_downloads(report, self.folder) + self.assertEqual(saved, self.folder / "report.txt") + self.assertEqual(saved.read_bytes(), report.read_bytes()) + self.assertEqual(self.names(), ["report.txt"]) + + def test_a_saved_file_is_never_executable(self): + script = self.make("setup.sh", b"echo hi", 0o755) + saved = attached.to_downloads(script, self.folder) + self.assertEqual(saved, self.folder / "setup.sh") + self.assertFalse(saved.stat().st_mode & 0o111) + + def test_the_same_file_already_there_but_executable_is_not_handed_back(self): + script = self.make("setup.sh", b"echo hi") + (self.folder / "setup.sh").write_bytes(b"echo hi") + os.chmod(self.folder / "setup.sh", 0o755) + saved = attached.to_downloads(script, self.folder) + self.assertEqual(saved, self.folder / "setup (2).sh") + self.assertFalse(saved.stat().st_mode & 0o111) + self.assertEqual(saved.read_bytes(), b"echo hi") + # Saved again: the copy made just now, not a third one. + self.assertEqual(attached.to_downloads(script, self.folder), saved) + self.assertEqual(self.names(), ["setup (2).sh", "setup.sh"]) + + def test_the_same_file_is_found_again_and_a_different_one_gets_a_number(self): + pdf = self.make("plan.pdf", b"%PDF-1") + first = attached.to_downloads(pdf, self.folder) + self.assertEqual(attached.to_downloads(pdf, self.folder), first) + pdf.write_bytes(b"%PDF-2") + self.assertEqual(attached.to_downloads(pdf, self.folder), self.folder / "plan (2).pdf") + self.assertEqual((self.folder / "plan.pdf").read_bytes(), b"%PDF-1") + self.assertEqual(self.names(), ["plan (2).pdf", "plan.pdf"]) + + def test_a_link_of_that_name_is_passed_over(self): + pdf = self.make("plan.pdf", b"%PDF") + elsewhere = self.made / "elsewhere.pdf" + elsewhere.write_bytes(b"%PDF") + (self.folder / "plan.pdf").symlink_to(elsewhere) + self.assertEqual(attached.to_downloads(pdf, self.folder), self.folder / "plan (2).pdf") + self.assertTrue((self.folder / "plan.pdf").is_symlink()) + self.assertEqual(elsewhere.read_bytes(), b"%PDF") + + def test_a_disk_without_hard_links_still_gets_the_whole_file(self): + pdf = self.make("plan.pdf", b"%PDF") + (self.folder / "plan.pdf").write_bytes(b"other") + with mock.patch.object(attached.os, "link", side_effect=PermissionError(1, "Operation not permitted")): + saved = attached.to_downloads(pdf, self.folder) + self.assertEqual(saved, self.folder / "plan (2).pdf") + self.assertEqual(saved.read_bytes(), b"%PDF") + self.assertEqual((self.folder / "plan.pdf").read_bytes(), b"other") + self.assertEqual(self.names(), ["plan (2).pdf", "plan.pdf"]) + + if __name__ == "__main__": unittest.main() From 3d33cd33b614d8b23cd9623e855260989682b50c Mon Sep 17 00:00:00 2001 From: Abhishek Anand Date: Thu, 3 Dec 2026 17:52:59 +0530 Subject: [PATCH 4/5] Reuse the copy a simultaneous click saved, pass over files that cannot be read, and name the saved file when nothing can open it The name is given only by a hard link of the whole copy, so no empty placeholder is ever left in Downloads; a disk without hard links gets a plain error. When the link loses to another click that saved the same bytes, that file is reused. A same-name file that cannot be read counts as someone else's. A missing opener or one that hangs is treated as a failed open, so the reply still says where the file was saved. --- coderunner/files/attached.py | 38 ++++++++++++------------------------ coderunner/server/gateway.py | 7 +++++-- tests/test_attached.py | 33 ++++++++++++++++++++++++------- tests/test_gateway.py | 22 +++++++++++++++++++++ 4 files changed, 66 insertions(+), 34 deletions(-) diff --git a/coderunner/files/attached.py b/coderunner/files/attached.py index f7863cd..00067cd 100644 --- a/coderunner/files/attached.py +++ b/coderunner/files/attached.py @@ -261,7 +261,6 @@ def to_downloads(copy: pathlib.Path, folder: pathlib.Path | None = None) -> path name, or "name (2).ext" beside a different file of that name. Clicking the same file again finds the one saved before rather than making another. Never executable, whatever the sandbox made it, and never half-written: the name is taken only once the whole file is there.""" - import filecmp folder = folder or pathlib.Path.home() / "Downloads" folder.mkdir(parents=True, exist_ok=True) stem, suffix = copy.stem, copy.suffix @@ -269,20 +268,17 @@ def to_downloads(copy: pathlib.Path, folder: pathlib.Path | None = None) -> path try: for n in range(1, 1000): target = folder / (copy.name if n == 1 else f"{stem} ({n}){suffix}") - if target.is_symlink(): - continue - if target.is_file(): - # The same file saved before, unless that one could run. - if not target.stat().st_mode & 0o111 and filecmp.cmp(copy, target, shallow=False): + if target.is_symlink() or target.exists(): + if _saved_before(copy, target): return target continue - if target.exists(): - continue if tmp is None: tmp = _hidden_copy(copy, folder) try: - _claim(tmp, target) + os.link(tmp, target) # the name, given only to the whole file and never over another except FileExistsError: + if _saved_before(copy, target): # a click at the same moment saved the same file + return target continue return target finally: @@ -305,20 +301,12 @@ def _hidden_copy(copy: pathlib.Path, folder: pathlib.Path) -> pathlib.Path: return pathlib.Path(name) -def _claim(tmp: pathlib.Path, target: pathlib.Path) -> None: - """Give the finished copy its name, never over a file already there (FileExistsError).""" - try: - os.link(tmp, target) - return - except FileExistsError: - raise - except OSError: # a disk without hard links: hold the name, then put the copy in its place - pass - with open(target, "xb"): - pass +def _saved_before(copy: pathlib.Path, target: pathlib.Path) -> bool: + """target is this same file saved before: a plain file, not executable, with the same bytes. One that cannot + be read is someone else's.""" + import filecmp try: - os.replace(tmp, target) - except BaseException: - with contextlib.suppress(FileNotFoundError): - os.unlink(target) - raise + return not target.is_symlink() and target.is_file() and not target.stat().st_mode & 0o111 and \ + filecmp.cmp(copy, target, shallow=False) + except OSError: + return False diff --git a/coderunner/server/gateway.py b/coderunner/server/gateway.py index fd359a9..89ba5a1 100644 --- a/coderunner/server/gateway.py +++ b/coderunner/server/gateway.py @@ -624,10 +624,13 @@ async def open_file(request: Request): argv = ["open", str(path)] if opens else ["open", "-R", str(path)] else: argv = ["xdg-open", str(path if opens else path.parent)] - done = await asyncio.to_thread(subprocess.run, argv, capture_output=True, timeout=20) + try: + failed = (await asyncio.to_thread(subprocess.run, argv, capture_output=True, timeout=20)).returncode + except (OSError, subprocess.TimeoutExpired): # no opener here (xdg-open missing), or it hung + failed = True svc.audit.write("file.opened", path=str(path), shown=not opens, origin=principal(request)) saved = {"saved": str(path)} if made else {} - if done.returncode: + if failed: if made: return JSONResponse({"opened": False, "shown": False, **saved}) return JSONResponse({"error": "It could not be opened."}, status_code=500) diff --git a/tests/test_attached.py b/tests/test_attached.py index e9f0713..6748351 100644 --- a/tests/test_attached.py +++ b/tests/test_attached.py @@ -469,16 +469,35 @@ def test_a_link_of_that_name_is_passed_over(self): self.assertTrue((self.folder / "plan.pdf").is_symlink()) self.assertEqual(elsewhere.read_bytes(), b"%PDF") - def test_a_disk_without_hard_links_still_gets_the_whole_file(self): + def test_a_disk_without_hard_links_says_so_and_leaves_nothing(self): pdf = self.make("plan.pdf", b"%PDF") - (self.folder / "plan.pdf").write_bytes(b"other") with mock.patch.object(attached.os, "link", side_effect=PermissionError(1, "Operation not permitted")): - saved = attached.to_downloads(pdf, self.folder) - self.assertEqual(saved, self.folder / "plan (2).pdf") - self.assertEqual(saved.read_bytes(), b"%PDF") - self.assertEqual((self.folder / "plan.pdf").read_bytes(), b"other") - self.assertEqual(self.names(), ["plan (2).pdf", "plan.pdf"]) + with self.assertRaises(OSError): + attached.to_downloads(pdf, self.folder) + self.assertEqual(self.names(), []) + def test_two_clicks_at_once_save_one_copy(self): + pdf = self.make("plan.pdf", b"%PDF") + real = os.link + + def other_click_first(src, dst): + # The other click links its whole copy to the name between this one's look and its link. + (self.folder / "plan.pdf").write_bytes(b"%PDF") + os.chmod(self.folder / "plan.pdf", 0o600) + return real(src, dst) + with mock.patch.object(attached.os, "link", other_click_first): + self.assertEqual(attached.to_downloads(pdf, self.folder), self.folder / "plan.pdf") + self.assertEqual(self.names(), ["plan.pdf"]) + + @unittest.skipIf(os.geteuid() == 0, "root reads any file") + def test_a_file_of_that_name_that_cannot_be_read_is_passed_over(self): + pdf = self.make("plan.pdf", b"%PDF") + locked = self.folder / "plan.pdf" + locked.write_bytes(b"%PDX") + os.chmod(locked, 0) + self.addCleanup(os.chmod, locked, 0o600) + self.assertEqual(attached.to_downloads(pdf, self.folder), self.folder / "plan (2).pdf") + self.assertEqual(self.names(), ["plan (2).pdf", "plan.pdf"]) if __name__ == "__main__": unittest.main() diff --git a/tests/test_gateway.py b/tests/test_gateway.py index 08ca9e2..d75be2f 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -304,6 +304,28 @@ def run(argv, **kwargs): self.assertEqual((downloads / "setup.sh").read_text(), "someone else's") self.assertFalse(os.access(downloads / "setup (2).sh", os.X_OK)) + async def test_a_saved_file_is_still_named_when_nothing_here_can_open_it(self): + import subprocess + import tempfile + from unittest import mock + outputs = pathlib.Path(tempfile.mkdtemp()).resolve() + (outputs / "report.pdf").write_bytes(b"%PDF") + user = pathlib.Path(tempfile.mkdtemp()).resolve() + self.svc.files = None + admin = {"Authorization": "Bearer " + ADMIN} + for problem in (FileNotFoundError(2, "No such file or directory: 'xdg-open'"), + subprocess.TimeoutExpired(["xdg-open"], 20)): + with mock.patch("coderunner.server.gateway.subprocess.run", side_effect=problem), \ + mock.patch("coderunner.server.gateway.sys.platform", "linux"), \ + mock.patch("coderunner.files.attached.outputs_dir", return_value=outputs), \ + mock.patch("coderunner.core.paths.home", return_value=pathlib.Path(tempfile.mkdtemp())), \ + mock.patch("pathlib.Path.home", return_value=user): + async with self.client() as client: + got = await client.post("/api/files/open", json={"path": "/app/uploads/outputs/report.pdf"}, + headers=admin) + self.assertEqual((got.status_code, got.json()), + (200, {"opened": False, "shown": False, "saved": str(user / "Downloads" / "report.pdf")})) + def test_a_copy_is_taken_without_following_a_link_at_any_step(self): import os import tempfile From e296a972cb383ba9c8a9cfa86aacaf0e078e244e Mon Sep 17 00:00:00 2001 From: Abhishek Anand Date: Thu, 3 Dec 2026 18:03:58 +0530 Subject: [PATCH 5/5] Make the download tests' files owner-only --- tests/test_attached.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_attached.py b/tests/test_attached.py index 6748351..9dc8cff 100644 --- a/tests/test_attached.py +++ b/tests/test_attached.py @@ -406,7 +406,7 @@ def setUp(self): self.made.mkdir() self.folder.mkdir() - def make(self, name, data, mode=0o644): + def make(self, name, data, mode=0o600): path = self.made / name path.write_bytes(data) os.chmod(path, mode) @@ -434,7 +434,7 @@ def half(src, out, *args): self.assertEqual(self.names(), ["report.txt"]) def test_a_saved_file_is_never_executable(self): - script = self.make("setup.sh", b"echo hi", 0o755) + script = self.make("setup.sh", b"echo hi", 0o700) saved = attached.to_downloads(script, self.folder) self.assertEqual(saved, self.folder / "setup.sh") self.assertFalse(saved.stat().st_mode & 0o111) @@ -442,7 +442,7 @@ def test_a_saved_file_is_never_executable(self): def test_the_same_file_already_there_but_executable_is_not_handed_back(self): script = self.make("setup.sh", b"echo hi") (self.folder / "setup.sh").write_bytes(b"echo hi") - os.chmod(self.folder / "setup.sh", 0o755) + os.chmod(self.folder / "setup.sh", 0o700) saved = attached.to_downloads(script, self.folder) self.assertEqual(saved, self.folder / "setup (2).sh") self.assertFalse(saved.stat().st_mode & 0o111)