Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions apps/console/src/lib/chat-openwork-proxy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { describe, expect, it } from 'vitest';
import {
rewriteOpenworkChatHtml,
rewriteOpenworkLocation,
} from './chat-openwork-proxy';

describe('rewriteOpenworkChatHtml', () => {
it('prefixes root-absolute assets and stamps the register impl', () => {
const html = `<!doctype html><html lang="en"><head>
<link rel="icon" href="/openwork-mark.svg" />
<script type="module" crossorigin src="/assets/app-abc.js"></script>
<link rel="stylesheet" href="/assets/index-abc.css">
</head><body></body></html>`;
const out = rewriteOpenworkChatHtml(html);
expect(out).toContain('data-register-impl="openwork.chat"');
expect(out).toContain('href="/chat/openwork-mark.svg"');
expect(out).toContain('src="/chat/assets/app-abc.js"');
expect(out).toContain('href="/chat/assets/index-abc.css"');
expect(out).not.toContain('src="/assets/');
});

it('does not double-prefix paths already under /chat', () => {
const html = `<html data-register-impl="openwork.chat"><script src="/chat/assets/x.js"></script></html>`;
expect(rewriteOpenworkChatHtml(html)).toContain('src="/chat/assets/x.js"');
expect(rewriteOpenworkChatHtml(html)).not.toContain('src="/chat/chat/');
});
Comment on lines +22 to +26
});

