Skip to content

Commit 2ce038a

Browse files
feat(coderd): add open_preview chat tool
Root chats outside plan mode get open_preview. It takes a short title and exactly one of port (an existing HTTP server) or path (an HTML file or a directory with index.html, published through the workspace agent). The result records the workspace, agent name and either the port or the preview ID the agent returned, which the UI uses to build the preview app URL.
1 parent 2209295 commit 2ce038a

9 files changed

Lines changed: 358 additions & 11 deletions

File tree

‎coderd/coderd.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -945,6 +945,7 @@ func New(options *Options) *API {
945945
AlwaysEnableDebugLogs: options.DeploymentValues.AI.Chat.DebugLoggingEnabled.Value(),
946946
StreamSilenceTimeout: streamSilenceTimeout,
947947
DisableCallerSuppliedTools: options.DeploymentValues.DisableChatCallerSuppliedTools.Value(),
948+
EnablePreviews: options.AppHostname != "",
948949
Experiments: experiments,
949950
AgentConn: api.agentProvider.AgentConn,
950951
AgentInactiveDisconnectTimeout: api.AgentInactiveDisconnectTimeout,

‎coderd/workspaceapps/appurl/appurl.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,8 +148,8 @@ func (a *ApplicationURL) ChangePortProtocol(target string) ApplicationURL {
148148
return newAppURL
149149
}
150150

151-
// IsPreviewID reports whether id has the format of an agent static preview
152-
// ID, e.g. "0123abcd".
151+
// IsPreviewID reports whether id has the format of a file preview ID, e.g.
152+
// "0123abcd".
153153
func IsPreviewID(id string) bool {
154154
return previewIDRegex.MatchString(id)
155155
}

‎coderd/x/chatd/ARCHITECTURE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1174,6 +1174,7 @@ The generation goroutine supports:
11741174
- subagents (`spawn_agent`, `wait_agent`, `message_agent`, `interrupt_agent`, `list_agents`, `list_subagent_models`)
11751175
- file links
11761176
- workspace binding
1177+
<!-- TODO: document root-only open_preview tool results (registered only when a wildcard app hostname is configured) (required title, path source), daemon-lifetime file publication served by the agent API (port 4) under /api/v0/previews/{id}/, with preview IDs that the agent assigns per path, routed through `preview--<id>` and `preview--<port>` workspace app hostnames that ignore port shares, sandbox responses and reject requests from other previews, the chat-scoped preview catalog endpoint under /chats/{chat}/previews, and frontend preview activation. -->
11771178
- plan mode
11781179
- respecting model configuration
11791180
- provider-specific tools like web search and computer use

‎coderd/x/chatd/chatd.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,7 @@ type Server struct {
179179
providerAPIKeys chatprovider.ProviderAPIKeys
180180
allowBYOK bool
181181
disableCallerSuppliedTools bool
182+
enablePreviews bool
182183
oidcTokenSource mcpclient.UserOIDCTokenSource
183184
mcpHTTPClient *http.Client
184185
internalMCPServers []InternalMCPServer
@@ -1251,6 +1252,10 @@ type Config struct {
12511252

12521253
AgentCapacityUnlock AgentCapacityUnlock
12531254

1255+
// EnablePreviews registers the open_preview tool. Previews are served
1256+
// on wildcard app hostnames, so enable it only when one is configured.
1257+
EnablePreviews bool
1258+
12541259
// OIDCTokenSource resolves the calling user's OIDC access
12551260
// token for MCP servers configured with auth_type=user_oidc.
12561261
// May be nil if the deployment has no OIDC provider; servers
@@ -1355,6 +1360,7 @@ func New(ps pubsub.Pubsub, cfg Config) (*Server, error) {
13551360
providerAPIKeys: cfg.ProviderAPIKeys,
13561361
allowBYOK: allowBYOK,
13571362
disableCallerSuppliedTools: cfg.DisableCallerSuppliedTools,
1363+
enablePreviews: cfg.EnablePreviews,
13581364
oidcTokenSource: cfg.OIDCTokenSource,
13591365
mcpHTTPClient: mcpHTTPClient,
13601366
internalMCPServers: cfg.InternalMCPServers,

‎coderd/x/chatd/chatd_internal_test.go‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1337,10 +1337,9 @@ func TestTurnWorkspaceContext_StaleBindingRepair(t *testing.T) {
13371337
require.Equal(t, updatedChat, currentChat)
13381338
}
13391339

1340-
func TestTurnWorkspaceContextGetWorkspaceConnLazyValidationSwitchesWorkspaceAgent(t *testing.T) {
1340+
func TestTurnWorkspaceContextGetPreviewWorkspaceLazyValidationSwitchesWorkspaceAgent(t *testing.T) {
13411341
t.Parallel()
13421342

1343-
ctx := context.Background()
13441343
ctrl := gomock.NewController(t)
13451344
db := dbmock.NewMockStore(ctrl)
13461345
expectAgentBindingTx(db)
@@ -1362,7 +1361,7 @@ func TestTurnWorkspaceContextGetWorkspaceConnLazyValidationSwitchesWorkspaceAgen
13621361
},
13631362
}
13641363
staleAgent := database.WorkspaceAgent{ID: staleAgentID}
1365-
currentAgent := database.WorkspaceAgent{ID: currentAgentID}
1364+
currentAgent := database.WorkspaceAgent{ID: currentAgentID, Name: "main"}
13661365
updatedChat := chat
13671366
updatedChat.BuildID = uuid.NullUUID{UUID: buildID, Valid: true}
13681367
updatedChat.AgentID = uuid.NullUUID{UUID: currentAgentID, Valid: true}
@@ -1407,9 +1406,12 @@ func TestTurnWorkspaceContextGetWorkspaceConnLazyValidationSwitchesWorkspaceAgen
14071406
}
14081407
t.Cleanup(workspaceCtx.close)
14091408

1410-
gotConn, err := workspaceCtx.getWorkspaceConn(ctx)
1409+
ctx := testutil.Context(t, testutil.WaitLong)
1410+
preview, err := workspaceCtx.getPreviewWorkspace(ctx)
14111411
require.NoError(t, err)
1412-
require.Same(t, conn, gotConn)
1412+
require.Equal(t, "main", preview.AgentName)
1413+
require.Same(t, conn, preview.Conn)
1414+
require.Equal(t, workspaceID, preview.WorkspaceID)
14131415
require.Equal(t, []uuid.UUID{staleAgentID, currentAgentID}, dialed)
14141416
require.Equal(t, updatedChat, currentChat)
14151417

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
package chattool
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"path"
7+
"strings"
8+
"unicode"
9+
"unicode/utf8"
10+
11+
"charm.land/fantasy"
12+
"github.com/google/uuid"
13+
14+
"github.com/coder/coder/v2/codersdk/workspacesdk"
15+
)
16+
17+
const (
18+
maxPreviewTitleLength = 80
19+
maxPreviewURLPathLength = 2048
20+
)
21+
22+
// OpenPreviewResult is the open_preview tool result. The chat previews
23+
// endpoint decodes stored results with this type, so its JSON keys must stay
24+
// stable.
25+
type OpenPreviewResult struct {
26+
OK bool `json:"ok"`
27+
Title string `json:"title"`
28+
WorkspaceID uuid.UUID `json:"workspace_id"`
29+
AgentName string `json:"agent_name"`
30+
// Exactly one of Port or PreviewID identifies the preview on the agent.
31+
Port int32 `json:"port,omitempty"`
32+
PreviewID string `json:"preview_id,omitempty"`
33+
// Path is the file or directory a PreviewID preview serves, with symlinks
34+
// resolved.
35+
Path string `json:"path,omitempty"`
36+
// URLPath is the path and query a port preview opens at, such as
37+
// "/?folder=/home/coder". It is empty for the server's root.
38+
URLPath string `json:"url_path,omitempty"`
39+
}
40+
41+
// PreviewWorkspace binds a preview to the workspace connection used to open it.
42+
type PreviewWorkspace struct {
43+
Conn workspacesdk.AgentConn
44+
WorkspaceID uuid.UUID
45+
AgentName string
46+
}
47+
48+
// OpenPreviewOptions configures the open_preview tool.
49+
type OpenPreviewOptions struct {
50+
GetWorkspace func(context.Context) (PreviewWorkspace, error)
51+
}
52+
53+
// OpenPreviewArgs are the open_preview tool arguments.
54+
type OpenPreviewArgs struct {
55+
Title string `json:"title" description:"Short name for the preview shown in the user's preview selector, such as Docs site or Signup form. At most 80 characters."`
56+
Port *int `json:"port,omitempty" description:"Port of an existing HTTP server, between 1000 and 65535. Do not combine with path."`
57+
Path string `json:"path,omitempty" description:"Absolute workspace path to an HTML file or a directory containing index.html. Do not combine with port."`
58+
URLPath string `json:"url_path,omitempty" description:"Path and query to open on the port's server, such as /?folder=/home/coder/project. Only with port. Defaults to /."`
59+
}
60+
61+
// IsPreviewURLPath reports whether s is a path and optional query that cannot
62+
// change the origin when appended to a preview URL.
63+
func IsPreviewURLPath(s string) bool {
64+
return len(s) <= maxPreviewURLPathLength &&
65+
strings.HasPrefix(s, "/") &&
66+
!strings.HasPrefix(s, "//") &&
67+
!strings.ContainsAny(s, `\#`) &&
68+
!strings.ContainsFunc(s, unicode.IsControl)
69+
}
70+
71+
// OpenPreview returns a tool that opens a workspace preview in the user's UI.
72+
func OpenPreview(options OpenPreviewOptions) fantasy.AgentTool {
73+
return fantasy.NewAgentTool(
74+
"open_preview",
75+
"Open and select an embedded preview for the user. Pass a short title and exactly one of port or path. "+
76+
"Use port for an existing HTTP web app; this does not start the app or wait for it to be ready. "+
77+
"Add url_path to open the app at a path and query other than /, for example /?folder=/home/coder/project. "+
78+
"Use path for an HTML file or a directory containing index.html; the workspace daemon publishes the files through Coder. "+
79+
"A file publishes only that file. To include CSS, JavaScript, images, or other pages, publish their directory instead. "+
80+
"Directory contents are published, so use a dedicated output directory without secrets. Directory listing is disabled. "+
81+
"Call this again to refresh after changing static files, or to restore a preview after its server or the workspace daemon restarts. "+
82+
"Path previews last until the workspace daemon stops, and at most 64 paths can be published until it restarts.",
83+
func(ctx context.Context, args OpenPreviewArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
84+
args.Title = strings.TrimSpace(args.Title)
85+
if args.Title == "" {
86+
return fantasy.NewTextErrorResponse("title is required"), nil
87+
}
88+
if utf8.RuneCountInString(args.Title) > maxPreviewTitleLength {
89+
return fantasy.NewTextErrorResponse(fmt.Sprintf("title must be at most %d characters", maxPreviewTitleLength)), nil
90+
}
91+
92+
args.Path = strings.TrimSpace(args.Path)
93+
hasPort, hasPath := args.Port != nil, args.Path != ""
94+
if hasPort == hasPath {
95+
return fantasy.NewTextErrorResponse("provide exactly one of port or path"), nil
96+
}
97+
if hasPath {
98+
if !path.IsAbs(args.Path) {
99+
return fantasy.NewTextErrorResponse("path must be absolute"), nil
100+
}
101+
// Clean so /out/ and /out share a preview ID.
102+
args.Path = path.Clean(args.Path)
103+
}
104+
105+
// Preview hostnames match only four- or five-digit ports.
106+
var port int32
107+
if hasPort {
108+
if *args.Port < 1000 || *args.Port > 65535 {
109+
return fantasy.NewTextErrorResponse("port must be between 1000 and 65535"), nil
110+
}
111+
port = int32(*args.Port)
112+
}
113+
114+
args.URLPath = strings.TrimSpace(args.URLPath)
115+
if args.URLPath == "/" {
116+
// Store "/" as empty so it is listed as the same preview as no
117+
// URL path.
118+
args.URLPath = ""
119+
}
120+
if args.URLPath != "" && !hasPort {
121+
return fantasy.NewTextErrorResponse("url_path can only be used with port"), nil
122+
}
123+
if args.URLPath != "" && !IsPreviewURLPath(args.URLPath) {
124+
return fantasy.NewTextErrorResponse("url_path must start with a single /, contain only a path and query, and have no backslashes, fragments or control characters"), nil
125+
}
126+
127+
if options.GetWorkspace == nil {
128+
return fantasy.NewTextErrorResponse("workspace connection resolver is not configured"), nil
129+
}
130+
workspace, err := options.GetWorkspace(ctx)
131+
if err != nil {
132+
return fantasy.NewTextErrorResponse(err.Error()), nil
133+
}
134+
135+
result := OpenPreviewResult{
136+
OK: true,
137+
Title: args.Title,
138+
WorkspaceID: workspace.WorkspaceID,
139+
AgentName: workspace.AgentName,
140+
}
141+
if hasPort {
142+
result.Port = port
143+
result.URLPath = args.URLPath
144+
return marshalToolResponse(result), nil
145+
}
146+
147+
preview, err := workspace.Conn.OpenPreview(ctx, workspacesdk.OpenPreviewRequest{Path: args.Path})
148+
if err != nil {
149+
return fantasy.NewTextErrorResponse("open file preview: " + err.Error()), nil
150+
}
151+
152+
result.PreviewID = preview.ID
153+
result.Path = preview.Path
154+
return marshalToolResponse(result), nil
155+
},
156+
)
157+
}

0 commit comments

Comments
 (0)