Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(terminal): add a persistent in-page linux terminal (#102878)

Marius Andra6d3a5f61f6dc
diff --git a/common/esbuilder/utils.mjs b/common/esbuilder/utils.mjs
index 49eb73f0482b..16ac470fc459 100644
--- a/common/esbuilder/utils.mjs
+++ b/common/esbuilder/utils.mjs
@@ -255,6 +255,7 @@ export const commonConfig = {
alias: {
buffer: 'buffer',
crypto: 'crypto-browserify',
+ 'node:crypto': 'crypto-browserify',
stream: 'stream-browserify',
},
tsconfig: tsconfigPath,
@@ -263,6 +264,8 @@ export const commonConfig = {
'process.env.NODE_ENV': isDev ? '"development"' : '"production"',
},
loader: {
+ '.bin': 'file',
+ '.wasm': 'file',
'.ttf': 'file',
'.png': 'file',
'.gif': 'file',
diff --git a/frontend/bin/build-terminal-tools.py b/frontend/bin/build-terminal-tools.py
new file mode 100644
index 000000000000..4a84b9a9f980
--- /dev/null
+++ b/frontend/bin/build-terminal-tools.py
@@ -0,0 +1,108 @@
+import io
+import sys
+import gzip
+import json
+import hashlib
+import tarfile
+import tempfile
+from pathlib import Path
+
+import requests
+
+FRONTEND = Path(__file__).resolve().parents[1]
+ASSETS = FRONTEND / "src" / "scenes" / "terminal" / "assets"
+MANIFEST = FRONTEND / "public" / "terminal" / "tools-manifest.json"
+PREFIX = "opt/posthog-tools"
+
+
+def download(url: str, algorithm: str, expected: str) -> bytes:
+ with requests.get(url, timeout=60) as response:
+ response.raise_for_status()
+ data = response.content
+ if hashlib.new(algorithm, data).hexdigest() != expected:
+ raise ValueError(f"Checksum mismatch: {url}")
+ return data
+
+
+def normalized(info: tarfile.TarInfo) -> tarfile.TarInfo:
+ info.uid = info.gid = info.mtime = 0
+ info.uname = info.gname = ""
+ # The source modes follow the build host: the umask decides what mkdir and write_text produce,
+ # and Linux reports every symlink as 0o777 because the kernel stores no symlink permissions.
+ # Fix the modes here so the same inputs give the same archive on every machine.
+ info.mode = 0o755 if info.isdir() or info.issym() or info.mode & 0o111 else 0o644
+ return info
+
+
+def build() -> None:
+ manifest = json.loads(MANIFEST.read_text())
+ with tempfile.TemporaryDirectory(prefix="posthog-terminal-tools-") as temporary:
+ root = Path(temporary)
+ tools = root / PREFIX
+ tools.mkdir(parents=True)
+ for package in manifest["packages"]:
+ data = download(f"{manifest['repository']}/{package['file']}", "sha256", package["sha256"])
+ # APK signatures, metadata, and payload are concatenated tar streams.
+ with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz", ignore_zeros=True) as archive:
+ members = [member for member in archive if member.name.startswith(("etc/", "lib/", "usr/"))]
+ archive.extractall(tools, members=members, filter="data")
+
+ licenses = tools / "licenses"
+ licenses.mkdir()
+ for source in manifest["sources"]:
+ data = download(source["url"], "sha512", source["sha512"])
+ with tarfile.open(fileobj=io.BytesIO(data)) as archive:
+ notices = []
+ for filename in source["license_files"]:
+ license_file = archive.extractfile(filename)
+ if license_file is None:
+ raise ValueError(f"Missing license: {filename}")
+ notices.append(filename.encode() + b"\n\n" + license_file.read())
+ (licenses / f"{source['name']}.txt").write_bytes(b"\n\n".join(notices))
+ (licenses / "tools-manifest.json").write_text(json.dumps(manifest, indent=4) + "\n")
+ (tools / "etc/nanorc").write_text(f'include "/{PREFIX}/usr/share/nano/*.nanorc"\n')
+ for directory in ("etc/mc", "usr/share/mc", "usr/lib/mc"):
+ link = root / directory
+ link.parent.mkdir(parents=True, exist_ok=True)
+ link.symlink_to(f"/{PREFIX}/{directory}")
+
+ wrappers = root / "usr/bin"
+ wrappers.mkdir(parents=True, exist_ok=True)
+ for command in ("nano", "tree", "ncdu", "mc", "mcview", "mcedit", "mcdiff"):
+ arguments = ""
+ if command == "nano":
+ arguments = f"--rcfile=/{PREFIX}/etc/nanorc "
+ elif command.startswith("mc"):
+ arguments = "-u "
+ wrapper = wrappers / command
+ # Isolate musl and ncurses from the guest's existing uClibc programs.
+ wrapper.write_text(
+ "#!/bin/sh\n"
+ f"export TERMINFO=/{PREFIX}/etc/terminfo LANG=C.UTF-8\n"
+ 'export TZ="$(cat /etc/TZ)"\n'
+ f"exec /{PREFIX}/lib/ld-musl-i386.so.1 "
+ f"--library-path /{PREFIX}/lib:/{PREFIX}/usr/lib "
+ f'/{PREFIX}/usr/bin/{command} {arguments}"$@"\n'
+ )
+ wrapper.chmod(0o755)
+
+ buffer = io.BytesIO()
+ with tarfile.open(fileobj=buffer, mode="w", format=tarfile.USTAR_FORMAT) as archive:
+ for path in sorted(root.rglob("*")):
+ archive.add(path, arcname=path.relative_to(root), recursive=False, filter=normalized)
+ # A fixed gzip header keeps the vendored archive reproducible.
+ with io.BytesIO() as compressed:
+ with gzip.GzipFile(fileobj=compressed, mode="wb", filename="", mtime=0) as output:
+ output.write(buffer.getvalue())
+ bundle = compressed.getvalue()
+ (ASSETS / "tools-linux-i386.tar.gz.bin").write_bytes(bundle)
+ (ASSETS / "hashes.json").write_text(
+ json.dumps({"toolsSha256": hashlib.sha256(bundle).hexdigest()}, indent=4) + "\n"
+ )
+ sys.stdout.write(
+ f"tools-linux-i386.tar.gz.bin: {len(bundle)} bytes, SHA-256 {hashlib.sha256(bundle).hexdigest()}\n"
+ )
+
+
+if __name__ == "__main__":
+ build()
diff --git a/frontend/package.json b/frontend/package.json
index eaf1f77fae2a..b41990c79627 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -199,6 +199,8 @@
"@tiptap/suggestion": "3.20.6",
"@vapi-ai/web": "2.5.2",
"@vitejs/plugin-react": "catalog:",
+ "@xterm/addon-fit": "0.10.0",
+ "@xterm/xterm": "5.5.0",
"@xyflow/react": "^12.6.0",
"bloommx": "^1.0.3",
"buffer": "^6.0.3",
@@ -292,6 +294,7 @@
"ts-pattern": "catalog:",
"use-debounce": "catalog:",
"use-resize-observer": "^8.0.0",
+ "v86": "0.5.458",
"zod": "^4.3.6",
"zxcvbn": "^4.4.2"
},
diff --git a/frontend/public/terminal/firmware-manifest.json b/frontend/public/terminal/firmware-manifest.json
new file mode 100644
index 000000000000..96b2f9144885
--- /dev/null
+++ b/frontend/public/terminal/firmware-manifest.json
@@ -0,0 +1,19 @@
+{
+ "name": "SeaBIOS",
+ "version": "1.16.2",
+ "source": "https://github.com/coreboot/seabios/tree/rel-1.16.2",
+ "repository": "https://github.com/copy/v86/tree/589487c7758a2775f606ec631bd78609497f6e05/bios",
+ "build_recipe": "https://github.com/copy/v86/blob/589487c7758a2775f606ec631bd78609497f6e05/bios/fetch-and-build-seabios.sh",
+ "files": [
+ {
+ "file": "seabios.bin",
+ "size": 131072,
+ "sha256": "73e3f359102e3a9982c35fce98eb7cd08f18303ac7f1ba6ebfbe6cdc1c244d98"
+ },
+ {
+ "file": "vgabios.bin",
+ "size": 36352,
+ "sha256": "a4bc0d80cc3ca028c73dafa8fee396b8d054ce87ebd8abfbd31b06b437607880"
+ }
+ ]
+}
diff --git a/frontend/public/terminal/glibc-COPYING.LIB.txt b/frontend/public/terminal/glibc-COPYING.LIB.txt
new file mode 100644
index 000000000000..4362b49151d7
--- /dev/null
+++ b/frontend/public/terminal/glibc-COPYING.LIB.txt
@@ -0,0 +1,502 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
diff --git a/frontend/public/terminal/jq-COPYING.txt b/frontend/public/terminal/jq-COPYING.txt
new file mode 100644
index 000000000000..c21d3f1645c7
--- /dev/null
+++ b/frontend/public/terminal/jq-COPYING.txt
@@ -0,0 +1,176 @@
+jq is copyright (C) 2012 Stephen Dolan
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+
+
+jq's documentation (everything found under the docs/ subdirectory in
+the source tree) is licensed under the Creative Commons CC BY 3.0
+license, which can be found at:
+
+ https://creativecommons.org/licenses/by/3.0/
+
+The documentation website includes a copy of Twitter's Bootstrap and
+relies on Bonsai, Liquid templates and various other projects, look
+them up for detailed licensing conditions.
+
+
+
+jq incorporates David M. Gay's dtoa.c and g_fmt.c, which bear the
+following notices:
+
+dtoa.c:
+The author of this software is David M. Gay.
+
+Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
+
+Permission to use, copy, modify, and distribute this software for any
+purpose without fee is hereby granted, provided that this entire notice
+is included in all copies of any software which is or includes a copy
+or modification of this software and in all copies of the supporting
+documentation for such software.
+
+THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
+WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
+REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
+OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
+
+g_fmt.c:
+The author of this software is David M. Gay.
+
+Copyright (c) 1991, 1996 by Lucent Technologies.
+
+Permission to use, copy, modify, and distribute this software for any
+purpose without fee is hereby granted, provided that this entire notice
+is included in all copies of any software which is or includes a copy
+or modification of this software and in all copies of the supporting
+documentation for such software.
+
+THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
+WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
+REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
+OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
+
+
+
+jq uses parts of the open source C library "decNumber", which is distributed
+under the following license:
+
+
+ICU License - ICU 1.8.1 and later
+
+COPYRIGHT AND PERMISSION NOTICE
+
+Copyright (c) 1995-2005 International Business Machines Corporation and others
+All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, and/or sell copies of the Software, and to permit persons
+to whom the Software is furnished to do so, provided that the above
+copyright notice(s) and this permission notice appear in all copies of
+the Software and that both the above copyright notice(s) and this
+permission notice appear in supporting documentation.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
+INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
+FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
+WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+Except as contained in this notice, the name of a copyright holder
+shall not be used in advertising or otherwise to promote the sale, use
+or other dealings in this Software without prior written authorization
+of the copyright holder.
+
+--------------------------------------------------------------------------------
+All trademarks and registered trademarks mentioned herein are the property of their respective owners.
+
+
+
+jv_thread.h is copied from Heimdal's lib/base/heimbase.h and some code
+in jv.c is copied from Heimdal's lib/base/dll.c:
+
+
+Portions Copyright (c) 2016 Kungliga Tekniska Högskolan
+(Royal Institute of Technology, Stockholm, Sweden).
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+
+jq uses a modified version of NetBSD implementation strptime(),
+which is distributed under the following license:
+
+Copyright (c) 1997, 1998, 2005, 2008 The NetBSD Foundation, Inc.
+All rights reserved.
+
+This code was contributed to The NetBSD Foundation by Klaus Klein.
+Heavily optimised by David Laight
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
diff --git a/frontend/public/terminal/oniguruma-COPYING.txt b/frontend/public/terminal/oniguruma-COPYING.txt
new file mode 100644
index 000000000000..ee4d7cf05501
--- /dev/null
+++ b/frontend/public/terminal/oniguruma-COPYING.txt
@@ -0,0 +1,26 @@
+Oniguruma LICENSE
+-----------------
+
+Copyright (c) 2002-2021 K.Kosako <[email protected]>
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
diff --git a/frontend/public/terminal/seabios-COPYING.LESSER.txt b/frontend/public/terminal/seabios-COPYING.LESSER.txt
new file mode 100644
index 000000000000..fc8a5de7edf4
--- /dev/null
+++ b/frontend/public/terminal/seabios-COPYING.LESSER.txt
@@ -0,0 +1,165 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/frontend/public/terminal/seabios-COPYING.txt b/frontend/public/terminal/seabios-COPYING.txt
new file mode 100644
index 000000000000..94a9ed024d38
--- /dev/null
+++ b/frontend/public/terminal/seabios-COPYING.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/frontend/public/terminal/tools-manifest.json b/frontend/public/terminal/tools-manifest.json
new file mode 100644
index 000000000000..719c3b9ed91a
--- /dev/null
+++ b/frontend/public/terminal/tools-manifest.json
@@ -0,0 +1,244 @@
+{
+ "repository": "https://dl-cdn.alpinelinux.org/alpine/v3.22/main/x86",
+ "packages": [
+ {
+ "file": "e2fsprogs-libs-1.47.2-r2.apk",
+ "sha256": "8a3009b0b395ea5a8677b7fe140348d2a7024cc92b87b0d6bff5c41f09fd95a9"
+ },
+ {
+ "file": "glib-2.84.4-r0.apk",
+ "sha256": "3968ecacf16189e4ebf1f9695dfb1aee386c681424642f6f8e10f1fe907c6f85"
+ },
+ {
+ "file": "gpm-libs-1.20.7-r5.apk",
+ "sha256": "3558b07e905878d2e222fd974809140593e6a2938ab8cc87db9e548d1c9182c2"
+ },
+ {
+ "file": "libblkid-2.41.6-r1.apk",
+ "sha256": "b536871f26d239656f839e067868aa2582e9393e5bc5107765d301b7b0707f7c"
+ },
+ {
+ "file": "libcom_err-1.47.2-r2.apk",
+ "sha256": "f4cabaa4e7200926d2a5583a15a37aee9717f343dc46b9d5e04af61b07468125"
+ },
+ {
+ "file": "libcrypto3-3.5.8-r0.apk",
+ "sha256": "0e213a6181a38fcd71df7ec50980ce98e777de5abe605268ab8bcbfa53683738"
+ },
+ {
+ "file": "libeconf-0.6.3-r0.apk",
+ "sha256": "a7a6cd5efb005dc5e693cdeb31ed857929a01573c993b38eceaa3c5c29dfce3f"
+ },
+ {
+ "file": "libffi-3.4.8-r0.apk",
+ "sha256": "ad588b91a38f0c2828347080c96a39062af51a1f06ea3d5e170a988781ef18b6"
+ },
+ {
+ "file": "libintl-0.24.1-r0.apk",
+ "sha256": "fb7e92fb73abbcbae080aba6241d7dd1d552b841023cef072f2f12dfa9caf008"
+ },
+ {
+ "file": "libmount-2.41.6-r1.apk",
+ "sha256": "0e693b246131572ec34289918698fe0f44babe3ef528163787b92775c4bfbfc7"
+ },
+ {
+ "file": "libncursesw-6.5_p20250503-r0.apk",
+ "sha256": "b1262e30c3eb0c9a9b74dba4f33c36ca37e33c4a060429af22f371236bfd4d61"
+ },
+ {
+ "file": "libssh2-1.11.1-r2.apk",
+ "sha256": "0f4d181fdbd1c387133e7bfd35ec929f84b1d913e9fd5dd751157e64a1955c55"
+ },
+ {
+ "file": "mc-4.8.33-r2.apk",
+ "sha256": "65084360daead16e500b1153286fa5853aeda04cb0e2dbbfcb039fb20224faae"
+ },
+ {
+ "file": "musl-1.2.5-r12.apk",
+ "sha256": "d047373c9afb6eaac68df1d03128ac75803350b0368327af85cc95a5b042a1da"
+ },
+ {
+ "file": "nano-8.4-r0.apk",
+ "sha256": "d5fb5ce60cc5b0f3f10f2c5bde5a30ae06d93537b08f0bf57ffd522f8ec290aa"
+ },
+ {
+ "file": "nano-syntax-8.4-r0.apk",
+ "sha256": "890d993bab1d6b41b078168116b399cf5736ed19b4b3593097dd2810b4c28c9f"
+ },
+ {
+ "file": "ncdu-1.22-r0.apk",
+ "sha256": "b19f10b46b05eafccafb92b4d0d720e30e657869b3d9b344829c33d99b8734f0"
+ },
+ {
+ "file": "ncurses-terminfo-base-6.5_p20250503-r0.apk",
+ "sha256": "3264426877964e0ac55488ede6313e907d3663f831008b45fa27c95d60ac34b8"
+ },
+ {
+ "file": "pcre2-10.46-r0.apk",
+ "sha256": "eafeb653254c467dcdf2032a6a936db0c5f500733a49d16d6a1a8e5b0225f0b9"
+ },
+ {
+ "file": "slang-2.3.3-r3.apk",
+ "sha256": "d07fde42b22018ae7db036f46644cd98ae5018102071ec6ac3775d323a53a850"
+ },
+ {
+ "file": "tree-2.2.1-r0.apk",
+ "sha256": "7b6f11680a3f16097d99bb0a5558b62499b1cbea1d1c39f7fed58f38b5ae325b"
+ },
+ {
+ "file": "zlib-1.3.2-r0.apk",
+ "sha256": "486231ba02da32d11a86d29ff838a6991a435b8d8c433926278efdbbcaea74dd"
+ }
+ ],
+ "sources": [
+ {
+ "name": "nano",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/nano-8.4.tar.xz",
+ "sha512": "1b8258e341a8722114b24af9d4676fbd8a91dc3639786a81bcd192a7b4fbca87581ab8ebe49493dfb3599ae90b59f4df8ae2a4ee0c0c7ccec9a49b563c82f44a",
+ "recipe": "https://github.com/alpinelinux/aports/tree/eadb70705bb9ed4a955c88a318bcf204efe43c71/main/nano",
+ "license_files": ["nano-8.4/COPYING"]
+ },
+ {
+ "name": "tree",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/unix-tree-2.2.1.tar.gz",
+ "sha512": "e7f514c2c12bc409d28c83a2c359bf463f8c624b6fc78cb847e0849925dfca746a9dac9a9e55b721972c474a33dba99a069f69694eaa08c12f4ce77db6d49953",
+ "recipe": "https://github.com/alpinelinux/aports/tree/f716d231228886a4bdd36b0a0e1c546f3708a56d/main/tree",
+ "license_files": ["unix-tree-2.2.1/LICENSE"]
+ },
+ {
+ "name": "ncdu",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/ncdu-1.22.tar.gz",
+ "sha512": "04f338e7b0992c1d94893dc6f2ad80318618690232c7bba43cd9a01ce513052460ed396dca49a060f31dbbb72dcddd59e7f78715dbe0da937a7f3d7725f8d2c1",
+ "recipe": "https://github.com/alpinelinux/aports/tree/340f9cbafa599f670f3019cfdc76b5f989e43012/main/ncdu",
+ "license_files": ["ncdu-1.22/COPYING"]
+ },
+ {
+ "name": "musl",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/musl-1.2.5.tar.gz",
+ "sha512": "7bb7f7833923cd69c7a1a9b8a5f1784bfd5289663eb6061dcd43d583e45987df8a68a1be05d75cc1c88a3f5b610653d1a70f4a9cff4d8f7fd41ae73ee058c17c",
+ "recipe": "https://github.com/alpinelinux/aports/tree/1546f29a1fd233db15464ce000b6247ed71b31e7/main/musl",
+ "license_files": ["musl-1.2.5/COPYRIGHT"]
+ },
+ {
+ "name": "ncurses",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/ncurses-6.5-20250503.tgz",
+ "sha512": "b417ea609e497eb746ddb3bef89eafb9eb9e78e605b4b8445cc47f005c22dae24c2c461cd014f7a76c1c6e3f685e0363a7a229af24360b4505483e3bd36efd41",
+ "recipe": "https://github.com/alpinelinux/aports/tree/3fefbe8dda8b3e85458edb190e2f3a69ad16035c/main/ncurses",
+ "license_files": ["ncurses-6.5-20250503/COPYING"]
+ },
+ {
+ "name": "mc",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/mc-4.8.33.tar.xz",
+ "sha512": "3eb857af2fa689e9458aeef6d3b236fb92684e05c0e3e78e7e5a5fa5dba6431cae39bec51bc84598b0bb60579cb0a0679dcdc6e9f7d88ca85dc37ace251c8632",
+ "recipe": "https://github.com/alpinelinux/aports/tree/be0833caee3020f089f02c5d7223e971a9a11ffb/main/mc",
+ "license_files": ["mc-4.8.33/COPYING"]
+ },
+ {
+ "name": "libssh2",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/libssh2-1.11.1.tar.gz",
+ "sha512": "8703636fc28f0b12c8171712f3d605e0466a5bb9ba06e136c3203548fc3408ab07defd71dc801d7009a337e1e02fd60e8933a2a526d5ef0ce53153058d201233",
+ "recipe": "https://github.com/alpinelinux/aports/tree/fad04f2cfb529992124330b331c6e3d3859a9c8d/main/libssh2",
+ "license_files": ["libssh2-1.11.1/COPYING"]
+ },
+ {
+ "name": "zlib",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/zlib-1.3.2.tar.gz",
+ "sha512": "70963771ea5d763614278a69b474f09b7d237ef8f53b675a10fe31d9923aeef601504b35d7ebd1b1e7f347e9ebb048e6b3b47fffdf137e7bdc7e8d5eb4ec4692",
+ "recipe": "https://github.com/alpinelinux/aports/tree/0276ab73299b3fd158361983f2f4ba573e0f7526/main/zlib",
+ "license_files": ["zlib-1.3.2/LICENSE"]
+ },
+ {
+ "name": "openssl",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/openssl-3.5.8.tar.gz",
+ "sha512": "62a1dbed0fad75245b332e41b85a1f7c2379189525e7628a7cf68947d115e90a47f179e3f87d27641e5b2d357c357292179fc0e64eccecdebc81c083f7a8ebe4",
+ "recipe": "https://github.com/alpinelinux/aports/tree/1b80b7c3bf5ba3f13eb748ae953d9215d5a4bb62/main/openssl",
+ "license_files": ["openssl-3.5.8/LICENSE.txt"]
+ },
+ {
+ "name": "slang",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/slang-2.3.3.tar.bz2",
+ "sha512": "f882f09e3fcd53427de0f233c9fc3ab15497f2323007be9a084696c8cf810ffe2726cd003149e757df26198b390b9f8c1ff411dc6473513457bd0f94722f8490",
+ "recipe": "https://github.com/alpinelinux/aports/tree/37d693b12294d28fe8c91a6d6ea4ed81fa0c4d20/main/slang",
+ "license_files": ["slang-2.3.3/COPYING"]
+ },
+ {
+ "name": "gettext",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/gettext-0.24.1.tar.xz",
+ "sha512": "53d5c54105598cc6156b940ff82d9754f4b7cdeafcd2400206c975db9412012511b60a7ebefcd31068a0bc2d99173ecd93a66844c7f3a9772df69d53b3cebeb5",
+ "recipe": "https://github.com/alpinelinux/aports/tree/215a26431d1b09c56cb2a9ffe10175feb9518fd8/main/gettext",
+ "license_files": ["gettext-0.24.1/gettext-runtime/intl/COPYING.LIB"]
+ },
+ {
+ "name": "gpm",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/gpm-1.20.7.tar.bz2",
+ "sha512": "51c1141ed502f8b6bc846485a8e315bafe3cf2b7c9d1ea8a710d9748ff2058f29c7ab5715fc1730a8437c613181d2050f37b134e9288c69ba8ff7fb0be7ec0d1",
+ "recipe": "https://github.com/alpinelinux/aports/tree/d257c5ac154c6eb9e0b58a79e2db42ac9a63f180/main/gpm",
+ "license_files": ["gpm-1.20.7/COPYING"]
+ },
+ {
+ "name": "glib",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/glib-2.84.4.tar.xz",
+ "sha512": "2de9b2f7376c0e5f6ee585087090675d597c474199a10d04aad18df688b6ca77d17e93a86ec07482898663f51c82121992272496318138f77ca5ad2c340a4bd3",
+ "recipe": "https://github.com/alpinelinux/aports/tree/9a0d606dfb2af556b9b96a9e8bb511b2bd0ddbed/main/glib",
+ "license_files": [
+ "glib-2.84.4/LICENSES/Apache-2.0.txt",
+ "glib-2.84.4/LICENSES/CC0-1.0.txt",
+ "glib-2.84.4/LICENSES/GPL-2.0-or-later.txt",
+ "glib-2.84.4/LICENSES/LGPL-2.1-only.txt",
+ "glib-2.84.4/LICENSES/LGPL-2.1-or-later.txt",
+ "glib-2.84.4/LICENSES/LLVM-exception.txt",
+ "glib-2.84.4/LICENSES/LicenseRef-old-glib-tests.txt",
+ "glib-2.84.4/LICENSES/MIT.txt",
+ "glib-2.84.4/LICENSES/MPL-1.1.txt"
+ ]
+ },
+ {
+ "name": "pcre2",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/pcre2-10.46.tar.bz2",
+ "sha512": "795b0d74efb898347990c29fefc85f37ac81e7795f9d6a5598d1169a03c547df7ff7eac280f708b1fef68d3e7686e0d4cd55f0c6364e287ff2a983bbd1a3c334",
+ "recipe": "https://github.com/alpinelinux/aports/tree/a22c8c27a78e00ea7cf03e09c6033a6336ee22a2/main/pcre2",
+ "license_files": ["pcre2-10.46/LICENCE.md", "pcre2-10.46/COPYING"]
+ },
+ {
+ "name": "util-linux",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/util-linux-2.41.6.tar.xz",
+ "sha512": "db63574a6e854c1b56876a125631ca94fcca77067f5b59c293f1b06b7765eb5e284d3cb6d31d319d6f7e9f7070881321fa6b8cc11f3453281454e9943e477560",
+ "recipe": "https://github.com/alpinelinux/aports/tree/b91fb14e28957c6f5a13c02eb9ec136c82ebd50e/main/util-linux",
+ "license_files": [
+ "util-linux-2.41.6/libblkid/COPYING",
+ "util-linux-2.41.6/libmount/COPYING",
+ "util-linux-2.41.6/Documentation/licenses/COPYING.BSD-2-Clause",
+ "util-linux-2.41.6/Documentation/licenses/COPYING.BSD-3-Clause",
+ "util-linux-2.41.6/Documentation/licenses/COPYING.BSD-4-Clause-UC",
+ "util-linux-2.41.6/Documentation/licenses/COPYING.EUPL-1.2",
+ "util-linux-2.41.6/Documentation/licenses/COPYING.GPL-2.0-only",
+ "util-linux-2.41.6/Documentation/licenses/COPYING.GPL-2.0-or-later",
+ "util-linux-2.41.6/Documentation/licenses/COPYING.GPL-3.0-or-later",
+ "util-linux-2.41.6/Documentation/licenses/COPYING.ISC",
+ "util-linux-2.41.6/Documentation/licenses/COPYING.LGPL-2.1-or-later",
+ "util-linux-2.41.6/Documentation/licenses/COPYING.MIT"
+ ]
+ },
+ {
+ "name": "libeconf",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/libeconf-0.6.3.tar.gz",
+ "sha512": "6a177474efa03d4933c1fff85eaf159837b9c803d3be8a8e8a23c271bbcd38f5513bc30df37592721c1d139c36a698fb224be012fa947595c0e90904e22fdadb",
+ "recipe": "https://github.com/alpinelinux/aports/tree/1e0aa723fba50417893fe5f6cf72f76d044b8192/main/libeconf",
+ "license_files": ["libeconf-0.6.3/LICENSE"]
+ },
+ {
+ "name": "libffi",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/libffi-3.4.8.tar.gz",
+ "sha512": "05344c6c1a1a5b44704f6cf99277098d1ea3ac1dc11c2a691c501786a214f76184ec0637135588630db609ce79e49df3dbd00282dd61e7f21137afba70e24ffe",
+ "recipe": "https://github.com/alpinelinux/aports/tree/be5e49159a2ccca93a3290af3d8ab25443523363/main/libffi",
+ "license_files": ["libffi-3.4.8/LICENSE"]
+ },
+ {
+ "name": "e2fsprogs",
+ "url": "https://distfiles.alpinelinux.org/distfiles/v3.22/e2fsprogs-1.47.2.tar.gz",
+ "sha512": "1dc86535b72a4ab60e17a547efe5e137054eff6cad9f6cf9cc9485694ec6166687a9d5f50fb47a10e776a70c7690ade5445c0339731f83066abf33c01f70d9c7",
+ "recipe": "https://github.com/alpinelinux/aports/tree/13f83cd1a99fa6ea58c6f8c3538971f2fb9ac634/main/e2fsprogs",
+ "license_files": ["e2fsprogs-1.47.2/NOTICE"]
+ }
+ ]
+}
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f713d3d5507b..fe473dbde226 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11252,6 +11252,22 @@ snapshots:
hash: v1.k794b7964.d4169f92563f1a61588ba823f6be7392267558bfbb86124b6e53ec9b18056418.acrrts8TAMCVepFdVIC0S1wZjdtoI-atFC1n-9B9Qwk
scenes-app-tasks--unified-navigation--light:
hash: v1.k794b7964.e0a6374da2da7262d08d1992bea3898259837679f5676f4330400d27559ac5d2.0GaInhE5K4q2-DGSz6KrZX6vsXX_WN_S8oNY3a1_ZzQ
+ scenes-app-terminal--default--dark:
+ hash: v1.k794b7964.0647acd4cc4525c6a5f0f5792805408120e874f6092a92db0ecf559725e47646.ve96neC-YTgo1mBSm1W7F7LOcJAz4-F6qUaAiXrjy2E
+ scenes-app-terminal--default--light:
+ hash: v1.k794b7964.09ecf1a6454895b4cc8336ea75615e27733a6f0e83e6a195fac566de956d06ba.l93c7xJK2992oHa4ojwl2B886SAirPasa7wWkpDN7L4
+ scenes-app-terminal--dock-disabled--dark:
+ hash: v1.k794b7964.403a28973d9199c1f21d005d8e91c1aeeb8d6266d18ba452b1c9404d89c42f9f.xOYN9HKJQanfqMaWQiKm-X9bfiQQJYv7mOAQK-P79nA
+ scenes-app-terminal--dock-disabled--light:
+ hash: v1.k794b7964.e1da9d891b653a0dd1cdc0dcf691275939eeccd10984fbdb18112491996dd10e.qTozQ3cjfXfDTbvEmEYMI9VvOYu3fplg4taw3BZWges
+ scenes-app-terminal--docked--dark:
+ hash: v1.k794b7964.9cf16ceae317c34434348b2a81d9c8155f81257886d14608c40448299dd4ae1c.K-_OW8hU0PX7X3wi_KsnzhjcPdcUDcUjMVOB1U-EJTM
+ scenes-app-terminal--docked--light:
+ hash: v1.k794b7964.a34850192db6d63249686b7ef1922b1b479312471ce974d91295757a4fce059b.2_jI8KKm2oYMSRxI2Fo5n-3tOzjyxTJ3t_YS8iAH1I0
+ scenes-app-terminal--narrow--dark:
+ hash: v1.k794b7964.36aebe98c0f44e2bfd0b6223bfc7fc33ece3cf81d6391d9baaaef157a06693f5.88obmOSvpcyTNe5SBWsYApI9WFSS4pyaJF68cZQ2MU4
+ scenes-app-terminal--narrow--light:
+ hash: v1.k794b7964.40e632562614b2fe983176d4bf14e5f204c526bd638d6a6ca778329e27dd59ae.N38an_Fe-D_BhL7P4XXobQ__tv-dkQJx6efpeH8Ep1c
scenes-app-tracing-tracingimpactcounts--no-coverage--dark:
hash: v1.k794b7964.fcfa5be29c5721d0db9fa21ecab20f16c04a4074c9af7fb3a58311900e168a48.449yuARgMYf4b4FJpXH8evt5uiuySFxQx1sco2E2Qs0
scenes-app-tracing-tracingimpactcounts--no-coverage--light:
diff --git a/frontend/src/layout/navigation-3000/Navigation.scss b/frontend/src/layout/navigation-3000/Navigation.scss
index 9061f55fe30f..2a0abe3deb5a 100644
--- a/frontend/src/layout/navigation-3000/Navigation.scss
+++ b/frontend/src/layout/navigation-3000/Navigation.scss
@@ -40,12 +40,12 @@
position: relative;
display: flex;
width: 100%;
- height: 100vh;
+ height: calc(100vh - var(--terminal-dock-height, 0px));
// On mobile browsers 100vh includes the area behind the collapsible browser toolbar, pushing
// bottom-anchored UI (chat composers, sticky footers) out of the visible viewport with no way to
// scroll to it. dvh tracks the actually-visible viewport; 100vh above stays as the fallback.
- height: 100dvh;
+ height: calc(100dvh - var(--terminal-dock-height, 0px));
overflow: hidden;
background: var(--color-bg-primary);
@@ -728,8 +728,11 @@
display: grid;
grid-template: 'left content' 1fr / var(--left-nav-width) minmax(0, 1fr);
- height: 100vh;
- height: 100dvh; // see .Navigation3000 — keep bottom-anchored UI reachable on mobile
+ height: calc(100vh - var(--terminal-dock-height, 0px));
+ height: calc(
+ 100dvh - var(--terminal-dock-height, 0px)
+ ); // see .Navigation3000 — keep bottom-anchored UI reachable on mobile
+
overflow: hidden;
.storybook-test-runner & {
diff --git a/frontend/src/lib/components/Search/searchLogic.test.ts b/frontend/src/lib/components/Search/searchLogic.test.ts
index be760fc230f7..d6cd48a1898d 100644
--- a/frontend/src/lib/components/Search/searchLogic.test.ts
+++ b/frontend/src/lib/components/Search/searchLogic.test.ts
@@ -1,6 +1,9 @@
import { expectLogic } from 'kea-test-utils'
import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { terminalDockLogic } from 'scenes/terminal/terminalDockLogic'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
@@ -63,6 +66,30 @@ describe('searchLogic', () => {
jest.restoreAllMocks()
})
+ it.each([false, true])('gates the command-menu terminal toggle when enabled=%s', (enabled) => {
+ logic.unmount()
+ logic = searchLogic({ logicKey: 'command' })
+ logic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: enabled })
+
+ const toggle = logic.values.miscItems.find((item) => item.id === 'misc-toggle-terminal')
+ expect(!!toggle).toBe(enabled)
+ expect(terminalDockLogic.values.dockOpen).toBe(false)
+ if (toggle) {
+ toggle.onSelect?.()
+ expect(terminalDockLogic.values.dockOpen).toBe(true)
+ toggle.onSelect?.()
+ expect(terminalDockLogic.values.dockOpen).toBe(false)
+ toggle.onSelect?.()
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ expect(terminalDockLogic.values.dockOpen).toBe(false)
+ expect(logic.values.miscItems.some((item) => item.id === 'misc-toggle-terminal')).toBe(false)
+ }
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ terminalDockLogic.actions.toggleTerminal()
+ expect(terminalDockLogic.values.dockOpen).toBe(false)
+ })
+
it('aborts and cancels the in-flight person search when the term is cleared', async () => {
neverResolvingPersonSearch()
diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsx
index 5c487fd0013a..f932b7f10118 100644
--- a/frontend/src/lib/components/Search/searchLogic.tsx
+++ b/frontend/src/lib/components/Search/searchLogic.tsx
@@ -3,7 +3,15 @@ import type { BreakPointFunction } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
-import { IconBell, IconBuilding, IconClock, IconDownload, IconLeave, IconNotification } from '@posthog/icons'
+import {
+ IconBell,
+ IconBuilding,
+ IconClock,
+ IconDownload,
+ IconLeave,
+ IconNotification,
+ IconTerminal,
+} from '@posthog/icons'
import api, { isAbortError } from 'lib/api'
import { commandLogic } from 'lib/components/Command/commandLogic'
@@ -20,6 +28,7 @@ import { capitalizeFirstLetter, toSentenceCase } from 'lib/utils/strings'
import { billingLogic } from 'scenes/billing/billingLogic'
import { organizationIntegrationsLogic } from 'scenes/settings/organization/organizationIntegrationsLogic'
import { teamLogic } from 'scenes/teamLogic'
+import { terminalDockLogic } from 'scenes/terminal/terminalDockLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -262,6 +271,9 @@ export interface searchLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface searchLogicActions {
+ toggleTerminal: () => {
+ value: true
+ } // terminalDockLogic
loadAccountSearchResults: ({ searchTerm }: { searchTerm: string }) => {
searchTerm: string
}
@@ -473,7 +485,11 @@ export interface searchLogicMeta {
}
playlistItems: (playlistSearchResults: FileSystemEntry[]) => SearchItem[]
healthItems: (sceneLogViewsByRef: Record<string, string>) => SearchItem[]
- miscItems: (sceneLogViewsByRef: Record<string, string>) => SearchItem[]
+ miscItems: (
+ sceneLogViewsByRef: Record<string, string>,
+ featureFlags: FeatureFlagsSet,
+ arg: string
+ ) => SearchItem[]
settingsItems: (
featureFlags: FeatureFlagsSet,
organizationIntegrations: IntegrationType[] | null,
@@ -547,6 +563,7 @@ export const searchLogic = kea<searchLogicType>([
props({} as SearchLogicProps),
key((props) => props.logicKey),
connect(() => ({
+ actions: [terminalDockLogic, ['toggleTerminal']],
values: [
groupsModel,
['groupTypes', 'aggregationLabel'],
@@ -1280,8 +1297,27 @@ export const searchLogic = kea<searchLogicType>([
],
],
miscItems: [
- (s) => [s.sceneLogViewsByRef],
- (sceneLogViewsByRef: Record<string, string>): SearchItem[] => [
+ (s) => [s.sceneLogViewsByRef, s.featureFlags, (_, props: SearchLogicProps) => props.logicKey],
+ (
+ sceneLogViewsByRef: Record<string, string>,
+ featureFlags: FeatureFlagsSet,
+ logicKey: string
+ ): SearchItem[] => [
+ ...(logicKey === 'command' && featureFlags[FEATURE_FLAGS.POSTHOG_TERMINAL]
+ ? [
+ {
+ id: 'misc-toggle-terminal',
+ name: 'Toggle terminal',
+ displayName: 'Toggle terminal',
+ category: 'misc',
+ icon: <IconTerminal />,
+ itemType: null,
+ searchKeywords: ['terminal', 'shell', 'console'],
+ onSelect: () => terminalDockLogic.actions.toggleTerminal(),
+ record: { type: 'terminal' },
+ },
+ ]
+ : []),
{
id: 'misc-exports',
name: 'Exports',
diff --git a/frontend/src/lib/components/Shortcuts/Shortcut.test.tsx b/frontend/src/lib/components/Shortcuts/Shortcut.test.tsx
index 414ee6719c6a..02674a6d3061 100644
--- a/frontend/src/lib/components/Shortcuts/Shortcut.test.tsx
+++ b/frontend/src/lib/components/Shortcuts/Shortcut.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { cleanup, render, screen } from '@testing-library/react'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { AccessControlAction } from 'lib/components/AccessControlAction'
@@ -18,6 +18,34 @@ describe('Shortcut', () => {
cleanup()
})
+ test.each([
+ { capture: true, key: 'k', ctrlKey: true, metaKey: false, shiftKey: false, triggered: false },
+ { capture: true, key: 'j', ctrlKey: true, metaKey: false, shiftKey: false, triggered: false },
+ { capture: false, key: 'k', ctrlKey: true, metaKey: false, shiftKey: false, triggered: true },
+ { capture: true, key: 'k', ctrlKey: false, metaKey: true, shiftKey: false, triggered: true },
+ { capture: true, key: '`', ctrlKey: true, metaKey: false, shiftKey: false, triggered: true },
+ { capture: true, key: '~', ctrlKey: true, metaKey: false, shiftKey: true, triggered: true },
+ ])('respects control-key capture: %j', ({ capture, key, ctrlKey, metaKey, shiftKey, triggered }) => {
+ const onClick = jest.fn()
+ render(
+ <div data-shortcuts-ignore={capture ? 'ctrl' : undefined} data-shortcuts-allow-keys="` ~">
+ <textarea aria-label="Terminal" />
+ <Shortcut
+ name="TestControlCapture"
+ keybind={[['command', ...(shiftKey ? ['shift'] : []), key]]}
+ intent="Test shortcut"
+ interaction="click"
+ >
+ <LemonButton onClick={onClick}>Test shortcut</LemonButton>
+ </Shortcut>
+ </div>
+ )
+
+ fireEvent.keyDown(screen.getByLabelText('Terminal'), { key, ctrlKey, metaKey, shiftKey })
+
+ expect(onClick).toHaveBeenCalledTimes(triggered ? 1 : 0)
+ })
+
// AccessControlAction injects disabledReason through Shortcut, which must forward it to the child.
test.each([
[AccessControlLevel.Viewer, false],
diff --git a/frontend/src/lib/components/Shortcuts/shortcutLogic.tsx b/frontend/src/lib/components/Shortcuts/shortcutLogic.tsx
index a6c40ce162fd..71256563d9cf 100644
--- a/frontend/src/lib/components/Shortcuts/shortcutLogic.tsx
+++ b/frontend/src/lib/components/Shortcuts/shortcutLogic.tsx
@@ -169,6 +169,18 @@ export const shortcutLogic = kea<shortcutLogicType>([
cache.sequenceLastKeyTime = 0
cache.onKeyDown = (event: KeyboardEvent) => {
+ const target = event.composedPath()[0]
+ const controlKeyCapture =
+ target instanceof HTMLElement ? target.closest<HTMLElement>('[data-shortcuts-ignore="ctrl"]') : null
+ if (
+ event.ctrlKey &&
+ !event.metaKey &&
+ controlKeyCapture &&
+ !controlKeyCapture.dataset.shortcutsAllowKeys?.split(' ').includes(event.key)
+ ) {
+ // Terminal editors need control keys before application shortcuts capture them.
+ return
+ }
const commandKey = event.metaKey || event.ctrlKey
// Handle modifier-based shortcuts (Cmd+K, etc.)
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index a2f06b51db07..bef0d96961ff 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -163,6 +163,7 @@ export const RETENTION_FIRST_EVER_OCCURRENCE = 'retention_first_ever_occurrence'
// if you want the script to properly create a multivariate flag. You can also specify the different
// variant keys separated by commas, e.g. `multivariate=control,test,something_else`
export const FEATURE_FLAGS = {
+ POSTHOG_TERMINAL: 'posthog-terminal', // owner: @mariusandra
// Eternal feature flags, shouldn't be removed, helpful for debugging/maintenance reasons
BILLING_FORECASTING_ISSUES: 'billing-forecasting-issues', // owner: #team-billing, see `Billing.tsx`, used to raise a warning when billing is having problems
COMING_SOON_WAITLIST_SURVEYS: 'coming-soon-waitlist-surveys', // owner: #team-growth, see `FeaturePreviews.tsx`, swaps concept-stage one-click for an email waitlist survey
diff --git a/frontend/src/scenes/AuthenticatedShell.tsx b/frontend/src/scenes/AuthenticatedShell.tsx
index 54c0df60ab60..569f5f3bf7c0 100644
--- a/frontend/src/scenes/AuthenticatedShell.tsx
+++ b/frontend/src/scenes/AuthenticatedShell.tsx
@@ -1,4 +1,5 @@
import { useMountedLogic, useValues } from 'kea'
+import { Suspense } from 'react'
import { Slide, ToastContainer } from 'react-toastify'
import { Command } from 'lib/components/Command/Command'
@@ -8,10 +9,12 @@ import { ToastCloseButton } from 'lib/lemon-ui/LemonToast/LemonToast'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { eventIngestionRestrictionLogic } from 'lib/logic/eventIngestionRestrictionLogic'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { lazyWithRetry } from 'lib/utils/retryImport'
import { WizardHandoffDialog } from 'scenes/onboarding/shared/wizard-sync/WizardHandoffDialog'
import { WizardSyncDebugPanel } from 'scenes/onboarding/shared/wizard-sync/WizardSyncDebugPanel'
import { WizardSyncFab } from 'scenes/onboarding/shared/wizard-sync/WizardSyncFab'
+import { ErrorBoundary } from '~/layout/ErrorBoundary'
import { GlobalModals } from '~/layout/GlobalModals'
import { GlobalShortcuts } from '~/layout/GlobalShortcuts'
import { Navigation } from '~/layout/navigation-3000/Navigation'
@@ -21,6 +24,10 @@ import { ImpersonationNotice } from '~/layout/navigation/ImpersonationNotice'
import { sceneLogic } from './sceneLogic'
+const TerminalDock = lazyWithRetry(() =>
+ import('./terminal/TerminalDock').then(({ TerminalDock }) => ({ default: TerminalDock }))
+)
+
export default function AuthenticatedShell({ children }: { children: React.ReactNode }): JSX.Element {
useMountedLogic(apiStatusLogic)
useMountedLogic(eventIngestionRestrictionLogic)
@@ -38,6 +45,13 @@ export default function AuthenticatedShell({ children }: { children: React.React
<Navigation sceneConfig={sceneConfig}>{children}</Navigation>
<GlobalModals />
<GlobalShortcuts />
+ {featureFlags[FEATURE_FLAGS.POSTHOG_TERMINAL] && (
+ <ErrorBoundary className="fixed bottom-0 inset-x-0 max-h-[60vh] overflow-auto z-modal bg-surface-primary">
+ <Suspense fallback={null}>
+ <TerminalDock />
+ </Suspense>
+ </ErrorBoundary>
+ )}
<Command />
<ImpersonationNotice />
<WizardSyncFab />
diff --git a/frontend/src/scenes/appScenes.ts b/frontend/src/scenes/appScenes.ts
index a226b9524127..229773df05c2 100644
--- a/frontend/src/scenes/appScenes.ts
+++ b/frontend/src/scenes/appScenes.ts
@@ -30,6 +30,7 @@ export const appScenes: Record<Scene | string, () => any> = {
[Scene.DeadLetterQueue]: () => import('./instance/DeadLetterQueue/DeadLetterQueue'),
[Scene.Destinations]: () => import('./data-pipelines/DestinationsScene'),
[Scene.DebugHog]: () => import('./debug/hog/HogRepl'),
+ [Scene.Terminal]: () => import('./terminal/TerminalScene'),
[Scene.ProjectFiles]: () => import('./project-files/ProjectFilesScene'),
[Scene.DebugQuery]: () => import('./debug/DebugScene'),
[Scene.Error404]: () => ({ default: preloadedScenes[Scene.Error404].component }),
diff --git a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncSurface.tsx b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncSurface.tsx
index 27700bf290e9..9687196c2aca 100644
--- a/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncSurface.tsx
+++ b/frontend/src/scenes/onboarding/shared/wizard-sync/WizardSyncSurface.tsx
@@ -15,7 +15,7 @@ import { wizardSyncUiLogic } from './wizardSyncUiLogic'
// Corner anchor for the collapsed card and the minimized launcher. The dialog is a portal, so it
// positions itself.
-const CORNER = 'fixed bottom-5 right-5 z-[60]'
+const CORNER = 'fixed bottom-[calc(1.25rem+var(--terminal-dock-height,0px))] right-5 z-[60]'
// Shared presentation for a single run: the collapsed card or, once dismissed, the launcher, plus the
// dialog. Owns the elapsed clock and reads the shared dismiss/expand UI state.
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index b20fccc92a65..794eab117fc3 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -51,6 +51,7 @@ export enum Scene {
DebugHog = 'DebugHog',
ProjectFiles = 'ProjectFiles',
DebugQuery = 'DebugQuery',
+ Terminal = 'Terminal',
EarlyAccessFeatures = 'EarlyAccessFeatures',
Error404 = '404',
ErrorAccessDenied = 'AccessDenied',
diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.ts
index 3f0c1f574701..d42a8f814380 100644
--- a/frontend/src/scenes/scenes.ts
+++ b/frontend/src/scenes/scenes.ts
@@ -152,6 +152,7 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {
[Scene.DebugHog]: { projectBased: true, name: 'Hog Repl' },
[Scene.ProjectFiles]: { projectBased: true, name: 'Files', layout: 'app-full-scene-height' },
[Scene.DebugQuery]: { projectBased: true },
+ [Scene.Terminal]: { projectBased: true, name: 'Terminal', layout: 'app-full-scene-height' },
[Scene.Error404]: { name: 'Not found', projectBased: true },
[Scene.ErrorAccessDenied]: { name: 'Access denied' },
@@ -892,6 +893,7 @@ export const routes: Record<string, [Scene | string, string]> = {
[urls.stripeConfirmInstall()]: [Scene.StripeConfirmInstall, 'stripeConfirmInstall'],
[urls.debugQuery()]: [Scene.DebugQuery, 'debugQuery'],
[urls.debugHog()]: [Scene.DebugHog, 'debugHog'],
+ [urls.terminal()]: [Scene.Terminal, 'terminal'],
[urls.projectFiles()]: [Scene.ProjectFiles, 'projectFiles'],
[urls.notebook(':shortId')]: [Scene.Notebook, 'notebook'],
diff --git a/frontend/src/scenes/terminal/TerminalDock.tsx b/frontend/src/scenes/terminal/TerminalDock.tsx
new file mode 100644
index 000000000000..c2181bcfbcd1
--- /dev/null
+++ b/frontend/src/scenes/terminal/TerminalDock.tsx
@@ -0,0 +1,35 @@
+import { useActions, useValues } from 'kea'
+import { Suspense } from 'react'
+
+import { useShortcut } from 'lib/components/Shortcuts/useShortcut'
+import { lazyWithRetry } from 'lib/utils/retryImport'
+
+import { terminalDockLogic } from './terminalDockLogic'
+
+const TerminalPanel = lazyWithRetry(() =>
+ import('./TerminalPanel').then(({ TerminalPanel }) => ({ default: TerminalPanel }))
+)
+
+export function TerminalDock(): JSX.Element | null {
+ const { hasOpened, terminalEnabled } = useValues(terminalDockLogic)
+ const { toggleTerminal } = useActions(terminalDockLogic)
+ useShortcut({
+ name: 'toggle-terminal',
+ disabled: !terminalEnabled,
+ keybind: [
+ ['ctrl', '`'],
+ ['ctrl', 'shift', '~'],
+ ['command', '`'],
+ ['command', 'shift', '~'],
+ ],
+ intent: 'Toggle terminal',
+ interaction: 'function',
+ callback: toggleTerminal,
+ priority: 10,
+ })
+ return hasOpened ? (
+ <Suspense fallback={null}>
+ <TerminalPanel />
+ </Suspense>
+ ) : null
+}
diff --git a/frontend/src/scenes/terminal/TerminalPanel.tsx b/frontend/src/scenes/terminal/TerminalPanel.tsx
new file mode 100644
index 000000000000..6c5bf839a6a8
--- /dev/null
+++ b/frontend/src/scenes/terminal/TerminalPanel.tsx
@@ -0,0 +1,91 @@
+import { useActions, useMountedLogic, useValues } from 'kea'
+import { router } from 'kea-router'
+import { useLayoutEffect, useRef } from 'react'
+
+import { Resizer } from 'lib/components/Resizer/Resizer'
+import { resizerLogic } from 'lib/components/Resizer/resizerLogic'
+import { cn } from 'lib/utils/css-classes'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+
+import { terminalDockLogic } from './terminalDockLogic'
+import { terminalLogic } from './terminalLogic'
+import { TerminalView } from './TerminalView'
+
+export function TerminalPanel(): JSX.Element | null {
+ useMountedLogic(terminalLogic)
+ const { dockOpen, hasOpened, terminalEnabled } = useValues(terminalDockLogic)
+ const { setDockOpen } = useActions(terminalDockLogic)
+ const { location } = useValues(router)
+ const container = useRef<HTMLDivElement>(null)
+ const resizeProps = {
+ logicKey: 'terminal-dock',
+ placement: 'top' as const,
+ containerRef: container,
+ persistent: true,
+ }
+ const { desiredSize } = useValues(resizerLogic(resizeProps))
+ const { setDesiredSize } = useActions(resizerLogic(resizeProps))
+ const fullScene = removeProjectIdIfPresent(location.pathname) === '/terminal'
+ const visible = terminalEnabled && dockOpen && !fullScene
+ useLayoutEffect(() => {
+ const dock = container.current
+ if (!visible || !dock) {
+ return
+ }
+ const reserveSpace = (): void => {
+ document.documentElement.style.setProperty(
+ '--terminal-dock-height',
+ `${dock.getBoundingClientRect().height}px`
+ )
+ }
+ reserveSpace()
+ const observer = new ResizeObserver(reserveSpace)
+ observer.observe(dock)
+ return () => {
+ observer.disconnect()
+ document.documentElement.style.removeProperty('--terminal-dock-height')
+ }
+ }, [visible])
+ if (!hasOpened) {
+ return null
+ }
+ return (
+ <div
+ ref={container}
+ data-attr="terminal-dock"
+ aria-label="Terminal panel"
+ className={cn(
+ 'fixed inset-x-0 bottom-0 z-[calc(var(--z-scene-layout-content-panel)+1)] border-t bg-surface-primary shadow-lg pt-1 min-h-40 max-h-[80vh]',
+ !visible && 'hidden'
+ )}
+ style={{ height: desiredSize ?? 320 }}
+ >
+ <Resizer {...resizeProps} />
+ <button
+ type="button"
+ role="separator"
+ aria-label="Resize terminal"
+ aria-orientation="horizontal"
+ aria-valuenow={desiredSize ?? 320}
+ aria-valuemin={160}
+ aria-valuemax={Math.floor(window.innerHeight * 0.8)}
+ className="absolute top-0 left-1/2 w-12 h-1 rounded bg-border cursor-ns-resize focus-visible:ring"
+ onKeyDown={(event) => {
+ if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
+ event.preventDefault()
+ setDesiredSize(
+ Math.max(
+ 160,
+ Math.min(
+ window.innerHeight * 0.8,
+ (desiredSize ?? 320) + (event.key === 'ArrowUp' ? 40 : -40)
+ )
+ )
+ )
+ }
+ }}
+ />
+ {visible && <TerminalView onClose={() => setDockOpen(false)} />}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/terminal/TerminalScene.stories.tsx b/frontend/src/scenes/terminal/TerminalScene.stories.tsx
new file mode 100644
index 000000000000..73efae2e1ed7
--- /dev/null
+++ b/frontend/src/scenes/terminal/TerminalScene.stories.tsx
@@ -0,0 +1,324 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { useValues } from 'kea'
+import { router } from 'kea-router'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { Command } from 'lib/components/Command/Command'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+
+import { GlobalShortcuts } from '~/layout/GlobalShortcuts'
+import { useStorybookMocks } from '~/mocks/browser'
+
+import { expect, spyOn, waitFor } from 'storybook/test'
+
+import { TerminalDock } from './TerminalDock'
+import { terminalDockLogic } from './terminalDockLogic'
+import { terminalLogic } from './terminalLogic'
+import { TerminalRuntime } from './terminalRuntime'
+import { TerminalScene } from './TerminalScene'
+import type { TerminalSession } from './TerminalSession'
+
+function DockedTerminalPreview(): JSX.Element {
+ const { location } = useValues(router)
+ return (
+ <>
+ <div className="app-layout">
+ <div className="left-nav flex flex-col gap-2 p-4">
+ <LemonButton to="/notebooks/demonote">Notebook page</LemonButton>
+ <LemonButton to="/terminal">Full terminal</LemonButton>
+ </div>
+ <div className="main-content-container flex min-h-0 flex-col p-4">
+ {removeProjectIdIfPresent(location.pathname) === '/terminal' ? (
+ <TerminalScene />
+ ) : (
+ <p>Press Ctrl+backtick or use Toggle terminal in Cmd+K.</p>
+ )}
+ </div>
+ </div>
+ <GlobalShortcuts />
+ <Command />
+ <TerminalDock />
+ </>
+ )
+}
+
+const meta: Meta<typeof TerminalScene> = {
+ title: 'Scenes-App/Terminal',
+ component: TerminalScene,
+ parameters: { layout: 'padded', featureFlags: [FEATURE_FLAGS.POSTHOG_TERMINAL] },
+ beforeEach: () => {
+ // Visual snapshots must not depend on firmware downloads or Linux boot timing.
+ const start = spyOn(TerminalRuntime.prototype, 'start').mockImplementation(
+ async (_server, _signal, onReady) => {
+ const { view } = terminalLogic.cache.session as TerminalSession
+ view.options.cursorBlink = false
+ await new Promise<void>((resolve) =>
+ view.write(
+ 'PostHog terminal\r\n\r\n' +
+ '\x1b[32mposthog\x1b[0m:\x1b[34m/posthog/files\x1b[0m $ ls\r\n' +
+ 'Objects Research\r\n' +
+ '\x1b[32mposthog\x1b[0m:\x1b[34m/posthog/files\x1b[0m $ ',
+ resolve
+ )
+ )
+ onReady()
+ }
+ )
+ return () => start.mockRestore()
+ },
+ render: (_, { parameters }) => {
+ const notebook = {
+ id: '01900000-0000-7000-8000-000000000002',
+ short_id: 'demonote',
+ title: 'Welcome',
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'ph-markdown-notebook',
+ attrs: { markdown: '# Welcome\n\nExplore PostHog with ordinary Unix tools.\n' },
+ },
+ ],
+ },
+ version: 1,
+ user_access_level: 'editor',
+ }
+ const notebooks = new Map([[notebook.short_id, notebook]])
+ const paths = new Map([[notebook.id, 'Research/Welcome']])
+ const folders = new Map([['01900000-0000-7000-8000-000000000005', 'Research']])
+ const objects = [
+ { type: 'dashboard', route: 'dashboards', ref: '101', name: 'Overview' },
+ { type: 'insight', route: 'insights', ref: 'demoinsight', name: 'Signups' },
+ { type: 'feature_flag', route: 'feature_flags', ref: '102', name: 'New navigation' },
+ { type: 'cohort', route: 'cohorts', ref: '103', name: 'Active users' },
+ { type: 'action', route: 'actions', ref: '104', name: 'Checkout' },
+ { type: 'survey', route: 'surveys', ref: '01900000-0000-7000-8000-000000000006', name: 'Feedback' },
+ { type: 'experiment', route: 'experiments', ref: '105', name: 'Signup test' },
+ ]
+ const objectData = new Map<string, Record<string, unknown>>(
+ objects.map((item) => [
+ item.ref,
+ { id: item.ref, name: item.name, description: 'Terminal demo', user_access_level: 'editor' },
+ ])
+ )
+ useStorybookMocks({
+ get: {
+ ...Object.fromEntries(
+ objects.map((item) => [
+ `/api/projects/:projectId/${item.route}/${item.ref}/`,
+ () => [200, objectData.get(item.ref)],
+ ])
+ ),
+ '/api/projects/:projectId/file_system/': () => [
+ 200,
+ {
+ count: notebooks.size + folders.size + objects.length,
+ next: null,
+ results: [...notebooks.values()]
+ .map((item) => ({
+ id: item.id,
+ path: paths.get(item.id) ?? `Research/${item.title}`,
+ type: 'notebook',
+ ref: item.short_id,
+ user_access_level: 'editor',
+ }))
+ .concat(
+ [...folders].map(([id, path]) => ({
+ id,
+ path,
+ type: 'folder',
+ ref: '',
+ user_access_level: 'editor',
+ }))
+ )
+ .concat(
+ objects.map((item) => ({
+ id: `file-${item.ref}`,
+ path: `Objects/${item.name}`,
+ type: item.type,
+ ref: item.ref,
+ user_access_level: 'editor',
+ }))
+ ),
+ },
+ ],
+ '/api/projects/:projectId/notebooks/': () => [
+ 200,
+ {
+ count: notebooks.size,
+ next: null,
+ results: [...notebooks.values()].map(({ short_id, title, user_access_level }) => ({
+ short_id,
+ title,
+ user_access_level,
+ })),
+ },
+ ],
+ '/api/projects/:projectId/notebooks/:shortId/': ({ params }) =>
+ notebooks.has(String(params.shortId))
+ ? [200, notebooks.get(String(params.shortId))]
+ : [404, { detail: 'Not found' }],
+ '/api/projects/:projectId/mcp_server_installations/available_tools/': () => [
+ 200,
+ {
+ servers: [
+ {
+ installation_id: '01900000-0000-7000-8000-000000000003',
+ name: 'Demo',
+ slug: 'demo',
+ tools: [
+ {
+ name: 'echo',
+ description: 'Echo a message for this demo.',
+ input_schema: {
+ type: 'object',
+ properties: { text: { type: 'string' } },
+ required: ['text'],
+ },
+ annotations: { readOnlyHint: true },
+ approval_state: 'approved',
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ post: {
+ '/api/projects/:projectId/file_system/': async ({ request }) => {
+ const { path } = (await request.json()) as { path: string }
+ const id = crypto.randomUUID()
+ folders.set(id, path)
+ return [201, { id, path, type: 'folder', user_access_level: 'editor' }]
+ },
+ '/api/projects/:projectId/file_system/:id/move/': async ({ request, params }) => {
+ const id = String(params.id)
+ const { new_path } = (await request.json()) as { new_path: string }
+ const oldPath = folders.get(id) ?? paths.get(id)
+ if (!oldPath) {
+ return [404, { detail: 'Not found' }]
+ }
+ for (const entries of [paths, folders]) {
+ for (const [entryId, path] of entries) {
+ if (path === oldPath || path.startsWith(`${oldPath}/`)) {
+ entries.set(entryId, new_path + path.slice(oldPath.length))
+ }
+ }
+ }
+ return [200, { id, path: new_path }]
+ },
+ '/api/projects/:projectId/notebooks/': async ({ request }) => {
+ const body = (await request.json()) as typeof notebook
+ const created = {
+ ...notebook,
+ ...body,
+ id: '01900000-0000-7000-8000-000000000004',
+ short_id: 'democreated',
+ }
+ notebooks.set(created.short_id, created)
+ paths.set(created.id, `Research/${created.title}`)
+ return [201, created]
+ },
+ '/api/projects/:projectId/mcp_server_installations/:id/call_tool/': async ({ request }) => {
+ const body = (await request.json()) as { arguments: { text: string } }
+ return [200, { content: [], structured_content: { echo: body.arguments.text }, is_error: false }]
+ },
+ },
+ delete: {
+ '/api/projects/:projectId/file_system/:id/': ({ params }) => {
+ const id = String(params.id)
+ const folder = folders.get(id)
+ if (folder !== undefined) {
+ if ([...folders.values(), ...paths.values()].some((path) => path.startsWith(`${folder}/`))) {
+ return [409, { detail: 'Folder is not empty.' }]
+ }
+ folders.delete(id)
+ return [204]
+ }
+ const notebook = [...notebooks.values()].find((item) => item.id === id)
+ if (!notebook) {
+ return [404, { detail: 'Not found' }]
+ }
+ notebooks.delete(notebook.short_id)
+ paths.delete(id)
+ return [204]
+ },
+ '/api/projects/:projectId/notebooks/:shortId/': ({ params }) => {
+ notebooks.delete(String(params.shortId))
+ return [204, null]
+ },
+ },
+ patch: {
+ ...Object.fromEntries(
+ objects.map((item) => [
+ `/api/projects/:projectId/${item.route}/${item.ref}/`,
+ async ({ request }: { request: Request }) => {
+ const data = await request.json()
+ if (typeof data.name !== 'string' || !data.name.trim()) {
+ return [400, { detail: 'Name cannot be empty.' }]
+ }
+ const updated = { ...objectData.get(item.ref), ...data, id: item.ref }
+ objectData.set(item.ref, updated)
+ return [200, updated]
+ },
+ ])
+ ),
+ '/api/projects/:projectId/notebooks/:shortId/': async ({ request, params }) => {
+ const existing = notebooks.get(String(params.shortId))
+ if (!existing) {
+ return [404, { detail: 'Not found' }]
+ }
+ const update = (await request.json()) as typeof notebook
+ if (update.version !== existing.version) {
+ return [409, { detail: 'The notebook changed. Reopen it before saving.' }]
+ }
+ const updated = { ...existing, ...update, version: existing.version + 1 }
+ notebooks.set(updated.short_id, updated)
+ return [200, updated]
+ },
+ },
+ })
+ return parameters.docked ? (
+ <DockedTerminalPreview />
+ ) : (
+ <div className="h-[calc(100vh-2rem)]">
+ <TerminalScene />
+ </div>
+ )
+ },
+}
+export default meta
+
+export const Default: StoryObj<typeof TerminalScene> = {}
+export const Docked: StoryObj<typeof TerminalScene> = {
+ parameters: {
+ docked: true,
+ pageUrl: '/notebooks/demonote',
+ layout: 'fullscreen',
+ featureFlags: [FEATURE_FLAGS.POSTHOG_TERMINAL],
+ },
+ play: async () => {
+ await waitFor(() => expect(terminalDockLogic.isMounted()).toBe(true))
+ terminalDockLogic.actions.setDockOpen(true)
+ await waitFor(() => expect(terminalLogic.values.status).toBe('ready'))
+ },
+}
+export const DockDisabled: StoryObj<typeof TerminalScene> = {
+ parameters: {
+ docked: true,
+ pageUrl: '/notebooks/demonote',
+ layout: 'fullscreen',
+ featureFlags: { [FEATURE_FLAGS.POSTHOG_TERMINAL]: false },
+ },
+}
+export const Narrow: StoryObj<typeof TerminalScene> = {
+ decorators: [
+ (Story) => (
+ <div className="max-w-lg">
+ <Story />
+ </div>
+ ),
+ ],
+}
diff --git a/frontend/src/scenes/terminal/TerminalScene.tsx b/frontend/src/scenes/terminal/TerminalScene.tsx
new file mode 100644
index 000000000000..9e4247279816
--- /dev/null
+++ b/frontend/src/scenes/terminal/TerminalScene.tsx
@@ -0,0 +1,29 @@
+import { useValues } from 'kea'
+
+import { IconTerminal } from '@posthog/icons'
+
+import { NotFound } from 'lib/components/NotFound'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { SceneExport } from 'scenes/sceneTypes'
+
+import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+
+import { terminalDockLogic } from './terminalDockLogic'
+import { terminalLogic } from './terminalLogic'
+import { TerminalView } from './TerminalView'
+
+export const scene: SceneExport = { component: TerminalScene, logic: terminalLogic }
+export function TerminalScene(): JSX.Element {
+ const { receivedFeatureFlags } = useValues(featureFlagLogic)
+ const { terminalEnabled } = useValues(terminalDockLogic)
+ if (receivedFeatureFlags && !terminalEnabled) {
+ return <NotFound object="page" />
+ }
+ return (
+ <SceneContent className="h-full min-h-0 flex-1 pb-1">
+ <SceneTitleSection name="Terminal" resourceType={{ type: 'terminal', forceIcon: <IconTerminal /> }} />
+ {terminalEnabled && <TerminalView />}
+ </SceneContent>
+ )
+}
diff --git a/frontend/src/scenes/terminal/TerminalSession.test.ts b/frontend/src/scenes/terminal/TerminalSession.test.ts
new file mode 100644
index 000000000000..c63fbcbb5431
--- /dev/null
+++ b/frontend/src/scenes/terminal/TerminalSession.test.ts
@@ -0,0 +1,22 @@
+import { TerminalSession } from './TerminalSession'
+
+describe('TerminalSession', () => {
+ it('keeps the terminal surface out of session replay before any output renders', () => {
+ const session = new TerminalSession(
+ () => {},
+ () => {},
+ () => {},
+ () => {}
+ )
+ const container = document.createElement('div')
+ document.body.append(container)
+ try {
+ session.attach(container)
+ expect(container.firstElementChild?.classList.contains('ph-no-capture')).toBe(true)
+ expect(container.firstElementChild?.classList.contains('ph-replay-block')).toBe(true)
+ } finally {
+ session.dispose()
+ container.remove()
+ }
+ })
+})
diff --git a/frontend/src/scenes/terminal/TerminalSession.ts b/frontend/src/scenes/terminal/TerminalSession.ts
new file mode 100644
index 000000000000..d8a4712a1058
--- /dev/null
+++ b/frontend/src/scenes/terminal/TerminalSession.ts
@@ -0,0 +1,112 @@
+import '@xterm/xterm/css/xterm.css'
+
+import { FitAddon } from '@xterm/addon-fit'
+import { Terminal } from '@xterm/xterm'
+
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+
+export class TerminalSession {
+ private readonly colors = getComputedStyle(document.documentElement)
+ readonly view = new Terminal({
+ cursorBlink: true,
+ scrollback: 10_000,
+ fontSize: 13,
+ fontFamily: 'monospace',
+ screenReaderMode: true,
+ rightClickSelectsWord: true,
+ macOptionClickForcesSelection: true,
+ theme: {
+ background: '#000000',
+ foreground: this.colors.getPropertyValue('--color-gray-200').trim(),
+ cursor: this.colors.getPropertyValue('--color-gray-200').trim(),
+ selectionBackground: this.colors.getPropertyValue('--color-gray-700').trim(),
+ black: '#000000',
+ red: this.colors.getPropertyValue('--color-red-400').trim(),
+ green: this.colors.getPropertyValue('--color-green-400').trim(),
+ yellow: this.colors.getPropertyValue('--color-yellow-400').trim(),
+ blue: this.colors.getPropertyValue('--color-blue-400').trim(),
+ magenta: this.colors.getPropertyValue('--color-purple-400').trim(),
+ cyan: this.colors.getPropertyValue('--color-cyan-400').trim(),
+ white: this.colors.getPropertyValue('--color-gray-200').trim(),
+ brightBlack: this.colors.getPropertyValue('--color-gray-400').trim(),
+ brightRed: this.colors.getPropertyValue('--color-red-300').trim(),
+ brightGreen: this.colors.getPropertyValue('--color-green-300').trim(),
+ brightYellow: this.colors.getPropertyValue('--color-yellow-300').trim(),
+ brightBlue: this.colors.getPropertyValue('--color-blue-300').trim(),
+ brightMagenta: this.colors.getPropertyValue('--color-purple-300').trim(),
+ brightCyan: this.colors.getPropertyValue('--color-cyan-300').trim(),
+ brightWhite: '#ffffff',
+ },
+ })
+ private readonly element = document.createElement('div')
+ private readonly fit = new FitAddon()
+ private readonly observer = new ResizeObserver(() => this.resize())
+
+ constructor(
+ write: (data: string) => void,
+ resize: (columns: number, rows: number) => void,
+ select: (selected: boolean) => void,
+ paste: () => void
+ ) {
+ // Shell commands and project data must stay out of autocapture and session replay.
+ this.element.className = 'h-full min-w-0 bg-black ph-no-capture ph-replay-block'
+ this.element.dataset.shortcutsIgnore = 'ctrl'
+ this.element.dataset.shortcutsAllowKeys = '` ~'
+ this.view.loadAddon(this.fit)
+ this.view.open(this.element)
+ this.view.onData(write)
+ this.view.onResize(({ cols, rows }) => resize(cols, rows))
+ this.view.onSelectionChange(() => {
+ select(this.view.hasSelection())
+ if (this.view.hasSelection()) {
+ void copyToClipboard(this.view.getSelection(), 'terminal selection', { silent: true })
+ }
+ })
+ this.view.attachCustomKeyEventHandler((event) => {
+ if (event.ctrlKey && !event.metaKey) {
+ event.stopPropagation()
+ }
+ const key = event.key.toLowerCase()
+ if ((event.metaKey || (event.ctrlKey && event.shiftKey)) && (key === 'c' || key === 'v')) {
+ event.stopPropagation()
+ if (key === 'c' || !event.metaKey) {
+ event.preventDefault()
+ if (event.type === 'keydown') {
+ if (key === 'c' && this.view.hasSelection()) {
+ void copyToClipboard(this.view.getSelection(), 'terminal selection')
+ } else if (key === 'v') {
+ paste()
+ }
+ }
+ }
+ return false
+ }
+ return true
+ })
+ this.observer.observe(this.element)
+ }
+
+ attach(container: HTMLElement): void {
+ container.appendChild(this.element)
+ this.resize()
+ this.view.focus()
+ }
+
+ detach(container: HTMLElement): void {
+ if (this.element.parentElement === container) {
+ this.element.remove()
+ }
+ }
+
+ resize(): void {
+ if (this.element.clientWidth && this.element.clientHeight) {
+ this.fit.fit()
+ }
+ }
+
+ dispose(): void {
+ this.observer.disconnect()
+ this.view.dispose()
+ this.element.remove()
+ }
+}
diff --git a/frontend/src/scenes/terminal/TerminalView.tsx b/frontend/src/scenes/terminal/TerminalView.tsx
new file mode 100644
index 000000000000..c8dfe1d1e3ab
--- /dev/null
+++ b/frontend/src/scenes/terminal/TerminalView.tsx
@@ -0,0 +1,224 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useRef, useState } from 'react'
+
+import { IconCopy, IconInfo, IconStopFilled, IconX } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonMenu, LemonSelect, LemonTag, Popover } from '@posthog/lemon-ui'
+
+import { IconClipboardEdit } from 'lib/lemon-ui/icons'
+
+import { terminalLogic } from './terminalLogic'
+
+const examples = [
+ {
+ title: 'Get started',
+ commands: ['ls --color=auto', "find /posthog/files -name '*.md'", 'cat /posthog/README.txt', 'ph help'],
+ },
+ {
+ title: 'Explore files',
+ commands: [
+ 'mc',
+ 'tree -C -L 3 /posthog/files',
+ 'ncdu -r /posthog/files',
+ 'ls -lh /posthog/api',
+ 'pwd',
+ 'busybox',
+ ],
+ },
+ { title: 'PostHog tools', commands: ['ph tools', 'ph tools notebook', 'ph help notebooks-retrieve', 'ph refresh'] },
+ {
+ title: 'Edit and organize',
+ commands: [
+ 'nano Unfiled/Notebooks/Foobar.md',
+ "find /posthog/files -name '*.json'",
+ 'vi Unfiled/Notebooks/Foobar.md',
+ 'mkdir -p Research/Archive',
+ 'mv Unfiled/Notebooks/Foobar.md Research/Archive/',
+ ],
+ },
+ {
+ title: 'Read and filter',
+ commands: [
+ 'ph notebooks-list --limit 10 | jq .',
+ "grep -r -n 'revenue' /posthog/files",
+ "find /posthog/files -name '*.md' | wc -l",
+ 'jq -n \'{hello: "PostHog"}\'',
+ 'less /posthog/README.txt',
+ 'ls -la /tmp',
+ ],
+ },
+]
+
+export function TerminalView({
+ active: visible = true,
+ onClose,
+}: {
+ active?: boolean
+ onClose?: () => void
+}): JSX.Element {
+ const { status, error, saveError, hasSelection, pasting, clipboardError } = useValues(terminalLogic)
+ const { start, stop, attach, detach, insertCommand, copy, paste } = useActions(terminalLogic)
+ const container = useRef<HTMLDivElement>(null)
+ const [infoOpen, setInfoOpen] = useState(false)
+ useEffect(() => {
+ const host = container.current
+ if (!host || !visible) {
+ return
+ }
+ attach(host)
+ return () => detach(host)
+ }, [attach, detach, visible])
+
+ const active = status !== 'idle' && status !== 'error'
+ const starting = status === 'loading' || status === 'booting'
+
+ return (
+ <div className="h-full min-h-0 flex flex-col gap-1">
+ <div className="flex shrink-0 items-center gap-1 flex-wrap px-1">
+ <LemonSelect
+ size="xsmall"
+ value="posthog-linux-wasm"
+ aria-label="Environment"
+ data-attr="terminal-environment"
+ className="min-w-0 max-w-full"
+ truncateText={{ maxWidthClass: 'max-w-full' }}
+ options={[
+ {
+ title: 'Environment',
+ options: [
+ {
+ value: 'posthog-linux-wasm',
+ label: 'PostHog Linux WASM (in-browser, experimental)',
+ },
+ ],
+ },
+ ]}
+ />
+ <LemonButton
+ size="xsmall"
+ type="primary"
+ onClick={start}
+ loading={starting}
+ disabledReason={active ? 'The terminal is already running' : undefined}
+ data-attr="terminal-start"
+ >
+ Start Linux
+ </LemonButton>
+ <LemonButton
+ size="xsmall"
+ icon={<IconStopFilled />}
+ aria-label="Stop"
+ tooltip="Stop"
+ onClick={stop}
+ disabledReason={status === 'idle' ? 'Start the terminal first' : undefined}
+ data-attr="terminal-stop"
+ />
+ <LemonButton
+ size="xsmall"
+ icon={<IconCopy />}
+ aria-label="Copy"
+ tooltip="Copy"
+ onClick={copy}
+ disabledReason={!hasSelection ? 'Select terminal text to copy' : undefined}
+ data-attr="terminal-copy"
+ />
+ <LemonButton
+ size="xsmall"
+ icon={<IconClipboardEdit />}
+ aria-label="Paste"
+ tooltip="Paste"
+ onClick={paste}
+ loading={pasting}
+ disabledReason={status !== 'ready' ? 'Start the terminal first' : undefined}
+ data-attr="terminal-paste"
+ />
+ <LemonMenu
+ items={examples.map(({ title, commands }) => ({
+ title,
+ items: commands.map((command) => ({
+ label: <code className="whitespace-normal break-words">{command}</code>,
+ onClick: () => insertCommand(command),
+ })),
+ }))}
+ >
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ aria-label="Examples"
+ tooltip="Insert a command, then press Enter to run it."
+ disabledReason={status !== 'ready' ? 'Start the terminal first' : undefined}
+ >
+ Examples
+ </LemonButton>
+ </LemonMenu>
+ <span role="status" className="text-secondary ml-auto text-xs">
+ {status === 'loading'
+ ? 'Loading project files…'
+ : status === 'booting'
+ ? 'Starting Linux…'
+ : status === 'ready'
+ ? 'Ready'
+ : status === 'error'
+ ? 'Could not start'
+ : 'Stopped'}
+ </span>
+ <Popover
+ visible={infoOpen}
+ onClickOutside={() => setInfoOpen(false)}
+ placement="bottom-end"
+ overlay={
+ <div className="flex max-w-80 flex-col items-start gap-3 p-1 text-sm">
+ <LemonTag type="warning">Experiment</LemonTag>
+ <p className="mb-0">
+ Linux in your browser, with your PostHog project mounted at <code>/posthog</code>. The
+ first start downloads Linux and bundled tools.
+ </p>
+ <p className="mb-0">
+ Commands and file edits can change real data. Local files and unsaved edits disappear
+ when you reload PostHog or stop Linux.
+ </p>
+ <p className="mb-0">
+ Choose an example to insert it, then press Enter. Tab completes paths and ph commands.
+ Ctrl+C interrupts. Scroll up for history.
+ </p>
+ <p className="mb-0">
+ Selecting text copies it automatically. In apps that capture the mouse, such as mc, hold
+ Option on macOS or Shift on Linux and Windows while selecting. Copy/paste with ⌘C/⌘V on
+ macOS or Ctrl+Shift+C/V on Linux and Windows.
+ </p>
+ </div>
+ }
+ >
+ <LemonButton
+ size="xsmall"
+ icon={<IconInfo />}
+ aria-label="Terminal information"
+ aria-expanded={infoOpen}
+ active={infoOpen}
+ onClick={() => setInfoOpen(!infoOpen)}
+ />
+ </Popover>
+ {onClose && (
+ <LemonButton
+ size="xsmall"
+ icon={<IconX />}
+ aria-label="Hide terminal"
+ tooltip="Hide terminal"
+ onClick={onClose}
+ />
+ )}
+ </div>
+ {error && <LemonBanner type="error">{error}</LemonBanner>}
+ {saveError && <LemonBanner type="error">{saveError}</LemonBanner>}
+ {clipboardError && <LemonBanner type="error">{clipboardError}</LemonBanner>}
+ <div
+ aria-label="Linux terminal"
+ data-attr="posthog-terminal"
+ translate="no"
+ className="min-h-0 min-w-0 flex-1 overflow-hidden px-1 pb-1 bg-[var(--color-black)] text-[var(--color-white)]"
+ >
+ {/* xterm's fit addon counts padding on its parent as usable space. */}
+ <div ref={container} className="h-full min-w-0 bg-[var(--color-black)]" />
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/terminal/assets.d.ts b/frontend/src/scenes/terminal/assets.d.ts
new file mode 100644
index 000000000000..d98a82aade2f
--- /dev/null
+++ b/frontend/src/scenes/terminal/assets.d.ts
@@ -0,0 +1,9 @@
+declare module '*.wasm?url' {
+ const url: string
+ export default url
+}
+
+declare module '*.bin?url' {
+ const url: string
+ export default url
+}
diff --git a/frontend/src/scenes/terminal/assets/buildroot-bzimage.bin b/frontend/src/scenes/terminal/assets/buildroot-bzimage.bin
new file mode 100644
index 000000000000..5e149f7ab2bc
Binary files /dev/null and b/frontend/src/scenes/terminal/assets/buildroot-bzimage.bin differ
diff --git a/frontend/src/scenes/terminal/assets/hashes.json b/frontend/src/scenes/terminal/assets/hashes.json
new file mode 100644
index 000000000000..a97420ed4438
--- /dev/null
+++ b/frontend/src/scenes/terminal/assets/hashes.json
@@ -0,0 +1,3 @@
+{
+ "toolsSha256": "50c8d847c3811249d512245b0b506cfab5cc4b625cc5fa6079cb605a7681b2cc"
+}
diff --git a/frontend/src/scenes/terminal/assets/jq-linux-i386.bin b/frontend/src/scenes/terminal/assets/jq-linux-i386.bin
new file mode 100644
index 000000000000..86f5bb3a1aac
Binary files /dev/null and b/frontend/src/scenes/terminal/assets/jq-linux-i386.bin differ
diff --git a/frontend/src/scenes/terminal/assets/seabios.bin b/frontend/src/scenes/terminal/assets/seabios.bin
new file mode 100644
index 000000000000..8c9ab8ffea3b
Binary files /dev/null and b/frontend/src/scenes/terminal/assets/seabios.bin differ
diff --git a/frontend/src/scenes/terminal/assets/tools-linux-i386.tar.gz.bin b/frontend/src/scenes/terminal/assets/tools-linux-i386.tar.gz.bin
new file mode 100644
index 000000000000..357b906fbf9b
Binary files /dev/null and b/frontend/src/scenes/terminal/assets/tools-linux-i386.tar.gz.bin differ
diff --git a/frontend/src/scenes/terminal/assets/vgabios.bin b/frontend/src/scenes/terminal/assets/vgabios.bin
new file mode 100644
index 000000000000..bd393e2b5edb
Binary files /dev/null and b/frontend/src/scenes/terminal/assets/vgabios.bin differ
diff --git a/frontend/src/scenes/terminal/ninepCodec.ts b/frontend/src/scenes/terminal/ninepCodec.ts
new file mode 100644
index 000000000000..71a1f64004c0
--- /dev/null
+++ b/frontend/src/scenes/terminal/ninepCodec.ts
@@ -0,0 +1,102 @@
+const encoder = new TextEncoder()
+const decoder = new TextDecoder()
+
+export class NinePReader {
+ private offset = 0
+ private view: DataView
+
+ constructor(private bytes: Uint8Array) {
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
+ }
+
+ number(size: 1 | 2 | 4 | 8): number {
+ const value =
+ size === 8
+ ? Number(this.view.getBigUint64(this.offset, true))
+ : size === 4
+ ? this.view.getUint32(this.offset, true)
+ : size === 2
+ ? this.view.getUint16(this.offset, true)
+ : this.view.getUint8(this.offset)
+ this.offset += size
+ if (!Number.isSafeInteger(value)) {
+ throw new Error('File offset is too large')
+ }
+ return value
+ }
+
+ data(size: number): Uint8Array {
+ if (this.offset + size > this.bytes.length) {
+ throw new Error('Truncated 9P message')
+ }
+ const result = this.bytes.slice(this.offset, this.offset + size)
+ this.offset += size
+ return result
+ }
+
+ string(): string {
+ return decoder.decode(this.data(this.number(2)))
+ }
+}
+
+export class NinePWriter {
+ private bytes = new Uint8Array(256)
+ private view = new DataView(this.bytes.buffer)
+ private length = 0
+
+ // Every 9P message crosses this writer, and a file read fills it one packet at a time.
+ private reserve(size: number): void {
+ if (this.length + size <= this.bytes.length) {
+ return
+ }
+ let capacity = this.bytes.length * 2
+ while (capacity < this.length + size) {
+ capacity *= 2
+ }
+ const grown = new Uint8Array(capacity)
+ grown.set(this.bytes.subarray(0, this.length))
+ this.bytes = grown
+ this.view = new DataView(grown.buffer)
+ }
+
+ number(value: number, size: 1 | 2 | 4 | 8): this {
+ this.reserve(size)
+ if (size === 8) {
+ this.view.setBigUint64(this.length, BigInt(value), true)
+ } else if (size === 4) {
+ this.view.setUint32(this.length, value, true)
+ } else if (size === 2) {
+ this.view.setUint16(this.length, value, true)
+ } else {
+ this.view.setUint8(this.length, value)
+ }
+ this.length += size
+ return this
+ }
+
+ data(value: Uint8Array): this {
+ this.reserve(value.length)
+ this.bytes.set(value, this.length)
+ this.length += value.length
+ return this
+ }
+
+ string(value: string): this {
+ const bytes = encoder.encode(value)
+ return this.number(bytes.length, 2).data(bytes)
+ }
+
+ build(): Uint8Array {
+ return this.bytes.slice(0, this.length)
+ }
+
+ frame(type: number, tag: number): Uint8Array {
+ const frame = new Uint8Array(this.length + 7)
+ const view = new DataView(frame.buffer)
+ view.setUint32(0, frame.length, true)
+ view.setUint8(4, type)
+ view.setUint16(5, tag, true)
+ frame.set(this.bytes.subarray(0, this.length), 7)
+ return frame
+ }
+}
diff --git a/frontend/src/scenes/terminal/ninepServer.test.ts b/frontend/src/scenes/terminal/ninepServer.test.ts
new file mode 100644
index 000000000000..339bf99daef4
--- /dev/null
+++ b/frontend/src/scenes/terminal/ninepServer.test.ts
@@ -0,0 +1,408 @@
+import { NinePReader, NinePWriter } from './ninepCodec'
+import { NinePServer } from './ninepServer'
+import { MAX_TERMINAL_FILE_BYTES, TerminalFilesystem } from './terminalFilesystem'
+
+describe('PostHog 9P filesystem', () => {
+ const encoder = new TextEncoder()
+ const decoder = new TextDecoder()
+ let filesystem: TerminalFilesystem
+ let server: NinePServer
+ let saved: string
+ let failSave: boolean
+ let errors: string[]
+
+ async function request(type: number, body = new NinePWriter()): Promise<{ type: number; body: NinePReader }> {
+ const bytes = await new Promise<Uint8Array>((resolve) => server.handle(body.frame(type, 42), resolve))
+ const reader = new NinePReader(bytes)
+ expect(reader.number(4)).toBe(bytes.length)
+ const responseType = reader.number(1)
+ expect(reader.number(2)).toBe(42)
+ return { type: responseType, body: reader }
+ }
+
+ async function walk(name: string, fid = 2): Promise<void> {
+ const response = await request(110, new NinePWriter().number(1, 4).number(fid, 4).number(1, 2).string(name))
+ expect(response.type).toBe(111)
+ }
+
+ async function open(flags: number, fid = 2): Promise<number> {
+ return (await request(12, new NinePWriter().number(fid, 4).number(flags, 4))).type
+ }
+
+ async function write(text: string, offset = 0): Promise<number> {
+ const data = encoder.encode(text)
+ return (await request(118, new NinePWriter().number(2, 4).number(offset, 8).number(data.length, 4).data(data)))
+ .type
+ }
+
+ beforeEach(async () => {
+ saved = '# café 🦔\n'
+ failSave = false
+ errors = []
+ filesystem = new TerminalFilesystem()
+ filesystem.file(
+ 'note.md',
+ filesystem.root,
+ async () => ({
+ bytes: encoder.encode(saved),
+ save: async (data) => {
+ if (failSave) {
+ throw new Error('Conflict')
+ }
+ saved = decoder.decode(data)
+ },
+ }),
+ true
+ )
+ filesystem.text('view.json', filesystem.root, '{}')
+ server = new NinePServer(filesystem, (error) => errors.push(error))
+ await request(100, new NinePWriter().number(65536, 4).string('9P2000.L'))
+ await request(104, new NinePWriter().number(1, 4).number(0xffffffff, 4).string('root').string('').number(0, 4))
+ await walk('note.md')
+ })
+
+ it('reads UTF-8 by byte offset, and opens fresh content after a remote edit', async () => {
+ const load = jest.spyOn(filesystem.root.children!.get('note.md')!, 'open')
+ const stat = await request(24, new NinePWriter().number(2, 4).number(0x7ff, 8))
+ expect(stat.type).toBe(25)
+ stat.body.data(49)
+ expect(stat.body.number(8)).toBe(0)
+ expect(load).not.toHaveBeenCalled()
+ expect(await open(0)).toBe(13)
+ expect(load).toHaveBeenCalledTimes(1)
+ const response = await request(116, new NinePWriter().number(2, 4).number(2, 8).number(1024, 4))
+ expect(decoder.decode(response.body.data(response.body.number(4)))).toBe('café 🦔\n')
+ await request(120, new NinePWriter().number(2, 4))
+ saved = 'Changed in PostHog'
+ await walk('note.md')
+ await open(0)
+ const fresh = await request(116, new NinePWriter().number(2, 4).number(0, 8).number(1024, 4))
+ expect(decoder.decode(fresh.body.data(fresh.body.number(4)))).toBe(saved)
+ })
+
+ it.each([76, 122])(
+ 'unlinks through message %i without reopening deleted files or losing active edits',
+ async (type) => {
+ const note = filesystem.root.children!.get('note.md')!
+ note.remove = jest.fn(async () => {
+ filesystem.root.children!.delete(note.name)
+ note.removed = true
+ })
+ const remove = (): Promise<{ type: number; body: NinePReader }> =>
+ request(
+ type,
+ type === 76
+ ? new NinePWriter().number(1, 4).string('note.md').number(0, 4)
+ : new NinePWriter().number(3, 4)
+ )
+ await open(1)
+ await write('Edit')
+ await walk('note.md', 3)
+ expect((await remove()).body.number(4)).toBe(16)
+ expect(note.remove).not.toHaveBeenCalled()
+ await request(120, new NinePWriter().number(2, 4))
+ expect(saved).toContain('Edit')
+ await walk('note.md', 2)
+ await open(0)
+ await walk('note.md', 3)
+ await walk('note.md', 4)
+ expect((await remove()).type).toBe(type + 1)
+ const read = await request(116, new NinePWriter().number(2, 4).number(0, 8).number(1024, 4))
+ expect(decoder.decode(read.body.data(read.body.number(4)))).toBe(saved)
+ expect(await open(0, 4)).toBe(7)
+ expect(filesystem.root.children!.has('note.md')).toBe(false)
+ }
+ )
+
+ it('rejects nonempty folders, mismatched removal flags, and read-only mount entries', async () => {
+ const folder = filesystem.directory('folder', filesystem.root)
+ folder.remove = jest.fn(async () => {})
+ filesystem.text('child', folder, '')
+ const remove = (name: string, flags: number): Promise<{ type: number; body: NinePReader }> =>
+ request(76, new NinePWriter().number(1, 4).string(name).number(flags, 4))
+ expect((await remove('folder', 0x200)).body.number(4)).toBe(39)
+ expect((await remove('folder', 0)).body.number(4)).toBe(21)
+ expect((await remove('note.md', 0x200)).body.number(4)).toBe(20)
+ expect((await remove('view.json', 0)).body.number(4)).toBe(30)
+ expect((await remove('missing', 0)).body.number(4)).toBe(2)
+ expect(folder.remove).not.toHaveBeenCalled()
+ })
+
+ it.each([50, 120])('commits complete, truncated content on message %i', async (operation) => {
+ expect(await open(513)).toBe(13)
+ await write('short')
+ expect(saved).toBe('# café 🦔\n')
+ expect((await request(operation, new NinePWriter().number(2, 4).number(0, 4))).type).toBe(operation + 1)
+ expect(saved).toBe('short')
+ })
+
+ it('preserves failed edits in recovery and returns EIO without overwriting the remote file', async () => {
+ await open(513)
+ await write('My edit')
+ failSave = true
+ const response = await request(120, new NinePWriter().number(2, 4))
+ expect(response.type).toBe(7)
+ expect(response.body.number(4)).toBe(5)
+ expect(saved).toBe('# café 🦔\n')
+ const recovered = [...filesystem.recovery.children!.values()][0]
+ expect(decoder.decode((await recovered.open!()).bytes)).toBe('My edit')
+ expect(errors[0]).toContain(`/posthog/recovery/${recovered.name}`)
+ expect(errors[0]).toContain('Conflict')
+ await walk('note.md')
+ expect(await open(1)).toBe(13)
+ })
+
+ it.each([2, 3])('accepts Linux truncation through open or path fid %i', async (fid) => {
+ await open(1)
+ await walk('note.md', 3)
+ const response = await request(
+ 26,
+ new NinePWriter()
+ .number(fid, 4)
+ .number(0x68, 4)
+ .number(0, 4)
+ .number(0xffffffff, 4)
+ .number(0xffffffff, 4)
+ .number(0, 8)
+ .number(0, 8)
+ .number(0, 8)
+ .number(0, 8)
+ .number(0, 8)
+ )
+ expect(response.type).toBe(27)
+ await write('Truncated')
+ await request(120, new NinePWriter().number(2, 4))
+ expect(saved).toBe('Truncated')
+ })
+
+ it('commits a path-only truncate without keeping a writer lock', async () => {
+ const response = await request(
+ 26,
+ new NinePWriter().number(2, 4).number(8, 4).data(new Uint8Array(12)).number(0, 8)
+ )
+ expect(response.type).toBe(27)
+ expect(saved).toBe('')
+ expect(await open(1)).toBe(13)
+ await write('After truncate')
+ await request(120, new NinePWriter().number(2, 4))
+ expect(saved).toBe('After truncate')
+ })
+
+ it('rejects concurrent writers, writes through a read descriptor, and writes to read-only objects', async () => {
+ await open(1)
+ await walk('note.md', 3)
+ expect(await open(1, 3)).toBe(7)
+ await request(120, new NinePWriter().number(2, 4))
+ await walk('note.md')
+ await open(0)
+ expect(await write('bad')).toBe(7)
+ await walk('view.json', 4)
+ expect(await open(1, 4)).toBe(7)
+ expect(saved).toBe('# café 🦔\n')
+ })
+
+ it('assembles a chunked write from many packets, and keeps truncation and sparse gaps correct', async () => {
+ await open(1 | 512)
+ const chunk = 'abcdefgh'
+ let expected = ''
+ for (let index = 0; index < 200; index++) {
+ expect(await write(chunk, expected.length)).toBe(119)
+ expected += chunk
+ }
+ await request(120, new NinePWriter().number(2, 4))
+ expect(saved).toBe(expected)
+
+ await walk('note.md')
+ await open(1)
+ await write('ZZZZ', 8)
+ await request(120, new NinePWriter().number(2, 4))
+ expect(saved).toBe(`${expected.slice(0, 8)}ZZZZ${expected.slice(12)}`)
+
+ await walk('note.md')
+ await open(1 | 512)
+ await write('abcdefghij')
+ await request(26, new NinePWriter().number(2, 4).number(8, 4).data(new Uint8Array(12)).number(2, 8))
+ await write('Z', 4)
+ await request(120, new NinePWriter().number(2, 4))
+ expect(saved).toBe('ab\u0000\u0000Z')
+ })
+
+ it('frames a read that outgrows the response buffer without corrupting it', async () => {
+ saved = 'hedgehog \u{1F994} '.repeat(4000)
+ const body = encoder.encode(saved)
+ expect(await open(0)).toBe(13)
+ const response = await request(116, new NinePWriter().number(2, 4).number(0, 8).number(body.length, 4))
+ const returned = response.body.data(response.body.number(4))
+ expect(returned.length).toBe(body.length)
+ expect(decoder.decode(returned)).toBe(saved)
+ })
+
+ it('rejects oversized sparse writes without allocating their requested size', async () => {
+ await open(1)
+ expect(await write('x', MAX_TERMINAL_FILE_BYTES)).toBe(7)
+ await request(120, new NinePWriter().number(2, 4))
+ expect(saved).toBe('# café 🦔\n')
+ })
+
+ it.each([12, 24])('continues serving requests when a type %s reply throws', async (type) => {
+ let replied!: () => void
+ const attempted = new Promise<void>((resolve) => (replied = resolve))
+ const brokenReply = jest.fn(() => {
+ replied()
+ throw new RangeError('Guest buffer is outside memory')
+ })
+ server.handle(new NinePWriter().number(2, 4).number(0, 8).frame(type, 10), brokenReply)
+ await attempted
+ expect((await request(120, new NinePWriter().number(2, 4))).type).toBe(121)
+ expect(brokenReply).toHaveBeenCalledTimes(1)
+ })
+
+ it('cancels a pending open without blocking flush or replying to its reused tag', async () => {
+ let reading!: () => void
+ const started = new Promise<void>((resolve) => (reading = resolve))
+ filesystem.file('slow.json', filesystem.root, async (signal) => {
+ reading()
+ await new Promise<void>((_, reject) =>
+ signal!.addEventListener('abort', () => reject(signal!.reason), { once: true })
+ )
+ return { bytes: encoder.encode('never returned') }
+ })
+ await walk('slow.json', 3)
+ const originalReply = jest.fn()
+ server.handle(new NinePWriter().number(3, 4).number(0, 4).frame(12, 10), originalReply)
+ await started
+ expect((await request(108, new NinePWriter().number(10, 2))).type).toBe(109)
+ const bytes = await new Promise<Uint8Array>((resolve) =>
+ server.handle(new NinePWriter().number(1, 4).number(0x7ff, 8).frame(24, 10), resolve)
+ )
+ const response = new NinePReader(bytes)
+ response.number(4)
+ expect(response.number(1)).toBe(25)
+ expect(response.number(2)).toBe(10)
+ expect(originalReply).not.toHaveBeenCalled()
+ expect((await request(120, new NinePWriter().number(3, 4))).type).toBe(121)
+ })
+
+ it('shares writer locks across mounted aliases, including truncation and deletion', async () => {
+ const note = filesystem.root.children!.get('note.md')!
+ note.writeKey = 'notebook:note'
+ const alias = filesystem.file('alias.json', filesystem.root, note.open!, true)
+ alias.writeKey = note.writeKey
+ alias.remove = jest.fn(async () => {})
+ await open(1)
+ await walk('alias.json', 3)
+ expect(await open(1, 3)).toBe(7)
+ const truncate = await request(
+ 26,
+ new NinePWriter().number(3, 4).number(8, 4).data(new Uint8Array(12)).number(0, 8)
+ )
+ expect(truncate.body.number(4)).toBe(16)
+ const remove = await request(76, new NinePWriter().number(1, 4).string('alias.json').number(0, 4))
+ expect(remove.body.number(4)).toBe(16)
+ expect(alias.remove).not.toHaveBeenCalled()
+ await request(120, new NinePWriter().number(2, 4))
+ expect(await open(1, 3)).toBe(13)
+ })
+
+ it('appends to freshly loaded content even when the guest sends a stale size as its offset', async () => {
+ expect(await open(1025)).toBe(13)
+ await write('Appended', 0)
+ await write(' twice', 8)
+ await request(120, new NinePWriter().number(2, 4))
+ expect(saved).toBe('# café 🦔\nAppended twice')
+ })
+
+ it('lists unrelated directories while an API save is pending', async () => {
+ let saving!: () => void
+ let finish!: () => void
+ const started = new Promise<void>((resolve) => (saving = resolve))
+ const pending = new Promise<void>((resolve) => (finish = resolve))
+ filesystem.file(
+ 'slow-write.json',
+ filesystem.root,
+ async () => ({
+ bytes: encoder.encode('{}'),
+ save: async () => {
+ saving()
+ await pending
+ },
+ }),
+ true
+ )
+ await walk('slow-write.json')
+ await open(513)
+ await write('{}')
+ const closed = new Promise<Uint8Array>((resolve) =>
+ server.handle(new NinePWriter().number(2, 4).frame(120, 10), resolve)
+ )
+ await started
+ try {
+ expect((await request(24, new NinePWriter().number(1, 4).number(0x7ff, 8))).type).toBe(25)
+ expect((await request(40, new NinePWriter().number(1, 4).number(0, 8).number(1024, 4))).type).toBe(41)
+ await walk('view.json', 3)
+ } finally {
+ finish()
+ await closed
+ }
+ })
+
+ it('keeps directory offsets stable across paginated readdir', async () => {
+ const names: string[] = []
+ let offset = 0
+ while (true) {
+ const response = await request(40, new NinePWriter().number(1, 4).number(offset, 8).number(45, 4))
+ const length = response.body.number(4)
+ if (!length) {
+ break
+ }
+ const entry = new NinePReader(response.body.data(length))
+ entry.data(13)
+ offset = entry.number(8)
+ entry.number(1)
+ names.push(entry.string())
+ }
+ expect(names).toEqual(['.', '..', 'recovery', 'note.md', 'view.json'])
+ })
+
+ it('does not drop later entries when a listed one is removed between pages', async () => {
+ const names: string[] = []
+ let offset = 0
+ while (true) {
+ const response = await request(40, new NinePWriter().number(1, 4).number(offset, 8).number(45, 4))
+ const length = response.body.number(4)
+ if (!length) {
+ break
+ }
+ const entry = new NinePReader(response.body.data(length))
+ entry.data(13)
+ offset = entry.number(8)
+ entry.number(1)
+ const name = entry.string()
+ names.push(name)
+ if (name === 'recovery') {
+ filesystem.root.children!.delete('recovery')
+ }
+ }
+ expect(names).toEqual(['.', '..', 'recovery', 'note.md', 'view.json'])
+ })
+
+ it('shows a fresh directory when a listing restarts from the beginning', async () => {
+ const read = async (offset: number): Promise<string> => {
+ const response = await request(40, new NinePWriter().number(1, 4).number(offset, 8).number(45, 4))
+ const length = response.body.number(4)
+ if (!length) {
+ return ''
+ }
+ const entry = new NinePReader(response.body.data(length))
+ entry.data(13)
+ entry.number(8)
+ entry.number(1)
+ return entry.string()
+ }
+ await read(0)
+ filesystem.text('added.json', filesystem.root, '{}')
+ expect(await read(5)).toBe('')
+ await read(0)
+ expect(await read(5)).toBe('added.json')
+ })
+})
diff --git a/frontend/src/scenes/terminal/ninepServer.ts b/frontend/src/scenes/terminal/ninepServer.ts
new file mode 100644
index 000000000000..278b5eac6904
--- /dev/null
+++ b/frontend/src/scenes/terminal/ninepServer.ts
@@ -0,0 +1,485 @@
+import { NinePReader, NinePWriter } from './ninepCodec'
+import {
+ FilesystemError,
+ MAX_TERMINAL_FILE_BYTES,
+ TerminalFile,
+ TerminalFilesystem,
+ TerminalNode,
+} from './terminalFilesystem'
+
+interface Fid {
+ node: TerminalNode
+ file?: TerminalFile
+ entries?: TerminalNode[]
+ capacity?: Uint8Array
+ dirty?: boolean
+ writing?: boolean
+ append?: boolean
+ failed?: boolean
+}
+
+function qid(writer: NinePWriter, node: TerminalNode): NinePWriter {
+ return writer
+ .number(node.children ? 128 : 0, 1)
+ .number(0, 4)
+ .number(node.id, 8)
+}
+
+export class NinePServer {
+ private fids = new Map<number, Fid>()
+ private writers = new Set<string | number>()
+ private requests = new Map<number, AbortController>()
+ private queue: Promise<void> = Promise.resolve()
+ private messageSize = 256 * 1024
+
+ constructor(
+ readonly filesystem: TerminalFilesystem,
+ private onSaveError: (message: string) => void
+ ) {}
+
+ // Keep API operations ordered, but let local metadata and buffered reads proceed during a slow request.
+ handle = (bytes: Uint8Array, reply: (bytes: Uint8Array) => void): void => {
+ const respond = (response: Uint8Array): void => {
+ try {
+ reply(response)
+ } catch {
+ // A bad guest reply buffer must not stop requests on other descriptors.
+ }
+ }
+ const reader = new NinePReader(bytes)
+ let tag = 0xffff
+ let type: number
+ try {
+ const size = reader.number(4)
+ type = reader.number(1)
+ tag = reader.number(2)
+ if (size !== bytes.length || size > this.messageSize) {
+ throw new FilesystemError(22)
+ }
+ if (type === 108) {
+ this.requests.get(reader.number(2))?.abort()
+ respond(new NinePWriter().frame(109, tag))
+ return
+ }
+ } catch (error) {
+ respond(new NinePWriter().number(error instanceof FilesystemError ? error.errno : 5, 4).frame(7, tag))
+ return
+ }
+ const controller = new AbortController()
+ this.requests.set(tag, controller)
+ const execute = async (): Promise<void> => {
+ try {
+ if (controller.signal.aborted) {
+ return
+ }
+ const result = await this.request(type, reader, controller.signal)
+ if (!controller.signal.aborted) {
+ respond(result.frame(type + 1, tag))
+ }
+ } catch (error) {
+ if (!controller.signal.aborted) {
+ respond(
+ new NinePWriter().number(error instanceof FilesystemError ? error.errno : 5, 4).frame(7, tag)
+ )
+ }
+ } finally {
+ if (this.requests.get(tag) === controller) {
+ this.requests.delete(tag)
+ }
+ }
+ }
+ if ([24, 40, 110, 116].includes(type)) {
+ void execute()
+ } else {
+ this.queue = this.queue.then(execute)
+ }
+ }
+
+ private fid(id: number): Fid {
+ const fid = this.fids.get(id)
+ if (!fid) {
+ throw new FilesystemError(9)
+ }
+ return fid
+ }
+
+ private async open(fid: Fid, flags: number, signal?: AbortSignal): Promise<void> {
+ if (fid.node.removed) {
+ throw new FilesystemError(2)
+ }
+ if (fid.node.children) {
+ if (flags & 3) {
+ throw new FilesystemError(21)
+ }
+ return
+ }
+ const writing = !!(flags & 3)
+ const writeKey = fid.node.writeKey ?? fid.node.id
+ if (writing && (!fid.node.writable || this.writers.has(writeKey))) {
+ throw new FilesystemError(fid.node.writable ? 16 : 30)
+ }
+ const file = await fid.node.open!(signal)
+ if (signal?.aborted) {
+ throw new FilesystemError(4)
+ }
+ fid.file = file
+ if (writing && !fid.file.save) {
+ throw new FilesystemError(30)
+ }
+ fid.writing = writing
+ fid.append = !!(flags & 1024)
+ if (writing) {
+ this.writers.add(writeKey)
+ }
+ if (writing && flags & 512) {
+ fid.file.bytes = new Uint8Array()
+ fid.dirty = true
+ }
+ fid.node.size = fid.file.bytes.length
+ }
+
+ private async save(fid: Fid): Promise<void> {
+ if (!fid.dirty || !fid.file?.save) {
+ return
+ }
+ if (fid.failed) {
+ throw new FilesystemError(5)
+ }
+ try {
+ await fid.file.save(fid.file.bytes)
+ fid.dirty = false
+ fid.node.size = fid.file.bytes.length
+ } catch (error) {
+ fid.failed = true
+ const recovery = this.filesystem.recover(fid.node, fid.file.bytes)
+ const detail =
+ error instanceof Error
+ ? error.message
+ : error && typeof error === 'object' && 'detail' in error && typeof error.detail === 'string'
+ ? error.detail
+ : 'Check your access, JSON fields, or concurrent edits.'
+ this.onSaveError(`Could not save ${fid.node.name}. ${detail} Your edit is in ${recovery}.`)
+ throw new FilesystemError(5)
+ }
+ }
+
+ private async truncate(fid: Fid, size: number): Promise<void> {
+ if (size > MAX_TERMINAL_FILE_BYTES) {
+ throw new FilesystemError(27)
+ }
+ // Linux can truncate through a path fid while a separate open fid owns the write.
+ const writer = [...this.fids.values()].find((candidate) => candidate.node === fid.node && candidate.writing)
+ if (!writer && this.writers.has(fid.node.writeKey ?? fid.node.id)) {
+ throw new FilesystemError(16)
+ }
+ const target: Fid = writer ?? { node: fid.node }
+ if (!writer) {
+ await this.open(target, 1)
+ }
+ try {
+ if (!target.file || target.failed) {
+ throw new FilesystemError(5)
+ }
+ const bytes = new Uint8Array(size)
+ bytes.set(target.file.bytes.subarray(0, size))
+ target.file.bytes = bytes
+ target.node.size = size
+ target.dirty = true
+ if (!writer) {
+ await this.save(target)
+ }
+ } finally {
+ if (!writer) {
+ this.writers.delete(target.node.writeKey ?? target.node.id)
+ }
+ }
+ }
+
+ private validateDestination(parent: TerminalNode, name: string): void {
+ if (!parent.children) {
+ throw new FilesystemError(20)
+ }
+ if (!name || name === '.' || name === '..' || /[/\x00]/.test(name)) {
+ throw new FilesystemError(22)
+ }
+ if (parent.children.has(name)) {
+ // Replacing a project object would delete data, so require an unused destination.
+ throw new FilesystemError(17)
+ }
+ }
+
+ private async rename(node: TerminalNode, parent: TerminalNode, name: string): Promise<void> {
+ if (node.parent === parent && node.name === name) {
+ return
+ }
+ this.validateDestination(parent, name)
+ for (let ancestor: TerminalNode | undefined = parent; ancestor; ancestor = ancestor.parent) {
+ if (ancestor === node) {
+ throw new FilesystemError(22)
+ }
+ }
+ if (!node.rename || !parent.mkdir) {
+ throw new FilesystemError(30)
+ }
+ await node.rename(parent, name)
+ }
+
+ private async remove(node: TerminalNode, directory: boolean): Promise<void> {
+ if (node.removed) {
+ throw new FilesystemError(2)
+ }
+ if (!!node.children !== directory) {
+ throw new FilesystemError(directory ? 20 : 21)
+ }
+ if (!node.remove) {
+ throw new FilesystemError(30)
+ }
+ if (node.children?.size) {
+ throw new FilesystemError(39)
+ }
+ if (this.writers.has(node.writeKey ?? node.id)) {
+ throw new FilesystemError(16)
+ }
+ await node.remove()
+ }
+
+ private async request(type: number, reader: NinePReader, signal: AbortSignal): Promise<NinePWriter> {
+ const result = new NinePWriter()
+ switch (type) {
+ case 100: {
+ this.messageSize = Math.min(reader.number(4), 256 * 1024)
+ const version = reader.string()
+ return result.number(this.messageSize, 4).string(version === '9P2000.L' ? version : 'unknown')
+ }
+ case 104: {
+ const id = reader.number(4)
+ reader.number(4)
+ reader.string()
+ const mount = reader.string()
+ if (mount && mount !== '/') {
+ throw new FilesystemError(2)
+ }
+ this.fids.set(id, { node: this.filesystem.root })
+ return qid(result, this.filesystem.root)
+ }
+ case 108:
+ return result
+ case 110: {
+ let node = this.fid(reader.number(4)).node
+ const newId = reader.number(4)
+ const count = reader.number(2)
+ const walked: TerminalNode[] = []
+ for (let i = 0; i < count; i++) {
+ const name = reader.string()
+ const next = name === '..' ? (node.parent ?? node) : name === '.' ? node : node.children?.get(name)
+ if (!next) {
+ if (!walked.length) {
+ throw new FilesystemError(2)
+ }
+ break
+ }
+ node = next
+ walked.push(node)
+ }
+ this.fids.set(newId, { node })
+ result.number(walked.length, 2)
+ walked.forEach((entry) => qid(result, entry))
+ return result
+ }
+ case 12: {
+ const fid = this.fid(reader.number(4))
+ await this.open(fid, reader.number(4), signal)
+ return qid(result, fid.node).number(this.messageSize - 24, 4)
+ }
+ case 72: {
+ const parent = this.fid(reader.number(4)).node
+ const name = reader.string()
+ this.validateDestination(parent, name)
+ if (!parent.mkdir) {
+ throw new FilesystemError(30)
+ }
+ return qid(result, await parent.mkdir(name))
+ }
+ case 76: {
+ const parent = this.fid(reader.number(4)).node
+ const name = reader.string()
+ const flags = reader.number(4)
+ if (flags & ~0x200 || name === '.' || name === '..') {
+ throw new FilesystemError(22)
+ }
+ if (!parent.children) {
+ throw new FilesystemError(20)
+ }
+ const node = parent.children.get(name)
+ if (!node) {
+ throw new FilesystemError(2)
+ }
+ await this.remove(node, !!(flags & 0x200))
+ return result
+ }
+ case 122: {
+ const id = reader.number(4)
+ const fid = this.fid(id)
+ try {
+ await this.remove(fid.node, !!fid.node.children)
+ } finally {
+ if (fid.writing) {
+ this.writers.delete(fid.node.writeKey ?? fid.node.id)
+ }
+ this.fids.delete(id)
+ }
+ return result
+ }
+ case 20: {
+ const node = this.fid(reader.number(4)).node
+ const parent = this.fid(reader.number(4)).node
+ await this.rename(node, parent, reader.string())
+ return result
+ }
+ case 74: {
+ const source = this.fid(reader.number(4)).node
+ const node = source.children?.get(reader.string())
+ const parent = this.fid(reader.number(4)).node
+ const name = reader.string()
+ if (!node) {
+ throw new FilesystemError(2)
+ }
+ await this.rename(node, parent, name)
+ return result
+ }
+ case 24: {
+ const fid = this.fid(reader.number(4))
+ const node = fid.node
+ // Like procfs, unopened API files report zero bytes without fetching their contents.
+ result.number(0x7ff, 8)
+ qid(result, node)
+ result.number(node.children ? (node.mkdir ? 0o40755 : 0o40555) : node.writable ? 0o100644 : 0o100444, 4)
+ result
+ .number(0, 4)
+ .number(0, 4)
+ .number(node.children ? 2 : 1, 8)
+ .number(0, 8)
+ result
+ .number(node.size, 8)
+ .number(4096, 8)
+ .number(Math.ceil(node.size / 512), 8)
+ for (let i = 0; i < 10; i++) {
+ result.number(0, 8)
+ }
+ return result
+ }
+ case 40: {
+ const fid = this.fid(reader.number(4))
+ const node = fid.node
+ const offset = reader.number(8)
+ const count = Math.min(reader.number(4), this.messageSize - 11)
+ if (!node.children) {
+ throw new FilesystemError(20)
+ }
+ // An offset indexes this list, so one listing holds its snapshot across pages. A
+ // removal between pages would otherwise shift the rest and drop an entry.
+ const entries =
+ offset === 0 || !fid.entries ? [node, node.parent ?? node, ...node.children.values()] : fid.entries
+ fid.entries = entries
+ const data = new NinePWriter()
+ let length = 0
+ for (let i = offset; i < entries.length; i++) {
+ const entry = entries[i]
+ const bytes = qid(new NinePWriter(), entry)
+ .number(i + 1, 8)
+ .number(entry.children ? 4 : 8, 1)
+ .string(i === 0 ? '.' : i === 1 ? '..' : entry.name)
+ .build()
+ if (length + bytes.length > count) {
+ break
+ }
+ data.data(bytes)
+ length += bytes.length
+ }
+ return result.number(length, 4).data(data.build())
+ }
+ case 116: {
+ const fid = this.fid(reader.number(4))
+ const offset = reader.number(8)
+ const count = Math.min(reader.number(4), this.messageSize - 11)
+ if (!fid.file) {
+ throw new FilesystemError(9)
+ }
+ const data = fid.file.bytes.slice(offset, offset + count)
+ return result.number(data.length, 4).data(data)
+ }
+ case 118: {
+ const fid = this.fid(reader.number(4))
+ const requestedOffset = reader.number(8)
+ const count = reader.number(4)
+ if (!fid.writing || !fid.file || fid.failed) {
+ throw new FilesystemError(9)
+ }
+ // The guest can still have an unknown inode size when an API file opens with O_APPEND.
+ const offset = fid.append ? fid.file.bytes.length : requestedOffset
+ if (offset + count > MAX_TERMINAL_FILE_BYTES) {
+ throw new FilesystemError(27)
+ }
+ const length = Math.max(fid.file.bytes.length, offset + count)
+ // Linux sends a file as many small packets, so the buffer grows in doubling steps
+ // and the file keeps a view of it. Copying it per packet would cost O(size squared).
+ const previous = fid.capacity?.buffer === fid.file.bytes.buffer ? fid.capacity : undefined
+ let capacity = previous
+ if (!capacity || length > capacity.length) {
+ const grown = previous ? Math.max(length, previous.length * 2) : length
+ capacity = new Uint8Array(Math.min(grown, MAX_TERMINAL_FILE_BYTES))
+ capacity.set(fid.file.bytes)
+ fid.capacity = capacity
+ }
+ capacity.set(reader.data(count), offset)
+ fid.file.bytes = capacity.subarray(0, length)
+ fid.dirty = true
+ fid.node.size = length
+ return result.number(count, 4)
+ }
+ case 26: {
+ const fid = this.fid(reader.number(4))
+ const valid = reader.number(4)
+ reader.data(12)
+ const size = reader.number(8)
+ // Linux includes mtime and ctime when truncating through shell redirection.
+ if (valid & ~0x1f8) {
+ throw new FilesystemError(95)
+ }
+ if (valid & 8) {
+ await this.truncate(fid, size)
+ }
+ return result
+ }
+ case 50:
+ await this.save(this.fid(reader.number(4)))
+ return result
+ case 120: {
+ const id = reader.number(4)
+ const fid = this.fid(id)
+ try {
+ await this.save(fid)
+ } finally {
+ if (fid.writing) {
+ this.writers.delete(fid.node.writeKey ?? fid.node.id)
+ }
+ this.fids.delete(id)
+ }
+ return result
+ }
+ case 8:
+ return result
+ .number(0x01021997, 4)
+ .number(4096, 4)
+ .number(0, 8)
+ .number(0, 8)
+ .number(0, 8)
+ .number(0, 8)
+ .number(0, 8)
+ .number(0, 8)
+ .number(255, 4)
+ default:
+ throw new FilesystemError(95)
+ }
+ }
+}
diff --git a/frontend/src/scenes/terminal/posthogCommands.test.ts b/frontend/src/scenes/terminal/posthogCommands.test.ts
new file mode 100644
index 000000000000..2f692e6c6a88
--- /dev/null
+++ b/frontend/src/scenes/terminal/posthogCommands.test.ts
@@ -0,0 +1,317 @@
+import { fileSystemList } from '~/generated/core/api'
+import type { FileSystemApi } from '~/generated/core/api.schemas'
+
+import {
+ mcpServerInstallationsAvailableToolsRetrieve,
+ mcpServerInstallationsCallToolCreate,
+} from 'products/mcp_store/frontend/generated/api'
+import {
+ notebooksCreate,
+ notebooksList,
+ notebooksPartialUpdate,
+ notebooksRetrieve,
+} from 'products/notebooks/frontend/generated/api'
+import type { NotebookApi } from 'products/notebooks/frontend/generated/api.schemas'
+import { insightsRetrieve } from 'products/product_analytics/frontend/generated/api'
+
+import { PosthogCommands } from './posthogCommands'
+import { PosthogFilesystem } from './posthogFilesystem'
+import { MAX_TERMINAL_FILE_BYTES } from './terminalFilesystem'
+
+jest.mock('~/generated/core/api', () => ({ fileSystemList: jest.fn() }))
+jest.mock('products/notebooks/frontend/generated/api', () => ({
+ notebooksList: jest.fn(),
+ notebooksRetrieve: jest.fn(),
+ notebooksPartialUpdate: jest.fn(),
+ notebooksCreate: jest.fn(),
+}))
+jest.mock('products/mcp_store/frontend/generated/api', () => ({
+ mcpServerInstallationsAvailableToolsRetrieve: jest.fn(),
+ mcpServerInstallationsCallToolCreate: jest.fn(),
+}))
+jest.mock('products/product_analytics/frontend/generated/api', () => ({
+ insightsRetrieve: jest.fn(),
+ insightsList: jest.fn(),
+}))
+
+describe('PostHog terminal commands', () => {
+ let commands: PosthogCommands
+ let filesystem: PosthogFilesystem
+ const cwd = '/posthog/files/Research'
+ const author = {
+ id: 1,
+ uuid: '01900000-0000-7000-8000-000000000001',
+ email: '[email protected]',
+ hedgehog_config: null,
+ }
+
+ beforeEach(async () => {
+ jest.clearAllMocks()
+ jest.mocked(fileSystemList).mockResolvedValue({
+ count: 1,
+ next: null,
+ results: [
+ {
+ id: 'fs-note',
+ ref: 'shortnote',
+ type: 'notebook',
+ path: 'Research/Notes',
+ user_access_level: 'editor',
+ } as FileSystemApi,
+ ],
+ })
+ jest.mocked(notebooksList).mockResolvedValue({
+ count: 1,
+ next: null,
+ results: [
+ {
+ id: '01900000-0000-7000-8000-000000000002',
+ short_id: 'shortnote',
+ title: 'Notes',
+ deleted: false,
+ user_access_level: 'editor',
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: author,
+ last_modified_at: '2026-01-01T00:00:00Z',
+ last_modified_by: author,
+ },
+ ],
+ })
+ jest.mocked(notebooksRetrieve).mockResolvedValue({ short_id: 'shortnote', title: 'Notes' } as NotebookApi)
+ jest.mocked(notebooksPartialUpdate).mockResolvedValue({ short_id: 'shortnote', deleted: true } as NotebookApi)
+ jest.mocked(notebooksCreate).mockResolvedValue({ short_id: 'newnote' } as NotebookApi)
+ jest.mocked(mcpServerInstallationsAvailableToolsRetrieve).mockResolvedValue({
+ servers: [
+ {
+ installation_id: 'server-id',
+ slug: 'example',
+ name: 'Example',
+ tools: [
+ {
+ name: 'echo',
+ description: 'Echo arguments',
+ input_schema: { type: 'object', properties: { text: { type: 'string' } } },
+ approval_state: 'approved',
+ annotations: { readOnlyHint: true },
+ },
+ {
+ name: 'convert',
+ description: 'Convert arguments',
+ input_schema: {
+ type: 'object',
+ $defs: { Count: { type: 'integer' } },
+ properties: {
+ dry_run: { anyOf: [{ type: 'boolean' }, { type: 'null' }] },
+ force: { type: ['boolean', 'null'] },
+ limit: { $ref: '#/$defs/Count' },
+ query: { oneOf: [{ type: 'object' }, { type: 'array' }] },
+ note: { anyOf: [{ type: 'string' }, { type: 'object' }] },
+ },
+ },
+ approval_state: 'approved',
+ annotations: { readOnlyHint: true },
+ },
+ ],
+ },
+ ],
+ })
+ jest.mocked(mcpServerInstallationsCallToolCreate).mockResolvedValue({
+ content: [],
+ is_error: false,
+ structured_content: { echoed: true },
+ })
+ const signal = new AbortController().signal
+ filesystem = new PosthogFilesystem('42', signal)
+ await filesystem.load()
+ commands = new PosthogCommands('42', signal, filesystem)
+ })
+
+ it.each([
+ ['notebook-delete', './Notes.md'],
+ ['notebooks-destroy', '--short-id', 'shortnote'],
+ ['notebook-delete', '--json', '{"short_id":"shortnote"}'],
+ ])('soft-deletes a notebook using %s %s', async (...argv) => {
+ await expect(commands.execute(argv, cwd)).resolves.toEqual({
+ deleted: 'shortnote',
+ })
+ expect(notebooksPartialUpdate).toHaveBeenCalledWith(
+ '42',
+ 'shortnote',
+ { deleted: true },
+ expect.objectContaining({ signal: expect.any(AbortSignal) })
+ )
+ expect(notebooksRetrieve).not.toHaveBeenCalled()
+ expect(mcpServerInstallationsAvailableToolsRetrieve).not.toHaveBeenCalled()
+ await expect(commands.execute(['dashboard-get', './Notes.md'], cwd)).rejects.toThrow('Expected a dashboard')
+ })
+
+ it.each([
+ ['notebook-delete', '..'],
+ ['notebook-delete', '--short-id', '%2e%2e'],
+ ['notebook-delete', '--json', '{"short_id":".."}'],
+ ['notebook-update', '..'],
+ ['notebook-get', 'shortnote?format=json'],
+ ['notebook-get', 'shortnote#'],
+ ['notebook-get', 'shortnote\n'],
+ ['insight-get', '..\\..\\99\\insights\\42'],
+ ['insight-get', '%2e%2e'],
+ ])('rejects unsafe object IDs in %s %s before an API request', async (...argv) => {
+ await expect(commands.execute(argv, cwd)).rejects.toThrow()
+ expect(notebooksPartialUpdate).not.toHaveBeenCalled()
+ expect(notebooksRetrieve).not.toHaveBeenCalled()
+ expect(insightsRetrieve).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['notebook-get', 'Ab12Cd34'],
+ ['notebook-get', 'Café123'],
+ ['insight-get', 'Ab12Cd34'],
+ ['insight-get', '123456789012345'],
+ ])('accepts supported IDs in %s %s', async (command, id) => {
+ await commands.execute([command, id], cwd)
+ if (command === 'notebook-get') {
+ expect(notebooksRetrieve).toHaveBeenCalledWith('42', id, expect.anything())
+ } else {
+ expect(insightsRetrieve).toHaveBeenCalledWith('42', id, undefined, expect.anything())
+ }
+ })
+
+ it('validates object IDs resolved from project files', async () => {
+ jest.mocked(fileSystemList).mockResolvedValue({
+ count: 1,
+ next: null,
+ results: [
+ {
+ id: 'fs-note',
+ ref: '..',
+ type: 'notebook',
+ path: 'Research/Notes',
+ user_access_level: 'editor',
+ } as FileSystemApi,
+ ],
+ })
+ await filesystem.load()
+
+ await expect(commands.execute(['notebook-delete', './Notes.json'], cwd)).rejects.toThrow()
+ expect(notebooksPartialUpdate).not.toHaveBeenCalled()
+ })
+
+ it('parses typed flags while preserving strings and rejects unknown arguments before making API calls', async () => {
+ await commands.execute(['notebooks-list', '--limit', '10'], cwd)
+ expect(notebooksList).toHaveBeenLastCalledWith('42', { limit: 10 }, expect.anything())
+ await commands.execute(['notebook-create', '--title', 'true', '--markdown', '# café 🦔\nbody'], cwd)
+ expect(notebooksCreate).toHaveBeenCalledWith(
+ '42',
+ expect.objectContaining({ title: 'true', text_content: '# true\n\n# café 🦔\nbody' }),
+ expect.anything()
+ )
+ await expect(
+ commands.execute(['notebook-delete', '--json', '{"short_id":"shortnote","project_id":"99"}'], cwd)
+ ).rejects.toThrow()
+ expect(notebooksPartialUpdate).not.toHaveBeenCalled()
+ await expect(commands.execute(['notebooks-list', '--limti', '10'], cwd)).rejects.toThrow('Unknown argument')
+ })
+
+ it('keeps notebook search text in step with a content update', async () => {
+ const markdown = '# Notes\n\nrewritten body'
+ const content = {
+ type: 'doc',
+ content: [{ type: 'ph-markdown-notebook', attrs: { nodeId: 'markdown-notebook-v2', markdown } }],
+ }
+ await commands.execute(['notebook-update', '--json', JSON.stringify({ short_id: 'shortnote', content })], cwd)
+ expect(notebooksPartialUpdate).toHaveBeenLastCalledWith(
+ '42',
+ 'shortnote',
+ { content, text_content: markdown },
+ expect.anything()
+ )
+ await commands.execute(
+ ['notebook-update', '--json', JSON.stringify({ short_id: 'shortnote', content, text_content: 'chosen' })],
+ cwd
+ )
+ expect(notebooksPartialUpdate).toHaveBeenLastCalledWith(
+ '42',
+ 'shortnote',
+ { content, text_content: 'chosen' },
+ expect.anything()
+ )
+ jest.mocked(notebooksPartialUpdate).mockClear()
+ await expect(
+ commands.execute(
+ [
+ 'notebook-update',
+ '--json',
+ JSON.stringify({ short_id: 'shortnote', content: { type: 'doc', content: [{ type: 'p' }] } }),
+ ],
+ cwd
+ )
+ ).rejects.toThrow('Include text_content')
+ expect(notebooksPartialUpdate).not.toHaveBeenCalled()
+ })
+
+ it('resolves argument types through references, unions and type arrays', async () => {
+ await commands.execute(
+ ['example/convert', '--dry-run', '--force', '--limit', '10', '--query', '{"kind":"events"}'],
+ cwd
+ )
+ expect(mcpServerInstallationsCallToolCreate).toHaveBeenLastCalledWith(
+ '42',
+ 'server-id',
+ {
+ tool_name: 'convert',
+ arguments: { dry_run: true, force: true, limit: 10, query: { kind: 'events' } },
+ },
+ expect.anything()
+ )
+ await commands.execute(['example/convert', '--note', 'plain text'], cwd)
+ expect(mcpServerInstallationsCallToolCreate).toHaveBeenLastCalledWith(
+ '42',
+ 'server-id',
+ { tool_name: 'convert', arguments: { note: 'plain text' } },
+ expect.anything()
+ )
+ await expect(commands.execute(['example/convert', '--limit', 'ten'], cwd)).rejects.toThrow(
+ 'Invalid integer value for --limit.'
+ )
+ })
+
+ it('discovers connected MCP tools and exposes their schemas as files', async () => {
+ const tools = await commands.execute(['tools', 'echo'], cwd)
+ // The fixture declares readOnlyHint, which the terminal must not repeat as a safety claim.
+ expect(tools).toEqual([{ name: 'example/echo', description: 'Echo arguments', readOnly: false }])
+ const schema = filesystem.root.children!.get('tools')!.children!.get('example%2Fecho.json')!
+ expect(
+ JSON.parse(new TextDecoder().decode((await schema.open!()).bytes)).inputSchema.properties.text.type
+ ).toBe('string')
+ await expect(commands.execute(['example/echo', '--text', 'false'], cwd)).resolves.toEqual({ echoed: true })
+ expect(mcpServerInstallationsCallToolCreate).toHaveBeenCalledWith(
+ '42',
+ 'server-id',
+ { tool_name: 'echo', arguments: { text: 'false' } },
+ expect.anything()
+ )
+ jest.mocked(mcpServerInstallationsCallToolCreate).mockResolvedValue({
+ content: [{ type: 'text', text: 'Tool failed' }],
+ is_error: true,
+ })
+ await expect(commands.execute(['example/echo', '--text', 'hello'], cwd)).rejects.toThrow('Tool failed')
+ })
+
+ it('returns an error envelope through the filesystem bridge rather than a stale successful result', async () => {
+ const directory = filesystem.root.children!.get('.ph')!
+ const request = await directory.children!.get('request')!.open!()
+ const response = directory.children!.get('response')!
+ const read = async (): Promise<unknown> => JSON.parse(new TextDecoder().decode((await response.open!()).bytes))
+ await request.save!(new TextEncoder().encode(JSON.stringify({ argv: ['notebook-get', './Notes.md'], cwd })))
+ expect(await read()).toMatchObject({ ok: true, result: { short_id: 'shortnote' } })
+ await request.save!(new TextEncoder().encode('{invalid'))
+ expect(await read()).toMatchObject({ ok: false })
+ jest.mocked(notebooksRetrieve).mockRejectedValue(new Error('Not allowed'))
+ await request.save!(new TextEncoder().encode(JSON.stringify({ argv: ['notebook-get', './Notes.md'], cwd })))
+ expect(await read()).toEqual({ ok: false, error: 'Not allowed' })
+ jest.mocked(notebooksRetrieve).mockRejectedValue(new Error('x'.repeat(MAX_TERMINAL_FILE_BYTES + 1)))
+ await request.save!(new TextEncoder().encode(JSON.stringify({ argv: ['notebook-get', './Notes.md'], cwd })))
+ expect((await response.open!()).bytes.length).toBeLessThan(MAX_TERMINAL_FILE_BYTES)
+ expect(await read()).toEqual({ ok: false, error: expect.stringContaining('exceeds 4 MiB') })
+ })
+})
diff --git a/frontend/src/scenes/terminal/posthogCommands.ts b/frontend/src/scenes/terminal/posthogCommands.ts
new file mode 100644
index 000000000000..26597848a986
--- /dev/null
+++ b/frontend/src/scenes/terminal/posthogCommands.ts
@@ -0,0 +1,410 @@
+import { z } from 'zod'
+
+import { dashboardsList, dashboardsRetrieve } from 'products/dashboards/frontend/generated/api'
+import { featureFlagsList, featureFlagsRetrieve } from 'products/feature_flags/frontend/generated/api'
+import {
+ mcpServerInstallationsAvailableToolsRetrieve,
+ mcpServerInstallationsCallToolCreate,
+} from 'products/mcp_store/frontend/generated/api'
+import {
+ notebooksCreate,
+ notebooksList,
+ notebooksPartialUpdate,
+ notebooksRetrieve,
+} from 'products/notebooks/frontend/generated/api'
+import { NotebooksPartialUpdateBody } from 'products/notebooks/frontend/generated/api.zod'
+import { insightsList, insightsRetrieve } from 'products/product_analytics/frontend/generated/api'
+
+import { markdownNode, PosthogFilesystem, terminalFilename } from './posthogFilesystem'
+import { TerminalCommands } from './terminalCommands'
+
+interface Command {
+ name: string
+ description: string
+ inputSchema: Record<string, unknown>
+ readOnly: boolean
+ reference?: { parameter: string; type: string }
+ invoke: (args: Record<string, unknown>) => Promise<unknown>
+}
+
+const aliases: Record<string, string> = {
+ 'notebook-list': 'notebooks-list',
+ 'notebook-get': 'notebooks-retrieve',
+ 'notebook-create': 'notebooks-create-markdown',
+ 'notebook-update': 'notebooks-partial-update',
+ 'notebook-delete': 'notebooks-destroy',
+}
+
+const help = `ph: PostHog commands
+
+ph tools [search] List project commands and connected MCP tools
+ph help <command> Show arguments and whether a command writes data
+ph <command> [ID or file] Run a command
+ph <command> --key value Set a named argument
+ph <command> --json '{...}' Supply a JSON arguments object
+ph <command> --json @args.json Read arguments from a Linux file
+ph <command> --json - Read arguments from stdin
+ph refresh Reload the project tree and connected tool catalog
+
+Examples:
+ ph notebooks-list --limit 10 | jq .results
+ ph notebook-get '/posthog/files/Research/Notes.md'
+ ph notebook-create --title 'Notes' --markdown @/tmp/notes.md
+ ph notebook-delete <short-id>
+ ph help notebook-delete
+
+An @file value reads its contents. Built-in IDs can be paths under /posthog/files
+or /posthog/api. JSON results go to stdout; errors go to stderr with a nonzero exit.
+Connected tools use server/tool names from ph tools and their existing MCP permissions.
+The built-in commands cover notebooks and reading insights, dashboards, and feature flags.
+Tool schemas are files under /posthog/tools. Run ph refresh after creating or deleting objects.
+`
+
+function command<T extends z.ZodType>(
+ name: string,
+ description: string,
+ schema: T,
+ invoke: (args: z.infer<T>) => Promise<unknown>,
+ options: Pick<Command, 'readOnly' | 'reference'> = { readOnly: true }
+): Command {
+ return {
+ name,
+ description,
+ inputSchema: z.toJSONSchema(schema),
+ ...options,
+ invoke: async (args) => invoke(schema.parse(args)),
+ }
+}
+
+function object(value: unknown): Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {}
+}
+
+// Notebook search reads text_content, and the API keeps the stored value when an update omits it,
+// so a content change has to carry the matching text the way every other writer does.
+function notebookUpdate<T extends { content?: unknown; text_content?: string | null }>(body: T): T {
+ if (body.content === undefined || body.text_content !== undefined) {
+ return body
+ }
+ const node = markdownNode(body.content)
+ if (!node) {
+ throw new Error('Include text_content when updating content that is not a markdown notebook.')
+ }
+ return { ...body, text_content: node.attrs.markdown }
+}
+
+const jsonTypes = ['number', 'integer', 'boolean', 'object', 'array']
+
+// Connected MCP servers write their own schemas, so a property can state its type through a
+// reference, a composed branch, or a type array instead of a plain `type`.
+function schemaTypes(property: unknown, root: Record<string, unknown>, depth = 0): Set<string> {
+ const types = new Set<string>()
+ const node = object(property)
+ if (depth > 8) {
+ return types
+ }
+ const pointer = typeof node.$ref === 'string' ? /^#\/(\$defs|definitions)\/([^/]+)$/.exec(node.$ref) : null
+ if (pointer) {
+ const name = pointer[2].replaceAll('~1', '/').replaceAll('~0', '~')
+ for (const type of schemaTypes(object(root[pointer[1]])[name], root, depth + 1)) {
+ types.add(type)
+ }
+ }
+ for (const type of Array.isArray(node.type) ? node.type : [node.type]) {
+ if (typeof type === 'string' && type !== 'null') {
+ types.add(type)
+ }
+ }
+ for (const key of ['anyOf', 'oneOf', 'allOf']) {
+ for (const branch of Array.isArray(node[key]) ? (node[key] as unknown[]) : []) {
+ for (const type of schemaTypes(branch, root, depth + 1)) {
+ types.add(type)
+ }
+ }
+ }
+ return types
+}
+
+export class PosthogCommands {
+ private readonly commands = new Map<string, Command>()
+ private readonly toolDirectory
+ private connectedLoaded = false
+
+ constructor(
+ private projectId: string,
+ private signal: AbortSignal,
+ private filesystem: PosthogFilesystem
+ ) {
+ this.toolDirectory = filesystem.directory('tools', filesystem.root)
+ const options = { signal }
+ const pagination = z
+ .object({
+ limit: z.number().int().positive().optional(),
+ offset: z.number().int().nonnegative().optional(),
+ })
+ .strict()
+ const shortId = z
+ .object({
+ short_id: z
+ .string()
+ .regex(/^[\p{L}\p{N}]{1,12}(?![\s\S])/u, 'Use a notebook ID with up to 12 letters or numbers.'),
+ })
+ .strict()
+ const insightId = z
+ .object({
+ short_id: z
+ .string()
+ .regex(/^(?:[A-Za-z0-9]{1,12}|[0-9]+)(?![\s\S])/, 'Use an insight short ID or numeric ID.'),
+ })
+ .strict()
+ const id = z.object({ id: z.number().int().positive() }).strict()
+ const notebook = { parameter: 'short_id', type: 'notebook' }
+ const builtins = [
+ command(
+ 'notebooks-list',
+ 'List notebooks in this project.',
+ pagination.extend({ search: z.string().optional() }),
+ (args) => notebooksList(projectId, args, options)
+ ),
+ command(
+ 'notebooks-retrieve',
+ 'Read a notebook by short ID or filesystem path.',
+ shortId,
+ ({ short_id }) => notebooksRetrieve(projectId, short_id, options),
+ { readOnly: true, reference: notebook }
+ ),
+ command(
+ 'notebooks-destroy',
+ 'Delete a notebook from PostHog.',
+ shortId,
+ async ({ short_id }) => {
+ await notebooksPartialUpdate(projectId, short_id, { deleted: true }, options)
+ return { deleted: short_id }
+ },
+ { readOnly: false, reference: notebook }
+ ),
+ command(
+ 'notebooks-partial-update',
+ 'Update a notebook. Include version when changing its contents.',
+ NotebooksPartialUpdateBody.extend(shortId.shape).strict(),
+ ({ short_id, ...body }) => notebooksPartialUpdate(projectId, short_id, notebookUpdate(body), options),
+ { readOnly: false, reference: notebook }
+ ),
+ command(
+ 'notebooks-create-markdown',
+ 'Create a markdown notebook. Its title becomes the first heading.',
+ z.object({ title: z.string().min(1).max(256), markdown: z.string().optional() }).strict(),
+ async ({ title, markdown }) => {
+ const text = `# ${title}${markdown?.trim() ? `\n\n${markdown.trim()}` : ''}`
+ return notebooksCreate(
+ projectId,
+ {
+ title,
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'ph-markdown-notebook',
+ attrs: { nodeId: 'markdown-notebook-v2', markdown: text },
+ },
+ ],
+ },
+ text_content: text,
+ },
+ options
+ )
+ },
+ { readOnly: false }
+ ),
+ command('insights-list', 'List insights in this project.', pagination, (args) =>
+ insightsList(projectId, args, options)
+ ),
+ command(
+ 'insight-get',
+ 'Read an insight by short ID or filesystem path.',
+ insightId,
+ ({ short_id }) => insightsRetrieve(projectId, short_id, undefined, options),
+ { readOnly: true, reference: { parameter: 'short_id', type: 'insight' } }
+ ),
+ command('dashboards-get-all', 'List dashboards in this project.', pagination, (args) =>
+ dashboardsList(projectId, args, options)
+ ),
+ command(
+ 'dashboard-get',
+ 'Read a dashboard by ID or filesystem path.',
+ id,
+ ({ id }) => dashboardsRetrieve(projectId, id, undefined, options),
+ { readOnly: true, reference: { parameter: 'id', type: 'dashboard' } }
+ ),
+ command('feature-flag-get-all', 'List feature flags in this project.', pagination, (args) =>
+ featureFlagsList(projectId, args, options)
+ ),
+ command(
+ 'feature-flag-get-definition',
+ 'Read a feature flag by ID or filesystem path.',
+ id,
+ ({ id }) => featureFlagsRetrieve(projectId, id, options),
+ { readOnly: true, reference: { parameter: 'id', type: 'feature_flag' } }
+ ),
+ ]
+ for (const tool of builtins) {
+ this.register(tool)
+ }
+ new TerminalCommands(filesystem, (argv, cwd) => this.execute(argv, cwd))
+ }
+
+ private register(tool: Command): void {
+ this.commands.set(tool.name, tool)
+ const { invoke: _, ...description } = tool
+ this.filesystem.text(
+ `${terminalFilename(tool.name)}.json`,
+ this.toolDirectory,
+ JSON.stringify(description, null, 2)
+ )
+ }
+
+ private async loadConnected(): Promise<void> {
+ if (this.connectedLoaded) {
+ return
+ }
+ const { servers } = await mcpServerInstallationsAvailableToolsRetrieve(this.projectId, { signal: this.signal })
+ for (const server of servers) {
+ const namespace =
+ servers.filter((candidate) => candidate.slug === server.slug).length > 1
+ ? `${server.slug}@${server.installation_id}`
+ : server.slug
+ for (const tool of server.tools) {
+ this.register({
+ name: `${namespace}/${tool.name}`,
+ description: `${tool.description}${tool.approval_state === 'needs_approval' ? '\nNeeds approval in Settings → MCP servers.' : ''}`,
+ inputSchema: tool.input_schema,
+ // Upstream MCP annotations are advisory, so readOnlyHint cannot prove that a
+ // connected tool only reads. Report every connected tool as a writer until the
+ // gateway returns its own classification.
+ readOnly: false,
+ invoke: async (args) => {
+ const result = await mcpServerInstallationsCallToolCreate(
+ this.projectId,
+ server.installation_id,
+ { tool_name: tool.name, arguments: args },
+ { signal: this.signal }
+ )
+ if (result.is_error) {
+ throw new Error(JSON.stringify(result.content))
+ }
+ return result.structured_content ?? result.content
+ },
+ })
+ }
+ }
+ this.connectedLoaded = true
+ }
+
+ private parseArguments(tool: Command, argv: string[], cwd: string): Record<string, unknown> {
+ const args: Record<string, unknown> = Object.create(null)
+ const properties = object(tool.inputSchema.properties)
+ for (let index = 0; index < argv.length; index++) {
+ const argument = argv[index]
+ if (argument === '--json') {
+ const value: unknown = JSON.parse(argv[++index] ?? '')
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
+ throw new Error('--json requires a JSON object.')
+ }
+ Object.assign(args, value)
+ } else if (argument.startsWith('--')) {
+ const equals = argument.indexOf('=')
+ const rawName = argument.slice(2, equals < 0 ? undefined : equals)
+ const name = rawName in properties ? rawName : rawName.replaceAll('-', '_')
+ if (!(name in properties)) {
+ throw new Error(`Unknown argument --${rawName}. Run ph help ${tool.name}.`)
+ }
+ const types = schemaTypes(properties[name], tool.inputSchema)
+ const flag = types.size > 0 && [...types].every((type) => type === 'boolean')
+ const value =
+ equals >= 0
+ ? argument.slice(equals + 1)
+ : flag && (!argv[index + 1] || argv[index + 1].startsWith('--'))
+ ? 'true'
+ : argv[++index]
+ if (value === undefined) {
+ throw new Error(`Missing value for --${rawName}.`)
+ }
+ args[name] = value
+ } else if (tool.reference && args[tool.reference.parameter] === undefined) {
+ args[tool.reference.parameter] = argument
+ } else {
+ throw new Error(`Unexpected argument ${argument}. Run ph help ${tool.name}.`)
+ }
+ }
+ if (tool.reference && typeof args[tool.reference.parameter] === 'string') {
+ args[tool.reference.parameter] = this.filesystem.resolveReference(
+ args[tool.reference.parameter] as string,
+ cwd,
+ tool.reference.type
+ )
+ }
+ for (const [name, value] of Object.entries(args)) {
+ const types = [...schemaTypes(properties[name], tool.inputSchema)]
+ // A property that also accepts a string keeps the text it was given.
+ if (typeof value === 'string' && types.length > 0 && types.every((type) => jsonTypes.includes(type))) {
+ try {
+ args[name] = JSON.parse(value)
+ } catch {
+ throw new Error(`Invalid ${types.join(' or ')} value for --${name}.`)
+ }
+ }
+ }
+ return args
+ }
+
+ async execute(argv: string[], cwd: string): Promise<unknown> {
+ const [name = 'help', ...rest] = argv
+ if (name === 'help' || name === '--help') {
+ if (!rest.length) {
+ return help
+ }
+ const tool = await this.find(rest[0])
+ const { invoke: _, ...description } = tool
+ return description
+ }
+ if (name === 'refresh') {
+ await this.filesystem.load()
+ this.connectedLoaded = false
+ for (const key of this.commands.keys()) {
+ if (key.includes('/')) {
+ this.commands.delete(key)
+ this.toolDirectory.children!.delete(`${terminalFilename(key)}.json`)
+ }
+ }
+ await this.loadConnected()
+ return 'Project files and connected tools refreshed.'
+ }
+ if (name === 'tools') {
+ await this.loadConnected()
+ const search = rest.join(' ').toLowerCase()
+ return [...this.commands.values()]
+ .filter((tool) => `${tool.name} ${tool.description}`.toLowerCase().includes(search))
+ .map(({ name, description, readOnly }) => ({ name, description, readOnly }))
+ }
+ const tool = await this.find(name)
+ if (rest.length === 1 && rest[0] === '--help') {
+ const { invoke: _, ...description } = tool
+ return description
+ }
+ return tool.invoke(this.parseArguments(tool, rest, cwd))
+ }
+
+ private async find(name: string): Promise<Command> {
+ const canonical = aliases[name] ?? name
+ if (!this.commands.has(canonical)) {
+ await this.loadConnected()
+ }
+ const tool = this.commands.get(canonical)
+ if (!tool) {
+ throw new Error(`Unknown command ${name}. Run ph tools to find a command.`)
+ }
+ return tool
+ }
+}
diff --git a/frontend/src/scenes/terminal/posthogFilesystem.test.ts b/frontend/src/scenes/terminal/posthogFilesystem.test.ts
new file mode 100644
index 000000000000..7fd1f47c2aa9
--- /dev/null
+++ b/frontend/src/scenes/terminal/posthogFilesystem.test.ts
@@ -0,0 +1,582 @@
+import apiMutator from 'lib/api-orval-mutator'
+
+import { fileSystemCreate, fileSystemDestroy, fileSystemList, fileSystemRetrieve } from '~/generated/core/api'
+import type { FileSystemApi } from '~/generated/core/api.schemas'
+
+import { notebooksList, notebooksPartialUpdate, notebooksRetrieve } from 'products/notebooks/frontend/generated/api'
+import type { NotebookApi, NotebookMinimalApi } from 'products/notebooks/frontend/generated/api.schemas'
+
+import { NinePReader, NinePWriter } from './ninepCodec'
+import { NinePServer } from './ninepServer'
+import { PosthogFilesystem, terminalFilename } from './posthogFilesystem'
+
+jest.mock('~/generated/core/api', () => ({
+ ...jest.requireActual('~/generated/core/api'),
+ fileSystemList: jest.fn(),
+ fileSystemCreate: jest.fn(),
+ fileSystemDestroy: jest.fn(),
+ fileSystemRetrieve: jest.fn(),
+}))
+jest.mock('lib/api-orval-mutator', () => {
+ const mutator = jest.fn()
+ return { __esModule: true, default: mutator, apiMutator: mutator }
+})
+jest.mock('products/notebooks/frontend/generated/api', () => ({
+ notebooksRetrieve: jest.fn(),
+ notebooksList: jest.fn(),
+ notebooksPartialUpdate: jest.fn(),
+}))
+
+describe('PostHog filesystem projection', () => {
+ const decoder = new TextDecoder()
+ const entry = (id: string, path: string, type = 'notebook'): FileSystemApi => ({
+ id,
+ path,
+ type,
+ ref: id,
+ depth: 2,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ last_viewed_at: null,
+ user_access_level: 'editor',
+ })
+ const notebook = {
+ short_id: 'note1',
+ version: 7,
+ user_access_level: 'editor',
+ content: {
+ type: 'doc',
+ content: [{ type: 'ph-markdown-notebook', attrs: { markdown: '# Hello 🦔', nodeId: 'preserved' } }],
+ },
+ } as NotebookApi
+ const notebookIndex: NotebookMinimalApi = {
+ ...notebook,
+ title: 'Notes',
+ deleted: false,
+ user_access_level: 'editor',
+ }
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ jest.mocked(fileSystemList).mockResolvedValue({
+ count: 1,
+ next: null,
+ results: [entry('note1', 'Research/Notes')],
+ })
+ jest.mocked(notebooksList).mockResolvedValue({
+ count: 2,
+ next: null,
+ results: [notebookIndex, { ...notebookIndex, short_id: 'note2' }],
+ })
+ jest.mocked(notebooksRetrieve).mockResolvedValue(notebook)
+ })
+
+ it('projects markdown without changing the stored path and saves with the version it read', async () => {
+ const session = new AbortController()
+ const read = new AbortController()
+ const fs = new PosthogFilesystem('42', session.signal)
+ await fs.load()
+ expect(fs.resolveReference('./Notes.md', '/posthog/files/Research', 'notebook')).toBe('note1')
+ expect(fs.resolveReference('/posthog/api/notebook/note1.json', '/', 'notebook')).toBe('note1')
+ expect(() => fs.resolveReference('./Notes.md', '/posthog/files/Research', 'dashboard')).toThrow(
+ 'Expected a dashboard'
+ )
+ expect(notebooksRetrieve).not.toHaveBeenCalled()
+ expect(notebooksList).toHaveBeenCalledWith(
+ '42',
+ { contains: 'markdown-notebook', limit: 500, offset: 0 },
+ expect.anything()
+ )
+ const file = fs.root.children!.get('files')!.children!.get('Research')!.children!.get('Notes.md')!
+ expect(file.writable).toBe(true)
+ const opened = await file.open!(read.signal)
+ expect(decoder.decode(opened.bytes)).toBe('# Hello 🦔')
+ read.abort()
+ expect(jest.mocked(notebooksRetrieve).mock.calls[0][2]?.signal).not.toBe(session.signal)
+ await opened.save!(opened.bytes)
+ expect(notebooksPartialUpdate).not.toHaveBeenCalled()
+ jest.mocked(notebooksPartialUpdate).mockResolvedValue({ ...notebook, version: 8 })
+ await opened.save!(new TextEncoder().encode('# Updated'))
+ expect(notebooksPartialUpdate).toHaveBeenCalledWith(
+ '42',
+ 'note1',
+ {
+ content: {
+ type: 'doc',
+ content: [{ type: 'ph-markdown-notebook', attrs: { markdown: '# Updated', nodeId: 'preserved' } }],
+ },
+ text_content: '# Updated',
+ version: 7,
+ },
+ expect.objectContaining({ signal: session.signal })
+ )
+ await opened.save!(new TextEncoder().encode('# Updated'))
+ expect(notebooksPartialUpdate).toHaveBeenCalledTimes(1)
+ jest.mocked(notebooksPartialUpdate).mockRejectedValue(new Error('Version conflict'))
+ await expect(opened.save!(new TextEncoder().encode('Conflict'))).rejects.toThrow('Version conflict')
+ expect(jest.mocked(notebooksPartialUpdate).mock.calls[1][2]?.version).toBe(8)
+ })
+
+ it('refreshes through retained directory and file handles without saving deleted objects', async () => {
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ await fs.load()
+ const note = fs.root.children!.get('files')!.children!.get('Research')!.children!.get('Notes.md')!
+ const apiNote = fs.root.children!.get('api')!.children!.get('notebook')!.children!.get('note1.json')!
+ const opened = await note.open!()
+ const openedApi = await apiNote.open!()
+ const server = new NinePServer(fs, jest.fn())
+ const request = async (type: number, body: NinePWriter): Promise<{ type: number; body: NinePReader }> => {
+ const bytes = await new Promise<Uint8Array>((resolve) => server.handle(body.frame(type, 1), resolve))
+ const response = new NinePReader(bytes)
+ response.number(4)
+ const responseType = response.number(1)
+ response.number(2)
+ return { type: responseType, body: response }
+ }
+ await request(104, new NinePWriter().number(1, 4).number(0xffffffff, 4).string('root').string(''))
+ await request(110, new NinePWriter().number(1, 4).number(2, 4).number(2, 2).string('files').string('Research'))
+ jest.mocked(fileSystemList).mockResolvedValue({
+ count: 2,
+ next: null,
+ results: [entry('note1', 'Research/Notes'), entry('note2', 'Research/New')],
+ })
+ jest.mocked(notebooksRetrieve).mockClear()
+ await fs.load()
+ expect(fs.root.children!.get('files')!.children!.get('Research')!.children!.get('Notes.md')).toBe(note)
+ expect(fs.root.children!.get('api')!.children!.get('notebook')!.children!.get('note1.json')).toBe(apiNote)
+ expect(
+ (await request(110, new NinePWriter().number(2, 4).number(3, 4).number(1, 2).string('New.md'))).type
+ ).toBe(111)
+ jest.mocked(fileSystemCreate).mockResolvedValue(entry('folder', 'Research/New folder', 'folder'))
+ expect((await request(72, new NinePWriter().number(2, 4).string('New folder'))).type).toBe(73)
+ expect(fileSystemCreate).toHaveBeenLastCalledWith(
+ '42',
+ { path: 'Research/New folder', type: 'folder' },
+ expect.anything()
+ )
+ jest.mocked(fileSystemList).mockResolvedValue({ count: 1, next: null, results: [entry('note1', 'Renamed')] })
+ await fs.load()
+ const renamed = fs.root.children!.get('files')!.children!.get('Renamed.md')!
+ expect(renamed).toBe(note)
+ expect(fs.resolveReference('Renamed.md', '/posthog/files', 'notebook')).toBe('note1')
+ expect(() => fs.resolveReference('Research/Notes.md', '/posthog/files', 'notebook')).toThrow('No project file')
+ jest.mocked(notebooksPartialUpdate).mockResolvedValue({ ...notebook, version: 8 })
+ await opened.save!(new TextEncoder().encode('Save after refresh'))
+ expect(notebooksPartialUpdate).toHaveBeenCalledWith(
+ '42',
+ 'note1',
+ expect.objectContaining({ version: 7, text_content: 'Save after refresh' }),
+ expect.anything()
+ )
+ jest.mocked(fileSystemList).mockResolvedValue({ count: 0, next: null, results: [] })
+ await fs.load()
+ jest.mocked(notebooksPartialUpdate).mockClear()
+ await expect(opened.save!(new TextEncoder().encode('Deleted notebook'))).rejects.toMatchObject({ errno: 116 })
+ await expect(openedApi.save!(new TextEncoder().encode('{"title":"Deleted notebook"}'))).rejects.toMatchObject({
+ errno: 116,
+ })
+ expect(notebooksPartialUpdate).not.toHaveBeenCalled()
+ expect(notebooksRetrieve).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['markdown', 'read'],
+ ['markdown', 'session'],
+ ['JSON', 'read'],
+ ['JSON', 'session'],
+ ])('cancels a pending %s read when the %s ends', async (format, aborted) => {
+ const session = new AbortController()
+ const read = new AbortController()
+ const fs = new PosthogFilesystem('42', session.signal)
+ await fs.load()
+ jest.mocked(notebooksRetrieve).mockImplementationOnce(
+ (_, __, options) =>
+ new Promise((_, reject) => {
+ options!.signal!.addEventListener('abort', () => reject(new Error('Read canceled')), { once: true })
+ })
+ )
+ const node =
+ format === 'markdown'
+ ? fs.root.children!.get('files')!.children!.get('Research')!.children!.get('Notes.md')!
+ : fs.root.children!.get('api')!.children!.get('notebook')!.children!.get('note1.json')!
+ const result = node.open!(read.signal)
+ ;(aborted === 'read' ? read : session).abort()
+ await expect(result).rejects.toThrow('Read canceled')
+ })
+
+ it('removes project references and empty folders only after the API succeeds, without loading bodies', async () => {
+ jest.mocked(fileSystemList).mockResolvedValue({
+ count: 3,
+ results: [
+ entry('folder', 'Research', 'folder'),
+ entry('note1', 'Research/Notes'),
+ { ...entry('alias', 'Copy'), ref: 'note1' },
+ ],
+ })
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ await fs.load()
+ const files = fs.root.children!.get('files')!
+ const folder = files.children!.get('Research')!
+ const note = folder.children!.get('Notes.md')!
+ await expect(folder.remove!()).rejects.toMatchObject({ errno: 39 })
+ expect(fileSystemDestroy).not.toHaveBeenCalled()
+ jest.mocked(fileSystemDestroy).mockRejectedValueOnce({ status: 403 })
+ await expect(note.remove!()).rejects.toMatchObject({ errno: 13 })
+ expect(fs.resolveReference('Research/Notes.md', '/posthog/files')).toBe('note1')
+ jest.mocked(fileSystemDestroy).mockResolvedValue(undefined)
+ await note.remove!()
+ expect(fileSystemDestroy).toHaveBeenLastCalledWith('42', 'note1', { recursive: false }, expect.anything())
+ expect(folder.children!.size).toBe(0)
+ expect(() => fs.resolveReference('Research/Notes.md', '/posthog/files')).toThrow('No project file')
+ expect(fs.resolveReference('/posthog/api/notebook/note1.json', '/')).toBe('note1')
+ await files.children!.get('Copy.md')!.remove!()
+ expect(() => fs.resolveReference('/posthog/api/notebook/note1.json', '/')).toThrow('No project file')
+ jest.mocked(fileSystemDestroy).mockRejectedValueOnce({ status: 409 })
+ await expect(folder.remove!()).rejects.toMatchObject({ errno: 39 })
+ expect(files.children!.get('Research')).toBe(folder)
+ await folder.remove!()
+ expect(files.children!.has('Research')).toBe(false)
+ expect(fileSystemDestroy).toHaveBeenLastCalledWith('42', 'folder', { recursive: false }, expect.anything())
+ expect(notebooksRetrieve).not.toHaveBeenCalled()
+ })
+
+ it('rejects moves of implicit folders without creating records or changing their contents', async () => {
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ await fs.load()
+ const files = fs.root.children!.get('files')!
+ const folder = files.children!.get('Research')!
+ const note = folder.children!.get('Notes.md')!
+
+ await expect(folder.rename!(files, 'Published')).rejects.toMatchObject({ errno: 95 })
+ expect(fileSystemCreate).not.toHaveBeenCalled()
+ expect(apiMutator).not.toHaveBeenCalled()
+ expect(files.children!.get('Research')).toBe(folder)
+ expect(files.children!.has('Published')).toBe(false)
+ expect(folder.children!.get('Notes.md')).toBe(note)
+ expect(note.parent).toBe(folder)
+ })
+
+ it.each(['Notes', 'Notes.md'])(
+ 'persists mkdir and moves of %s, preserves open files, and refuses replacement and cycles',
+ async (storedName) => {
+ jest.mocked(fileSystemList).mockResolvedValue({
+ count: 2,
+ results: [entry('research', 'Research', 'folder'), entry('note1', `Research/${storedName}`)],
+ })
+ jest.mocked(fileSystemCreate).mockImplementation(async (_, body) => entry('created', body.path, 'folder'))
+ jest.mocked(apiMutator).mockResolvedValue({})
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ await fs.load()
+ const server = new NinePServer(fs, jest.fn())
+ const request = async (type: number, body: NinePWriter): Promise<{ type: number; body: NinePReader }> => {
+ const bytes = await new Promise<Uint8Array>((resolve) => server.handle(body.frame(type, 1), resolve))
+ const response = new NinePReader(bytes)
+ response.number(4)
+ const responseType = response.number(1)
+ response.number(2)
+ return { type: responseType, body: response }
+ }
+ const walk = async (from: number, to: number, name: string): Promise<void> => {
+ expect(
+ (await request(110, new NinePWriter().number(from, 4).number(to, 4).number(1, 2).string(name))).type
+ ).toBe(111)
+ }
+ const move = (
+ from: number,
+ name: string,
+ to: number,
+ newName: string
+ ): Promise<{ type: number; body: NinePReader }> =>
+ request(74, new NinePWriter().number(from, 4).string(name).number(to, 4).string(newName))
+ await request(
+ 104,
+ new NinePWriter().number(1, 4).number(0xffffffff, 4).string('root').string('').number(0, 4)
+ )
+ await walk(1, 2, 'files')
+ await walk(2, 3, 'Research')
+ await walk(3, 4, 'Notes.md')
+ const note = fs.root.children!.get('files')!.children!.get('Research')!.children!.get('Notes.md')!
+ const opened = await note.open!()
+ jest.mocked(notebooksRetrieve).mockClear()
+ const mkdir = await request(
+ 72,
+ new NinePWriter().number(2, 4).string('Archive').number(0o755, 4).number(0, 4)
+ )
+ expect(mkdir.type).toBe(73)
+ expect(fileSystemCreate).toHaveBeenCalledWith('42', { path: 'Archive', type: 'folder' }, expect.anything())
+ await walk(2, 5, 'Archive')
+ expect((await move(3, 'Notes.md', 5, 'Renamed.md')).type).toBe(75)
+ expect(apiMutator).toHaveBeenLastCalledWith(
+ '/api/projects/42/file_system/note1/move/',
+ expect.objectContaining({
+ method: 'POST',
+ body: JSON.stringify({
+ new_path: storedName.endsWith('.md') ? 'Archive/Renamed.md' : 'Archive/Renamed',
+ }),
+ })
+ )
+ expect(fs.resolveReference('Archive/Renamed.md', '/posthog/files', 'notebook')).toBe('note1')
+ expect(() => fs.resolveReference('Research/Notes.md', '/posthog/files')).toThrow('No project file')
+ expect(fs.root.children!.get('files')!.children!.get('Archive')!.children!.get('Renamed.md')).toBe(note)
+ const rename = await request(20, new NinePWriter().number(5, 4).number(2, 4).string('Published'))
+ expect(rename.type).toBe(21)
+ expect(apiMutator).toHaveBeenLastCalledWith(
+ '/api/projects/42/file_system/created/move/',
+ expect.objectContaining({
+ body: JSON.stringify({ new_path: 'Published' }),
+ })
+ )
+ expect(fs.resolveReference('Published/Renamed.md', '/posthog/files', 'notebook')).toBe('note1')
+ expect(notebooksRetrieve).not.toHaveBeenCalled()
+ jest.mocked(notebooksPartialUpdate).mockResolvedValue({ ...notebook, version: 8 })
+ await opened.save!(new TextEncoder().encode('Edit after move'))
+ expect(notebooksPartialUpdate).toHaveBeenCalledWith(
+ '42',
+ 'note1',
+ expect.objectContaining({ version: 7 }),
+ expect.anything()
+ )
+ const collision = await move(2, 'Published', 2, 'Research')
+ expect(collision.type).toBe(7)
+ expect(collision.body.number(4)).toBe(17)
+ const cycle = await move(2, 'Published', 5, 'Nested')
+ expect(cycle.type).toBe(7)
+ expect(cycle.body.number(4)).toBe(22)
+ const outside = await move(2, 'Published', 1, 'Outside')
+ expect(outside.type).toBe(7)
+ expect(outside.body.number(4)).toBe(30)
+ expect(apiMutator).toHaveBeenCalledTimes(2)
+ jest.mocked(apiMutator).mockRejectedValue(new Error('Permission denied'))
+ expect((await move(5, 'Renamed.md', 3, 'Denied.md')).type).toBe(7)
+ expect(fs.resolveReference('Published/Renamed.md', '/posthog/files', 'notebook')).toBe('note1')
+ expect(() => fs.resolveReference('Research/Denied.md', '/posthog/files')).toThrow('No project file')
+ }
+ )
+
+ it('loads every page and keeps legacy notebooks and duplicate names accessible', async () => {
+ jest.mocked(fileSystemList)
+ .mockResolvedValueOnce({ count: 3, next: '/next', results: [entry('note1', 'Research/Notes')] })
+ .mockResolvedValueOnce({
+ count: 3,
+ next: null,
+ results: [entry('note2', 'Research/Notes'), entry('legacy', 'Research/Legacy')],
+ })
+ jest.mocked(notebooksRetrieve).mockImplementation(async (_, id) =>
+ id === 'legacy' ? { ...notebook, content: { type: 'doc', content: [{ type: 'paragraph' }] } } : notebook
+ )
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ await fs.load()
+ const directory = fs.root.children!.get('files')!.children!.get('Research')!
+ expect([...directory.children!.keys()].sort()).toEqual(['Legacy.json', 'Notes.md', 'Notes~note2.md'])
+ expect(directory.children!.get('Legacy.json')!.writable).toBe(true)
+ const api = fs.root.children!.get('api')!.children!.get('notebook')!.children!.get('note1.json')!
+ expect(JSON.parse(decoder.decode((await api.open!()).bytes)).version).toBe(7)
+ expect(jest.mocked(fileSystemList).mock.calls[1][1]?.offset).toBe(1)
+ })
+
+ it('does not offer writes on viewer notebooks or expose entries without read access', async () => {
+ jest.mocked(fileSystemList).mockResolvedValue({
+ count: 2,
+ results: [entry('note1', 'Notes'), { ...entry('hidden', 'Hidden'), user_access_level: 'none' }],
+ })
+ jest.mocked(notebooksList).mockResolvedValue({
+ count: 1,
+ results: [{ ...notebookIndex, user_access_level: 'viewer' }],
+ })
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ await fs.load()
+ const files = fs.root.children!.get('files')!
+ expect([...files.children!.keys()]).toEqual(['Notes.md'])
+ expect(files.children!.get('Notes.md')!.writable).toBe(false)
+ expect(fs.root.children!.get('api')!.children!.get('notebook')!.children!.get('note1.json')!.writable).toBe(
+ false
+ )
+ })
+
+ it.each([
+ ['dashboard', 'dashboards', '12'],
+ ['insight', 'insights', 'insightId'],
+ ['feature_flag', 'feature_flags', '13'],
+ ['cohort', 'cohorts', '14'],
+ ['action', 'actions', '15'],
+ ['survey', 'surveys', '01900000-0000-7000-8000-000000000003'],
+ ['experiment', 'experiments', '16'],
+ ])('reads and saves %s JSON through its project-scoped endpoint from both mounts', async (type, route, ref) => {
+ jest.mocked(fileSystemList).mockResolvedValue({ count: 1, results: [entry(ref, 'Object', type)] })
+ const original = {
+ id: ref,
+ name: 'Original',
+ nested: { enabled: false },
+ readonly_field: 'from API',
+ restriction_level: 0,
+ ...(['experiment', 'feature_flag'].includes(type) ? { version: 7 } : {}),
+ }
+ jest.mocked(apiMutator).mockResolvedValue(original)
+ const signal = new AbortController().signal
+ const fs = new PosthogFilesystem('42', signal)
+ await fs.load()
+ expect(apiMutator).not.toHaveBeenCalled()
+ const files = [
+ fs.root.children!.get('files')!.children!.get('Object.json')!,
+ fs.root.children!.get('api')!.children!.get(type)!.children!.get(`${ref}.json`)!,
+ ]
+ for (const file of files) {
+ expect(file.writable).toBe(true)
+ const opened = await file.open!()
+ expect(JSON.parse(decoder.decode(opened.bytes))).toEqual(original)
+ expect(apiMutator).toHaveBeenLastCalledWith(`/api/projects/42/${route}/${ref}/`, { method: 'GET', signal })
+ const callsBeforeSave = jest.mocked(apiMutator).mock.calls.length
+ await opened.save!(opened.bytes)
+ expect(apiMutator).toHaveBeenCalledTimes(callsBeforeSave)
+ const edited = { ...original, id: 'another-id', name: 'Edited', nested: { enabled: true } }
+ await opened.save!(new TextEncoder().encode(JSON.stringify(edited)))
+ expect(apiMutator).toHaveBeenLastCalledWith(`/api/projects/42/${route}/${ref}/`, {
+ method: 'PATCH',
+ signal,
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ id: 'another-id',
+ name: 'Edited',
+ nested: { enabled: true },
+ ...(['experiment', 'feature_flag'].includes(type) ? { version: 7 } : {}),
+ }),
+ })
+ }
+ })
+
+ it('rejects invalid JSON and propagates API failures without retrying a failed update', async () => {
+ jest.mocked(fileSystemList).mockResolvedValue({ count: 1, results: [entry('12', 'Object', 'dashboard')] })
+ jest.mocked(apiMutator).mockResolvedValue({ id: 12, name: 'Original' })
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ await fs.load()
+ const file = await fs.root.children!.get('files')!.children!.get('Object.json')!.open!()
+ jest.mocked(apiMutator).mockClear()
+ for (const invalid of ['{', 'null', '[]', '"text"', '123']) {
+ await expect(file.save!(new TextEncoder().encode(invalid))).rejects.toThrow(/JSON/)
+ }
+ expect(apiMutator).not.toHaveBeenCalled()
+ const error = { status: 400, detail: 'Name cannot be empty.' }
+ jest.mocked(apiMutator).mockRejectedValueOnce(error)
+ await expect(file.save!(new TextEncoder().encode('{"name":""}'))).rejects.toBe(error)
+ expect(apiMutator).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps unsupported objects and viewer JSON read-only', async () => {
+ jest.mocked(fileSystemList).mockResolvedValue({
+ count: 2,
+ results: [
+ entry('unsupported', 'Unknown', 'unknown'),
+ { ...entry('12', 'View only', 'dashboard'), user_access_level: 'viewer' },
+ ],
+ })
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ await fs.load()
+ for (const node of fs.root.children!.get('files')!.children!.values()) {
+ expect(node.writable).toBe(false)
+ }
+ for (const directory of fs.root.children!.get('api')!.children!.values()) {
+ expect([...directory.children!.values()][0].writable).toBe(false)
+ }
+ })
+
+ it.each([
+ ['notebook', 'invalid/id'],
+ ['insight', 'invalid?query'],
+ ['survey', 'invalid-id'],
+ ['dashboard', 'not-a-number'],
+ ['dashboard', '9007199254740993'],
+ ])('keeps %s records with invalid object IDs read-only', async (type, ref) => {
+ jest.mocked(fileSystemList).mockResolvedValue({
+ count: 1,
+ results: [{ ...entry('record', 'Object', type), ref }],
+ })
+ jest.mocked(fileSystemRetrieve).mockResolvedValue({ ...entry('record', 'Object', type), ref })
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ await fs.load()
+ const nodes = [
+ fs.root.children!.get('files')!.children!.get('Object.json')!,
+ fs.root
+ .children!.get('api')!
+ .children!.get(type)!
+ .children!.get(`${terminalFilename(ref)}.json`)!,
+ ]
+ for (const node of nodes) {
+ expect(node.writable).toBe(false)
+ expect((await node.open!()).save).toBeUndefined()
+ }
+ expect(fileSystemRetrieve).toHaveBeenCalledTimes(2)
+ expect(fileSystemRetrieve).toHaveBeenLastCalledWith('42', 'record', expect.anything())
+ expect(apiMutator).not.toHaveBeenCalled()
+ expect(notebooksRetrieve).not.toHaveBeenCalled()
+ })
+
+ it('saves notebook JSON with the opened version and advances it after a successful save', async () => {
+ const session = new AbortController()
+ const read = new AbortController()
+ const fs = new PosthogFilesystem('42', session.signal)
+ await fs.load()
+ const file = await fs.root.children!.get('api')!.children!.get('notebook')!.children!.get('note1.json')!.open!(
+ read.signal
+ )
+ read.abort()
+ expect(jest.mocked(notebooksRetrieve).mock.calls[0][2]?.signal).not.toBe(session.signal)
+ jest.mocked(notebooksPartialUpdate).mockResolvedValue({ ...notebook, version: 8 })
+ await file.save!(file.bytes)
+ expect(notebooksPartialUpdate).not.toHaveBeenCalled()
+ const data = new TextEncoder().encode(JSON.stringify({ ...notebook, title: 'Edited', version: 99 }))
+ await file.save!(data)
+ expect(notebooksPartialUpdate).toHaveBeenLastCalledWith(
+ '42',
+ 'note1',
+ expect.objectContaining({ title: 'Edited', version: 7 }),
+ expect.objectContaining({ signal: session.signal })
+ )
+ await file.save!(data)
+ expect(notebooksPartialUpdate).toHaveBeenLastCalledWith(
+ '42',
+ 'note1',
+ expect.objectContaining({ version: 8 }),
+ expect.objectContaining({ signal: session.signal })
+ )
+ })
+
+ it('keeps notebook search text synchronized when saving JSON content', async () => {
+ const fs = new PosthogFilesystem('42', new AbortController().signal)
+ await fs.load()
+ const file = await fs.root.children!.get('api')!.children!.get('notebook')!.children!.get('note1.json')!.open!()
+ const content = {
+ type: 'doc',
+ content: [{ type: 'ph-markdown-notebook', attrs: { markdown: 'New search text' } }],
+ }
+ await file.save!(new TextEncoder().encode(JSON.stringify({ ...notebook, content })))
+ expect(notebooksPartialUpdate).toHaveBeenLastCalledWith(
+ '42',
+ 'note1',
+ { content, text_content: 'New search text', version: 7 },
+ expect.anything()
+ )
+ })
+
+ it.each([
+ ['..', '%2E%2E'],
+ ['.', '%2E'],
+ ['a/b', 'a%2Fb'],
+ ['%2F', '%252F'],
+ ['hello\nworld', 'hello%0Aworld'],
+ ['csi\u009bm', 'csi%C2%9Bm'],
+ ['osc\u009d0;x', 'osc%C2%9D0;x'],
+ ['pad\u0080', 'pad%C2%80'],
+ ['keeps\u00a0non-control', 'keeps\u00a0non-control'],
+ ])('maps %j to a Unix filename without changing directory structure', (input, expected) => {
+ expect(terminalFilename(input)).toBe(expected)
+ })
+
+ it('keeps long Unicode names addressable within Linux filename limits', () => {
+ const first = terminalFilename('🦔'.repeat(100))
+ const second = terminalFilename('🦔'.repeat(101))
+ expect(new TextEncoder().encode(first).length).toBeLessThan(180)
+ expect(first).not.toBe(second)
+ expect(first).toBe(terminalFilename('🦔'.repeat(100)))
+ expect(first).not.toContain('\uFFFD')
+ })
+})
diff --git a/frontend/src/scenes/terminal/posthogFilesystem.ts b/frontend/src/scenes/terminal/posthogFilesystem.ts
new file mode 100644
index 000000000000..756a819864eb
--- /dev/null
+++ b/frontend/src/scenes/terminal/posthogFilesystem.ts
@@ -0,0 +1,719 @@
+import apiMutator from 'lib/api-orval-mutator'
+
+import {
+ fileSystemCreate,
+ fileSystemDestroy,
+ fileSystemList,
+ fileSystemRetrieve,
+ getFileSystemMoveCreateUrl,
+} from '~/generated/core/api'
+import type { FileSystemApi } from '~/generated/core/api.schemas'
+import { joinPath, splitPath } from '~/layout/panel-layout/ProjectTree/utils'
+
+import { actionsPartialUpdate, actionsRetrieve } from 'products/actions/frontend/generated/api'
+import { cohortsPartialUpdate, cohortsRetrieve } from 'products/cohorts/frontend/generated/api'
+import { dashboardsPartialUpdate, dashboardsRetrieve } from 'products/dashboards/frontend/generated/api'
+import { experimentsPartialUpdate, experimentsRetrieve } from 'products/experiments/frontend/generated/api'
+import { featureFlagsPartialUpdate, featureFlagsRetrieve } from 'products/feature_flags/frontend/generated/api'
+import { notebooksList, notebooksPartialUpdate, notebooksRetrieve } from 'products/notebooks/frontend/generated/api'
+import type { NotebookMinimalApi } from 'products/notebooks/frontend/generated/api.schemas'
+import { insightsPartialUpdate, insightsRetrieve } from 'products/product_analytics/frontend/generated/api'
+import { surveysPartialUpdate, surveysRetrieve } from 'products/surveys/frontend/generated/api'
+
+import {
+ FilesystemError,
+ MAX_TERMINAL_FILE_BYTES,
+ TerminalFile,
+ TerminalFilesystem,
+ TerminalNode,
+} from './terminalFilesystem'
+
+const encoder = new TextEncoder()
+const decoder = new TextDecoder('utf-8', { fatal: true })
+
+export function terminalFilename(name: string): string {
+ // xterm runs C0, DEL and C1 code points as control functions, so a printed name must not contain them.
+ const safe = name.replace(/[%/\x00-\x1f\x7f-\x9f]/g, (character) => encodeURIComponent(character))
+ if (encoder.encode(safe).length > 180) {
+ // Leave room for extensions and collision suffixes within Linux's 255-byte limit.
+ let prefix = ''
+ for (const character of safe) {
+ if (encoder.encode(prefix + character).length > 160) {
+ break
+ }
+ prefix += character
+ }
+ let hash = 0xcbf29ce484222325n
+ for (const byte of encoder.encode(safe)) {
+ hash = BigInt.asUintN(64, (hash ^ BigInt(byte)) * 0x100000001b3n)
+ }
+ return `${prefix}~${hash.toString(16)}`
+ }
+ return safe === '.' || safe === '..' ? safe.replace(/\./g, '%2E') : safe || 'Untitled'
+}
+
+export function markdownNode(
+ content: unknown
+): { attrs: { markdown: string; [key: string]: unknown }; [key: string]: unknown } | null {
+ if (!content || typeof content !== 'object' || !('content' in content) || !Array.isArray(content.content)) {
+ return null
+ }
+ const nodes = content.content
+ if (
+ nodes.length !== 1 ||
+ nodes[0]?.type !== 'ph-markdown-notebook' ||
+ typeof nodes[0]?.attrs?.markdown !== 'string'
+ ) {
+ return null
+ }
+ return nodes[0]
+}
+
+function bytes(text: string): Uint8Array {
+ const result = encoder.encode(text)
+ if (result.length > MAX_TERMINAL_FILE_BYTES) {
+ throw new Error('This file exceeds the terminal file size limit of 4 MiB.')
+ }
+ return result
+}
+
+function jsonFile(value: unknown): TerminalFile {
+ return { bytes: bytes(`${JSON.stringify(value, null, 2)}\n`) }
+}
+
+export const TERMINAL_README = `PostHog terminal
+
+This is a Linux virtual machine running in your browser.
+
+/posthog/files Your project tree. Markdown notebooks have a .md extension.
+/posthog/api JSON representations, grouped by object type and ID.
+/posthog/tools Command descriptions and argument schemas. Run ph tools to discover MCP tools.
+/posthog/recovery Edits that could not be saved. Copy them before leaving this page.
+/root and /tmp Local Linux files. These disappear when you stop Linux or reload PostHog.
+
+Try:
+ mc
+ ls --color=auto /posthog/files
+ find /posthog/files -name '*.md'
+ grep -r 'revenue' /posthog/files
+ cat '/posthog/files/Unfiled/Notebooks/My notebook.md'
+ vi '/posthog/files/Unfiled/Notebooks/My notebook.md'
+ nano '/posthog/files/Unfiled/Notebooks/My notebook.md'
+ tree -C -L 3 /posthog/files
+ ncdu -r /posthog/files
+ jq '.title' /posthog/api/notebook/<short-id>.json
+ ph help
+ ph tools notebook
+ ph notebook-get '/posthog/files/Unfiled/Notebooks/My notebook.md'
+
+Saving an existing .md notebook updates PostHog using your current permissions.
+JSON files for notebooks, dashboards, insights, feature flags, cohorts, actions,
+surveys, and experiments are editable in both mounts when you have edit access.
+Saving sends changed JSON fields to the existing API endpoint with PATCH. The mounted
+path selects the object, even if you edit an ID inside the JSON. API validation
+and read-only fields still apply. Unsupported object types remain read-only.
+Writes commit on fsync or close. Notebook saves use version checks; other objects
+use their API's update behavior. Invalid JSON and API failures fail the save.
+Check the browser's save error banner and /posthog/recovery for failed edits.
+Use mkdir to create project folders and mv to move or rename files and folders
+inside /posthog/files. Keep .md or .json extensions when renaming files.
+Moves preserve object IDs and folder contents. Existing destinations cannot be
+replaced. Folders inferred from file paths cannot be moved; move their files instead.
+Use rm to remove files, rmdir for empty folders, and rm -r for folder trees.
+Removing the last file reference deletes the PostHog object, using your permissions.
+Files open for writing must be closed before removal. Use ph notebook-create to create notebooks.
+Work in /tmp for programs that save by renaming a temporary file,
+then use cat /tmp/edited.md > '/posthog/files/path/to/notebook.md'.
+
+Directories are a snapshot from startup. File contents load from the API on open.
+Listing directories never downloads object contents. Sizes are zero until a file
+is opened, then show its last known size. Startup uses the notebook index to find
+markdown notebooks without fetching their bodies.
+Run ph refresh to discover new or renamed objects. Unsupported object types
+expose their filesystem record as JSON. Legacy rich-text notebooks stay JSON.
+Characters that cannot appear in Unix filenames are percent-encoded. Duplicate
+names receive an ID suffix. Long names get a shortened prefix and stable hash.
+Extensions do not change the names stored in PostHog.
+
+The VM has no network connection and receives no API tokens or session cookies.
+The browser makes authenticated requests through the existing PostHog APIs.
+Files are limited to 4 MiB. Use Ctrl+C to interrupt, Tab to complete, and the
+mouse wheel for scrollback. Run busybox to see the installed Unix utilities.
+jq 1.8.2 is installed for JSON queries and formatting.
+nano 8.4 edits text with syntax highlighting. Ctrl+S saves; Ctrl+X exits.
+mc opens Midnight Commander. Tab switches panels; F3 views, F4 edits, F10 quits.
+Use Escape then a digit if your browser or keyboard captures function keys.
+mcview, mcedit, and mcdiff also run directly from the shell.
+tree lists folders and files. ncdu -r browses disk usage without allowing deletion.
+Project file sizes stay zero until opened; ncdu does not download their contents.
+Bundled tool licenses and source links are in /opt/posthog-tools/licenses.
+ph runs project commands and tools from connected MCP servers with your permissions.
+Run ph help <command> for its arguments. Notebook commands accept IDs or file paths.
+Use --json @file.json or --json - for arguments from a file or stdin.
+Commands such as ph notebook-delete change real data. Errors exit nonzero.
+Selecting text copies it automatically. You can also copy with Cmd+C (macOS) or
+Ctrl+Shift+C (Linux/Windows).
+Paste with Cmd+V or Ctrl+Shift+V, or use the Copy selection and Paste buttons.
+
+Browser agents can use window.posthogTerminal.write('ls\\n') and
+window.posthogTerminal.read() to interact with this same terminal.
+`
+
+export class PosthogFilesystem extends TerminalFilesystem {
+ private readonly files = this.directory('files', this.root)
+ private readonly api = this.directory('api', this.root)
+ private readonly references = new Map<string, FileSystemApi>()
+ private readonly projectNodes = new Map<
+ TerminalNode,
+ { parts: string[]; entry?: FileSystemApi; extension?: string }
+ >()
+
+ resolveReference(value: string, cwd: string, type?: string): string {
+ const parts: string[] = []
+ for (const part of (value.startsWith('/') ? value : `${cwd}/${value}`).split('/')) {
+ if (part === '..') {
+ parts.pop()
+ } else if (part && part !== '.') {
+ parts.push(part)
+ }
+ }
+ const entry = this.references.get(`/${parts.join('/')}`)
+ if (entry) {
+ if (type && entry.type !== type) {
+ throw new Error(`Expected a ${type} file, but this is a ${entry.type} file.`)
+ }
+ if (!entry.ref) {
+ throw new Error('This file has no object ID. Pass the tool an ID directly.')
+ }
+ return entry.ref
+ }
+ if (value.includes('/') || /\.(md|json)$/.test(value)) {
+ throw new Error(`No project file at ${value}. Run ph refresh if the file was just created.`)
+ }
+ return value
+ }
+
+ constructor(
+ private projectId: string,
+ private signal: AbortSignal
+ ) {
+ super()
+ this.text('README.txt', this.root, TERMINAL_README)
+ this.registerDirectory(this.files, [])
+ }
+
+ private registerDirectory(node: TerminalNode, parts: string[], entry?: FileSystemApi): void {
+ this.projectNodes.set(node, { parts, entry })
+ node.mkdir = async (name) => {
+ const directory = this.projectNodes.get(node)
+ if (!directory) {
+ throw new FilesystemError(116)
+ }
+ const parts = [...directory.parts, this.storedName(name)]
+ const entry = await fileSystemCreate(
+ this.projectId,
+ { path: joinPath(parts), type: 'folder' },
+ { signal: this.signal }
+ )
+ const child = this.directory(name, node)
+ this.registerDirectory(child, parts, entry)
+ return child
+ }
+ if (node !== this.files) {
+ node.rename = (parent, name) => this.move(node, parent, name)
+ node.remove = () => this.remove(node)
+ }
+ }
+
+ private storedName(name: string): string {
+ try {
+ const decoded = decodeURIComponent(name)
+ return terminalFilename(decoded) === name ? decoded : name
+ } catch {
+ return name
+ }
+ }
+
+ private mountedPath(node: TerminalNode): string {
+ const parts = [node.name]
+ for (let parent = node.parent; parent && parent !== this.root; parent = parent.parent) {
+ parts.unshift(parent.name)
+ }
+ return `/posthog/${parts.join('/')}`
+ }
+
+ private async remove(node: TerminalNode): Promise<void> {
+ const source = this.projectNodes.get(node)
+ if (!source || node.removed) {
+ throw new FilesystemError(116)
+ }
+ if (node.children?.size) {
+ throw new FilesystemError(39)
+ }
+ if (source.entry) {
+ try {
+ await fileSystemDestroy(this.projectId, source.entry.id, { recursive: false }, { signal: this.signal })
+ } catch (error) {
+ const status = error && typeof error === 'object' && 'status' in error ? error.status : undefined
+ throw new FilesystemError(status === 409 ? 39 : status === 403 ? 13 : status === 404 ? 2 : 5)
+ }
+ }
+ this.references.delete(this.mountedPath(node))
+ this.projectNodes.delete(node)
+ node.parent!.children!.delete(node.name)
+ node.removed = true
+ const entry = source.entry
+ if (
+ entry &&
+ !node.children &&
+ ![...this.projectNodes.values()].some(
+ ({ entry: other }) => other && other.type === entry.type && other.ref === entry.ref
+ )
+ ) {
+ const type = this.api.children!.get(terminalFilename(entry.type ?? 'unknown'))
+ const name = `${terminalFilename(entry.ref ?? entry.id)}.json`
+ const apiNode = type?.children?.get(name)
+ if (apiNode) {
+ apiNode.removed = true
+ this.references.delete(this.mountedPath(apiNode))
+ type!.children!.delete(name)
+ }
+ }
+ }
+
+ private async move(node: TerminalNode, parent: TerminalNode, name: string): Promise<void> {
+ const source = this.projectNodes.get(node)
+ const destination = this.projectNodes.get(parent)
+ if (!source || !destination) {
+ throw new FilesystemError(116)
+ }
+ if (source.extension && !name.endsWith(source.extension)) {
+ throw new FilesystemError(22)
+ }
+ const originalName = source.parts[source.parts.length - 1]
+ const projectedExtension = source.extension && !originalName.endsWith(source.extension) ? source.extension : ''
+ const basename =
+ name === node.name
+ ? originalName
+ : this.storedName(projectedExtension ? name.slice(0, -projectedExtension.length) : name)
+ if (!basename) {
+ throw new FilesystemError(22)
+ }
+ const parts = [...destination.parts, basename]
+ const entry = source.entry
+ if (!entry) {
+ // Creating an implicit folder before moving it cannot be rolled back safely when it has children.
+ throw new FilesystemError(95)
+ }
+ // The generated move body describes a filesystem row, but this action requires new_path.
+ await apiMutator<FileSystemApi>(getFileSystemMoveCreateUrl(this.projectId, entry.id), {
+ method: 'POST',
+ body: JSON.stringify({ new_path: joinPath(parts) }),
+ signal: this.signal,
+ })
+ const descendants = [...this.projectNodes].filter(([candidate]) => {
+ for (let ancestor: TerminalNode | undefined = candidate; ancestor; ancestor = ancestor.parent) {
+ if (ancestor === node) {
+ return true
+ }
+ }
+ return false
+ })
+ for (const [child] of descendants) {
+ this.references.delete(this.mountedPath(child))
+ }
+ const oldDepth = source.parts.length
+ node.parent!.children!.delete(node.name)
+ node.parent = parent
+ node.name = name
+ parent.children!.set(name, node)
+ for (const [child, metadata] of descendants) {
+ metadata.parts = [...parts, ...metadata.parts.slice(oldDepth)]
+ if (metadata.entry) {
+ metadata.entry.path = joinPath(metadata.parts)
+ this.references.set(this.mountedPath(child), metadata.entry)
+ }
+ }
+ }
+
+ private validReference(entry: FileSystemApi): boolean {
+ const ref = entry.ref
+ if (!ref) {
+ return false
+ }
+ switch (entry.type) {
+ case 'notebook':
+ return /^[\p{L}\p{N}]{1,12}(?![\s\S])/u.test(ref)
+ case 'insight':
+ return /^(?:[A-Za-z0-9]{1,12}|[0-9]+)(?![\s\S])/.test(ref)
+ case 'survey':
+ return /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}(?![\s\S])/i.test(ref)
+ case 'dashboard':
+ case 'feature_flag':
+ case 'cohort':
+ case 'action':
+ case 'experiment':
+ return /^[1-9][0-9]*(?![\s\S])/.test(ref) && Number.isSafeInteger(Number(ref))
+ default:
+ return false
+ }
+ }
+
+ private objectApi(
+ entry: FileSystemApi,
+ signal?: AbortSignal
+ ):
+ | {
+ read: () => Promise<unknown>
+ update: (data: Record<string, unknown>) => Promise<unknown>
+ }
+ | undefined {
+ const options = { signal: this.signal }
+ const readOptions = { signal: signal ?? this.signal }
+ const ref = entry.ref
+ if (!ref || !this.validReference(entry)) {
+ return undefined
+ }
+ switch (entry.type) {
+ case 'notebook':
+ return {
+ read: () => notebooksRetrieve(this.projectId, ref, readOptions),
+ update: (data) => notebooksPartialUpdate(this.projectId, ref, data, options),
+ }
+ case 'dashboard':
+ return {
+ read: () => dashboardsRetrieve(this.projectId, Number(ref), undefined, readOptions),
+ update: (data) => dashboardsPartialUpdate(this.projectId, Number(ref), data, undefined, options),
+ }
+ case 'insight':
+ return {
+ read: () => insightsRetrieve(this.projectId, ref, undefined, readOptions),
+ update: (data) => insightsPartialUpdate(this.projectId, ref, data, undefined, options),
+ }
+ case 'feature_flag':
+ return {
+ read: () => featureFlagsRetrieve(this.projectId, Number(ref), readOptions),
+ update: (data) => featureFlagsPartialUpdate(this.projectId, Number(ref), data, options),
+ }
+ case 'cohort':
+ return {
+ read: () => cohortsRetrieve(this.projectId, Number(ref), readOptions),
+ update: (data) => cohortsPartialUpdate(this.projectId, Number(ref), data, options),
+ }
+ case 'action':
+ return {
+ read: () => actionsRetrieve(this.projectId, Number(ref), undefined, readOptions),
+ update: (data) => actionsPartialUpdate(this.projectId, Number(ref), data, undefined, options),
+ }
+ case 'survey':
+ return {
+ read: () => surveysRetrieve(this.projectId, ref, readOptions),
+ update: (data) => surveysPartialUpdate(this.projectId, ref, data, options),
+ }
+ case 'experiment':
+ return {
+ read: () => experimentsRetrieve(this.projectId, Number(ref), readOptions),
+ update: (data) => experimentsPartialUpdate(this.projectId, Number(ref), data, options),
+ }
+ default:
+ return undefined
+ }
+ }
+
+ private async json(entry: FileSystemApi, writable: boolean, signal?: AbortSignal): Promise<TerminalFile> {
+ const endpoint = this.objectApi(entry, signal)
+ let value = endpoint
+ ? await endpoint.read()
+ : await fileSystemRetrieve(this.projectId, entry.id, {
+ signal: signal ?? this.signal,
+ })
+ return {
+ ...jsonFile(value),
+ save:
+ writable && endpoint
+ ? async (data) => {
+ let update: unknown
+ try {
+ update = JSON.parse(decoder.decode(data))
+ } catch {
+ throw new Error('Invalid JSON. Fix the JSON syntax before saving.')
+ }
+ if (!update || typeof update !== 'object' || Array.isArray(update)) {
+ throw new Error('The JSON must contain an object with the fields to update.')
+ }
+ const original = value && typeof value === 'object' ? value : {}
+ const payload = Object.fromEntries(
+ Object.entries(update).filter(
+ ([key, value]) =>
+ JSON.stringify(value) !==
+ JSON.stringify((original as Record<string, unknown>)[key])
+ )
+ )
+ if (!Object.keys(payload).length) {
+ return
+ }
+ if (entry.type === 'notebook' && 'content' in payload && !('text_content' in payload)) {
+ const node = markdownNode(payload.content)
+ if (!node) {
+ throw new Error('Include text_content when changing non-markdown notebook content.')
+ }
+ payload.text_content = node.attrs.markdown
+ }
+ // These APIs skip their conflict check when `version` is absent, and the
+ // filter above drops it because it matches what the read returned. A cohort
+ // stays out: its version counts calculations rather than writes.
+ if (
+ ['notebook', 'experiment', 'feature_flag'].includes(entry.type ?? '') &&
+ value &&
+ typeof value === 'object' &&
+ 'version' in value
+ ) {
+ payload.version = value.version
+ }
+ value = await endpoint.update(payload)
+ }
+ : undefined,
+ }
+ }
+
+ private async notebook(entry: FileSystemApi, signal?: AbortSignal): Promise<TerminalFile> {
+ if (!this.validReference(entry)) {
+ throw new FilesystemError(22)
+ }
+ let notebook = await notebooksRetrieve(this.projectId, entry.ref!, {
+ signal: signal ?? this.signal,
+ })
+ const node = markdownNode(notebook.content)
+ if (!node) {
+ throw new Error('Notebook format changed. Restart the terminal to refresh the filename.')
+ }
+ let saved = node.attrs.markdown
+ return {
+ bytes: bytes(saved),
+ save: async (data) => {
+ const markdown = decoder.decode(data)
+ // Editors rewrite the whole file on save, so a save that changed nothing would
+ // otherwise bump the version and reattribute the last edit to the person who
+ // only looked at the notebook.
+ if (markdown === saved) {
+ return
+ }
+ notebook = await notebooksPartialUpdate(
+ this.projectId,
+ entry.ref!,
+ {
+ content: {
+ ...(notebook.content as object),
+ content: [{ ...node, attrs: { ...node.attrs, markdown } }],
+ },
+ text_content: markdown,
+ version: notebook.version,
+ },
+ { signal: this.signal }
+ )
+ saved = markdown
+ },
+ }
+ }
+
+ async load(): Promise<void> {
+ const entries: FileSystemApi[] = []
+ let offset = 0
+ while (true) {
+ const page = await fileSystemList(this.projectId, { limit: 500, offset }, { signal: this.signal })
+ entries.push(...page.results)
+ if (!page.next) {
+ break
+ }
+ if (!page.results.length || entries.length > 50_000) {
+ throw new Error('This project tree is too large for the terminal experiment.')
+ }
+ offset += page.results.length
+ }
+ entries.sort((a, b) => a.path.localeCompare(b.path) || a.id.localeCompare(b.id))
+ const markdownNotebooks = new Map<string, NotebookMinimalApi>()
+ if (entries.some((entry) => entry.type === 'notebook')) {
+ let offset = 0
+ while (true) {
+ const page = await notebooksList(
+ this.projectId,
+ { contains: 'markdown-notebook', limit: 500, offset },
+ { signal: this.signal }
+ )
+ for (const notebook of page.results) {
+ markdownNotebooks.set(notebook.short_id, notebook)
+ }
+ if (!page.next) {
+ break
+ }
+ if (!page.results.length || offset > 50_000) {
+ throw new Error('This notebook index is too large for the terminal experiment.')
+ }
+ offset += page.results.length
+ }
+ }
+ const previousNodes = this.mountedNodes()
+ const directories = new Map(
+ [...previousNodes].filter((node) => node.children).map((node) => [this.mountedPath(node), node])
+ )
+ const files = new Map(
+ [...this.projectNodes]
+ .filter(([, metadata]) => metadata.entry && metadata.extension)
+ .map(([node, metadata]) => [this.fileIdentity(metadata.entry!, metadata.extension!), node])
+ )
+ const apiFiles = new Map(
+ [...previousNodes]
+ .filter((node) => !node.children && node.parent?.parent === this.api)
+ .map((node) => [this.mountedPath(node), node])
+ )
+ for (const node of previousNodes) {
+ node.children?.clear()
+ }
+ this.references.clear()
+ this.projectNodes.clear()
+ this.registerDirectory(this.files, [])
+ for (const entry of entries.filter((item) => item.type === 'folder' && item.user_access_level !== 'none')) {
+ const parts = splitPath(entry.path)
+ this.registerDirectory(this.parent(parts, this.files, directories), parts, entry)
+ }
+ for (const entry of entries) {
+ if (entry.type === 'folder' || entry.user_access_level === 'none') {
+ continue
+ }
+ const notebook = entry.type === 'notebook' ? markdownNotebooks.get(entry.ref ?? '') : undefined
+ const parts = splitPath(entry.path)
+ const basename = terminalFilename(parts.pop() ?? 'Untitled')
+ const parent = this.parent(parts, this.files, directories)
+ const extension = notebook ? '.md' : '.json'
+ let name = basename.endsWith(extension) ? basename : `${basename}${extension}`
+ if (parent.children!.has(name)) {
+ name = `${basename}~${entry.id}${extension}`
+ }
+ let duplicate = 1
+ while (parent.children!.has(name)) {
+ name = `${basename}~${entry.id}-${duplicate++}${extension}`
+ }
+ const access = notebook?.user_access_level ?? entry.user_access_level
+ const writable =
+ !!this.objectApi(entry) &&
+ entry.user_access_level !== 'viewer' &&
+ (access === null || ['editor', 'manager'].includes(access ?? ''))
+ const file = this.mountFile(
+ name,
+ parent,
+ notebook ? (signal) => this.notebook(entry, signal) : (signal) => this.json(entry, writable, signal),
+ writable,
+ files.get(this.fileIdentity(entry, extension))
+ )
+ file.writeKey = JSON.stringify([entry.type, entry.ref ?? entry.id])
+ this.projectNodes.set(file, { parts: splitPath(entry.path), entry, extension })
+ file.rename = (parent, name) => this.move(file, parent, name)
+ file.remove = () => this.remove(file)
+ this.references.set(`/posthog/files/${[...parts.map(terminalFilename), name].join('/')}`, entry)
+ const type = this.mountDirectory(terminalFilename(entry.type ?? 'unknown'), this.api, directories)
+ const apiName = `${terminalFilename(entry.ref ?? entry.id)}.json`
+ if (!type.children!.has(apiName)) {
+ const apiFile = this.mountFile(
+ apiName,
+ type,
+ (signal) => this.json(entry, writable, signal),
+ writable,
+ apiFiles.get(`${this.mountedPath(type)}/${apiName}`)
+ )
+ apiFile.writeKey = file.writeKey
+ this.references.set(`/posthog/api/${type.name}/${apiName}`, entry)
+ }
+ }
+ const currentNodes = this.mountedNodes()
+ for (const node of previousNodes) {
+ if (!currentNodes.has(node)) {
+ node.removed = true
+ }
+ }
+ }
+
+ private fileIdentity(entry: FileSystemApi, extension: string): string {
+ return JSON.stringify([entry.id, entry.type, entry.ref, extension])
+ }
+
+ private mountedNodes(): Set<TerminalNode> {
+ const nodes = new Set<TerminalNode>([this.files, this.api])
+ for (const node of nodes) {
+ for (const child of node.children?.values() ?? []) {
+ nodes.add(child)
+ }
+ }
+ return nodes
+ }
+
+ private mountDirectory(name: string, parent: TerminalNode, directories: Map<string, TerminalNode>): TerminalNode {
+ const node = directories.get(`${this.mountedPath(parent)}/${name}`) ?? this.directory(name, parent)
+ parent.children!.set(name, node)
+ return node
+ }
+
+ private async readFile(
+ open: (signal?: AbortSignal) => Promise<TerminalFile>,
+ signal?: AbortSignal
+ ): Promise<TerminalFile> {
+ if (!signal) {
+ return open(this.signal)
+ }
+ const controller = new AbortController()
+ const abort = (): void => controller.abort()
+ this.signal.addEventListener('abort', abort, { once: true })
+ signal.addEventListener('abort', abort, { once: true })
+ try {
+ if (this.signal.aborted || signal.aborted) {
+ controller.abort()
+ }
+ return await open(controller.signal)
+ } finally {
+ this.signal.removeEventListener('abort', abort)
+ signal.removeEventListener('abort', abort)
+ }
+ }
+
+ private mountFile(
+ name: string,
+ parent: TerminalNode,
+ open: (signal?: AbortSignal) => Promise<TerminalFile>,
+ writable: boolean,
+ existing?: TerminalNode
+ ): TerminalNode {
+ const node = existing ?? this.file(name, parent, open, writable)
+ node.name = name
+ node.parent = parent
+ node.writable = writable
+ node.open = async (signal) => {
+ if (node.removed) {
+ throw new FilesystemError(116)
+ }
+ const file = await this.readFile(open, signal)
+ const save = file.save
+ return {
+ ...file,
+ save: save
+ ? async (bytes) => {
+ if (node.removed) {
+ throw new FilesystemError(116)
+ }
+ await save(bytes)
+ }
+ : undefined,
+ }
+ }
+ parent.children!.set(name, node)
+ return node
+ }
+
+ private parent(parts: string[], root: TerminalNode, directories: Map<string, TerminalNode>): TerminalNode {
+ return parts.reduce((parent, part, index) => {
+ const node = this.mountDirectory(terminalFilename(part), parent, directories)
+ if (!this.projectNodes.has(node)) {
+ this.registerDirectory(node, parts.slice(0, index + 1))
+ }
+ return node
+ }, root)
+ }
+}
diff --git a/frontend/src/scenes/terminal/terminalCommands.ts b/frontend/src/scenes/terminal/terminalCommands.ts
new file mode 100644
index 000000000000..5ffb63aec98c
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalCommands.ts
@@ -0,0 +1,93 @@
+import { MAX_TERMINAL_FILE_BYTES, TerminalFilesystem } from './terminalFilesystem'
+
+export const PH_SCRIPT = String.raw`#!/bin/sh
+set -eu
+set -o pipefail
+temporary=$(mktemp -d)
+trap 'rm -rf "$temporary"' EXIT
+trap 'exit 130' HUP INT TERM
+previous=''
+for argument in "$@"; do
+ original="$argument"
+ { case "$argument" in
+ @*) cat -- "$(printf '%s' "$argument" | cut -c2-)" ;;
+ -)
+ if [ "$previous" = '--json' ]; then
+ cat
+ else
+ printf '%s' "$argument"
+ fi
+ ;;
+ *) printf '%s' "$argument" ;;
+ esac; } | base64 | tr -d '\n'
+ previous="$original"
+ printf '\n'
+done > "$temporary/args"
+jq -Rs --arg cwd "$PWD" '{argv: (split("\n")[:-1] | map(@base64d)), cwd: $cwd}' < "$temporary/args" > "$temporary/request"
+exec 9>/tmp/posthog-ph.lock
+flock -x 9
+cat "$temporary/request" > /posthog/.ph/request
+response=$(cat /posthog/.ph/response)
+flock -u 9
+if printf '%s' "$response" | jq -e '.ok' >/dev/null; then
+ printf '%s' "$response" | jq -r '.result'
+else
+ printf '%s' "$response" | jq -r '.error' >&2
+ exit 1
+fi
+`
+
+export class TerminalCommands {
+ constructor(filesystem: TerminalFilesystem, execute: (argv: string[], cwd: string) => Promise<unknown>) {
+ const encoder = new TextEncoder()
+ const decoder = new TextDecoder('utf-8', { fatal: true })
+ const envelope = (value: object): Uint8Array => encoder.encode(JSON.stringify(value))
+ let response = envelope({ ok: false, error: 'Run a ph command first.' })
+ const directory = filesystem.directory('.ph', filesystem.root)
+ const responseNode = filesystem.file('response', directory, async () => ({ bytes: response }))
+ filesystem.file(
+ 'request',
+ directory,
+ async () => ({
+ bytes: new Uint8Array(),
+ save: async (bytes) => {
+ try {
+ const request = JSON.parse(decoder.decode(bytes))
+ if (
+ !request ||
+ !Array.isArray(request.argv) ||
+ request.argv.length > 1000 ||
+ !request.argv.every((value: unknown) => typeof value === 'string') ||
+ typeof request.cwd !== 'string'
+ ) {
+ throw new Error('Invalid command request. Run ph help for usage.')
+ }
+ const result = await execute(request.argv, request.cwd)
+ const encoded = envelope({ ok: true, result: result ?? null })
+ if (encoded.length > MAX_TERMINAL_FILE_BYTES) {
+ throw new Error('The result exceeds 4 MiB. Reduce the limit or narrow the query.')
+ }
+ response = encoded
+ } catch (error) {
+ // A failed tool can put its whole payload in the message, and the guest reads
+ // this file into a shell variable inside a 128 MiB virtual machine.
+ const encoded = envelope({
+ ok: false,
+ error: error instanceof Error ? error.message : 'The command failed. Try ph help.',
+ })
+ response =
+ encoded.length > MAX_TERMINAL_FILE_BYTES
+ ? envelope({
+ ok: false,
+ error: 'The command failed, and its error exceeds 4 MiB. Check the tool that returned it.',
+ })
+ : encoded
+ }
+ responseNode.size = response.length
+ },
+ }),
+ true
+ )
+ filesystem.text('ph', filesystem.directory('bin', filesystem.root), PH_SCRIPT)
+ }
+}
diff --git a/frontend/src/scenes/terminal/terminalDockLogic.ts b/frontend/src/scenes/terminal/terminalDockLogic.ts
new file mode 100644
index 000000000000..5630251ede04
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalDockLogic.ts
@@ -0,0 +1,100 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { router } from 'kea-router'
+
+import { commandLogic } from 'lib/components/Command/commandLogic'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+
+import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface terminalDockLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ dockOpen: boolean
+ hasOpened: boolean
+ terminalEnabled: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface terminalDockLogicActions {
+ focusTerminal: () => {
+ value: true
+ }
+ setDockOpen: (open: boolean) => {
+ open: boolean
+ }
+ toggleTerminal: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface terminalDockLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ terminalEnabled: (featureFlags: FeatureFlagsSet) => boolean
+ }
+}
+
+export type terminalDockLogicType = MakeLogicType<
+ terminalDockLogicValues,
+ terminalDockLogicActions,
+ Record<string, any>,
+ terminalDockLogicMeta
+>
+
+export const terminalDockLogic = kea<terminalDockLogicType>([
+ path(['scenes', 'terminal', 'terminalDockLogic']),
+ connect({ values: [featureFlagLogic, ['featureFlags']] }),
+ actions({
+ toggleTerminal: true,
+ focusTerminal: true,
+ setDockOpen: (open: boolean) => ({ open }),
+ }),
+ reducers({
+ dockOpen: [false, { setDockOpen: (_, { open }) => open }],
+ hasOpened: [false, { setDockOpen: (state, { open }) => state || open }],
+ }),
+ selectors({
+ terminalEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.POSTHOG_TERMINAL],
+ ],
+ }),
+ listeners(({ actions, values, cache }) => ({
+ toggleTerminal: () => {
+ if (!values.terminalEnabled) {
+ return
+ }
+ if (removeProjectIdIfPresent(router.values.location.pathname) === '/terminal') {
+ actions.focusTerminal()
+ } else {
+ actions.setDockOpen(!values.dockOpen)
+ }
+ },
+ setDockOpen: ({ open }) => {
+ if (open) {
+ cache.previousFocus = document.activeElement?.closest('[role="dialog"]')
+ ? cache.commandFocus
+ : document.activeElement
+ } else {
+ if (cache.previousFocus?.isConnected) {
+ cache.previousFocus.focus()
+ }
+ }
+ },
+ [commandLogic.actionTypes.openCommand]: () => {
+ cache.commandFocus = document.activeElement
+ },
+ [commandLogic.actionTypes.toggleCommand]: () => {
+ if (commandLogic.values.isCommandOpen) {
+ cache.commandFocus = document.activeElement
+ }
+ },
+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {
+ if (!values.terminalEnabled && values.dockOpen) {
+ actions.setDockOpen(false)
+ }
+ },
+ })),
+])
diff --git a/frontend/src/scenes/terminal/terminalFilesystem.ts b/frontend/src/scenes/terminal/terminalFilesystem.ts
new file mode 100644
index 000000000000..15058914df12
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalFilesystem.ts
@@ -0,0 +1,68 @@
+export interface TerminalFile {
+ bytes: Uint8Array
+ save?: (bytes: Uint8Array) => Promise<void>
+}
+
+export interface TerminalNode {
+ id: number
+ name: string
+ parent?: TerminalNode
+ children?: Map<string, TerminalNode>
+ open?: (signal?: AbortSignal) => Promise<TerminalFile>
+ size: number
+ writable: boolean
+ writeKey?: string
+ mkdir?: (name: string) => Promise<TerminalNode>
+ rename?: (parent: TerminalNode, name: string) => Promise<void>
+ remove?: () => Promise<void>
+ removed?: boolean
+}
+
+export class FilesystemError extends Error {
+ constructor(readonly errno: number) {
+ super(`Filesystem error ${errno}`)
+ }
+}
+
+export const MAX_TERMINAL_FILE_BYTES = 4 * 1024 * 1024
+
+export class TerminalFilesystem {
+ private nextId = 1
+ readonly root: TerminalNode = this.directory('')
+ readonly recovery = this.directory('recovery', this.root)
+
+ directory(name: string, parent?: TerminalNode): TerminalNode {
+ const existing = parent?.children?.get(name)
+ if (existing?.children) {
+ return existing
+ }
+ const node: TerminalNode = { id: this.nextId++, name, parent, children: new Map(), size: 0, writable: false }
+ parent?.children?.set(name, node)
+ return node
+ }
+
+ file(
+ name: string,
+ parent: TerminalNode,
+ open: (signal?: AbortSignal) => Promise<TerminalFile>,
+ writable = false
+ ): TerminalNode {
+ const node: TerminalNode = { id: this.nextId++, name, parent, open, size: 0, writable }
+ parent.children?.set(name, node)
+ return node
+ }
+
+ text(name: string, parent: TerminalNode, text: string): TerminalNode {
+ const bytes = new TextEncoder().encode(text)
+ const node = this.file(name, parent, async () => ({ bytes }))
+ node.size = bytes.length
+ return node
+ }
+
+ recover(node: TerminalNode, bytes: Uint8Array): string {
+ const name = `${node.id}-${this.nextId}-${node.name}`
+ const copy = bytes.slice()
+ this.file(name, this.recovery, async () => ({ bytes: copy })).size = copy.length
+ return `/posthog/recovery/${name}`
+ }
+}
diff --git a/frontend/src/scenes/terminal/terminalLogic.test.ts b/frontend/src/scenes/terminal/terminalLogic.test.ts
new file mode 100644
index 000000000000..9f4dbafa432d
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalLogic.test.ts
@@ -0,0 +1,97 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { waitFor } from '@testing-library/react'
+
+import { commandLogic } from 'lib/components/Command/commandLogic'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import { terminalDockLogic } from './terminalDockLogic'
+import { terminalLogic } from './terminalLogic'
+import { TerminalRuntime } from './terminalRuntime'
+
+jest.mock('./terminalRuntime', () => ({
+ TerminalRuntime: jest.fn().mockImplementation(() => ({
+ start: jest.fn(async (_server, _signal, ready) => ready()),
+ dispose: jest.fn(),
+ resize: jest.fn(),
+ syncClock: jest.fn(),
+ read: jest.fn(() => ''),
+ })),
+}))
+jest.mock('./TerminalSession', () => ({
+ TerminalSession: jest.fn().mockImplementation(() => ({
+ attach: jest.fn(),
+ detach: jest.fn(),
+ dispose: jest.fn(),
+ view: { clear: jest.fn(), write: jest.fn(), cols: 80, rows: 24 },
+ })),
+}))
+jest.mock('./posthogFilesystem', () => ({
+ PosthogFilesystem: jest.fn().mockImplementation(() => ({ load: jest.fn(async () => {}) })),
+}))
+jest.mock('./posthogCommands', () => ({ PosthogCommands: jest.fn() }))
+
+describe('terminal lifecycle', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: true })
+ terminalLogic.mount()
+ })
+
+ it('does not boot without the flag and stops an active session on revocation', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: false })
+ terminalLogic.actions.attach(document.createElement('div'))
+ expect(TerminalRuntime).not.toHaveBeenCalled()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: true })
+ terminalLogic.actions.start()
+ await waitFor(() => expect(terminalLogic.values.status).toBe('ready'))
+ const runtime = jest.mocked(TerminalRuntime).mock.results[0].value
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.POSTHOG_TERMINAL]: false })
+ expect(runtime.dispose).toHaveBeenCalledTimes(1)
+ expect(window.posthogTerminal).toBeUndefined()
+ expect(terminalLogic.values.status).toBe('idle')
+ })
+
+ it('preserves Stop across reattachment and project changes', async () => {
+ terminalLogic.actions.attach(document.createElement('div'))
+ await waitFor(() => expect(terminalLogic.values.status).toBe('ready'))
+ terminalLogic.actions.stop()
+ terminalLogic.actions.attach(document.createElement('div'))
+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, id: MOCK_DEFAULT_TEAM.id + 1 })
+ expect(TerminalRuntime).toHaveBeenCalledTimes(1)
+ expect(terminalLogic.values.runRequested).toBe(false)
+ })
+
+ it('retries a requested start when the project arrives', async () => {
+ teamLogic.actions.loadCurrentTeamSuccess(null)
+ terminalLogic.actions.attach(document.createElement('div'))
+ expect(TerminalRuntime).not.toHaveBeenCalled()
+ teamLogic.actions.loadCurrentTeamSuccess(MOCK_DEFAULT_TEAM)
+ await waitFor(() => expect(terminalLogic.values.status).toBe('ready'))
+ expect(TerminalRuntime).toHaveBeenCalledTimes(1)
+ })
+
+ it('restores the command menu opener after the dialog element disappears', () => {
+ commandLogic.mount()
+ const opener = document.createElement('button')
+ const dialog = document.createElement('div')
+ dialog.setAttribute('role', 'dialog')
+ const result = document.createElement('button')
+ dialog.appendChild(result)
+ document.body.append(opener, dialog)
+ opener.focus()
+ commandLogic.actions.openCommand('keyboard-shortcut')
+ result.focus()
+ terminalDockLogic.actions.setDockOpen(true)
+ dialog.remove()
+ terminalDockLogic.actions.setDockOpen(false)
+ expect(document.activeElement).toBe(opener)
+ opener.remove()
+ })
+})
diff --git a/frontend/src/scenes/terminal/terminalLogic.ts b/frontend/src/scenes/terminal/terminalLogic.ts
new file mode 100644
index 000000000000..2da3b7614e86
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalLogic.ts
@@ -0,0 +1,285 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
+
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { NinePServer } from './ninepServer'
+import { PosthogCommands } from './posthogCommands'
+import { PosthogFilesystem } from './posthogFilesystem'
+import { terminalDockLogic } from './terminalDockLogic'
+import { TerminalRuntime } from './terminalRuntime'
+import { TerminalSession } from './TerminalSession'
+
+export interface TerminalAgent {
+ write: (data: string) => void
+ read: () => string
+}
+
+declare global {
+ interface Window {
+ posthogTerminal?: TerminalAgent
+ }
+}
+
+export type TerminalStatus = 'idle' | 'loading' | 'booting' | 'ready' | 'error'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface terminalLogicValues {
+ currentTeamId: number | null // teamLogic
+ terminalEnabled: boolean // terminalDockLogic
+ clipboardError: string | null
+ error: string | null
+ hasSelection: boolean
+ hasStarted: boolean
+ pasting: boolean
+ runRequested: boolean
+ saveError: string | null
+ status: TerminalStatus
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface terminalLogicActions {
+ focusTerminal: () => {
+ value: true
+ } // terminalDockLogic
+ attach: (container: HTMLElement) => {
+ container: HTMLElement
+ }
+ copy: () => {
+ value: true
+ }
+ detach: (container: HTMLElement) => {
+ container: HTMLElement
+ }
+ focus: () => {
+ value: true
+ }
+ insertCommand: (command: string) => {
+ command: string
+ }
+ paste: () => {
+ value: true
+ }
+ setClipboardError: (error: string | null) => {
+ error: string | null
+ }
+ setError: (error: string | null) => {
+ error: string | null
+ }
+ setHasSelection: (selected: boolean) => {
+ selected: boolean
+ }
+ setPasting: (pasting: boolean) => {
+ pasting: boolean
+ }
+ setSaveError: (error: string | null) => {
+ error: string | null
+ }
+ setStatus: (status: TerminalStatus) => {
+ status: TerminalStatus
+ }
+ start: () => {
+ value: true
+ }
+ stop: () => {
+ value: true
+ }
+}
+
+export type terminalLogicType = MakeLogicType<terminalLogicValues, terminalLogicActions>
+
+export const terminalLogic = kea<terminalLogicType>([
+ path(['scenes', 'terminal', 'terminalLogic']),
+ connect({
+ values: [teamLogic, ['currentTeamId'], terminalDockLogic, ['terminalEnabled']],
+ actions: [terminalDockLogic, ['focusTerminal']],
+ }),
+ actions({
+ start: true,
+ attach: (container: HTMLElement) => ({ container }),
+ detach: (container: HTMLElement) => ({ container }),
+ focus: true,
+ insertCommand: (command: string) => ({ command }),
+ copy: true,
+ paste: true,
+ setHasSelection: (selected: boolean) => ({ selected }),
+ setClipboardError: (error: string | null) => ({ error }),
+ setPasting: (pasting: boolean) => ({ pasting }),
+ stop: true,
+ setStatus: (status: TerminalStatus) => ({ status }),
+ setError: (error: string | null) => ({ error }),
+ setSaveError: (error: string | null) => ({ error }),
+ }),
+ reducers({
+ hasStarted: [false, { start: () => true }],
+ runRequested: [false, { start: () => true, stop: () => false }],
+ hasSelection: [false, { setHasSelection: (_, { selected }) => selected }],
+ pasting: [false, { setPasting: (_, { pasting }) => pasting }],
+ clipboardError: [null as string | null, { setClipboardError: (_, { error }) => error }],
+ status: ['idle' as TerminalStatus, { setStatus: (_, { status }) => status, stop: () => 'idle' }],
+ // Stop destroys the session, including the recovery copies a save error points at.
+ error: [null as string | null, { setError: (_, { error }) => error, start: () => null, stop: () => null }],
+ saveError: [
+ null as string | null,
+ { setSaveError: (_, { error }) => error, start: () => null, stop: () => null },
+ ],
+ }),
+ listeners(({ actions, values, cache }) => ({
+ attach: ({ container }) => {
+ if (!cache.session) {
+ cache.session = new TerminalSession(
+ (data) => cache.runtime?.write(data),
+ (columns, rows) => cache.runtime?.resize(columns, rows),
+ actions.setHasSelection,
+ actions.paste
+ )
+ cache.disposables.add(
+ () => () => {
+ cache.session.dispose()
+ cache.session = null
+ },
+ 'screen',
+ { pauseOnPageHidden: false }
+ )
+ }
+ cache.session.attach(container)
+ if (!values.hasStarted) {
+ actions.start()
+ }
+ },
+ detach: ({ container }) => cache.session?.detach(container),
+ focus: () => cache.session?.view.focus(),
+ focusTerminal: () => actions.focus(),
+ insertCommand: ({ command }) => {
+ cache.session?.view.paste(command)
+ actions.focus()
+ },
+ copy: () => void copyToClipboard(cache.session?.view.getSelection() ?? '', 'terminal selection'),
+ paste: async () => {
+ if (values.pasting) {
+ return
+ }
+ actions.setPasting(true)
+ actions.setClipboardError(null)
+ try {
+ const text = await navigator.clipboard.readText()
+ cache.session?.view.paste(text)
+ actions.focus()
+ } catch {
+ actions.setClipboardError(
+ 'Could not read the clipboard. Focus the terminal and use your browser’s paste shortcut.'
+ )
+ } finally {
+ actions.setPasting(false)
+ }
+ },
+ [teamLogic.actionTypes.loadCurrentTeamSuccess]: ({ currentTeam }) => {
+ if (cache.projectId === currentTeam?.id) {
+ return
+ }
+ const restart = values.runRequested
+ actions.stop()
+ cache.filesystem = null
+ cache.session?.view.clear()
+ if (restart && cache.session) {
+ actions.start()
+ }
+ },
+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {
+ if (!values.terminalEnabled) {
+ actions.stop()
+ }
+ },
+ start: async (_, breakpoint) => {
+ const projectId = values.currentTeamId
+ if (!values.terminalEnabled || !projectId || ['loading', 'booting', 'ready'].includes(values.status)) {
+ return
+ }
+ if (!cache.session) {
+ return
+ }
+ cache.projectId = projectId
+ const runtime = new TerminalRuntime((bytes) => cache.session?.view.write(bytes))
+ cache.runtime = runtime
+ cache.session.view.clear()
+ runtime.resize(cache.session.view.cols, cache.session.view.rows)
+ const controller = new AbortController()
+ const disposables = cache.disposables
+ disposables.add(
+ () => () => {
+ controller.abort()
+ disposables.dispose('clock-sync')
+ runtime.dispose()
+ if (cache.runtime === runtime) {
+ cache.runtime = null
+ cache.filesystem = null
+ }
+ if (window.posthogTerminal?.read === agent.read) {
+ delete window.posthogTerminal
+ }
+ },
+ 'terminal',
+ { pauseOnPageHidden: false }
+ )
+ const agent: TerminalAgent = { write: (data) => runtime.write(data), read: () => runtime.read() }
+ actions.setStatus('loading')
+ try {
+ const filesystem = new PosthogFilesystem(String(projectId), controller.signal)
+ await filesystem.load()
+ breakpoint()
+ if (controller.signal.aborted) {
+ return
+ }
+ cache.filesystem = filesystem
+ new PosthogCommands(String(projectId), controller.signal, filesystem)
+ actions.setStatus('booting')
+ const server = new NinePServer(filesystem, (error) => {
+ if (!controller.signal.aborted) {
+ actions.setSaveError(error)
+ }
+ })
+ await runtime.start(server, controller.signal, () => {
+ if (!controller.signal.aborted) {
+ window.posthogTerminal = agent
+ actions.setStatus('ready')
+ disposables.add(() => {
+ runtime.syncClock()
+ const interval = setInterval(() => runtime.syncClock(), 30_000)
+ return () => clearInterval(interval)
+ }, 'clock-sync')
+ }
+ })
+ if (controller.signal.aborted) {
+ return
+ }
+ disposables.add(
+ () => {
+ const timeout = setTimeout(() => {
+ if (!controller.signal.aborted && values.status === 'booting') {
+ actions.setError('Linux did not finish starting. Stop the terminal and try again.')
+ actions.setStatus('error')
+ disposables.dispose('terminal')
+ }
+ }, 90_000)
+ return () => clearTimeout(timeout)
+ },
+ 'boot-timeout',
+ { pauseOnPageHidden: false }
+ )
+ } catch (error) {
+ if (!controller.signal.aborted) {
+ actions.setError(
+ error instanceof Error ? error.message : 'Could not start the terminal. Try again.'
+ )
+ actions.setStatus('error')
+ disposables.dispose('terminal')
+ }
+ }
+ },
+ stop: () => {
+ cache.disposables.dispose('terminal')
+ cache.disposables.dispose('boot-timeout')
+ },
+ })),
+])
diff --git a/frontend/src/scenes/terminal/terminalRuntime.test.ts b/frontend/src/scenes/terminal/terminalRuntime.test.ts
new file mode 100644
index 000000000000..ab2cea238582
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalRuntime.test.ts
@@ -0,0 +1,96 @@
+import { V86 } from 'v86'
+
+import assetHashes from './assets/hashes.json'
+import { NinePServer } from './ninepServer'
+import { TerminalFilesystem } from './terminalFilesystem'
+import { TerminalRuntime } from './terminalRuntime'
+
+jest.mock('v86', () => ({ V86: jest.fn() }))
+jest.mock('v86/build/v86.wasm?url', () => 'wasm', { virtual: true })
+jest.mock('./assets/seabios.bin?url', () => 'bios', { virtual: true })
+jest.mock('./assets/vgabios.bin?url', () => 'vga', { virtual: true })
+jest.mock('./assets/buildroot-bzimage.bin?url', () => 'kernel', { virtual: true })
+jest.mock('./assets/jq-linux-i386.bin?url', () => 'jq', { virtual: true })
+jest.mock('./assets/tools-linux-i386.tar.gz.bin?url', () => 'tools', { virtual: true })
+
+describe('terminal VM lifecycle', () => {
+ const originalGlobals = {
+ fetch: globalThis.fetch,
+ Blob: globalThis.Blob,
+ Response: globalThis.Response,
+ DecompressionStream: globalThis.DecompressionStream,
+ }
+ const originalSubtle = Object.getOwnPropertyDescriptor(crypto, 'subtle')
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ const hashes = [
+ '73e3f359102e3a9982c35fce98eb7cd08f18303ac7f1ba6ebfbe6cdc1c244d98',
+ 'a4bc0d80cc3ca028c73dafa8fee396b8d054ce87ebd8abfbd31b06b437607880',
+ '7befbaea31e249d9a518c4b95fa42b2a193d0e3de46250d617cbdeb866ee28b0',
+ 'ba996e8ce436973e2f39e2639405a37e8c81ba8c722b71c83996278ad0af16dd',
+ assetHashes.toolsSha256,
+ ]
+ Object.defineProperty(crypto, 'subtle', {
+ configurable: true,
+ value: {
+ digest: jest.fn(
+ async () => Uint8Array.from(hashes.shift()!.match(/../g)!, (hex) => parseInt(hex, 16)).buffer
+ ),
+ },
+ })
+ Object.assign(globalThis, {
+ fetch: jest.fn(async () => ({ ok: true, arrayBuffer: async () => new ArrayBuffer(0) })),
+ Blob: jest.fn(() => ({ stream: () => ({ pipeThrough: () => ({}) }) })),
+ Response: jest.fn(() => ({ arrayBuffer: async () => new ArrayBuffer(0) })),
+ DecompressionStream: jest.fn(),
+ })
+ })
+
+ afterEach(() => {
+ Object.assign(globalThis, originalGlobals)
+ if (originalSubtle) {
+ Object.defineProperty(crypto, 'subtle', originalSubtle)
+ } else {
+ Reflect.deleteProperty(crypto, 'subtle')
+ }
+ })
+
+ it.each(['initializing', 'loaded'])(
+ 'stops a VM that is %s without allowing late output or startup',
+ async (phase) => {
+ const listeners = new Map<string, (value?: number) => void>()
+ const emulator = {
+ add_listener: jest.fn((event, callback) => listeners.set(event, callback)),
+ run: jest.fn(),
+ destroy: jest.fn(async () => {}),
+ }
+ jest.mocked(V86).mockImplementation(() => emulator as unknown as V86)
+ const output = jest.fn()
+ const ready = jest.fn()
+ const runtime = new TerminalRuntime(output)
+ await runtime.start(
+ new NinePServer(new TerminalFilesystem(), jest.fn()),
+ new AbortController().signal,
+ ready
+ )
+ expect(V86).toHaveBeenCalledWith(expect.objectContaining({ autostart: false }))
+ if (phase === 'loaded') {
+ listeners.get('emulator-loaded')!()
+ expect(emulator.run).toHaveBeenCalledTimes(1)
+ }
+ runtime.dispose()
+ if (phase === 'initializing') {
+ expect(emulator.destroy).not.toHaveBeenCalled()
+ listeners.get('emulator-loaded')!()
+ expect(emulator.run).not.toHaveBeenCalled()
+ }
+ listeners.get('serial0-output-byte')!(65)
+ listeners.get('serial1-output-byte')!(30)
+ expect(emulator.destroy).toHaveBeenCalledTimes(1)
+ expect(runtime.read()).toBe('')
+ expect(output).not.toHaveBeenCalled()
+ expect(ready).not.toHaveBeenCalled()
+ }
+ )
+})
diff --git a/frontend/src/scenes/terminal/terminalRuntime.ts b/frontend/src/scenes/terminal/terminalRuntime.ts
new file mode 100644
index 000000000000..05252d75bd79
--- /dev/null
+++ b/frontend/src/scenes/terminal/terminalRuntime.ts
@@ -0,0 +1,228 @@
+import type { V86 } from 'v86'
+import wasmUrl from 'v86/build/v86.wasm?url'
+
+import kernelUrl from './assets/buildroot-bzimage.bin?url'
+import assetHashes from './assets/hashes.json'
+import jqUrl from './assets/jq-linux-i386.bin?url'
+import biosUrl from './assets/seabios.bin?url'
+import toolsUrl from './assets/tools-linux-i386.tar.gz.bin?url'
+import vgaBiosUrl from './assets/vgabios.bin?url'
+import { NinePServer } from './ninepServer'
+
+function browserClock(): { timestamp: number; timezone: string } {
+ const now = new Date()
+ const offset = now.getTimezoneOffset()
+ const hours = Math.floor(Math.abs(offset) / 60)
+ const minutes = String(Math.abs(offset) % 60).padStart(2, '0')
+ // POSIX timezone offsets have the opposite sign to the displayed UTC offset.
+ const label = `${offset > 0 ? '-' : '+'}${String(hours).padStart(2, '0')}${minutes}`
+ return {
+ timestamp: Math.floor(now.getTime() / 1000),
+ timezone: offset === 0 ? 'UTC0' : `<${label}>${offset > 0 ? '' : '-'}${hours}:${minutes}`,
+ }
+}
+
+async function verifiedImage(url: string, sha256: string, signal: AbortSignal): Promise<ArrayBuffer> {
+ const response = await fetch(url, {
+ signal,
+ credentials: 'omit',
+ referrerPolicy: 'no-referrer',
+ })
+ if (!response.ok) {
+ throw new Error(`Terminal download failed (${response.status}). Retry starting the terminal.`)
+ }
+ const buffer = await response.arrayBuffer()
+ const digest = await crypto.subtle.digest('SHA-256', buffer)
+ const actual = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')
+ if (actual !== sha256) {
+ throw new Error('Terminal download verification failed. Reload PostHog before trying again.')
+ }
+ return buffer
+}
+
+export class TerminalRuntime {
+ private emulator?: V86
+ private emulatorLoaded = false
+ private output = ''
+ private decoder = new TextDecoder()
+ private outputBuffer = new Uint8Array(8192)
+ private outputLength = 0
+ private outputScheduled = false
+ private ready = false
+ private disposed = false
+ private columns = 80
+ private rows = 24
+
+ constructor(private onOutput: (bytes: Uint8Array) => void) {}
+
+ async start(server: NinePServer, signal: AbortSignal, onReady: () => void): Promise<void> {
+ const { V86 } = await import('v86')
+ if (signal.aborted || this.disposed) {
+ return
+ }
+ const [bios, vgaBios, kernel, jq, tools] = await Promise.all([
+ verifiedImage(biosUrl, '73e3f359102e3a9982c35fce98eb7cd08f18303ac7f1ba6ebfbe6cdc1c244d98', signal),
+ verifiedImage(vgaBiosUrl, 'a4bc0d80cc3ca028c73dafa8fee396b8d054ce87ebd8abfbd31b06b437607880', signal),
+ verifiedImage(
+ // This image's uncached 9P reads work before API file sizes are known; Linux 6.8 clamps them to zero.
+ kernelUrl,
+ '7befbaea31e249d9a518c4b95fa42b2a193d0e3de46250d617cbdeb866ee28b0',
+ signal
+ ),
+ verifiedImage(jqUrl, 'ba996e8ce436973e2f39e2639405a37e8c81ba8c722b71c83996278ad0af16dd', signal),
+ verifiedImage(toolsUrl, assetHashes.toolsSha256, signal),
+ ])
+ if (signal.aborted || this.disposed) {
+ return
+ }
+ // The guest's BusyBox tar has no gzip support.
+ const toolsArchive = await new Response(
+ new Blob([tools]).stream().pipeThrough(new DecompressionStream('gzip'))
+ ).arrayBuffer()
+ if (signal.aborted || this.disposed) {
+ return
+ }
+ const bin = server.filesystem.directory('bin', server.filesystem.root)
+ server.filesystem.file('jq', bin, async () => ({ bytes: new Uint8Array(jq) })).size = jq.byteLength
+ server.filesystem.file('tools.tar', bin, async () => ({ bytes: new Uint8Array(toolsArchive) })).size =
+ toolsArchive.byteLength
+ const emulator = (this.emulator = new V86({
+ wasm_path: wasmUrl,
+ bios: { buffer: bios },
+ vga_bios: { buffer: vgaBios },
+ bzimage: { buffer: kernel },
+ memory_size: 128 * 1024 * 1024,
+ filesystem: { handle9p: server.handle },
+ cmdline: 'tsc=reliable mitigations=off random.trust_cpu=on',
+ disable_keyboard: true,
+ disable_mouse: true,
+ disable_speaker: true,
+ uart1: true,
+ autostart: false,
+ }))
+ emulator.add_listener('emulator-loaded', () => {
+ this.emulatorLoaded = true
+ if (this.disposed || signal.aborted) {
+ void emulator.destroy()
+ } else {
+ emulator.run()
+ }
+ })
+ let boot = ''
+ let configured = false
+ emulator.add_listener('serial1-output-byte', (byte: number) => {
+ if (this.disposed) {
+ return
+ }
+ if (configured && !this.ready && byte === 30) {
+ this.ready = true
+ this.resize(this.columns, this.rows)
+ onReady()
+ }
+ })
+ emulator.add_listener('serial0-output-byte', (byte: number) => {
+ if (this.disposed) {
+ return
+ }
+ this.outputBuffer[this.outputLength++] = byte
+ if (this.outputLength === this.outputBuffer.length) {
+ this.flushOutput()
+ }
+ if (!this.outputScheduled) {
+ this.outputScheduled = true
+ queueMicrotask(() => {
+ this.outputScheduled = false
+ this.flushOutput()
+ })
+ }
+ if (configured) {
+ return
+ }
+ boot = (boot + String.fromCharCode(byte)).slice(-4096)
+ if (!configured && boot.endsWith('~% ')) {
+ configured = true
+ const clock = browserClock()
+ const setup = new TextEncoder().encode(
+ [
+ `stty rows ${this.rows} cols ${this.columns}`,
+ 'export TERM=xterm-256color',
+ 'unset TZ',
+ `printf '%s\\n' '${clock.timezone}' > /etc/TZ`,
+ `date -s @${clock.timestamp} > /dev/null`,
+ 'tar -xf /posthog/bin/tools.tar -C / || exit',
+ 'export EDITOR=nano VISUAL=nano',
+ 'cp /posthog/bin/jq /usr/bin/jq && chmod +x /usr/bin/jq || exit',
+ 'cp /posthog/bin/ph /usr/bin/ph && chmod +x /usr/bin/ph || exit',
+ 'stty -F /dev/ttyS1 raw -echo',
+ // Detach the control helper so the shell's wait command only waits for user jobs.
+ '(while read -r command first second; do case "$command" in resize) stty -F /dev/ttyS0 rows "$first" cols "$second";; clock) date -s "@$first" > /dev/null; printf "%s\\n" "$second" > /etc/TZ;; esac; done < /dev/ttyS1 &)',
+ "alias ls='ls --color=auto'",
+ "export PS1='\\[\\033[32m\\]posthog\\[\\033[0m\\]:\\[\\033[34m\\]\\w\\[\\033[0m\\] $ '",
+ 'cd /posthog/files',
+ 'clear',
+ "printf 'PostHog terminal\\n\\nTry:\\n mc\\n tree -C -L 3\\n nano Unfiled/Notebooks/Foobar.md\\n vi Unfiled/Notebooks/Foobar.md\\n ncdu -r /posthog/files\\n mkdir Research\\n ph tools\\n ph notebooks-list --limit 10 | jq .\\n cat /posthog/README.txt\\n\\nUse your own notebook path. In nano, Ctrl+S saves and Ctrl+X exits.\\nIn vi, save with :wq; quit with :q!. Selecting text copies it.\\nFolder creation and moves update PostHog.\\n\\n'",
+ 'stty echo',
+ "printf '\\036' > /dev/ttyS1",
+ ].join('\n') + '\n'
+ )
+ server.filesystem.file('init.sh', bin, async () => ({ bytes: setup })).size = setup.byteLength
+ // Source setup from 9P to stay within the guest shell's input limit.
+ // Parse the bootstrap together so stty cannot flush queued serial input.
+ emulator.serial0_send(
+ 'stty -echo; mkdir -p /posthog; umount /mnt; mount -t 9p -o trans=virtio,version=9p2000.L,cache=none host9p /posthog && . /posthog/bin/init.sh\n'
+ )
+ }
+ })
+ }
+
+ write(data: string): void {
+ if (this.ready) {
+ this.emulator?.serial_send_bytes(0, new TextEncoder().encode(data))
+ }
+ }
+
+ read(): string {
+ this.flushOutput()
+ return this.output.slice(-1_000_000)
+ }
+
+ private flushOutput(): void {
+ if (!this.outputLength || this.disposed) {
+ return
+ }
+ const data = this.outputBuffer.slice(0, this.outputLength)
+ this.outputLength = 0
+ this.output += this.decoder.decode(data, { stream: true })
+ if (this.output.length > 1_100_000) {
+ this.output = this.output.slice(-1_000_000)
+ }
+ this.onOutput(data)
+ }
+
+ syncClock(): void {
+ if (this.ready && !this.disposed) {
+ const { timestamp, timezone } = browserClock()
+ this.emulator?.serial_send_bytes(1, new TextEncoder().encode(`clock ${timestamp} ${timezone}\n`))
+ }
+ }
+
+ resize(columns: number, rows: number): void {
+ this.columns = Math.max(20, Math.min(500, Math.floor(columns)))
+ this.rows = Math.max(5, Math.min(200, Math.floor(rows)))
+ if (this.ready) {
+ this.emulator?.serial_send_bytes(1, new TextEncoder().encode(`resize ${this.rows} ${this.columns}\n`))
+ }
+ }
+
+ dispose(): void {
+ this.disposed = true
+ this.ready = false
+ // V86 cannot destroy its CPU until asynchronous WASM initialization has finished.
+ if (this.emulatorLoaded) {
+ void this.emulator?.destroy()
+ }
+ this.emulator = undefined
+ this.output = ''
+ this.outputLength = 0
+ }
+}
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index f6ac3e75437e..f1916f8b6c71 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -296,6 +296,7 @@ export const urls = {
debugQuery: (query?: string | Record<string, any>): string =>
combineUrl('/debug', {}, query ? { q: typeof query === 'string' ? query : JSON.stringify(query) } : {}).url,
debugHog: (): string => '/debug/hog',
+ terminal: (): string => '/terminal',
projectFiles: (folder = ''): string => combineUrl('/files', folder ? { folder } : {}).url,
moveToPostHogCloud: (): string => '/move-to-cloud',
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 000000000000..a49304ae9e99
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,11 @@
+--- a/build/libv86.mjs
++++ b/build/libv86.mjs
+@@ -334,7 +334,7 @@
+ b+="JIT_CACHE_SIZE="+a.wm.exports.jit_get_cache_size()+"\n";b+="FLAT_SEGMENTS="+a.wm.exports.has_flat_segmentation()+"\n";b+="wasm memory size: "+(a.wasm_memory.buffer.byteLength>>20)+"m\n";b=b+"Config:\nJIT_DISABLED="+(a.wm.exports.get_jit_config(0)+"\n");b+="MAX_PAGES="+a.wm.exports.get_jit_config(1)+"\n";b+="JIT_USE_LOOP_SAFETY="+!!a.wm.exports.get_jit_config(2)+"\n";b+="MAX_EXTRA_BASIC_BLOCKS="+a.wm.exports.get_jit_config(3)+"\n";a=[gb(a,!1,!1,!1,!1),gb(a,!0,!1,!1,!1),gb(a,!1,!0,!1,!1),gb(a,!1,
+ !1,!0,!1),gb(a,!1,!1,!1,!0)].join("\n\n");return b+a};function Fc(a){this.message=a||"File not found"}Fc.prototype=Error.prototype;"undefined"!==typeof module&&"undefined"!==typeof module.exports?module.exports.V86=Q:"undefined"!==typeof window?window.V86=Q:"function"===typeof importScripts&&(self.V86=Q);function G(a,b){this.stopping=this.running=!1;this.idle=!0;this.tick_counter=0;this.worker=null;this.cpu=new S(a,b,()=>{this.idle&&this.next_tick(0)});this.bus=a;this.register_yield()}G.prototype.run=
+ function(){this.stopping=!1;this.running||(this.running=!0,this.bus.send("emulator-started"));this.next_tick(0)};G.prototype.do_tick=function(){if(this.stopping||!this.running)this.stopping=this.running=!1,this.bus.send("emulator-stopped");else{this.idle=!1;var a=this.cpu.main_loop();this.next_tick(a)}};G.prototype.next_tick=function(a){const b=++this.tick_counter;this.idle=!0;this.yield(a,b)};G.prototype.yield_callback=function(a){a===this.tick_counter&&this.do_tick()};G.prototype.stop=function(){this.running&&
+-(this.stopping=!0)};G.prototype.destroy=function(){this.unregister_yield()};G.prototype.restart=function(){this.cpu.reboot_internal()};G.prototype.init=function(a){this.cpu.init(a,this.bus);this.bus.send("emulator-ready")};if("undefined"!==typeof process)G.prototype.yield=function(a,b){1>a?global.setImmediate(c=>this.yield_callback(c),b):setTimeout(c=>this.yield_callback(c),a,b)},G.prototype.register_yield=function(){},G.prototype.unregister_yield=function(){};else if(globalThis.scheduler&&"function"===
++(this.stopping=!0)};G.prototype.destroy=function(){this.unregister_yield()};G.prototype.restart=function(){this.cpu.reboot_internal()};G.prototype.init=function(a){this.cpu.init(a,this.bus);this.bus.send("emulator-ready")};if("undefined"!==typeof process&&process.versions&&process.versions.node)G.prototype.yield=function(a,b){1>a?global.setImmediate(c=>this.yield_callback(c),b):setTimeout(c=>this.yield_callback(c),a,b)},G.prototype.register_yield=function(){},G.prototype.unregister_yield=function(){};else if(globalThis.scheduler&&"function"===
+ typeof globalThis.scheduler.postTask&&location.href.includes("use-scheduling-api"))G.prototype.yield=function(a,b){a=Math.max(0,a);globalThis.scheduler.postTask(()=>this.yield_callback(b),{delay:a})},G.prototype.register_yield=function(){},G.prototype.unregister_yield=function(){};else if("undefined"!==typeof Worker){function a(){let b;globalThis.onmessage=function(c){const d=c.data.t;b=b&&clearTimeout(b);1>d?postMessage(c.data.tick):b=setTimeout(()=>postMessage(c.data.tick),d)}}G.prototype.register_yield=
+ function(){const b=URL.createObjectURL(new Blob(["("+a.toString()+")()"],{type:"text/javascript"}));this.worker=new Worker(b);this.worker.onmessage=c=>this.yield_callback(c.data);URL.revokeObjectURL(b)};G.prototype.yield=function(b,c){this.worker.postMessage({t:b,tick:c})};G.prototype.unregister_yield=function(){this.worker&&this.worker.terminate();this.worker=null}}else G.prototype.yield=function(a){setTimeout(()=>{this.do_tick()},a)},G.prototype.register_yield=function(){},G.prototype.unregister_yield=
+ function(){};G.prototype.save_state=function(){for(var a=[],b=db(this.cpu,a),c=[],d=0,e=0;e<a.length;e++){var f=a[e].byteLength;c[e]={offset:d,length:f};d+=f;d=d+3&-4}e=JSON.stringify({buffer_infos:c,state:b});e=(new TextEncoder).encode(e);b=16+e.length;b=b+3&-4;f=b+d;d=new ArrayBuffer(f);var g=new Int32Array(d,0,4);(new Uint8Array(d,16,e.length)).set(e);b=new Uint8Array(d,b);g[0]=-2039052682;g[1]=6;g[2]=f;g[3]=e.length;for(e=0;e<a.length;e++)b.set(a[e],c[e].offset);return d};G.prototype.restore_state=
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d89e2159dc06..de9da8a59e07 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -207,6 +207,9 @@ patchedDependencies:
hash: 139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5
path: patches/[email protected]
+ hash: 567937f0364248ae4346886b1da715b6e5a29dd6835c33b66f3264a6bb95d37f
+ path: patches/[email protected]
importers:
@@ -995,6 +998,12 @@ importers:
'@vitejs/plugin-react':
specifier: 'catalog:'
+ '@xterm/addon-fit':
+ specifier: 0.10.0
+ version: 0.10.0(@xterm/[email protected])
+ '@xterm/xterm':
+ specifier: 5.5.0
+ version: 5.5.0
'@xyflow/react':
specifier: ^12.6.0
@@ -1274,6 +1283,9 @@ importers:
use-resize-observer:
specifier: ^8.0.0
+ v86:
+ specifier: 0.5.458
+ version: 0.5.458(patch_hash=567937f0364248ae4346886b1da715b6e5a29dd6835c33b66f3264a6bb95d37f)
zod:
specifier: ^4.3.6
version: 4.3.6
@@ -14062,6 +14074,11 @@ packages:
engines: {node: '>=14.6'}
deprecated: this version has critical issues, please update to the latest version
+ '@xterm/[email protected]':
+ resolution: {integrity: sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==}
+ peerDependencies:
+ '@xterm/xterm': ^5.0.0
+
resolution: {integrity: sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==}
@@ -23144,6 +23161,9 @@ packages:
resolution: {integrity: sha512-6z3GW9x8G1gd+JIIgQQQxXuiJtCXeAjp6RaPEPLv62mH3iPHPxV6W3robxtCzNErRo6ZwTmzWhsbNvjyEBKzKA==}
engines: {node: '>=10.12.0'}
+ resolution: {integrity: sha512-ixQE0RyfjMgrBvx5O+kq1AXPZwhUJVqD5Vhl2LBm8L4jgV2fVczYalbG4thu0vWSl42Q71DOwjIl5Y8mZHNpyA==}
+
resolution: {integrity: sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==}
@@ -34224,8 +34244,11 @@ snapshots:
'@xmldom/[email protected]': {}
- '@xterm/[email protected]':
- optional: true
+ dependencies:
+ '@xterm/xterm': 5.5.0
+
+ '@xterm/[email protected]': {}
'@xtuc/[email protected]': {}
@@ -46040,6 +46063,8 @@ snapshots:
'@types/istanbul-lib-coverage': 2.0.6
convert-source-map: 1.9.0
+ [email protected](patch_hash=567937f0364248ae4346886b1da715b6e5a29dd6835c33b66f3264a6bb95d37f): {}
+
dependencies:
spdx-correct: 3.1.1
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index fe73133023d7..629d49d4e352 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -103,6 +103,8 @@ overrides:
'@tiptap/extension-underline': 3.20.6
patchedDependencies:
+ # Browser process shims must not select v86's Node-only scheduler.
'@connectrpc/[email protected]': patches/@[email protected]
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index af7e92a77a31..f87d7b369d31 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -1634,6 +1634,11 @@
"params": [],
"scope": "project"
},
+ "terminal": {
+ "template": "/terminal",
+ "params": [],
+ "scope": "project"
+ },
"toolbarLaunch": {
"template": "/toolbar",
"params": [],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
index 92916ad93acf..56cda884f27a 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -13,7 +13,7 @@
"type": "object"
},
"url": {
- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/broadcasts\n/workflows/broadcasts/new\n/workflows/broadcasts/{id}\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/broadcasts\n/workflows/broadcasts/new\n/workflows/broadcasts/{id}\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
"type": "string"
}
},