describe('rewriteOpenworkLocation', () => {
it('prefixes absolute redirects', () => {
expect(rewriteOpenworkLocation('/')).toBe('/chat/');
expect(rewriteOpenworkLocation('/settings')).toBe('/chat/settings');
expect(rewriteOpenworkLocation('/chat/x')).toBe('/chat/x');
});
});
43 changes: 43 additions & 0 deletions apps/console/src/lib/chat-openwork-proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/** Rewrite OpenWork HTML so root-absolute assets load under the /chat proxy prefix.
*
* The workspace Vite app emits `/assets/...` and `/favicon-...` URLs. Middleware
* only proxies `/chat/*`, so those root paths 404 on the console origin and the
* page paints blank. Prefix them with `/chat` (already forwarded upstream).
*/
export function rewriteOpenworkChatHtml(html: string): string {
let out = html.includes('data-register-impl=')
? html
: html.replace(
/<html([^>]*)>/i,
'<html$1 data-register-impl="openwork.chat">',
);

// Attribute URLs: src="/assets/x", href="/favicon.png", etc.
out = out.replace(
/\b(href|src|poster)=(["'])\/(?!\/|chat\/)/g,
'$1=$2/chat/',
Comment on lines +16 to +18

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Route OpenWork API calls through the chat proxy

This rewrite only fixes static HTML attributes, but the proxied OpenWork bundle still derives its server base from window.location.origin: resolveOpenworkConnection() falls back to the bare origin in apps/chat/src/react-app/shell/openwork-connection.ts lines 92 to 95, and createOpenworkServerClient() then calls root paths such as /workspaces in apps/chat/src/app/lib/openwork-server.ts line 1339. Because this middleware only proxies /chat/*, those runtime requests hit the Next console origin instead of the workspace and the loaded UI cannot list workspaces or sessions. Inject or rewrite the OpenWork base to /chat (or proxy the required root API paths) along with the asset URLs.

Useful? React with 👍 / 👎.

);
Comment on lines +16 to +19

// Inline modulepreload / import maps occasionally use content URLs.
out = out.replace(
/\b(url)\((["']?)\/(?!\/|chat\/)/g,
'$1($2/chat/',
);

return out;
}

export function rewriteOpenworkLocation(location: string | null): string | null {
if (!location) return location;
if (location.startsWith('/chat/') || location === '/chat') return location;
if (location.startsWith('/')) return `/chat${location === '/' ? '/' : location}`;
try {
const url = new URL(location);
if (!url.pathname.startsWith('/chat')) {
url.pathname = `/chat${url.pathname === '/' ? '/' : url.pathname}`;
}
Comment on lines +35 to +38
return url.toString();
Comment on lines +35 to +39

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Keep workspace redirects on the console proxy.

A full upstream redirect such as https://workspace.example/settings becomes https://workspace.example/chat/settings. At apps/console/src/middleware.ts, Lines 68-70 forward that URL to the browser. The browser leaves the console origin instead of requesting /chat/settings, so the console-scoped cookie cannot support the redirected request.

Pass the workspace origin to this helper. For a full URL with that origin, return /chat${pathname}${search}${hash}. Preserve third-party and non-HTTP URLs. Also parse the pathname before testing the prefix so /chat?tab=x is not double-prefixed and /chatty is not treated as /chat.

Add coverage for a full workspace URL, an external OAuth URL, query and fragment preservation, and /chat?tab=x.

Proposed fix
-export function rewriteOpenworkLocation(location: string | null): string | null {
+export function rewriteOpenworkLocation(
+  location: string | null,
+  workspace: string,
+): string | null {
   if (!location) return location;
+  if (location.startsWith('//')) return location;
   if (location.startsWith('/chat/') || location === '/chat') return location;
   if (location.startsWith('/')) return `/chat${location === '/' ? '/' : location}`;
   try {
     const url = new URL(location);
-    if (!url.pathname.startsWith('/chat')) {
-      url.pathname = `/chat${url.pathname === '/' ? '/' : url.pathname}`;
-    }
-    return url.toString();
+    if (url.origin !== new URL(workspace).origin) return location;
+    if (url.pathname === '/chat' || url.pathname.startsWith('/chat/')) {
+      return `${url.pathname}${url.search}${url.hash}`;
+    }
+    return `/chat${url.pathname === '/' ? '/' : url.pathname}${url.search}${url.hash}`;
   } catch {
     return location;
   }
 }
- rewriteOpenworkLocation(location)
+ rewriteOpenworkLocation(location, WORKSPACE)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/console/src/lib/chat-openwork-proxy.ts` around lines 35 - 39, Update the
URL helper around the existing pathname-prefix logic to accept the workspace
origin and convert same-origin full HTTP(S) URLs into relative
`/chat${pathname}${search}${hash}` redirects. Parse pathname independently
before checking the prefix, preserving `/chat?tab=x` unchanged and avoiding
matches such as `/chatty`; leave third-party and non-HTTP URLs untouched. Add
coverage for same-origin workspace redirects, external OAuth URLs,
query/fragment preservation, and the `/chat?tab=x` case.

Comment on lines +35 to +39

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Return proxied absolute redirects to the console origin

When the workspace responds with an absolute Location, this code keeps that upstream origin and only changes the path. In production CONSOLE_WORKSPACE_URL can be a private/internal Railway host, so a redirect like http://commonplace-workspace.railway.internal/settings would be sent to the browser as http://commonplace-workspace.railway.internal/chat/settings, bypassing the console origin and failing for users; external absolute redirects are also mutated. For proxied redirects, same-upstream absolute locations should become console-relative /chat..., while other origins should be left alone.

Useful? React with 👍 / 👎.

} catch {
return location;
}
}
21 changes: 14 additions & 7 deletions apps/console/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { NextRequest, NextResponse } from 'next/server';
import {
rewriteOpenworkChatHtml,
rewriteOpenworkLocation,
} from '@/lib/chat-openwork-proxy';

// SOURCING: none. SPEC-COMMONPLACE-PRODUCTION-CUTOVER-1.0 GL6 / OW4.
// When CONSOLE_WORKSPACE_URL is set, /chat is reverse-proxied to the workspace
// chat door with the /chat prefix stripped. Cookie stays on the console origin.
// NextResponse.rewrite cannot target an arbitrary external origin here, so this
// is an explicit fetch proxy.
// is an explicit fetch proxy. HTML root-absolute asset URLs are rewritten under
// /chat so Vite bundles do not 404 on the console origin (blank OpenWork page).

const WORKSPACE = process.env.CONSOLE_WORKSPACE_URL?.replace(/\/$/, '') ?? '';

Expand Down Expand Up @@ -60,14 +65,16 @@ export async function middleware(request: NextRequest) {
const responseHeaders = new Headers(upstream.headers);
responseHeaders.set('x-register-impl', 'openwork.chat');

const location = upstream.headers.get('location');
if (location) {
responseHeaders.set('location', rewriteOpenworkLocation(location) ?? location);
}

if (upstreamContentType.includes('text/html')) {
const html = await upstream.text();
const stamped = html.includes('data-register-impl=')
? html
: html.replace(
/<html([^>]*)>/i,
'<html$1 data-register-impl="openwork.chat">',
);
const stamped = rewriteOpenworkChatHtml(html);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep OpenWork routing under the /chat mount

When this serves the rewritten OpenWork HTML at /chat, only the asset URLs are moved under the proxy prefix. I checked the proxied app: it mounts a plain BrowserRouter with no basename in apps/chat/src/index.react.tsx lines 40 and 48, and its wildcard route redirects unknown paths to /session in apps/chat/src/react-app/shell/app-root.tsx lines 289 to 290. As soon as the now-loadable bundle runs on /chat, it matches the wildcard and navigates the browser to console-root /session, outside this middleware, so /chat still will not stay on the OpenWork UI. Configure a /chat basename or otherwise rewrite the route base along with the assets.

Useful? React with 👍 / 👎.

// Content-Length from upstream is stale after rewrite.
responseHeaders.delete('content-length');
return new NextResponse(stamped, {
status: upstream.status,
headers: responseHeaders,
Expand Down
Loading