@el4cteo/rbx-studio-mcp 0.3.5 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,386 +1,552 @@
1
- --!strict
2
- --[[
3
- rbx-studio -- plugin entry point.
4
-
5
- Owns the toolbar UI, this window's Studio identity, and the command loop.
6
- Handlers do the actual work; this file only wires them to the transport and
7
- reports what is happening to the console widget.
8
- ]]
9
-
10
- local HttpService = game:GetService("HttpService")
11
- local RunService = game:GetService("RunService")
12
-
13
- local Config = require(script.Config)
14
- local Console = require(script.Console)
15
- local Dispatch = require(script.Dispatch)
16
- local LogBuffer = require(script.LogBuffer)
17
- local Phrase = require(script.Phrase)
18
- local Themes = require(script.Themes)
19
- local Transport = require(script.Transport)
20
- local Debug = require(script.handlers.Debug)
21
- local Assets = require(script.handlers.Assets)
22
- local Capture = require(script.handlers.Capture)
23
- local Character = require(script.handlers.Character)
24
- local Geometry = require(script.handlers.Geometry)
25
- local World = require(script.handlers.World)
26
- local Discover = require(script.handlers.Discover)
27
- local Exec = require(script.handlers.Exec)
28
- local Instances = require(script.handlers.Instances)
29
- local Perf = require(script.handlers.Perf)
30
- local Playtest = require(script.handlers.Playtest)
31
- local Viewport = require(script.handlers.Viewport)
32
- local Input = require(script.handlers.Input)
33
- local Device = require(script.handlers.Device)
34
- local Api = require(script.handlers.Api)
35
- local Scripts = require(script.handlers.Scripts)
36
- local Session = require(script.handlers.Session)
37
-
38
- local SETTING_PORT = "port"
39
- local SETTING_AUTOCONNECT = "autoConnect"
40
- local SETTING_FORCE_POLL = "forcePoll"
41
- local SETTING_THEME = "theme"
42
-
43
- --[[
44
- A fresh id per plugin load, which in practice means one per Studio window.
45
-
46
- This was originally persisted with `plugin:SetSetting`, on the reasoning that a
47
- stable id keeps reconnects mapping to the same session. That is wrong as soon
48
- as the user opens a second window: plugin settings live in one file shared by
49
- every Studio process, so both windows announce the same id, and the server
50
- treats the second connection as the first one reconnecting -- closing the
51
- original stream and making it impossible to address the two places separately.
52
-
53
- Held in memory instead. A reconnect within one load (the SSE stream hits its
54
- 30-minute cap) reuses this id, and `plugin.Unloading` detaches cleanly on
55
- reload, so ghost entries do not accumulate.
56
- ]]
57
- local SESSION_ID = HttpService:GenerateGUID(false)
58
-
59
- local function studioId(): string
60
- return SESSION_ID
61
- end
62
-
63
- --[[
64
- Whether this copy of the plugin can reach the bridge at all.
65
-
66
- Pressing Play loads the plugin into the playtest's DataModels as well as the
67
- editor's, and HttpService refuses every request from a client one: "Http
68
- requests can only be executed by game server". The transport read that as a
69
- dropped connection and retried forever, filling the console with red while
70
- nothing was actually wrong.
71
-
72
- The editor session and the play session's server can both connect and are
73
- worth connecting -- addressing a running server is useful. The client half
74
- simply says so once and stops.
75
- ]]
76
- local function canConnect(): (boolean, string?)
77
- if RunService:IsEdit() or RunService:IsServer() then
78
- return true, nil
79
- end
80
- --[[
81
- The wording names the fix, because the symptom is indistinguishable
82
- from a broken server: a user watching this window during a playtest
83
- sees a console that logs nothing while tools plainly work, and has no
84
- way to guess that the activity is in a different view of the same
85
- Studio. Reported once here and again as the strip's caption, since
86
- one line scrolled off the top is easy to miss.
87
- ]]
88
- return false,
89
- "client view of a playtest -- Studio forbids client sessions from making HTTP "
90
- .. "requests. The playtest's server session is connected and handling this "
91
- .. "place; switch Studio to the Server view (Test tab, Current: Server) to "
92
- .. "watch it work."
93
- end
94
-
95
- -- First thing, before any handler or the transport can log: the buffer only
96
- -- holds what was printed after it subscribed, so every line ahead of this call
97
- -- is unrecoverable. This runs even in a client session that will never connect,
98
- -- since the console tool reads it and connectivity is a separate question.
99
- LogBuffer.start()
100
-
101
- local storedPort = plugin:GetSetting(SETTING_PORT)
102
- if typeof(storedPort) == "number" then
103
- Config.setPort(storedPort)
104
- end
105
-
106
- Transport.setForcePoll(plugin:GetSetting(SETTING_FORCE_POLL) == true)
107
-
108
- --[[
109
- The console's colour preset, restored before anything is drawn.
110
-
111
- Applied here rather than after mounting so the panel is built in the right
112
- palette from the start -- restoring it afterwards would flash the default
113
- theme for a frame on every Studio launch. An unknown id (a preset renamed,
114
- or a setting written by a newer build) falls back to the default rather than
115
- failing, which is `Themes.get`'s job.
116
- ]]
117
- local storedTheme = plugin:GetSetting(SETTING_THEME)
118
- if typeof(storedTheme) == "string" then
119
- Themes.use(storedTheme)
120
- end
121
-
122
- Session.register()
123
- Discover.register()
124
- Debug.register()
125
- Instances.register()
126
- Perf.register(plugin)
127
- Playtest.register()
128
- Capture.register()
129
- Assets.register()
130
- Character.register()
131
- Geometry.register()
132
- World.register()
133
- Exec.register()
134
- Viewport.register()
135
- Scripts.register()
136
- Input.register()
137
- Device.register()
138
- Api.register()
139
-
140
- --[[
141
- The toolbar button.
142
-
143
- The icon has to be an uploaded asset: `CreateButton` takes a content string,
144
- and the only ones Studio resolves are `rbxassetid://` for uploaded images and
145
- `rbxasset://` for files that ship inside Studio itself. A path to something in
146
- this repository is not one of them, which is why the mark in `assets/` has to
147
- go through an upload before it can appear here.
148
-
149
- It used to borrow `textures/ui/common/robux.png` -- a Robux coin, sitting in
150
- the toolbar next to a plugin that has nothing to do with purchases.
151
- ]]
152
- local toolbar = plugin:CreateToolbar("rbx-studio")
153
- local button = toolbar:CreateButton(
154
- "rbx-studio",
155
- "Show the rbx-studio console",
156
- "rbxassetid://125390773465346"
157
- )
158
- button.ClickableWhenViewportHidden = true
159
-
160
- -- Enabled by default: the whole point is that opening a place shows you it
161
- -- connected without touching anything. Studio remembers the user's choice after
162
- -- the first time they close it.
163
- local widget = plugin:CreateDockWidgetPluginGuiAsync(
164
- "StudioMCP_Console",
165
- DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Float, true, false, 560, 320, 360, 200)
166
- )
167
- widget.Title = "rbx-studio"
168
-
169
- local currentStatus: Transport.Status = "disconnected"
170
-
171
- local function refreshMeta()
172
- Console.setStatus(
173
- currentStatus,
174
- string.format(
175
- "127.0.0.1:%d %s build %s",
176
- Config.getPort(),
177
- Transport.getMode(),
178
- Config.BUILD_ID
179
- )
180
- )
181
- button:SetActive(currentStatus == "connected")
182
- end
183
-
184
- local connect: () -> ()
185
-
186
- Console.mount(widget, {
187
- onReconnect = function()
188
- Console.log("info", "reconnect requested")
189
- Transport.stop()
190
- task.wait(0.2)
191
- connect()
192
- end,
193
- onClear = function()
194
- Console.clear()
195
- end,
196
- onTheme = function(id)
197
- plugin:SetSetting(SETTING_THEME, id)
198
- Console.log("dim", string.format("theme: %s", id))
199
- end,
200
- })
201
-
202
- Console.log("info", string.format("rbx-studio v%s", Config.PLUGIN_VERSION), "build " .. Config.BUILD_ID)
203
- Console.log("dim", string.format("place: %s (%d)", game.Name, game.PlaceId))
204
-
205
- local function onStatus(status: Transport.Status, detail: string?)
206
- local previous = currentStatus
207
- currentStatus = status
208
- refreshMeta()
209
-
210
- -- Only narrate transitions. The transport re-reports its state on every
211
- -- reconnect attempt, and echoing an unchanged status would bury real events.
212
- if status == previous and detail == nil then
213
- return
214
- end
215
-
216
- if status == "connected" then
217
- Console.log(
218
- "ok",
219
- string.format("connected to 127.0.0.1:%d", Config.getPort()),
220
- if detail then "(" .. detail .. ")" else nil
221
- )
222
- elseif status == "connecting" then
223
- Console.log("dim", string.format("connecting to 127.0.0.1:%d...", Config.getPort()))
224
- else
225
- Console.log("error", "disconnected", detail)
226
- end
227
- end
228
-
229
- --[[
230
- Runs each command on its own task. Handlers may yield -- `UpdateSourceAsync`
231
- and any `*Async` call does -- and serialising them would let one slow edit
232
- stall every other request on the stream.
233
- ]]
234
- local function onCommand(id: string, op: string, params: { [string]: any }?)
235
- task.spawn(function()
236
- local startedAt = os.clock()
237
- --[[
238
- Named for what it does, not for how it travels. `script.edit` on
239
- ServerScriptService.Systems.KillBrick reads as "Edit KillBrick",
240
- which is the thing someone watching actually wants to know; the wire
241
- name is kept alongside so the log still maps onto the protocol when
242
- something needs debugging.
243
- ]]
244
- local title = Phrase.of(op, params)
245
- --[[
246
- Announced synchronously, unlike the logging below.
247
-
248
- Deferring this looked like free latency and was not. `beginCall` sets
249
- two labels and some fields -- it never touches the RichText log, which
250
- is where the cost actually is -- and deferring it let a call that
251
- finished inside one frame record its result before the call had been
252
- announced, so the bar on the trace lost the name it was supposed to
253
- carry. A microsecond is not worth an ordering hazard.
254
- ]]
255
- Console.beginCall(title, Phrase.kindOf(op))
256
-
257
- local result = Dispatch.invoke(id, op, params)
258
- local milliseconds = (os.clock() - startedAt) * 1000
259
-
260
- --[[
261
- The answer goes out before the console hears about it.
262
-
263
- This used to be the last line of the function, which put a
264
- `table.concat` of three hundred strings, a RichText relayout of the
265
- whole log, two `Instance.new` calls and a forty-bar relayout in front
266
- of the reply on its way back to the agent. None of that is work the
267
- caller asked for, and all of it was being billed to the round trip
268
- this project measures. Drawing happens below, on time the agent is no
269
- longer waiting for.
270
- ]]
271
- Transport.sendResult(result)
272
-
273
- local elapsed = string.format("%.0fms", milliseconds)
274
- Console.recordCall(result.ok, milliseconds)
275
-
276
- if result.ok then
277
- Console.log("reply", title, elapsed)
278
- else
279
- local err = result.error
280
- Console.log(
281
- "error",
282
- string.format("%s failed: %s", title, if err then err.code else "unknown"),
283
- elapsed
284
- )
285
- if err and err.message then
286
- Console.log("dim", " " .. err.message)
287
- end
288
- end
289
- end)
290
- end
291
-
292
- --[[
293
- Bridge news that is not a command.
294
-
295
- Kept deliberately narrow: an unknown event is ignored rather than logged,
296
- because a newer server talking to an older plugin is a supported situation
297
- and "unknown event" rows would be the only symptom of it working correctly.
298
- ]]
299
- local function onEvent(event: { [string]: any })
300
- if event.event == "clients" and typeof(event.count) == "number" then
301
- Console.setClients(event.count)
302
- elseif event.event == "agent" and event.state == "finished" then
303
- Console.agentFinished()
304
- end
305
- end
306
-
307
- function connect()
308
- local allowed, reason = canConnect()
309
- if not allowed then
310
- -- Reported as standby rather than an error: nothing failed, and this
311
- -- session was never going to connect.
312
- currentStatus = "disconnected"
313
- Console.log("dim", "standby", reason)
314
- Console.setStatus(
315
- "standby",
316
- string.format("%s build %s", "client view", Config.BUILD_ID)
317
- )
318
- Console.setCaption("switch to the Server view to watch this playtest")
319
- return
320
- end
321
- Transport.start(studioId(), { onCommand = onCommand, onStatus = onStatus, onEvent = onEvent })
322
- plugin:SetSetting(SETTING_AUTOCONNECT, true)
323
- end
324
-
325
- button.Click:Connect(function()
326
- widget.Enabled = not widget.Enabled
327
- end)
328
-
329
- plugin.Unloading:Connect(function()
330
- Transport.stop()
331
- end)
332
-
333
- --[[
334
- Switches this session between the push and long-poll transports.
335
-
336
- Registered here rather than in a handler module because it is the only
337
- command that has to reach back into the plugin object and the connection
338
- loop, both of which live in this file -- and registered THIS far down the
339
- file on purpose: `connect` is a forward-declared local, so a closure written
340
- above its declaration captures the global of that name instead, which is nil.
341
- That cost a session. The plugin loaded and connected perfectly, and then died
342
- the first time somebody asked it to switch transport.
343
-
344
- The reply is sent before the reconnect, and the reconnect is deferred:
345
- tearing the stream down inside the handler would strand the answer to the
346
- very call that asked for the switch, which is a confusing way to succeed.
347
- ]]
348
- Dispatch.registerAll("studio", {
349
- transport = function(params: { [string]: any }): { [string]: any }
350
- local requested = params.mode
351
- if requested ~= nil and requested ~= "sse" and requested ~= "poll" then
352
- Dispatch.fail("BAD_PARAMS", 'transport mode must be "sse" or "poll".')
353
- end
354
- if requested == nil then
355
- return { mode = Transport.getMode(), forcePoll = Transport.getForcePoll(), changed = false }
356
- end
357
-
358
- local wantPoll = requested == "poll"
359
- if Transport.getMode() == requested and Transport.getForcePoll() == wantPoll then
360
- return { mode = Transport.getMode(), forcePoll = wantPoll, changed = false }
361
- end
362
-
363
- Transport.setForcePoll(wantPoll)
364
- plugin:SetSetting(SETTING_FORCE_POLL, wantPoll)
365
- task.defer(function()
366
- Transport.stop()
367
- task.wait(0.1)
368
- connect()
369
- end)
370
- return {
371
- mode = requested,
372
- forcePoll = wantPoll,
373
- changed = true,
374
- note = "Reconnecting on the new transport; the next call will use it.",
375
- }
376
- end,
377
- })
378
-
379
- refreshMeta()
380
-
381
- -- Connect on load unless the user explicitly disconnected last session.
382
- if plugin:GetSetting(SETTING_AUTOCONNECT) ~= false then
383
- connect()
384
- else
385
- Console.log("warn", "auto-connect disabled — press reconnect to start")
386
- end
1
+ --!strict
2
+ --[[
3
+ rbx-studio -- plugin entry point.
4
+
5
+ Owns the toolbar UI, this window's Studio identity, and the command loop.
6
+ Handlers do the actual work; this file only wires them to the transport and
7
+ reports what is happening to the console widget.
8
+ ]]
9
+
10
+ local HttpService = game:GetService("HttpService")
11
+ local RunService = game:GetService("RunService")
12
+
13
+ local Config = require(script.Config)
14
+ local Console = require(script.Console)
15
+ local Dispatch = require(script.Dispatch)
16
+ local LogBuffer = require(script.LogBuffer)
17
+ local Mirror = require(script.Mirror)
18
+ local Phrase = require(script.Phrase)
19
+ local Themes = require(script.Themes)
20
+ local Transport = require(script.Transport)
21
+ local Debug = require(script.handlers.Debug)
22
+ local Assets = require(script.handlers.Assets)
23
+ local Capture = require(script.handlers.Capture)
24
+ local Character = require(script.handlers.Character)
25
+ local Geometry = require(script.handlers.Geometry)
26
+ local World = require(script.handlers.World)
27
+ local Discover = require(script.handlers.Discover)
28
+ local Exec = require(script.handlers.Exec)
29
+ local Instances = require(script.handlers.Instances)
30
+ local Perf = require(script.handlers.Perf)
31
+ local Playtest = require(script.handlers.Playtest)
32
+ local Viewport = require(script.handlers.Viewport)
33
+ local Input = require(script.handlers.Input)
34
+ local Device = require(script.handlers.Device)
35
+ local Api = require(script.handlers.Api)
36
+ local Scripts = require(script.handlers.Scripts)
37
+ local Session = require(script.handlers.Session)
38
+
39
+ local SETTING_PORT = "port"
40
+ local SETTING_AUTOCONNECT = "autoConnect"
41
+ local SETTING_FORCE_POLL = "forcePoll"
42
+ local SETTING_THEME = "theme"
43
+ local SETTING_WIDGET_OPEN = "widgetOpen"
44
+ local SETTING_WIDGET_SIZE = "widgetSize"
45
+
46
+ --[[
47
+ A fresh id per plugin load, which in practice means one per Studio window.
48
+
49
+ This was originally persisted with `plugin:SetSetting`, on the reasoning that a
50
+ stable id keeps reconnects mapping to the same session. That is wrong as soon
51
+ as the user opens a second window: plugin settings live in one file shared by
52
+ every Studio process, so both windows announce the same id, and the server
53
+ treats the second connection as the first one reconnecting -- closing the
54
+ original stream and making it impossible to address the two places separately.
55
+
56
+ Held in memory instead. A reconnect within one load (the SSE stream hits its
57
+ 30-minute cap) reuses this id, and `plugin.Unloading` detaches cleanly on
58
+ reload, so ghost entries do not accumulate.
59
+ ]]
60
+ local SESSION_ID = HttpService:GenerateGUID(false)
61
+
62
+ local function studioId(): string
63
+ return SESSION_ID
64
+ end
65
+
66
+ --[[
67
+ Whether this copy of the plugin can reach the bridge at all.
68
+
69
+ Pressing Play loads the plugin into the playtest's DataModels as well as the
70
+ editor's, and HttpService refuses every request from a client one: "Http
71
+ requests can only be executed by game server". The transport read that as a
72
+ dropped connection and retried forever, filling the console with red while
73
+ nothing was actually wrong.
74
+
75
+ The editor session and the play session's server can both connect and are
76
+ worth connecting -- addressing a running server is useful. The client half
77
+ simply says so once and stops.
78
+ ]]
79
+ local function canConnect(): (boolean, string?)
80
+ if RunService:IsEdit() or RunService:IsServer() then
81
+ return true, nil
82
+ end
83
+ --[[
84
+ The wording names the fix, because the symptom is indistinguishable
85
+ from a broken server: a user watching this window during a playtest
86
+ sees a console that logs nothing while tools plainly work, and has no
87
+ way to guess that the activity is in a different view of the same
88
+ Studio. Reported once here and again as the strip's caption, since
89
+ one line scrolled off the top is easy to miss.
90
+ ]]
91
+ return false,
92
+ "client view of a playtest -- Studio forbids client sessions from making HTTP "
93
+ .. "requests, so this panel cannot reach the bridge itself. It is MIRRORING "
94
+ .. "the playtest's server session instead, so the log and the strip below "
95
+ .. "are live. Switch to the Server view (Test tab, Current: Server) for the "
96
+ .. "session that is actually connected."
97
+ end
98
+
99
+ -- First thing, before any handler or the transport can log: the buffer only
100
+ -- holds what was printed after it subscribed, so every line ahead of this call
101
+ -- is unrecoverable. This runs even in a client session that will never connect,
102
+ -- since the console tool reads it and connectivity is a separate question.
103
+ LogBuffer.start()
104
+
105
+ local storedPort = plugin:GetSetting(SETTING_PORT)
106
+ if typeof(storedPort) == "number" then
107
+ Config.setPort(storedPort)
108
+ end
109
+
110
+ Transport.setForcePoll(plugin:GetSetting(SETTING_FORCE_POLL) == true)
111
+
112
+ --[[
113
+ The console's colour preset, restored before anything is drawn.
114
+
115
+ Applied here rather than after mounting so the panel is built in the right
116
+ palette from the start -- restoring it afterwards would flash the default
117
+ theme for a frame on every Studio launch. An unknown id (a preset renamed,
118
+ or a setting written by a newer build) falls back to the default rather than
119
+ failing, which is `Themes.get`'s job.
120
+ ]]
121
+ local storedTheme = plugin:GetSetting(SETTING_THEME)
122
+ if typeof(storedTheme) == "string" then
123
+ Themes.use(storedTheme)
124
+ end
125
+
126
+ --[[
127
+ Whether the restore above still has to be pushed into the console.
128
+
129
+ `Themes.use` moves the ACTIVE ID, and anything that reads the palette live
130
+ picks the change up for free -- which is why the prism cell came back on the
131
+ saved preset. `Console` does not read it live: it caches the palette in an
132
+ upvalue at module load, deliberately, so that forty read sites stay plain
133
+ field accesses. Module load happens at the `require` above, which is BEFORE
134
+ this line, so the cache held the default while the id said otherwise, and a
135
+ reload came back as the saved prism drawn in the default's colours.
136
+
137
+ It cannot simply be applied here either -- the console is not mounted yet.
138
+ So it is remembered and applied the moment it can be, right after mounting.
139
+ ]]
140
+ local themeNeedsApplying = typeof(storedTheme) == "string" and Themes.activeId() == storedTheme
141
+
142
+ Session.register()
143
+ Discover.register()
144
+ Debug.register()
145
+ Instances.register()
146
+ Perf.register(plugin)
147
+ Playtest.register()
148
+ Capture.register()
149
+ Assets.register()
150
+ Character.register()
151
+ Geometry.register()
152
+ World.register()
153
+ Exec.register()
154
+ Viewport.register()
155
+ Scripts.register()
156
+ Input.register()
157
+ Device.register()
158
+ Api.register()
159
+
160
+ --[[
161
+ The toolbar button.
162
+
163
+ The icon has to be an uploaded asset: `CreateButton` takes a content string,
164
+ and the only ones Studio resolves are `rbxassetid://` for uploaded images and
165
+ `rbxasset://` for files that ship inside Studio itself. A path to something in
166
+ this repository is not one of them, which is why the mark in `assets/` has to
167
+ go through an upload before it can appear here.
168
+
169
+ It used to borrow `textures/ui/common/robux.png` -- a Robux coin, sitting in
170
+ the toolbar next to a plugin that has nothing to do with purchases.
171
+ ]]
172
+ local toolbar = plugin:CreateToolbar("rbx-studio")
173
+ local button = toolbar:CreateButton(
174
+ "rbx-studio",
175
+ "Show the rbx-studio console",
176
+ "rbxassetid://125390773465346"
177
+ )
178
+ button.ClickableWhenViewportHidden = true
179
+
180
+ --[[
181
+ The panel, opened and sized the way the user last left it -- in EVERY
182
+ DataModel, which is the whole point.
183
+
184
+ Pressing Play loads this plugin again into the playtest's DataModels, and a
185
+ dock widget belongs to the DataModel that created it: the editor's is hidden
186
+ along with the editor's view, and the playtest's is a brand new widget that
187
+ Studio brings up closed and at the default size. So the panel vanished on
188
+ every playtest and came back, when the user re-opened it from the toolbar,
189
+ as a 560x320 float with whatever size they had chosen thrown away.
190
+
191
+ Studio's own restore does not cross that boundary, so the preference is kept
192
+ here instead and passed in as the INITIAL state, with `overrideEnabledRestore`
193
+ set so it is honoured rather than second-guessed. Written only from the
194
+ editor session -- see below -- so a playtest starting or ending can never
195
+ record a decision the user did not make.
196
+ ]]
197
+ local storedOpen = plugin:GetSetting(SETTING_WIDGET_OPEN)
198
+ local wantOpen = if typeof(storedOpen) == "boolean" then storedOpen else true
199
+
200
+ local floatWidth, floatHeight = 560, 320
201
+ local storedSize = plugin:GetSetting(SETTING_WIDGET_SIZE)
202
+ if typeof(storedSize) == "table" then
203
+ local saved = storedSize :: { [string]: any }
204
+ local x, y = tonumber(saved.x), tonumber(saved.y)
205
+ -- Guarded against nonsense: a zero or absurd size saved from a docked or
206
+ -- mid-teardown widget would otherwise be unrecoverable without clearing
207
+ -- settings by hand.
208
+ if x ~= nil and y ~= nil and x >= 360 and y >= 200 and x <= 4000 and y <= 4000 then
209
+ floatWidth, floatHeight = math.floor(x), math.floor(y)
210
+ end
211
+ end
212
+
213
+ local widget = plugin:CreateDockWidgetPluginGuiAsync(
214
+ "StudioMCP_Console",
215
+ DockWidgetPluginGuiInfo.new(
216
+ Enum.InitialDockState.Float,
217
+ wantOpen,
218
+ -- Override Studio's own enabled-restore: ours is the one that survives
219
+ -- the hop into a playtest DataModel, and two restores disagreeing is
220
+ -- what produced a panel that was open in the editor and closed in play.
221
+ true,
222
+ floatWidth,
223
+ floatHeight,
224
+ 360,
225
+ 200
226
+ )
227
+ )
228
+ widget.Title = "rbx-studio"
229
+
230
+ --[[
231
+ Remember what the user does with the panel, from the editor only.
232
+
233
+ The editor session is the one whose Enabled and size changes are actually
234
+ the user's: a playtest DataModel's widget is created, shown and destroyed by
235
+ Studio around the test, and letting those transitions write would persist a
236
+ "closed" the user never asked for -- reintroducing the bug through the back
237
+ door.
238
+ ]]
239
+ if RunService:IsEdit() then
240
+ local unloading = false
241
+ plugin.Unloading:Connect(function()
242
+ unloading = true
243
+ end)
244
+
245
+ widget:GetPropertyChangedSignal("Enabled"):Connect(function()
246
+ if not unloading then
247
+ plugin:SetSetting(SETTING_WIDGET_OPEN, widget.Enabled)
248
+ end
249
+ end)
250
+
251
+ -- Only a real, sane size, and only while the panel is up: a hidden or
252
+ -- collapsing widget reports sizes that are not a choice.
253
+ local function persistSize(): boolean
254
+ local size = widget.AbsoluteSize
255
+ if unloading or not widget.Enabled or size.X < 360 or size.Y < 200 then
256
+ return false
257
+ end
258
+ plugin:SetSetting(SETTING_WIDGET_SIZE, { x = math.floor(size.X), y = math.floor(size.Y) })
259
+ return true
260
+ end
261
+
262
+ widget:GetPropertyChangedSignal("AbsoluteSize"):Connect(persistSize)
263
+
264
+ --[[
265
+ Seed from the size Studio has already restored, rather than waiting for
266
+ a resize that may never come.
267
+
268
+ Without this the setting stays empty until the user happens to drag the
269
+ panel's edge, so the first playtest inherits the 560x320 default and the
270
+ window visibly shrinks -- which is the same complaint as it vanishing,
271
+ one step later. Studio settles the geometry a few frames after the widget
272
+ is created and fires no change event for it, so it is polled briefly and
273
+ then left alone.
274
+ ]]
275
+ task.defer(function()
276
+ for _ = 1, 40 do
277
+ if persistSize() then
278
+ return
279
+ end
280
+ task.wait(0.1)
281
+ end
282
+ end)
283
+ end
284
+
285
+ local currentStatus: Transport.Status = "disconnected"
286
+
287
+ local function refreshMeta()
288
+ Console.setStatus(
289
+ currentStatus,
290
+ string.format(
291
+ "127.0.0.1:%d %s build %s",
292
+ Config.getPort(),
293
+ Transport.getMode(),
294
+ Config.BUILD_ID
295
+ )
296
+ )
297
+ button:SetActive(currentStatus == "connected")
298
+ end
299
+
300
+ local connect: () -> ()
301
+
302
+ Console.mount(widget, {
303
+ onReconnect = function()
304
+ Console.log("info", "reconnect requested")
305
+ Transport.stop()
306
+ task.wait(0.2)
307
+ connect()
308
+ end,
309
+ onClear = function()
310
+ Console.clear()
311
+ end,
312
+ onTheme = function(id)
313
+ plugin:SetSetting(SETTING_THEME, id)
314
+ Console.log("dim", string.format("theme: %s", id))
315
+ end,
316
+ })
317
+
318
+ -- The saved preset, now that there is something to paint. Done immediately
319
+ -- after mounting and before the first line is logged, so nothing is ever drawn
320
+ -- in the wrong palette.
321
+ if themeNeedsApplying then
322
+ Console.applyTheme()
323
+ end
324
+
325
+ --[[
326
+ The playtest halves, joined.
327
+
328
+ The server half can reach the bridge and sees every command; the client half
329
+ is the one Studio actually shows during a playtest and can reach nothing. So
330
+ the server relays its console events and the client replays them, which is
331
+ the only way the panel in front of the user reacts to the work being done.
332
+
333
+ Note which side sets the observer: only the SERVER. The client replays
334
+ events through the same `Console` functions, and if it were also observing
335
+ it would echo each one straight back into the channel.
336
+ ]]
337
+ if Mirror.isPlaytestServer() then
338
+ Mirror.startServer()
339
+ Console.setObserver(function(kind, arguments)
340
+ Mirror.send(kind, arguments)
341
+ end)
342
+ elseif Mirror.isPlaytestClient() then
343
+ Console.setMirroring(true)
344
+ Mirror.startClient(function(kind, arguments)
345
+ if kind == "log" then
346
+ local level, message, detail = arguments[1], arguments[2], arguments[3]
347
+ if typeof(level) == "string" and typeof(message) == "string" then
348
+ Console.log(
349
+ level :: any,
350
+ message,
351
+ if typeof(detail) == "string" then detail else nil
352
+ )
353
+ end
354
+ elseif kind == "beginCall" then
355
+ local title, callKind = arguments[1], arguments[2]
356
+ if typeof(title) == "string" and typeof(callKind) == "string" then
357
+ Console.beginCall(title, callKind)
358
+ end
359
+ elseif kind == "recordCall" then
360
+ local ok, milliseconds = arguments[1], arguments[2]
361
+ if typeof(ok) == "boolean" and typeof(milliseconds) == "number" then
362
+ Console.recordCall(ok, milliseconds)
363
+ end
364
+ end
365
+ end)
366
+ end
367
+
368
+ Console.log("info", string.format("rbx-studio v%s", Config.PLUGIN_VERSION), "build " .. Config.BUILD_ID)
369
+ Console.log("dim", string.format("place: %s (%d)", game.Name, game.PlaceId))
370
+
371
+ local function onStatus(status: Transport.Status, detail: string?)
372
+ local previous = currentStatus
373
+ currentStatus = status
374
+ refreshMeta()
375
+
376
+ -- Only narrate transitions. The transport re-reports its state on every
377
+ -- reconnect attempt, and echoing an unchanged status would bury real events.
378
+ if status == previous and detail == nil then
379
+ return
380
+ end
381
+
382
+ if status == "connected" then
383
+ Console.log(
384
+ "ok",
385
+ string.format("connected to 127.0.0.1:%d", Config.getPort()),
386
+ if detail then "(" .. detail .. ")" else nil
387
+ )
388
+ elseif status == "connecting" then
389
+ Console.log("dim", string.format("connecting to 127.0.0.1:%d...", Config.getPort()))
390
+ else
391
+ Console.log("error", "disconnected", detail)
392
+ end
393
+ end
394
+
395
+ --[[
396
+ Runs each command on its own task. Handlers may yield -- `UpdateSourceAsync`
397
+ and any `*Async` call does -- and serialising them would let one slow edit
398
+ stall every other request on the stream.
399
+ ]]
400
+ local function onCommand(id: string, op: string, params: { [string]: any }?)
401
+ task.spawn(function()
402
+ local startedAt = os.clock()
403
+ --[[
404
+ Named for what it does, not for how it travels. `script.edit` on
405
+ ServerScriptService.Systems.KillBrick reads as "Edit KillBrick",
406
+ which is the thing someone watching actually wants to know; the wire
407
+ name is kept alongside so the log still maps onto the protocol when
408
+ something needs debugging.
409
+ ]]
410
+ local title = Phrase.of(op, params)
411
+ --[[
412
+ Announced synchronously, unlike the logging below.
413
+
414
+ Deferring this looked like free latency and was not. `beginCall` sets
415
+ two labels and some fields -- it never touches the RichText log, which
416
+ is where the cost actually is -- and deferring it let a call that
417
+ finished inside one frame record its result before the call had been
418
+ announced, so the bar on the trace lost the name it was supposed to
419
+ carry. A microsecond is not worth an ordering hazard.
420
+ ]]
421
+ Console.beginCall(title, Phrase.kindOf(op))
422
+
423
+ local result = Dispatch.invoke(id, op, params)
424
+ local milliseconds = (os.clock() - startedAt) * 1000
425
+
426
+ --[[
427
+ The answer goes out before the console hears about it.
428
+
429
+ This used to be the last line of the function, which put a
430
+ `table.concat` of three hundred strings, a RichText relayout of the
431
+ whole log, two `Instance.new` calls and a forty-bar relayout in front
432
+ of the reply on its way back to the agent. None of that is work the
433
+ caller asked for, and all of it was being billed to the round trip
434
+ this project measures. Drawing happens below, on time the agent is no
435
+ longer waiting for.
436
+ ]]
437
+ Transport.sendResult(result)
438
+
439
+ local elapsed = string.format("%.0fms", milliseconds)
440
+ Console.recordCall(result.ok, milliseconds)
441
+
442
+ if result.ok then
443
+ Console.log("reply", title, elapsed)
444
+ else
445
+ local err = result.error
446
+ Console.log(
447
+ "error",
448
+ string.format("%s failed: %s", title, if err then err.code else "unknown"),
449
+ elapsed
450
+ )
451
+ if err and err.message then
452
+ Console.log("dim", " " .. err.message)
453
+ end
454
+ end
455
+ end)
456
+ end
457
+
458
+ --[[
459
+ Bridge news that is not a command.
460
+
461
+ Kept deliberately narrow: an unknown event is ignored rather than logged,
462
+ because a newer server talking to an older plugin is a supported situation
463
+ and "unknown event" rows would be the only symptom of it working correctly.
464
+ ]]
465
+ local function onEvent(event: { [string]: any })
466
+ if event.event == "clients" and typeof(event.count) == "number" then
467
+ Console.setClients(event.count)
468
+ elseif event.event == "agent" and event.state == "finished" then
469
+ Console.agentFinished()
470
+ end
471
+ end
472
+
473
+ function connect()
474
+ local allowed, reason = canConnect()
475
+ if not allowed then
476
+ -- Reported as standby rather than an error: nothing failed, and this
477
+ -- session was never going to connect.
478
+ currentStatus = "disconnected"
479
+ Console.log("dim", "mirroring", reason)
480
+ Console.setStatus(
481
+ "mirroring",
482
+ string.format("%s build %s", "client view", Config.BUILD_ID)
483
+ )
484
+ Console.setCaption("mirroring the playtest server")
485
+ return
486
+ end
487
+ Transport.start(studioId(), { onCommand = onCommand, onStatus = onStatus, onEvent = onEvent })
488
+ plugin:SetSetting(SETTING_AUTOCONNECT, true)
489
+ end
490
+
491
+ button.Click:Connect(function()
492
+ widget.Enabled = not widget.Enabled
493
+ end)
494
+
495
+ plugin.Unloading:Connect(function()
496
+ Transport.stop()
497
+ end)
498
+
499
+ --[[
500
+ Switches this session between the push and long-poll transports.
501
+
502
+ Registered here rather than in a handler module because it is the only
503
+ command that has to reach back into the plugin object and the connection
504
+ loop, both of which live in this file -- and registered THIS far down the
505
+ file on purpose: `connect` is a forward-declared local, so a closure written
506
+ above its declaration captures the global of that name instead, which is nil.
507
+ That cost a session. The plugin loaded and connected perfectly, and then died
508
+ the first time somebody asked it to switch transport.
509
+
510
+ The reply is sent before the reconnect, and the reconnect is deferred:
511
+ tearing the stream down inside the handler would strand the answer to the
512
+ very call that asked for the switch, which is a confusing way to succeed.
513
+ ]]
514
+ Dispatch.registerAll("studio", {
515
+ transport = function(params: { [string]: any }): { [string]: any }
516
+ local requested = params.mode
517
+ if requested ~= nil and requested ~= "sse" and requested ~= "poll" then
518
+ Dispatch.fail("BAD_PARAMS", 'transport mode must be "sse" or "poll".')
519
+ end
520
+ if requested == nil then
521
+ return { mode = Transport.getMode(), forcePoll = Transport.getForcePoll(), changed = false }
522
+ end
523
+
524
+ local wantPoll = requested == "poll"
525
+ if Transport.getMode() == requested and Transport.getForcePoll() == wantPoll then
526
+ return { mode = Transport.getMode(), forcePoll = wantPoll, changed = false }
527
+ end
528
+
529
+ Transport.setForcePoll(wantPoll)
530
+ plugin:SetSetting(SETTING_FORCE_POLL, wantPoll)
531
+ task.defer(function()
532
+ Transport.stop()
533
+ task.wait(0.1)
534
+ connect()
535
+ end)
536
+ return {
537
+ mode = requested,
538
+ forcePoll = wantPoll,
539
+ changed = true,
540
+ note = "Reconnecting on the new transport; the next call will use it.",
541
+ }
542
+ end,
543
+ })
544
+
545
+ refreshMeta()
546
+
547
+ -- Connect on load unless the user explicitly disconnected last session.
548
+ if plugin:GetSetting(SETTING_AUTOCONNECT) ~= false then
549
+ connect()
550
+ else
551
+ Console.log("warn", "auto-connect disabled — press reconnect to start")
552
+ end