Skip to content

Commit f438c0a

Browse files
authored
Fix report export routing and stale artifact content (#407)
* Fix PDF export backend routing * Fix stale report artifact content * Allow DOCX export WebAssembly under CSP
1 parent 6ab6428 commit f438c0a

17 files changed

Lines changed: 831 additions & 126 deletions

‎docs/architecture/chat-rendering-pipeline.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,11 @@ When the session is done streaming and has artifacts, the `embeddedArtifactPaths
258258

259259
PDF export uses `fetch()` + blob download (not `<a>.click()` navigation) because the backend PDF generation takes 5-15 seconds. The `<a>.click()` pattern causes the browser to show "Site wasn't available" for slow responses. The `fetch()` approach shows a loading spinner on the Download button during generation.
260260

261-
Artifact content lookup is best-effort across three sources: local host path, live sandbox backend `PullFile`, then persisted transcript `write_file` arguments. The transcript fallback is a recovery/cache path for historical artifacts; it does not prove that the file currently exists in a resumed sandbox. Direct K8s backends should read live files through the backend abstraction first so `/root/foo.md` refers to the composed sandbox rootfs, then fall back only if the live sandbox is unavailable.
261+
DOCX export runs in the Studio browser via `@m2d/remark-docx`. That package's preprocessing path instantiates WebAssembly, so the Studio CSP permits `script-src 'wasm-unsafe-eval'` while still omitting general JavaScript `'unsafe-eval'`.
262+
263+
PDF export is Chrome-only. When sandboxing is enabled, the dedicated PDF browser manager must use the active sandbox backend's Chrome tunnel: Incus for `sandbox.backend: incus`, OpenShell for `openshell`, and direct backend tunneling for `k8s`. It must not silently fall back to Incus for non-Incus backends, and it must not switch to the pure-Go PDF renderer when Chrome cannot launch. Host Chrome is used only when sandboxing is disabled.
264+
265+
Artifact content lookup is best-effort across three sources: local host path, live sandbox backend `PullFile`, then persisted transcript reconstruction. The live sandbox read is attempted before transcript fallback whenever a session ID is available; if the backend reports a stopped-but-preserved session, the handler resumes it and waits for readiness before pulling the file. Direct K8s backends should read live files through the backend abstraction first so `/root/foo.md` refers to the composed sandbox rootfs, then fall back only if the live sandbox is unavailable. The transcript fallback is a recovery/cache path for historical artifacts: it replays the latest known `write_file` content plus subsequent matching `edit_file` mutations for the same path, but it does not prove that the file currently exists in a resumed sandbox.
262266

263267
## The Report Pipeline
264268

‎docs/architecture/sandbox-backends.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -386,7 +386,7 @@ The entrypoint runs as PID 1 with the privilege path selected at chart-install t
386386

387387
**Sandbox binary loader contract.** The intended sandbox `astonish-host` build is static (`CGO_ENABLED=0`), but the `astonish-sandbox-base` image also creates `/lib/ld-musl-x86_64.so.1 -> x86_64-linux-gnu/ld-linux-x86-64.so.2` as a compatibility guard. Without that loader path, a dynamically linked musl binary bind-mounted into the chroot fails with exit `127` and no node handshake (`backend exec: no node response in stdout`) even though `/usr/local/bin/astonish` exists.
388388

389-
**Browser-in-sandbox.** Direct K8s uses the same browser `Manager` callbacks as the other sandbox backends, but tunnels through `Backend.ExecStreaming` instead of Incus or OpenShell APIs. Browser tools resolve the current chat session, launch CloakBrowser/Chromium inside `/sandbox/rootfs` via `/usr/local/bin/astonish-shell`, keep that exec stream open so the browser stack stays alive, and connect Rod to CDP through a `socat` tunnel on port `9222`. When KasmVNC is installed, the launcher uses `Xkasmvnc :0` and exposes the web handoff endpoint on port `6901`; otherwise it falls back to `Xvfb :99` for browser automation without visual handoff. The browser dependency catalog explicitly installs GLib/GObject (`libglib2.0-0` on Debian bookworm, `libglib2.0-0t64` on Ubuntu noble) because CloakBrowser is a standalone Chromium binary and apt cannot infer its shared-library dependencies.
389+
**Browser-in-sandbox.** Direct K8s uses the same browser `Manager` callbacks as the other sandbox backends, but tunnels through `Backend.ExecStreaming` instead of Incus or OpenShell APIs. Browser tools resolve the current chat session, launch CloakBrowser/Chromium inside `/sandbox/rootfs` via `/usr/local/bin/astonish-shell`, keep that exec stream open so the browser stack stays alive, and connect Rod to CDP through a `socat` tunnel on port `9222`. The PDF export browser manager is wired to the same K8s callbacks, using the session ID as the tunnel handle; it does not fall back to Incus or to a non-Chrome renderer. When KasmVNC is installed, the launcher uses `Xkasmvnc :0` and exposes the web handoff endpoint on port `6901`; otherwise it falls back to `Xvfb :99` for browser automation without visual handoff. The browser dependency catalog explicitly installs GLib/GObject (`libglib2.0-0` on Debian bookworm, `libglib2.0-0t64` on Ubuntu noble) because CloakBrowser is a standalone Chromium binary and apt cannot infer its shared-library dependencies.
390390

391391
**Rejected alternative.** A separate init container performing the overlay mount would require either a `hostPath` volume (rejected — violates Pod Security Admission `baseline`) or a CSI volume that supports `mountPropagation: Bidirectional` between init and main containers (complex; not all CSI drivers honour it). Doing the mount in the main container's PID 1 keeps the pod spec minimal and works with any CSI driver.
392392

‎pkg/api/artifact_content_test.go‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package api
2+
3+
import (
4+
"context"
5+
"io"
6+
"strings"
7+
"testing"
8+
9+
"github.com/SAP/astonish/pkg/sandbox"
10+
"github.com/SAP/astonish/pkg/sandbox/mock"
11+
)
12+
13+
func TestPullArtifactFromSandboxBackendResumesStoppedSession(t *testing.T) {
14+
ctx := context.Background()
15+
backend := mock.New()
16+
if _, err := backend.CreateSession(ctx, sandbox.SessionSpec{SessionID: "sess-1", TemplateID: sandbox.BaseTemplateID}); err != nil {
17+
t.Fatalf("CreateSession() err = %v", err)
18+
}
19+
if err := backend.PushFile(ctx, "sess-1", "/tmp/report.md", strings.NewReader("live 2026"), 0o644); err != nil {
20+
t.Fatalf("PushFile() err = %v", err)
21+
}
22+
if err := backend.StopSession(ctx, "sess-1"); err != nil {
23+
t.Fatalf("StopSession() err = %v", err)
24+
}
25+
26+
content, ok := pullArtifactFromSandboxBackend(ctx, backend, "sess-1", "/tmp/report.md")
27+
if !ok {
28+
t.Fatal("expected sandbox content")
29+
}
30+
if string(content) != "live 2026" {
31+
t.Fatalf("content = %q, want %q", content, "live 2026")
32+
}
33+
if calls := backend.StartSessionCalls(); len(calls) != 1 || calls[0] != "sess-1" {
34+
t.Fatalf("StartSessionCalls() = %+v, want [sess-1]", calls)
35+
}
36+
if calls := backend.PullFileCalls(); len(calls) != 1 || calls[0].Path != "/tmp/report.md" {
37+
t.Fatalf("PullFileCalls() = %+v, want one pull for /tmp/report.md", calls)
38+
}
39+
}
40+
41+
func TestPullArtifactFromSandboxBackendDoesNotFallbackBeforePull(t *testing.T) {
42+
ctx := context.Background()
43+
backend := mock.New()
44+
if _, err := backend.CreateSession(ctx, sandbox.SessionSpec{SessionID: "sess-1", TemplateID: sandbox.BaseTemplateID}); err != nil {
45+
t.Fatalf("CreateSession() err = %v", err)
46+
}
47+
backend.PullFileFn = func(sessionID, path string) (io.ReadCloser, error) {
48+
return io.NopCloser(strings.NewReader("live content wins")), nil
49+
}
50+
51+
content, ok := pullArtifactFromSandboxBackend(ctx, backend, "sess-1", "/tmp/report.md")
52+
if !ok {
53+
t.Fatal("expected sandbox content")
54+
}
55+
if string(content) != "live content wins" {
56+
t.Fatalf("content = %q, want live sandbox content", content)
57+
}
58+
}

‎pkg/api/chat_utils.go‎

Lines changed: 162 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -547,21 +547,28 @@ func collectArtifacts(events session.Events) []ArtifactInfo {
547547
}
548548
pending := make(map[string]pendingWrite)
549549

550-
// Deduplicate by path (keep the last write to each file)
551-
seen := make(map[string]bool)
550+
// Deduplicate by path while keeping the most recent successful mutation for
551+
// each file. Reports often get revised through edit_file after their initial
552+
// write_file; the artifact metadata must point at that latest mutation.
553+
artifactIndex := make(map[string]int)
552554
var artifacts []ArtifactInfo
553555

554556
addArtifact := func(path, toolName string) {
555-
if path == "" || seen[path] {
557+
if path == "" {
556558
return
557559
}
558-
seen[path] = true
559-
artifacts = append(artifacts, ArtifactInfo{
560+
info := ArtifactInfo{
560561
Path: path,
561562
FileName: filepath.Base(path),
562563
FileType: fileTypeFromExt(filepath.Ext(path)),
563564
ToolName: toolName,
564-
})
565+
}
566+
if idx, ok := artifactIndex[path]; ok {
567+
artifacts[idx] = info
568+
return
569+
}
570+
artifactIndex[path] = len(artifacts)
571+
artifacts = append(artifacts, info)
565572
}
566573

567574
for i := range events.Len() {
@@ -1118,11 +1125,10 @@ func persistSessionMessage(ctx context.Context, svc session.Service, userID, ses
11181125
}
11191126
}
11201127

1121-
// readArtifactContentFromSession scans a session's persisted events for a
1122-
// write_file FunctionCall whose file_path matches the requested path, and
1123-
// returns the content argument. This is used as a fallback when the actual
1124-
// file no longer exists on disk (e.g., written to /tmp, or inside a sandbox
1125-
// container that is stopped).
1128+
// readArtifactContentFromSession scans a session's persisted events for the
1129+
// latest write_file/edit_file mutation whose path matches the requested path,
1130+
// and reconstructs the best-known content. This is used only as a fallback when
1131+
// the actual file cannot be read from the host or live sandbox.
11261132
func readArtifactContentFromSession(fs *persistentsession.FileStore, userID, sessionID, filePath string) (string, bool) {
11271133
if fs == nil {
11281134
return "", false
@@ -1137,44 +1143,13 @@ func readArtifactContentFromSession(fs *persistentsession.FileStore, userID, ses
11371143
return "", false
11381144
}
11391145

1140-
events := getResp.Session.Events()
1141-
cleanTarget := filepath.Clean(filePath)
1142-
1143-
// Scan from the end to find the most recent write to this path
1144-
for i := events.Len() - 1; i >= 0; i-- {
1145-
event := events.At(i)
1146-
if event.LLMResponse.Content == nil {
1147-
continue
1148-
}
1149-
for _, part := range event.LLMResponse.Content.Parts {
1150-
if part.FunctionCall == nil {
1151-
continue
1152-
}
1153-
if part.FunctionCall.Name != "write_file" {
1154-
continue
1155-
}
1156-
args := part.FunctionCall.Args
1157-
if args == nil {
1158-
continue
1159-
}
1160-
p, _ := args["file_path"].(string)
1161-
if filepath.Clean(p) != cleanTarget {
1162-
continue
1163-
}
1164-
content, _ := args["content"].(string)
1165-
if content != "" {
1166-
return content, true
1167-
}
1168-
}
1169-
}
1170-
return "", false
1146+
return readArtifactContentFromEvents(getResp.Session.Events(), filePath)
11711147
}
11721148

11731149
// readArtifactContentFromSessionStore is the platform-mode equivalent of
11741150
// readArtifactContentFromSession. It accepts a store.SessionStore (which may
11751151
// be backed by PostgreSQL) and uses ReadTranscriptEvents to load events, then
1176-
// scans them for a write_file FunctionCall whose file_path matches the
1177-
// requested path.
1152+
// reconstructs the latest known content for the requested path.
11781153
func readArtifactContentFromSessionStore(ss store.SessionStore, appName, userID, sessionID, filePath string) (string, bool) {
11791154
if ss == nil {
11801155
return "", false
@@ -1185,36 +1160,153 @@ func readArtifactContentFromSessionStore(ss store.SessionStore, appName, userID,
11851160
return "", false
11861161
}
11871162

1163+
return readArtifactContentFromEventSlice(events, filePath)
1164+
}
1165+
1166+
func readArtifactContentFromEvents(events session.Events, filePath string) (string, bool) {
1167+
if events == nil {
1168+
return "", false
1169+
}
1170+
items := make([]*session.Event, 0, events.Len())
1171+
for i := range events.Len() {
1172+
items = append(items, events.At(i))
1173+
}
1174+
return readArtifactContentFromEventSlice(items, filePath)
1175+
}
1176+
1177+
func readArtifactContentFromEventSlice(events []*session.Event, filePath string) (string, bool) {
11881178
cleanTarget := filepath.Clean(filePath)
1179+
var content string
1180+
var known bool
1181+
type pendingMutation struct {
1182+
previousContent string
1183+
previousKnown bool
1184+
}
1185+
pending := make(map[string]pendingMutation)
11891186

1190-
// Scan from the end to find the most recent write to this path
1191-
for i := len(events) - 1; i >= 0; i-- {
1192-
event := events[i]
1193-
if event.LLMResponse.Content == nil {
1187+
for _, event := range events {
1188+
if event == nil || event.LLMResponse.Content == nil {
11941189
continue
11951190
}
11961191
for _, part := range event.LLMResponse.Content.Parts {
1197-
if part.FunctionCall == nil {
1198-
continue
1199-
}
1200-
if part.FunctionCall.Name != "write_file" {
1201-
continue
1202-
}
1203-
args := part.FunctionCall.Args
1204-
if args == nil {
1205-
continue
1206-
}
1207-
p, _ := args["file_path"].(string)
1208-
if filepath.Clean(p) != cleanTarget {
1209-
continue
1192+
if part.FunctionCall != nil && part.FunctionCall.Args != nil {
1193+
args := part.FunctionCall.Args
1194+
switch part.FunctionCall.Name {
1195+
case "write_file":
1196+
p, _ := args["file_path"].(string)
1197+
if filepath.Clean(p) != cleanTarget {
1198+
continue
1199+
}
1200+
previous := pendingMutation{previousContent: content, previousKnown: known}
1201+
newContent, _ := args["content"].(string)
1202+
content = normalizeWriteFileFallbackContent(newContent)
1203+
known = true
1204+
if part.FunctionCall.ID != "" {
1205+
pending[part.FunctionCall.ID] = previous
1206+
}
1207+
case "edit_file":
1208+
p, _ := args["path"].(string)
1209+
if !known || filepath.Clean(p) != cleanTarget {
1210+
continue
1211+
}
1212+
updated, ok := applyEditFileFallback(content, args)
1213+
if ok {
1214+
previous := pendingMutation{previousContent: content, previousKnown: known}
1215+
content = updated
1216+
if part.FunctionCall.ID != "" {
1217+
pending[part.FunctionCall.ID] = previous
1218+
}
1219+
}
1220+
}
12101221
}
1211-
content, _ := args["content"].(string)
1212-
if content != "" {
1213-
return content, true
1222+
if part.FunctionResponse != nil {
1223+
previous, ok := pending[part.FunctionResponse.ID]
1224+
if !ok {
1225+
continue
1226+
}
1227+
delete(pending, part.FunctionResponse.ID)
1228+
if part.FunctionResponse.Response != nil {
1229+
if _, hasErr := part.FunctionResponse.Response["error"]; hasErr {
1230+
content = previous.previousContent
1231+
known = previous.previousKnown
1232+
}
1233+
}
12141234
}
12151235
}
12161236
}
1217-
return "", false
1237+
return content, known
1238+
}
1239+
1240+
func normalizeWriteFileFallbackContent(content string) string {
1241+
if extracted, ok := tryExtractStdoutFallback(content); ok {
1242+
return extracted
1243+
}
1244+
return content
1245+
}
1246+
1247+
func tryExtractStdoutFallback(input string) (string, bool) {
1248+
trimmed := strings.TrimSpace(input)
1249+
if trimmed == "" {
1250+
return "", false
1251+
}
1252+
1253+
var parsed map[string]any
1254+
if err := json.Unmarshal([]byte(trimmed), &parsed); err != nil {
1255+
return "", false
1256+
}
1257+
stdout, ok := parsed["stdout"]
1258+
if !ok {
1259+
return "", false
1260+
}
1261+
switch v := stdout.(type) {
1262+
case string:
1263+
return v, true
1264+
case []any:
1265+
lines := make([]string, 0, len(v))
1266+
for _, item := range v {
1267+
lines = append(lines, fmt.Sprintf("%v", item))
1268+
}
1269+
return strings.Join(lines, "\n"), true
1270+
default:
1271+
return "", false
1272+
}
1273+
}
1274+
1275+
func applyEditFileFallback(content string, args map[string]any) (string, bool) {
1276+
oldString, _ := args["old_string"].(string)
1277+
if oldString == "" {
1278+
return content, false
1279+
}
1280+
newString, _ := args["new_string"].(string)
1281+
regexMode, _ := args["regex"].(bool)
1282+
replaceAll, _ := args["replace_all"].(bool)
1283+
1284+
if regexMode {
1285+
re, err := regexp.Compile(oldString)
1286+
if err != nil {
1287+
return content, false
1288+
}
1289+
matches := re.FindAllStringIndex(content, -1)
1290+
if len(matches) == 0 || (len(matches) > 1 && !replaceAll) {
1291+
return content, false
1292+
}
1293+
if replaceAll {
1294+
return re.ReplaceAllString(content, newString), true
1295+
}
1296+
match := matches[0]
1297+
matched := content[match[0]:match[1]]
1298+
replaced := re.ReplaceAllString(matched, newString)
1299+
return content[:match[0]] + replaced + content[match[1]:], true
1300+
}
1301+
1302+
count := strings.Count(content, oldString)
1303+
if count == 0 || (count > 1 && !replaceAll) {
1304+
return content, false
1305+
}
1306+
if replaceAll {
1307+
return strings.ReplaceAll(content, oldString, newString), true
1308+
}
1309+
return strings.Replace(content, oldString, newString, 1), true
12181310
}
12191311

12201312
// --- Distill preview/saved persistence ---
@@ -1475,11 +1567,11 @@ func buildTutorialSceneSlideshowPayload(manifestPath string) (map[string]any, er
14751567
scenes = append(scenes, row)
14761568
}
14771569
return map[string]any{
1478-
"title": title,
1479-
"suite": manifest.Suite,
1480-
"drill": manifest.Drill,
1481-
"manifest_path": manifestPath,
1482-
"scenes": scenes,
1570+
"title": title,
1571+
"suite": manifest.Suite,
1572+
"drill": manifest.Drill,
1573+
"manifest_path": manifestPath,
1574+
"scenes": scenes,
14831575
}, nil
14841576
}
14851577

‎pkg/api/csp.go‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,19 @@ import (
1919
//
2020
// printf '%s' '<script content>' | openssl dgst -sha256 -binary | base64
2121
//
22+
// wasm-unsafe-eval allows WebAssembly compilation without allowing general
23+
// JavaScript eval. The client-side DOCX exporter uses @m2d/remark-docx, whose
24+
// image preprocessing path instantiates a WASM module even for markdown reports
25+
// without user-authored images.
26+
//
2227
// media-src allows blob: so Studio can play video/audio artifacts (e.g.
2328
// browser session recordings) loaded via createObjectURL after a credentialed
2429
// fetch — a bare <video src="/api/..."> cannot send team auth headers.
2530
//
2631
// fonts.googleapis.com/fonts.gstatic.com are used by the production index.html
2732
// font link. api.github.com is used by the client-side release update check.
2833
const cspPolicy = "default-src 'self'; " +
29-
"script-src 'self' 'sha256-QPIelXUbpkDESZsTgggSaMGNOA/Le9qMm+4Wa+lXIvs='; " +
34+
"script-src 'self' 'wasm-unsafe-eval' 'sha256-QPIelXUbpkDESZsTgggSaMGNOA/Le9qMm+4Wa+lXIvs='; " +
3035
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " +
3136
"img-src 'self' data: blob:; " +
3237
"media-src 'self' blob:; " +

0 commit comments

Comments
 (0)