@chrrxs/robloxstudio-mcp-inspector 3.3.0 → 3.4.0

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.
@@ -396,8 +396,14 @@ local function release(data)
396
396
  chunkBytes = CHUNK_BYTES,
397
397
  }
398
398
  end
399
+ -- ttlSeconds bounds how long the transfer may hold its slot. The broker passes
400
+ -- the request's remaining budget: once the server stopped waiting, nobody will
401
+ -- read the pixels, so the slot must not stay reserved for the full TTL.
399
402
  local validSize
400
- local function begin(data, capture)
403
+ local function begin(data, capture, ttlSeconds)
404
+ if ttlSeconds == nil then
405
+ ttlSeconds = TRANSFER_TTL_SECONDS
406
+ end
401
407
  prune()
402
408
  local id = data.transferId
403
409
  -- An older server cannot consume chunk descriptors. Let it use legacy
@@ -422,15 +428,20 @@ local function begin(data, capture)
422
428
  end
423
429
  -- ▲ ReadonlyMap.size ▲
424
430
  if _size >= MAX_TRANSFERS then
425
- return fail("two captures are already in flight; release or await them first")
431
+ local soonest = math.huge
432
+ for _, held in transfers do
433
+ soonest = math.min(soonest, held.expiresAt - os.clock())
434
+ end
435
+ return fail(`two earlier captures still hold this client's transfer slots; the first frees itself in {string.format("%.1f", math.max(0, soonest))} s, when its request deadline has passed. Retry after that.`)
426
436
  end
437
+ local ttl = math.clamp(ttlSeconds, 1, TRANSFER_TTL_SECONDS)
427
438
  local transfer = {
428
439
  offset = 0,
429
- expiresAt = os.clock() + TRANSFER_TTL_SECONDS,
440
+ expiresAt = os.clock() + ttl,
430
441
  }
431
442
  transfers[id] = transfer
432
443
  -- Capture only the ID, not the large payload, in the expiry closure.
433
- transfer.expiryThread = task.delay(TRANSFER_TTL_SECONDS, function()
444
+ transfer.expiryThread = task.delay(ttl, function()
434
445
  local current = transfers[id]
435
446
  if current ~= nil and os.clock() >= current.expiresAt then
436
447
  current.expiryThread = nil
@@ -670,8 +681,23 @@ local CLIENT_IDENTITY_KIND = "identity"
670
681
  -- A normal capture needs at most 15s sampling + 5s waiting for profiler data.
671
682
  -- Leave room for processing, then return a diagnostic before the outer 30s wait.
672
683
  local CLIENT_PROFILER_MAX_WAIT_SECONDS = 25
673
- local CLIENT_PROFILER_RESPONSE_RESERVE_SECONDS = 5
674
- local CLIENT_PROFILER_POLL_SECONDS = 0.05
684
+ -- Every forwarded request ends its local wait this long before the MCP
685
+ -- deadline, so the caller receives the broker's diagnosis instead of a bare
686
+ -- "executing; unknown" timeout from the server.
687
+ local CLIENT_RESPONSE_RESERVE_SECONDS = 5
688
+ local CLIENT_WAIT_POLL_SECONDS = 0.05
689
+ -- Client Peers send a heartbeat over this RemoteEvent every second, and the
690
+ -- server pings them back. Both use the same server-client connection as
691
+ -- InvokeClient, so they show whether the bridge channel is delivering,
692
+ -- separately from whether the game itself is running.
693
+ local HEARTBEAT_NAME = "__MCPClientBrokerHeartbeat"
694
+ local HEARTBEAT_INTERVAL_SECONDS = 1
695
+ -- Ten missed heartbeats, or a channel delay of ten seconds, marks the bridge as
696
+ -- stalled. While it is stalled and an earlier request went unanswered, new
697
+ -- requests are refused before sending (see unresponsiveBridge).
698
+ local BRIDGE_STALE_SECONDS = 10
699
+ local MAX_REPORTED_CLIENT_REQUESTS = 8
700
+ local CLIENT_REQUEST_REPORT_SECONDS = 60
675
701
  -- Endpoints the server-peer broker is allowed to forward to the client peer.
676
702
  -- Each requires the client peer's plugin VM (because the buffer / require
677
703
  -- cache / etc. lives there) so the server peer alone can't satisfy them.
@@ -835,121 +861,267 @@ local function sendClientIdentity(rf, attempt)
835
861
  end
836
862
  task.delay(proxyRetryDelay(attempt + 1), sendClientIdentity, rf, attempt + 1)
837
863
  end
838
- local function setupClientBroker(attempt)
864
+ local function routeClientRequest(payload)
865
+ if payload.endpoint == "/api/get-runtime-logs" then
866
+ return handleGetRuntimeLogs(payload.data)
867
+ end
868
+ if payload.endpoint == "/api/get-memory-breakdown" then
869
+ return MemoryHandlers.getMemoryBreakdown(payload.data or {})
870
+ end
871
+ if payload.endpoint == "/api/get-scene-analysis" then
872
+ return SceneAnalysisHandlers.getSceneAnalysis(payload.data or {})
873
+ end
874
+ if payload.endpoint == "/api/breakpoints" then
875
+ return BreakpointHandlers.breakpoints(payload.data or {})
876
+ end
877
+ if payload.endpoint == "/api/capture-script-profiler" then
878
+ return ScriptProfilerHandlers.captureScriptProfiler(payload.data or {})
879
+ end
880
+ if payload.endpoint == "/api/capture-micro-profiler" then
881
+ return MicroProfilerHandlers.captureMicroProfiler(payload.data or {})
882
+ end
883
+ if payload.endpoint == "/api/multiplayer-test-state" then
884
+ return handleMultiplayerTestState()
885
+ end
886
+ if payload.endpoint == "/api/multiplayer-test-leave-client" then
887
+ return handleMultiplayerTestLeaveClient()
888
+ end
889
+ if payload.endpoint == "/api/capture-begin" then
890
+ return CaptureHandlers.captureBegin()
891
+ end
892
+ if payload.endpoint == "/api/capture-studio" then
893
+ -- Every chunk read shares this request's deadline, so after it nobody
894
+ -- reads the pixels and the transfer slot can be freed.
895
+ local _expiresAtServerTime = payload.expiresAtServerTime
896
+ local ttl = if type(_expiresAtServerTime) == "number" then payload.expiresAtServerTime - Workspace:GetServerTimeNow() + 1 else nil
897
+ return CaptureTransfer.begin(payload.data or {}, function()
898
+ return CaptureHandlers.captureStudio(payload.data or {})
899
+ end, ttl)
900
+ end
901
+ if payload.endpoint == "/api/capture-markers" then
902
+ return CaptureHandlers.captureMarkers(payload.data or {})
903
+ end
904
+ if payload.endpoint == CaptureTransfer.READ_ENDPOINT then
905
+ return CaptureTransfer.read(payload.data or {})
906
+ end
907
+ if payload.endpoint == CaptureTransfer.RELEASE_ENDPOINT then
908
+ return CaptureTransfer.release(payload.data or {})
909
+ end
910
+ if payload.endpoint == "/api/simulate-mouse-input" then
911
+ return InputHandlers.simulateMouseInput(payload.data or {})
912
+ end
913
+ if payload.endpoint == "/api/simulate-keyboard-input" then
914
+ return InputHandlers.simulateKeyboardInput(payload.data or {})
915
+ end
916
+ if payload.endpoint == "/api/focus-viewport" then
917
+ return MetadataHandlers.focusViewport(payload.data or {})
918
+ end
919
+ if payload.endpoint == "/api/execute-luau" then
920
+ return handleExecuteLuau(payload.data)
921
+ end
922
+ if payload.endpoint == "/api/eval-runtime" then
923
+ return EvalRuntimeHandlers.evalRuntime(payload.data or {})
924
+ end
925
+ return {
926
+ error = `Unsupported client broker endpoint: {payload.endpoint}`,
927
+ }
928
+ end
929
+ -- Requests this client received recently, reported in heartbeats so the server
930
+ -- can tell "never arrived" from "still running" when a request times out.
931
+ local clientRequests = {}
932
+ local lastServerPing
933
+ local clientHeartbeatStarted = false
934
+ local function pruneClientRequests(now)
935
+ for requestId, observation in clientRequests do
936
+ if observation.finishedAt ~= nil and now - observation.finishedAt > CLIENT_REQUEST_REPORT_SECONDS then
937
+ clientRequests[requestId] = nil
938
+ end
939
+ end
940
+ end
941
+ local function reportedClientRequests(now)
942
+ pruneClientRequests(now)
943
+ local reported = {}
944
+ for _, observation in clientRequests do
945
+ table.insert(reported, observation)
946
+ end
947
+ -- Running requests first, then the most recently started.
948
+ table.sort(reported, function(a, b)
949
+ if (a.finishedAt == nil) ~= (b.finishedAt == nil) then
950
+ return a.finishedAt == nil
951
+ end
952
+ return a.startedAt > b.startedAt
953
+ end)
954
+ local limited = {}
955
+ do
956
+ local i = 0
957
+ local _shouldIncrement = false
958
+ while true do
959
+ if _shouldIncrement then
960
+ i += 1
961
+ else
962
+ _shouldIncrement = true
963
+ end
964
+ if not (i < math.min(#reported, MAX_REPORTED_CLIENT_REQUESTS)) then
965
+ break
966
+ end
967
+ local _arg0 = reported[i + 1]
968
+ table.insert(limited, _arg0)
969
+ end
970
+ end
971
+ return limited
972
+ end
973
+ local function handleClientInvoke(payload)
974
+ local _condition = not payload
975
+ if not _condition then
976
+ local _endpoint = payload.endpoint
977
+ _condition = not (type(_endpoint) == "string")
978
+ end
979
+ if _condition then
980
+ return {
981
+ error = "Client broker request is missing its endpoint.",
982
+ }
983
+ end
984
+ -- os.clock is VM-local. Only the engine-synchronized server clock can
985
+ -- reject an envelope that expired while travelling to this client. The
986
+ -- server already reported a timeout for it, so running it now would apply
987
+ -- a change the caller was told had an unknown outcome, long after the fact.
988
+ local now = Workspace:GetServerTimeNow()
989
+ local _remainingMs = payload.remainingMs
990
+ local _condition_1 = type(_remainingMs) == "number"
991
+ if _condition_1 then
992
+ _condition_1 = payload.remainingMs <= 0
993
+ end
994
+ local _condition_2 = _condition_1
995
+ if not _condition_2 then
996
+ local _expiresAtServerTime = payload.expiresAtServerTime
997
+ local _condition_3 = type(_expiresAtServerTime) == "number"
998
+ if _condition_3 then
999
+ _condition_3 = now >= payload.expiresAtServerTime
1000
+ end
1001
+ _condition_2 = _condition_3
1002
+ end
1003
+ if _condition_2 then
1004
+ local _expiresAtServerTime = payload.expiresAtServerTime
1005
+ local lateMs = if type(_expiresAtServerTime) == "number" then math.floor(math.max(0, now - payload.expiresAtServerTime) * 1000) else 0
1006
+ return {
1007
+ success = false,
1008
+ error = "client_broker_expired",
1009
+ stage = "client_broker_pre_start",
1010
+ requestId = payload.requestId,
1011
+ executionOutcome = "not_executed",
1012
+ lateMs = lateMs,
1013
+ message = `Request {tostring(payload.requestId)} ({payload.endpoint}) reached the client {lateMs} ms after its deadline, so it was not started.`,
1014
+ }
1015
+ end
1016
+ local _requestId = payload.requestId
1017
+ local requestId = if type(_requestId) == "string" then payload.requestId else nil
1018
+ local observation
1019
+ if requestId ~= nil then
1020
+ observation = {
1021
+ requestId = requestId,
1022
+ endpoint = payload.endpoint,
1023
+ startedAt = now,
1024
+ }
1025
+ local _observation = observation
1026
+ clientRequests[requestId] = _observation
1027
+ end
1028
+ local ok, result = pcall(function()
1029
+ return routeClientRequest(payload)
1030
+ end)
1031
+ if observation ~= nil then
1032
+ observation.finishedAt = Workspace:GetServerTimeNow()
1033
+ end
1034
+ -- Keep the engine's error propagation: InvokeClient raises on the server.
1035
+ if not ok then
1036
+ error(result, 0)
1037
+ end
1038
+ return result
1039
+ end
1040
+ local function startClientHeartbeat(attempt)
839
1041
  if attempt == nil then
840
1042
  attempt = 0
841
1043
  end
842
- if PeerRole.detect() ~= "client" then
1044
+ if clientHeartbeatStarted or PeerRole.detect() ~= "client" or not RunService:IsRunning() then
843
1045
  return nil
844
1046
  end
845
- local rf = ReplicatedStorage:WaitForChild(BROKER_NAME, 10)
846
- if not rf or not rf:IsA("RemoteFunction") then
847
- if attempt == 0 then
848
- warn(`[robloxstudio-mcp] client: {BROKER_NAME} not found; retrying`)
849
- end
850
- if RunService:IsRunning() then
851
- task.delay(proxyRetryDelay(attempt + 1), setupClientBroker, attempt + 1)
1047
+ local event = ReplicatedStorage:WaitForChild(HEARTBEAT_NAME, 10)
1048
+ if not event or not event:IsA("RemoteEvent") then
1049
+ -- An older server broker has no heartbeat channel; requests still work.
1050
+ if RunService:IsRunning() and attempt < 5 then
1051
+ task.delay(proxyRetryDelay(attempt + 1), startClientHeartbeat, attempt + 1)
852
1052
  end
853
1053
  return nil
854
1054
  end
855
- rf.OnClientInvoke = function(payload)
856
- local _condition = not payload
1055
+ clientHeartbeatStarted = true
1056
+ event.OnClientEvent:Connect(function(payload)
1057
+ local _payload = payload
1058
+ if not (type(_payload) == "table") then
1059
+ return nil
1060
+ end
1061
+ local ping = payload
1062
+ local _condition = ping.kind ~= "ping"
857
1063
  if not _condition then
858
- local _endpoint = payload.endpoint
859
- _condition = not (type(_endpoint) == "string")
1064
+ local _sentAt = ping.sentAt
1065
+ _condition = not (type(_sentAt) == "number")
860
1066
  end
861
1067
  if _condition then
862
- return {
863
- error = "Client broker request is missing its endpoint.",
864
- }
865
- end
866
- if payload and payload.endpoint == "/api/get-runtime-logs" then
867
- return handleGetRuntimeLogs(payload.data)
868
- end
869
- if payload and payload.endpoint == "/api/get-memory-breakdown" then
870
- return MemoryHandlers.getMemoryBreakdown(payload.data or {})
871
- end
872
- if payload and payload.endpoint == "/api/get-scene-analysis" then
873
- return SceneAnalysisHandlers.getSceneAnalysis(payload.data or {})
874
- end
875
- if payload and payload.endpoint == "/api/breakpoints" then
876
- return BreakpointHandlers.breakpoints(payload.data or {})
1068
+ return nil
877
1069
  end
878
- if payload and payload.endpoint == "/api/capture-script-profiler" then
879
- -- os.clock is VM-local. Only the engine-synchronized server clock can
880
- -- reject an envelope that expired while travelling to this client.
881
- local _remainingMs = payload.remainingMs
882
- local _condition_1 = type(_remainingMs) == "number"
883
- if _condition_1 then
884
- _condition_1 = payload.remainingMs <= 0
885
- end
886
- local _condition_2 = _condition_1
887
- if not _condition_2 then
888
- local _expiresAtServerTime = payload.expiresAtServerTime
889
- local _condition_3 = type(_expiresAtServerTime) == "number"
890
- if _condition_3 then
891
- _condition_3 = Workspace:GetServerTimeNow() >= payload.expiresAtServerTime
892
- end
893
- _condition_2 = _condition_3
894
- end
895
- if _condition_2 then
896
- return {
897
- success = false,
898
- error = "client_broker_expired",
899
- stage = "client_broker_pre_start",
900
- requestId = payload.requestId,
901
- executionOutcome = "not_executed",
902
- message = "Client profiler request expired before capture started.",
1070
+ lastServerPing = {
1071
+ sentAt = ping.sentAt,
1072
+ receivedAt = Workspace:GetServerTimeNow(),
1073
+ }
1074
+ end)
1075
+ task.spawn(function()
1076
+ while event.Parent ~= nil and RunService:IsRunning() do
1077
+ -- One failed beat must not end the loop: silence means "stalled".
1078
+ pcall(function()
1079
+ local now = Workspace:GetServerTimeNow()
1080
+ local _object = {
1081
+ kind = "heartbeat",
1082
+ sentAt = now,
903
1083
  }
904
- end
905
- return ScriptProfilerHandlers.captureScriptProfiler(payload.data or {})
906
- end
907
- if payload and payload.endpoint == "/api/capture-micro-profiler" then
908
- return MicroProfilerHandlers.captureMicroProfiler(payload.data or {})
909
- end
910
- if payload and payload.endpoint == "/api/multiplayer-test-state" then
911
- return handleMultiplayerTestState()
912
- end
913
- if payload and payload.endpoint == "/api/multiplayer-test-leave-client" then
914
- return handleMultiplayerTestLeaveClient()
915
- end
916
- if payload and payload.endpoint == "/api/capture-begin" then
917
- return CaptureHandlers.captureBegin()
918
- end
919
- if payload and payload.endpoint == "/api/capture-studio" then
920
- return CaptureTransfer.begin(payload.data or {}, function()
921
- return CaptureHandlers.captureStudio(payload.data or {})
1084
+ local _left = "pingSentAt"
1085
+ local _result = lastServerPing
1086
+ if _result ~= nil then
1087
+ _result = _result.sentAt
1088
+ end
1089
+ _object[_left] = _result
1090
+ local _left_1 = "pingReceivedAt"
1091
+ local _result_1 = lastServerPing
1092
+ if _result_1 ~= nil then
1093
+ _result_1 = _result_1.receivedAt
1094
+ end
1095
+ _object[_left_1] = _result_1
1096
+ _object.requests = reportedClientRequests(now)
1097
+ local heartbeat = _object
1098
+ event:FireServer(heartbeat)
922
1099
  end)
1100
+ task.wait(HEARTBEAT_INTERVAL_SECONDS)
923
1101
  end
924
- if payload and payload.endpoint == "/api/capture-markers" then
925
- return CaptureHandlers.captureMarkers(payload.data or {})
926
- end
927
- if payload and payload.endpoint == CaptureTransfer.READ_ENDPOINT then
928
- return CaptureTransfer.read(payload.data or {})
929
- end
930
- if payload and payload.endpoint == CaptureTransfer.RELEASE_ENDPOINT then
931
- return CaptureTransfer.release(payload.data or {})
932
- end
933
- if payload and payload.endpoint == "/api/simulate-mouse-input" then
934
- return InputHandlers.simulateMouseInput(payload.data or {})
935
- end
936
- if payload and payload.endpoint == "/api/simulate-keyboard-input" then
937
- return InputHandlers.simulateKeyboardInput(payload.data or {})
938
- end
939
- if payload and payload.endpoint == "/api/focus-viewport" then
940
- return MetadataHandlers.focusViewport(payload.data or {})
941
- end
942
- if payload and payload.endpoint == "/api/execute-luau" then
943
- return handleExecuteLuau(payload.data)
1102
+ clientHeartbeatStarted = false
1103
+ end)
1104
+ end
1105
+ local function setupClientBroker(attempt)
1106
+ if attempt == nil then
1107
+ attempt = 0
1108
+ end
1109
+ if PeerRole.detect() ~= "client" then
1110
+ return nil
1111
+ end
1112
+ local rf = ReplicatedStorage:WaitForChild(BROKER_NAME, 10)
1113
+ if not rf or not rf:IsA("RemoteFunction") then
1114
+ if attempt == 0 then
1115
+ warn(`[robloxstudio-mcp] client: {BROKER_NAME} not found; retrying`)
944
1116
  end
945
- if payload and payload.endpoint == "/api/eval-runtime" then
946
- return EvalRuntimeHandlers.evalRuntime(payload.data or {})
1117
+ if RunService:IsRunning() then
1118
+ task.delay(proxyRetryDelay(attempt + 1), setupClientBroker, attempt + 1)
947
1119
  end
948
- return {
949
- error = `Unsupported client broker endpoint: {payload.endpoint}`,
950
- }
1120
+ return nil
951
1121
  end
1122
+ rf.OnClientInvoke = handleClientInvoke
952
1123
  task.spawn(sendClientIdentity, rf, 0)
1124
+ task.spawn(startClientHeartbeat, 0)
953
1125
  end
954
1126
  local INITIAL_PROXY_RETRY_DELAY_SECONDS = 0.5
955
1127
  local MAX_PROXY_RETRY_DELAY_SECONDS = 5
@@ -1202,32 +1374,211 @@ local function refreshAllProxyRegistrations()
1202
1374
  task.spawn(registerProxyEntry, entry)
1203
1375
  end
1204
1376
  end
1205
- local function invokeClientProfiler(entry, target, data, context)
1377
+ local function msBetween(later, earlier)
1378
+ return math.floor(math.max(0, later - earlier) * 1000)
1379
+ end
1380
+ local function seconds(ms)
1381
+ return string.format("%.1f s", ms / 1000)
1382
+ end
1383
+ -- Everything here is measured with Workspace:GetServerTimeNow, which the engine
1384
+ -- keeps synchronized between the server and its clients.
1385
+ local function bridgeHealth(entry, requestId, dispatchedAt)
1386
+ local heartbeat = entry.heartbeat
1387
+ if heartbeat == nil then
1388
+ return {}
1389
+ end
1390
+ local now = Workspace:GetServerTimeNow()
1391
+ local health = {
1392
+ heartbeatAgeMs = msBetween(now, heartbeat.receivedAt),
1393
+ clientToServerDelayMs = msBetween(heartbeat.receivedAt, heartbeat.sentAt),
1394
+ }
1395
+ -- Pings leave every second, so the newest ping the client had seen is at most
1396
+ -- about a second old on a healthy channel. Its age measures server->client delay.
1397
+ if heartbeat.pingSentAt ~= nil then
1398
+ health.serverToClientDelayMs = msBetween(heartbeat.sentAt, heartbeat.pingSentAt)
1399
+ elseif entry.firstPingSentAt ~= nil and heartbeat.sentAt > entry.firstPingSentAt then
1400
+ health.serverToClientDelayMs = msBetween(heartbeat.sentAt, entry.firstPingSentAt)
1401
+ end
1402
+ if requestId ~= nil then
1403
+ local _exp = heartbeat.requests
1404
+ -- ▼ ReadonlyArray.find ▼
1405
+ local _callback = function(request)
1406
+ return request.requestId == requestId
1407
+ end
1408
+ local _result
1409
+ for _i, _v in _exp do
1410
+ if _callback(_v, _i - 1, _exp) == true then
1411
+ _result = _v
1412
+ break
1413
+ end
1414
+ end
1415
+ -- ▲ ReadonlyArray.find ▲
1416
+ local observed = _result
1417
+ if observed ~= nil then
1418
+ if observed.finishedAt == nil then
1419
+ health.requestState = "running"
1420
+ health.requestRunningMs = msBetween(now, observed.startedAt)
1421
+ else
1422
+ health.requestState = "completed"
1423
+ health.requestRunningMs = msBetween(observed.finishedAt, observed.startedAt)
1424
+ end
1425
+ elseif dispatchedAt ~= nil and heartbeat.pingSentAt ~= nil and heartbeat.pingSentAt > dispatchedAt and #heartbeat.requests < MAX_REPORTED_CLIENT_REQUESTS then
1426
+ health.requestState = "not_started"
1427
+ elseif dispatchedAt ~= nil and heartbeat.sentAt > dispatchedAt then
1428
+ health.requestState = "not_received"
1429
+ end
1430
+ end
1431
+ return health
1432
+ end
1433
+ local BACKLOG_EXPLANATION = "Requests to a client share the server-client connection with the game's replication and remote traffic, " .. "so a backlog there delays them while the game itself keeps running."
1434
+ local function describeBridgeHealth(health)
1435
+ if health.heartbeatAgeMs == nil then
1436
+ return "No heartbeat has arrived from this client's MCP bridge, so its liveness is unknown."
1437
+ end
1438
+ local _exp = seconds(health.heartbeatAgeMs)
1439
+ local _condition = health.clientToServerDelayMs
1440
+ if _condition == nil then
1441
+ _condition = 0
1442
+ end
1443
+ local channel = `Bridge heartbeat {_exp} ago; client->server delay {seconds(_condition)}` .. (if health.serverToClientDelayMs ~= nil then `; server->client delay {seconds(health.serverToClientDelayMs)}.` else ".")
1444
+ if health.heartbeatAgeMs > BRIDGE_STALE_SECONDS * 1000 then
1445
+ return `{channel} The client's MCP bridge has stopped sending heartbeats: either the client's Luau scheduler is blocked by a long-running script, or client->server messages are stalled. The game window can keep rendering in both cases.`
1446
+ end
1447
+ if health.requestState == "running" then
1448
+ local _condition_1 = health.requestRunningMs
1449
+ if _condition_1 == nil then
1450
+ _condition_1 = 0
1451
+ end
1452
+ return `{channel} The client received this request and its handler has been running for {seconds(_condition_1)}: the code is yielding or blocked inside the client.`
1453
+ end
1454
+ if health.requestState == "completed" then
1455
+ return `{channel} The client finished this request but its response has not arrived: client->server traffic is backlogged. {BACKLOG_EXPLANATION}`
1456
+ end
1457
+ if health.requestState == "not_started" then
1458
+ return `{channel} The client has received server messages sent after this request but has not started it: the client broker never ran it, or it is still queued inside the client.`
1459
+ end
1460
+ local _condition_1 = health.serverToClientDelayMs
1461
+ if _condition_1 == nil then
1462
+ _condition_1 = 0
1463
+ end
1464
+ local _condition_2 = _condition_1 > BRIDGE_STALE_SECONDS * 1000
1465
+ if not _condition_2 then
1466
+ _condition_2 = health.requestState == "not_received"
1467
+ end
1468
+ if _condition_2 then
1469
+ return `{channel} The request has not reached the client: server->client traffic is backlogged. {BACKLOG_EXPLANATION}`
1470
+ end
1471
+ local _condition_3 = health.clientToServerDelayMs
1472
+ if _condition_3 == nil then
1473
+ _condition_3 = 0
1474
+ end
1475
+ if _condition_3 > BRIDGE_STALE_SECONDS * 1000 then
1476
+ return `{channel} Client->server traffic is backlogged. {BACKLOG_EXPLANATION}`
1477
+ end
1478
+ return channel
1479
+ end
1480
+ -- A request sent into a stalled channel only waits out its deadline, and may
1481
+ -- then run on the client long after the caller gave up on it. Heartbeats alone
1482
+ -- are not enough to refuse: a request to this client must also have timed out
1483
+ -- with no answer since, so a broken heartbeat can never block a working channel.
1484
+ local function unresponsiveBridge(entry)
1485
+ if entry.lastTimeoutAt == nil then
1486
+ return nil
1487
+ end
1488
+ if entry.lastAnswerAt ~= nil and entry.lastAnswerAt > entry.lastTimeoutAt then
1489
+ return nil
1490
+ end
1491
+ local health = bridgeHealth(entry)
1492
+ if health.heartbeatAgeMs == nil then
1493
+ return nil
1494
+ end
1495
+ local staleMs = BRIDGE_STALE_SECONDS * 1000
1496
+ local _condition = health.heartbeatAgeMs > staleMs
1497
+ if not _condition then
1498
+ local _condition_1 = health.clientToServerDelayMs
1499
+ if _condition_1 == nil then
1500
+ _condition_1 = 0
1501
+ end
1502
+ _condition = _condition_1 > staleMs
1503
+ if not _condition then
1504
+ local _condition_2 = health.serverToClientDelayMs
1505
+ if _condition_2 == nil then
1506
+ _condition_2 = 0
1507
+ end
1508
+ _condition = _condition_2 > staleMs
1509
+ end
1510
+ end
1511
+ if _condition then
1512
+ return health
1513
+ end
1514
+ return nil
1515
+ end
1516
+ local function callFailure(call, code, stage, outcome, detail, health)
1517
+ call.context.executionOutcome = outcome
1518
+ local healthText = if health ~= nil then ` {describeBridgeHealth(health)}` else ""
1519
+ return {
1520
+ success = false,
1521
+ error = code,
1522
+ stage = stage,
1523
+ requestId = call.context.requestId,
1524
+ peerId = call.entry.peerId,
1525
+ target = call.target,
1526
+ endpoint = call.endpoint,
1527
+ elapsedMs = math.floor(math.max(0, os.clock() - call.startedAt) * 1000),
1528
+ executionOutcome = outcome,
1529
+ bridge = health,
1530
+ message = if outcome == "unknown" then `{detail}{healthText} Only the broker's local wait ended: a request that already started on the client is not cancelled or rolled back, and one still in transit is refused by the client once its deadline has passed. No retry was started.` else `{detail}{healthText} The request was not sent to the client.`,
1531
+ }
1532
+ end
1533
+ local function beginClientCall(entry, target, endpoint, context, maxWaitSeconds, reserveSeconds)
1206
1534
  local startedAt = os.clock()
1207
- local deadlineAt = math.min(context.deadlineAt - CLIENT_PROFILER_RESPONSE_RESERVE_SECONDS, startedAt + CLIENT_PROFILER_MAX_WAIT_SECONDS)
1208
- local failure = function(code, stage, outcome, detail)
1209
- context.executionOutcome = outcome
1210
- return {
1211
- success = false,
1212
- error = code,
1213
- stage = stage,
1214
- requestId = context.requestId,
1215
- peerId = entry.peerId,
1216
- target = target,
1217
- elapsedMs = math.floor(math.max(0, os.clock() - startedAt) * 1000),
1218
- executionOutcome = outcome,
1219
- message = if outcome == "unknown" then `{detail} Only the broker's local wait ended; remote execution may still be running. No retry was started.` else `{detail} Client profiler execution was not started.`,
1220
- }
1535
+ local remaining = context.deadlineAt - startedAt
1536
+ -- Short budgets (runtime log fan-out uses 5 s) keep most of their time.
1537
+ local _condition = reserveSeconds
1538
+ if _condition == nil then
1539
+ _condition = math.clamp(remaining * 0.2, 0.25, CLIENT_RESPONSE_RESERVE_SECONDS)
1540
+ end
1541
+ local reserve = _condition
1542
+ local deadlineAt = context.deadlineAt - reserve
1543
+ if maxWaitSeconds ~= nil then
1544
+ deadlineAt = math.min(deadlineAt, startedAt + maxWaitSeconds)
1545
+ end
1546
+ return {
1547
+ entry = entry,
1548
+ target = target,
1549
+ endpoint = endpoint,
1550
+ context = context,
1551
+ startedAt = startedAt,
1552
+ deadlineAt = deadlineAt,
1553
+ }
1554
+ end
1555
+ local function admitClientCall(call)
1556
+ if call.context.isCancelled() then
1557
+ return callFailure(call, "client_broker_cancelled", "client_broker_admission", "not_executed", "Request cancelled before client invocation.")
1221
1558
  end
1222
- if context.isCancelled() then
1223
- return failure("client_broker_cancelled", "client_broker_admission", "not_executed", "Request cancelled before client invocation.")
1559
+ if call.startedAt >= call.deadlineAt then
1560
+ return callFailure(call, "client_broker_timeout", "client_broker_admission", "not_executed", "Insufficient request budget for client invocation and response delivery.")
1224
1561
  end
1225
- if startedAt >= deadlineAt then
1226
- return failure("client_broker_timeout", "client_broker_admission", "not_executed", "Insufficient request budget for client invocation and response delivery.")
1562
+ local unresponsive = unresponsiveBridge(call.entry)
1563
+ if unresponsive ~= nil then
1564
+ return callFailure(call, "client_bridge_unresponsive", "client_broker_admission", "not_executed", `The MCP bridge to {call.target} is unresponsive, so {call.endpoint} was refused instead of waiting for its deadline. This is the plugin's server-to-client channel, not necessarily the game.`, unresponsive)
1227
1565
  end
1566
+ return nil
1567
+ end
1568
+ -- InvokeClient yields until the client answers, forever if it never does. Run it
1569
+ -- on its own thread and stop waiting at the call's deadline. requestId names
1570
+ -- this one invocation in the client's heartbeat reports.
1571
+ local function invokeClient(call, endpoint, data, requestId)
1572
+ if requestId == nil then
1573
+ requestId = call.context.requestId
1574
+ end
1575
+ local _binding = call
1576
+ local entry = _binding.entry
1577
+ local context = _binding.context
1578
+ local dispatchedAt = Workspace:GetServerTimeNow()
1228
1579
  local interrupted = function()
1229
1580
  if context.isCancelled() then
1230
- return failure("client_broker_cancelled", "client_broker_wait", "unknown", "Request cancelled while awaiting the client profiler response.")
1581
+ return callFailure(call, "client_broker_cancelled", "client_broker_wait", "unknown", `Request cancelled while awaiting {call.target}'s response.`)
1231
1582
  end
1232
1583
  local _peerId = entry.peerId
1233
1584
  local _condition = proxyByPeerId[_peerId] ~= entry
@@ -1239,28 +1590,34 @@ local function invokeClientProfiler(entry, target, data, context)
1239
1590
  end
1240
1591
  end
1241
1592
  if _condition then
1242
- return failure("client_broker_disconnected", "client_broker_wait", "unknown", "Client proxy disconnected while awaiting the profiler response.")
1593
+ return callFailure(call, "client_broker_disconnected", "client_broker_wait", "unknown", `Client proxy {call.target} disconnected while awaiting its response.`)
1243
1594
  end
1244
- if os.clock() >= deadlineAt then
1245
- return failure("client_broker_timeout", "client_broker_wait", "unknown", "Client profiler round-trip exceeded its response deadline.")
1595
+ if os.clock() >= call.deadlineAt then
1596
+ entry.lastTimeoutAt = os.clock()
1597
+ return callFailure(call, "client_broker_timeout", "client_broker_wait", "unknown", `{call.target} did not answer {endpoint} within {seconds(msBetween(os.clock(), call.startedAt))}.`, bridgeHealth(entry, requestId, dispatchedAt))
1246
1598
  end
1247
1599
  return nil
1248
1600
  end
1249
- local remainingMs = math.max(0, math.floor((deadlineAt - os.clock()) * 1000))
1601
+ local remainingMs = math.max(0, math.floor((call.deadlineAt - os.clock()) * 1000))
1602
+ local expiresAtServerTime = Workspace:GetServerTimeNow() + remainingMs / 1000
1250
1603
  local envelope = {
1251
- endpoint = "/api/capture-script-profiler",
1604
+ endpoint = endpoint,
1252
1605
  data = data,
1253
- requestId = context.requestId,
1606
+ requestId = requestId,
1254
1607
  remainingMs = remainingMs,
1255
- expiresAtServerTime = Workspace:GetServerTimeNow() + remainingMs / 1000,
1608
+ expiresAtServerTime = expiresAtServerTime,
1256
1609
  }
1257
1610
  local settled = false
1258
- local response
1611
+ local outcome
1259
1612
  context.executionOutcome = "unknown"
1260
1613
  local invocation = task.spawn(function()
1261
1614
  local ok, result = pcall(function()
1262
1615
  return entry.remote:InvokeClient(entry.player, envelope)
1263
1616
  end)
1617
+ -- Even a late answer shows the channel delivers again.
1618
+ if ok then
1619
+ entry.lastAnswerAt = os.clock()
1620
+ end
1264
1621
  -- Cancelling a suspended engine wait is best effort. A late return must
1265
1622
  -- never replace the chosen outcome, even if task.cancel was unavailable.
1266
1623
  if settled then
@@ -1268,16 +1625,28 @@ local function invokeClientProfiler(entry, target, data, context)
1268
1625
  end
1269
1626
  local interruption = interrupted()
1270
1627
  if interruption ~= nil then
1271
- response = interruption
1628
+ outcome = {
1629
+ ok = false,
1630
+ failure = interruption,
1631
+ }
1272
1632
  elseif not ok then
1273
- response = failure("client_broker_invoke_failed", "client_broker_wait", "unknown", `InvokeClient failed: {tostring(result)}`)
1633
+ outcome = {
1634
+ ok = false,
1635
+ failure = callFailure(call, "client_broker_invoke_failed", "client_broker_wait", "unknown", `InvokeClient failed: {tostring(result)}`),
1636
+ }
1274
1637
  elseif result == nil then
1275
- response = failure("client_broker_nil_response", "client_broker_wait", "unknown", "Client profiler returned no response.")
1638
+ outcome = {
1639
+ ok = false,
1640
+ failure = callFailure(call, "client_broker_nil_response", "client_broker_wait", "unknown", `{call.target} returned no response.`),
1641
+ }
1276
1642
  else
1277
- response = result
1278
- -- Only this endpoint's broker pre-start refusal establishes that no
1279
- -- remote capture ran. Other responses retain normal handler outcome
1280
- -- classification; arbitrary payload fields cannot override transport.
1643
+ outcome = {
1644
+ ok = true,
1645
+ result = result,
1646
+ }
1647
+ -- Only the client's own pre-start refusal establishes that nothing ran.
1648
+ -- Other responses keep normal handler outcome classification;
1649
+ -- arbitrary payload fields cannot override the transport observation.
1281
1650
  context.executionOutcome = nil
1282
1651
  if type(result) == "table" then
1283
1652
  local reply = result
@@ -1291,18 +1660,60 @@ local function invokeClientProfiler(entry, target, data, context)
1291
1660
  while not settled do
1292
1661
  local interruption = interrupted()
1293
1662
  if interruption ~= nil then
1294
- response = interruption
1663
+ outcome = {
1664
+ ok = false,
1665
+ failure = interruption,
1666
+ }
1295
1667
  settled = true
1296
1668
  -- This only releases the local coroutine; it cannot stop the remote
1297
- -- OnClientInvoke callback or roll back an already-started capture.
1669
+ -- OnClientInvoke callback or roll back work that already started.
1298
1670
  pcall(function()
1299
1671
  return task.cancel(invocation)
1300
1672
  end)
1301
1673
  break
1302
1674
  end
1303
- task.wait(math.min(CLIENT_PROFILER_POLL_SECONDS, deadlineAt - os.clock()))
1675
+ task.wait(math.min(CLIENT_WAIT_POLL_SECONDS, call.deadlineAt - os.clock()))
1676
+ end
1677
+ return outcome
1678
+ end
1679
+ local function invokeClientOnce(entry, target, endpoint, data, context, maxWaitSeconds, reserveSeconds)
1680
+ local call = beginClientCall(entry, target, endpoint, context, maxWaitSeconds, reserveSeconds)
1681
+ local refused = admitClientCall(call)
1682
+ if refused ~= nil then
1683
+ return refused
1684
+ end
1685
+ local outcome = invokeClient(call, endpoint, data)
1686
+ return if outcome.ok then outcome.result else outcome.failure
1687
+ end
1688
+ -- Screenshot transfer is several invocations; they share one deadline, and the
1689
+ -- first broker failure ends the transfer with that failure's diagnosis.
1690
+ local function invokeClientCapture(entry, target, data, context)
1691
+ local call = beginClientCall(entry, target, "/api/capture-studio", context)
1692
+ local refused = admitClientCall(call)
1693
+ if refused ~= nil then
1694
+ return refused
1695
+ end
1696
+ local brokerFailure
1697
+ local outcome
1698
+ local invocations = 0
1699
+ local result = CaptureTransfer.receive(function(captureEndpoint, captureData)
1700
+ if brokerFailure ~= nil then
1701
+ error("client broker failed", 0)
1702
+ end
1703
+ invocations += 1
1704
+ local invoked = invokeClient(call, captureEndpoint, captureData, `{context.requestId}:{invocations}`)
1705
+ if not invoked.ok then
1706
+ brokerFailure = invoked.failure
1707
+ outcome = context.executionOutcome
1708
+ error("client broker failed", 0)
1709
+ end
1710
+ return invoked.result
1711
+ end, data or {})
1712
+ if brokerFailure ~= nil then
1713
+ context.executionOutcome = outcome
1714
+ return brokerFailure
1304
1715
  end
1305
- return response
1716
+ return result
1306
1717
  end
1307
1718
  local function dispatchClientRequest(peerId, target, endpoint, data, context)
1308
1719
  if endpoint == "/api/capture-script-profiler" then
@@ -1348,33 +1759,123 @@ local function dispatchClientRequest(peerId, target, endpoint, data, context)
1348
1759
  }
1349
1760
  end
1350
1761
  if endpoint == "/api/capture-script-profiler" then
1351
- return invokeClientProfiler(entry, target, data, context)
1762
+ return invokeClientOnce(entry, target, endpoint, data, context, CLIENT_PROFILER_MAX_WAIT_SECONDS, CLIENT_RESPONSE_RESERVE_SECONDS)
1352
1763
  end
1353
1764
  if endpoint == "/api/capture-studio" then
1354
- return CaptureTransfer.receive(function(captureEndpoint, captureData)
1355
- return entry.remote:InvokeClient(entry.player, {
1356
- endpoint = captureEndpoint,
1357
- data = captureData,
1358
- })
1359
- end, data or {})
1765
+ return invokeClientCapture(entry, target, data, context)
1360
1766
  end
1361
- local envelope = {
1362
- endpoint = endpoint,
1363
- data = data,
1767
+ return invokeClientOnce(entry, target, endpoint, data, context)
1768
+ end
1769
+ local function optionalNumber(value)
1770
+ local _value = value
1771
+ local _condition = type(_value) == "number"
1772
+ if _condition then
1773
+ _condition = value == value
1774
+ end
1775
+ return if _condition then value else nil
1776
+ end
1777
+ local function parseHeartbeat(payload)
1778
+ local _payload = payload
1779
+ if not (type(_payload) == "table") then
1780
+ return nil
1781
+ end
1782
+ local fields = payload
1783
+ local sentAt = optionalNumber(fields.sentAt)
1784
+ if fields.kind ~= "heartbeat" or sentAt == nil then
1785
+ return nil
1786
+ end
1787
+ local requests = {}
1788
+ local _requests = fields.requests
1789
+ if type(_requests) == "table" then
1790
+ for _, value in fields.requests do
1791
+ if #requests >= MAX_REPORTED_CLIENT_REQUESTS then
1792
+ break
1793
+ end
1794
+ if not (type(value) == "table") then
1795
+ continue
1796
+ end
1797
+ local request = value
1798
+ local startedAt = optionalNumber(request.startedAt)
1799
+ local _requestId = request.requestId
1800
+ local _condition = not (type(_requestId) == "string")
1801
+ if not _condition then
1802
+ _condition = #request.requestId > 384
1803
+ if not _condition then
1804
+ local _endpoint = request.endpoint
1805
+ _condition = not (type(_endpoint) == "string")
1806
+ if not _condition then
1807
+ _condition = #request.endpoint > 128 or startedAt == nil
1808
+ end
1809
+ end
1810
+ end
1811
+ if _condition then
1812
+ continue
1813
+ end
1814
+ local _arg0 = {
1815
+ requestId = request.requestId,
1816
+ endpoint = request.endpoint,
1817
+ startedAt = startedAt,
1818
+ finishedAt = optionalNumber(request.finishedAt),
1819
+ }
1820
+ table.insert(requests, _arg0)
1821
+ end
1822
+ end
1823
+ return {
1824
+ kind = "heartbeat",
1825
+ sentAt = sentAt,
1826
+ pingSentAt = optionalNumber(fields.pingSentAt),
1827
+ pingReceivedAt = optionalNumber(fields.pingReceivedAt),
1828
+ requests = requests,
1364
1829
  }
1365
- local invokeOk, invokeResult = pcall(function()
1366
- return entry.remote:InvokeClient(entry.player, envelope)
1830
+ end
1831
+ local function setupHeartbeatChannel()
1832
+ local existing = ReplicatedStorage:FindFirstChild(HEARTBEAT_NAME)
1833
+ if existing ~= nil and not existing:IsA("RemoteEvent") then
1834
+ warn(`[robloxstudio-mcp] server: {HEARTBEAT_NAME} exists but is not a RemoteEvent; client bridge liveness is unavailable`)
1835
+ return nil
1836
+ end
1837
+ local event = existing or Instance.new("RemoteEvent")
1838
+ event.Name = HEARTBEAT_NAME
1839
+ event.OnServerEvent:Connect(function(player, payload)
1840
+ local _player = player
1841
+ local entry = proxyByPlayer[_player]
1842
+ if entry == nil then
1843
+ return nil
1844
+ end
1845
+ local heartbeat = parseHeartbeat(payload)
1846
+ if heartbeat == nil then
1847
+ return nil
1848
+ end
1849
+ local _object = table.clone(heartbeat)
1850
+ setmetatable(_object, nil)
1851
+ _object.receivedAt = Workspace:GetServerTimeNow()
1852
+ entry.heartbeat = _object
1367
1853
  end)
1368
- if not invokeOk then
1369
- return {
1370
- success = false,
1371
- error = `InvokeClient failed: {tostring(invokeResult)}`,
1372
- }
1854
+ if event.Parent == nil then
1855
+ event.Parent = ReplicatedStorage
1373
1856
  end
1374
- return if invokeResult ~= nil then invokeResult else {
1375
- success = false,
1376
- error = "nil response",
1377
- }
1857
+ task.spawn(function()
1858
+ while event.Parent ~= nil and RunService:IsRunning() do
1859
+ local sentAt = Workspace:GetServerTimeNow()
1860
+ -- Only clients that have shown they listen get pings, so an older
1861
+ -- client never accumulates unhandled events.
1862
+ for player, entry in proxyByPlayer do
1863
+ if entry.heartbeat == nil then
1864
+ continue
1865
+ end
1866
+ if entry.firstPingSentAt == nil then
1867
+ entry.firstPingSentAt = sentAt
1868
+ end
1869
+ pcall(function()
1870
+ return event:FireClient(player, {
1871
+ kind = "ping",
1872
+ sentAt = sentAt,
1873
+ })
1874
+ end)
1875
+ end
1876
+ task.wait(HEARTBEAT_INTERVAL_SECONDS)
1877
+ end
1878
+ end)
1378
1879
  end
1379
1880
  local function setupServerBroker()
1380
1881
  if serverBrokerStarted then
@@ -1414,6 +1915,9 @@ local function setupServerBroker()
1414
1915
  success = true,
1415
1916
  }
1416
1917
  end
1918
+ -- Publish the heartbeat channel first, so a client that finds the broker
1919
+ -- also finds its liveness channel.
1920
+ setupHeartbeatChannel()
1417
1921
  if rf.Parent == nil then
1418
1922
  rf.Parent = ReplicatedStorage
1419
1923
  end
@@ -1981,9 +2485,9 @@ local function computeBridgeStamp()
1981
2485
  for i = 1, #combined do
1982
2486
  h = (h * 33 + (string.byte(combined, i))) % 2147483647
1983
2487
  end
1984
- -- "3.3.0" is replaced with the package version at package time
2488
+ -- "3.4.0" is replaced with the package version at package time
1985
2489
  -- (scripts/build-plugin.mjs injectVersion), so a release bump also restamps.
1986
- return `{tostring(h)}-3.3.0`
2490
+ return `{tostring(h)}-3.4.0`
1987
2491
  end
1988
2492
  local BRIDGE_STAMP = computeBridgeStamp()
1989
2493
  local function setSource(scriptInst, source)
@@ -4892,6 +5396,8 @@ return {
4892
5396
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
4893
5397
  local TS = require(script.Parent.Parent.Parent.include.RuntimeLib)
4894
5398
  local RunService = TS.import(script, script.Parent.Parent.Parent, "node_modules", "@rbxts", "services").RunService
5399
+ -- Length of one MicroProfiler tick for this snapshot. CPU threads and frame
5400
+ -- boundaries use TickToMsCpu; the GPU thread uses TickToMsGpu.
4895
5401
  local DEFAULT_DURATION_MS = 1000
4896
5402
  local MIN_DURATION_MS = 100
4897
5403
  local MAX_DURATION_MS = 5000
@@ -4904,6 +5410,25 @@ local MAX_EVENTS = 1000000
4904
5410
  local COOPERATIVE_CLOCK_CHECK_INTERVAL = 128
4905
5411
  local MAX_COOPERATIVE_SLICE_SECONDS = 0.008
4906
5412
  local DEFAULT_FRAME_WINDOW = 240
5413
+ -- The engine holds at most 256 frames, and fresh Studio peers already use 256.
5414
+ -- SetFrameLimit only narrows the view of retained frames (lowering it hides
5415
+ -- frames, raising it shows them again); the profiler's memory budget often holds
5416
+ -- fewer. Changing the limit clears counter history; setting the same value does not.
5417
+ local HISTORY_FRAME_LIMIT = 256
5418
+ -- A recording peer shows a new frame after one task.wait() almost always;
5419
+ -- Studio hitches of up to 12 frames (~0.2 s) were observed.
5420
+ local RECORDING_PROBE_SECONDS = 0.3
5421
+ -- Each probe copies the whole snapshot, so re-read at this interval after the
5422
+ -- first one-frame check instead of every frame.
5423
+ local RECORDING_PROBE_INTERVAL_SECONDS = 0.1
5424
+ -- A capture's first frame with scope events can arrive several frames after
5425
+ -- EnableCapture (on a fresh Studio peer the first frame took ~70 ms and frames
5426
+ -- 1-5 had no events). Check every frame for the first FIRST_FRAME_FAST_POLLS
5427
+ -- checks, then at the poll interval, for at most the timeout. Each check copies
5428
+ -- the snapshot, so the count stays bounded.
5429
+ local FIRST_FRAME_TIMEOUT_SECONDS = 0.5
5430
+ local FIRST_FRAME_FAST_POLLS = 12
5431
+ local FIRST_FRAME_POLL_SECONDS = 0.05
4907
5432
  local BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
4908
5433
  local PAD_BYTE = (string.byte("="))
4909
5434
  local B64 = {}
@@ -5070,8 +5595,10 @@ end
5070
5595
  local function stringContains(haystack, needle)
5071
5596
  return (string.find(string.lower(haystack), string.lower(needle), 1, true)) ~= nil
5072
5597
  end
5073
- local function rawToUs(raw)
5074
- return math.floor(raw / 1000 + 0.5)
5598
+ -- Spans above this are corrupt (the old raw-tick bound, 1e12 ns, was 1000 s).
5599
+ local MAX_SPAN_US = 1e9
5600
+ local function roundUs(us)
5601
+ return math.floor(us + 0.5)
5075
5602
  end
5076
5603
  local function round2(value)
5077
5604
  return math.floor(value * 100 + 0.5) / 100
@@ -5112,7 +5639,7 @@ local function pickFields(row, fields)
5112
5639
  end
5113
5640
  return out
5114
5641
  end
5115
- local function addFrameRaw(map, frameId, raw)
5642
+ local function addFrameUs(map, frameId, us)
5116
5643
  if frameId <= 0 then
5117
5644
  return nil
5118
5645
  end
@@ -5124,15 +5651,15 @@ local function addFrameRaw(map, frameId, raw)
5124
5651
  if _condition == nil then
5125
5652
  _condition = 0
5126
5653
  end
5127
- local _arg1 = _condition + raw
5654
+ local _arg1 = _condition + us
5128
5655
  _map[_exp] = _arg1
5129
5656
  end
5130
- local function summarizeFrameImpact(frameRawById, analyzedFrames, checkpoint)
5131
- local _condition = frameRawById == nil
5657
+ local function summarizeFrameImpact(frameUsById, analyzedFrames, checkpoint)
5658
+ local _condition = frameUsById == nil
5132
5659
  if not _condition then
5133
5660
  -- ▼ ReadonlyMap.size ▼
5134
5661
  local _size = 0
5135
- for _ in frameRawById do
5662
+ for _ in frameUsById do
5136
5663
  _size += 1
5137
5664
  end
5138
5665
  -- ▲ ReadonlyMap.size ▲
@@ -5151,9 +5678,9 @@ local function summarizeFrameImpact(frameRawById, analyzedFrames, checkpoint)
5151
5678
  local totalUs = 0
5152
5679
  local maxUs = 0
5153
5680
  local maxFrameId = 0
5154
- for frameId, raw in frameRawById do
5681
+ for frameId, exactUs in frameUsById do
5155
5682
  checkpoint()
5156
- local us = rawToUs(raw)
5683
+ local us = roundUs(exactUs)
5157
5684
  table.insert(values, us)
5158
5685
  totalUs += us
5159
5686
  if us > maxUs then
@@ -5253,6 +5780,100 @@ local function safeCall(fn)
5253
5780
  end
5254
5781
  return false, tostring(value)
5255
5782
  end
5783
+ local function readNewestFrame(LibMP, checkEvents)
5784
+ if checkEvents == nil then
5785
+ checkEvents = false
5786
+ end
5787
+ local readOk, data = safeCall(function()
5788
+ return LibMP.Control:CaptureToBufferSync()
5789
+ end)
5790
+ if not readOk then
5791
+ return nil
5792
+ end
5793
+ local openOk, opened = safeCall(function()
5794
+ return LibMP.Session.OpenFromBuffer(data)
5795
+ end)
5796
+ if not openOk or not (opened ~= "" and opened) then
5797
+ return nil
5798
+ end
5799
+ local session = opened
5800
+ local infoOk, info = safeCall(function()
5801
+ local newest = session:GetFrameIdMax()
5802
+ -- A GetFrameDesc view is invalidated by the next Get/Fetch call on the
5803
+ -- session, so read it immediately.
5804
+ local desc = if newest > 0 then session:GetFrameDesc(newest) else nil
5805
+ local absolute = if desc ~= nil then desc:FrameAbsoluteId() else 0
5806
+ local hasEvents = false
5807
+ if checkEvents and newest > 0 then
5808
+ local iterator = session:CreateLogIterator()
5809
+ local configured = safeCall(function()
5810
+ iterator:Configure({
5811
+ StartFrameId = newest,
5812
+ EndFrameId = newest,
5813
+ SkipGpuThreads = true,
5814
+ SkipEvents = true,
5815
+ SkipPausedFrames = true,
5816
+ SkipFrameBoundaries = true,
5817
+ })
5818
+ return true
5819
+ end)
5820
+ if configured then
5821
+ local stepped, steppedResult = safeCall(function()
5822
+ return iterator:Step()
5823
+ end)
5824
+ hasEvents = stepped and steppedResult == true
5825
+ end
5826
+ iterator:Dispose()
5827
+ end
5828
+ return {
5829
+ id = math.max(newest, 0),
5830
+ absolute = absolute,
5831
+ hasEvents = hasEvents,
5832
+ }
5833
+ end)
5834
+ session:Dispose()
5835
+ return if infoOk then info else nil
5836
+ end
5837
+ -- LibMP cannot report whether capture is on. A paused peer serves the same
5838
+ -- cached frames on every read, so only a recording peer's newest absolute frame
5839
+ -- ID advances. Studio peers start with capture paused. This must run before the
5840
+ -- tool calls EnableProfiler: on a fresh peer EnableProfiler alone starts frames
5841
+ -- recording, which would read as a peer that was already recording.
5842
+ local function detectRecording(LibMP)
5843
+ local first = readNewestFrame(LibMP)
5844
+ if first == nil then
5845
+ return {
5846
+ recording = false,
5847
+ known = false,
5848
+ boundaryAbsolute = 0,
5849
+ boundaryFrameId = 0,
5850
+ }
5851
+ end
5852
+ local deadline = os.clock() + RECORDING_PROBE_SECONDS
5853
+ local waitSeconds
5854
+ while os.clock() < deadline do
5855
+ task.wait(waitSeconds)
5856
+ waitSeconds = RECORDING_PROBE_INTERVAL_SECONDS
5857
+ local latest = readNewestFrame(LibMP)
5858
+ if latest == nil then
5859
+ break
5860
+ end
5861
+ if latest.absolute ~= first.absolute then
5862
+ return {
5863
+ recording = true,
5864
+ known = true,
5865
+ boundaryAbsolute = latest.absolute,
5866
+ boundaryFrameId = latest.id,
5867
+ }
5868
+ end
5869
+ end
5870
+ return {
5871
+ recording = false,
5872
+ known = true,
5873
+ boundaryAbsolute = first.absolute,
5874
+ boundaryFrameId = first.id,
5875
+ }
5876
+ end
5256
5877
  local function isIdleTimer(info)
5257
5878
  local name = string.lower(info.name)
5258
5879
  if name == "sleep" or name == "idle" then
@@ -5314,7 +5935,7 @@ local function recommendedToolsForGroups(groups, targetRole)
5314
5935
  end
5315
5936
  return tools
5316
5937
  end
5317
- local function collectFrameSummary(session, startFrame, frameMax, checkpoint)
5938
+ local function collectFrameSummary(session, startFrame, frameMax, usPerTickCpu, checkpoint)
5318
5939
  local frameRows = {}
5319
5940
  local durations = {}
5320
5941
  local incompleteFrames = 0
@@ -5343,20 +5964,25 @@ local function collectFrameSummary(session, startFrame, frameMax, checkpoint)
5343
5964
  local desc = descOrErr
5344
5965
  local tickStart = desc:TickStartCpu()
5345
5966
  local tickEnd = desc:TickEndCpu()
5346
- local durationRaw = tickEnd - tickStart
5967
+ local durationExactUs = (tickEnd - tickStart) * usPerTickCpu
5347
5968
  local isIncomplete = desc:IsIncomplete()
5348
5969
  local isPaused = desc:IsPaused()
5349
5970
  if isIncomplete then
5350
5971
  incompleteFrames += 1
5351
5972
  end
5973
+ -- Pausing capture leaves one frame spanning the whole pause (seconds long,
5974
+ -- IsPaused). It holds no captured work, so it is counted but not timed,
5975
+ -- matching the event iterator's SkipPausedFrames.
5352
5976
  if isPaused then
5353
5977
  pausedFrames += 1
5978
+ _frameId = frameId
5979
+ continue
5354
5980
  end
5355
- if durationRaw <= 0 or durationRaw > 1000000000000 then
5981
+ if durationExactUs <= 0 or durationExactUs > MAX_SPAN_US then
5356
5982
  _frameId = frameId
5357
5983
  continue
5358
5984
  end
5359
- local durationUs = rawToUs(durationRaw)
5985
+ local durationUs = roundUs(durationExactUs)
5360
5986
  table.insert(durations, durationUs)
5361
5987
  local row = {
5362
5988
  frame_id = frameId,
@@ -5365,9 +5991,6 @@ local function collectFrameSummary(session, startFrame, frameMax, checkpoint)
5365
5991
  if isIncomplete then
5366
5992
  row.incomplete = true
5367
5993
  end
5368
- if isPaused then
5369
- row.paused = true
5370
- end
5371
5994
  table.insert(frameRows, row)
5372
5995
  _frameId = frameId
5373
5996
  end
@@ -5459,8 +6082,14 @@ local function captureMicroProfiler(requestData)
5459
6082
  backend = backend,
5460
6083
  }
5461
6084
  end
6085
+ -- Studio peers start with capture paused. Leave the peer as found: if
6086
+ -- something else is already recording, keep it recording; otherwise pause
6087
+ -- again after the export.
6088
+ local prior = detectRecording(LibMP)
6089
+ -- Keep the engine default instead of narrowing history to frame_window:
6090
+ -- frame_window selects frames during analysis.
5462
6091
  local frameLimitOk, frameLimitResult = safeCall(function()
5463
- return LibMP.Control:SetFrameLimit(math.min(frameWindow, 256))
6092
+ return LibMP.Control:SetFrameLimit(HISTORY_FRAME_LIMIT)
5464
6093
  end)
5465
6094
  if not frameLimitOk then
5466
6095
  return {
@@ -5469,6 +6098,9 @@ local function captureMicroProfiler(requestData)
5469
6098
  backend = backend,
5470
6099
  }
5471
6100
  end
6101
+ -- Profiling is on by default in Studio and the tool never turns it off. It
6102
+ -- must follow the recording check: on a fresh peer EnableProfiler alone
6103
+ -- starts frames recording.
5472
6104
  local profilerOk, profilerResult = safeCall(function()
5473
6105
  return LibMP.Control:EnableProfiler(true)
5474
6106
  end)
@@ -5479,31 +6111,72 @@ local function captureMicroProfiler(requestData)
5479
6111
  backend = backend,
5480
6112
  }
5481
6113
  end
5482
- local captureStartOk, captureStartResult = safeCall(function()
5483
- return LibMP.Control:EnableCapture(true)
5484
- end)
5485
- if not captureStartOk then
5486
- return {
5487
- error = "micro_profiler_capture_start_failed",
5488
- message = tostring(captureStartResult),
5489
- backend = backend,
5490
- }
6114
+ -- Absolute ID of the capture's first analyzed frame. Frames before it predate
6115
+ -- the capture or are instrumentation warm-up without scope events.
6116
+ local windowStartAbsolute = prior.boundaryAbsolute + 1
6117
+ -- Frame ID of that frame. Frame IDs run on without gaps, so dropped frames
6118
+ -- from the window are counted exactly against it.
6119
+ local windowStartFrameId = prior.boundaryFrameId + 1
6120
+ local firstFrameWaitMs = 0
6121
+ -- When the first-frame wait times out, the window starts right after the
6122
+ -- pre-capture frame and so includes the frames recorded during the wait.
6123
+ local windowStartsAtWait
6124
+ if not prior.recording then
6125
+ local captureStartOk, captureStartResult = safeCall(function()
6126
+ return LibMP.Control:EnableCapture(true)
6127
+ end)
6128
+ if not captureStartOk then
6129
+ return {
6130
+ error = "micro_profiler_capture_start_failed",
6131
+ message = tostring(captureStartResult),
6132
+ backend = backend,
6133
+ }
6134
+ end
6135
+ -- The first frames after capture starts can carry no scope events yet
6136
+ -- (frames 1-5 of a fresh peer's first capture), so start timing
6137
+ -- duration_ms at the first frame with events; the analysis starts there too.
6138
+ local waitStartedAt = os.clock()
6139
+ windowStartsAtWait = waitStartedAt
6140
+ local polls = 0
6141
+ while os.clock() - waitStartedAt < FIRST_FRAME_TIMEOUT_SECONDS do
6142
+ task.wait(if polls < FIRST_FRAME_FAST_POLLS then nil else FIRST_FRAME_POLL_SECONDS)
6143
+ polls += 1
6144
+ local latest = readNewestFrame(LibMP, true)
6145
+ if latest ~= nil and latest.absolute > prior.boundaryAbsolute and latest.hasEvents then
6146
+ windowStartAbsolute = latest.absolute
6147
+ windowStartFrameId = latest.id
6148
+ windowStartsAtWait = nil
6149
+ break
6150
+ end
6151
+ end
6152
+ firstFrameWaitMs = (os.clock() - waitStartedAt) * 1000
5491
6153
  end
6154
+ local timerStartedAt = os.clock()
5492
6155
  task.wait(durationMs / 1000)
6156
+ -- Wall time covered by the analysis window: from the first analyzed frame, or
6157
+ -- from the start of the wait when it timed out.
6158
+ local _exp = os.clock()
6159
+ local _condition_1 = windowStartsAtWait
6160
+ if _condition_1 == nil then
6161
+ _condition_1 = timerStartedAt
6162
+ end
6163
+ local captureWallMs = (_exp - _condition_1) * 1000
5493
6164
  -- Active reads synchronize the engine's data; paused reads can return an
5494
- -- empty or stale cache. Export first, then pause, including on export failure.
6165
+ -- empty or stale cache. Export first, then restore, including on export failure.
5495
6166
  local bufferOk, snapshotOrErr = safeCall(function()
5496
6167
  return LibMP.Control:CaptureToBufferSync()
5497
6168
  end)
5498
- local captureStopOk, captureStopResult = safeCall(function()
5499
- return LibMP.Control:EnableCapture(false)
5500
- end)
5501
- if not captureStopOk then
5502
- return {
5503
- error = "micro_profiler_capture_stop_failed",
5504
- message = tostring(captureStopResult),
5505
- backend = backend,
5506
- }
6169
+ if not prior.recording then
6170
+ local captureStopOk, captureStopResult = safeCall(function()
6171
+ return LibMP.Control:EnableCapture(false)
6172
+ end)
6173
+ if not captureStopOk then
6174
+ return {
6175
+ error = "micro_profiler_capture_stop_failed",
6176
+ message = tostring(captureStopResult),
6177
+ backend = backend,
6178
+ }
6179
+ end
5507
6180
  end
5508
6181
  if not bufferOk then
5509
6182
  return {
@@ -5533,13 +6206,94 @@ local function captureMicroProfiler(requestData)
5533
6206
  backend = backend,
5534
6207
  }
5535
6208
  end
6209
+ -- MicroProfiler ticks are not nanoseconds: their length comes from the
6210
+ -- snapshot's clock (for example 2.1e-7 ms on a 4.7 GHz CPU timer). GPU-thread
6211
+ -- timestamps use their own clock.
6212
+ local clockOk, clockOrErr = safeCall(function()
6213
+ return session:FetchGlobalDesc()
6214
+ end)
6215
+ local clock = if clockOk then clockOrErr else nil
6216
+ local _tickToMsCpu = clock
6217
+ if _tickToMsCpu ~= nil then
6218
+ _tickToMsCpu = _tickToMsCpu.TickToMsCpu
6219
+ end
6220
+ local tickToMsCpu = _tickToMsCpu
6221
+ local _tickToMsGpu = clock
6222
+ if _tickToMsGpu ~= nil then
6223
+ _tickToMsGpu = _tickToMsGpu.TickToMsGpu
6224
+ end
6225
+ local tickToMsGpu = _tickToMsGpu
6226
+ local validTickLength = function(value)
6227
+ local _value = value
6228
+ local _condition_2 = type(_value) == "number"
6229
+ if _condition_2 then
6230
+ _condition_2 = value > 0 and value < math.huge
6231
+ end
6232
+ return _condition_2
6233
+ end
6234
+ if not validTickLength(tickToMsCpu) or (includeGpu and not validTickLength(tickToMsGpu)) then
6235
+ session:Dispose()
6236
+ return {
6237
+ error = "micro_profiler_clock_unavailable",
6238
+ message = "The MicroProfiler snapshot did not report a valid tick length, so its times cannot be converted.",
6239
+ tick_to_ms_cpu = tickToMsCpu,
6240
+ tick_to_ms_gpu = tickToMsGpu,
6241
+ buffer_bytes = buffer.len(snapshot),
6242
+ backend = backend,
6243
+ }
6244
+ end
6245
+ local usPerTickCpu = tickToMsCpu * 1000
6246
+ local usPerTickGpu = if validTickLength(tickToMsGpu) then tickToMsGpu * 1000 else usPerTickCpu
5536
6247
  local timerIds = session:FetchTimerIds() or {}
5537
6248
  local threadIds = session:FetchThreadIds() or {}
5538
6249
  local frameMin = session:GetFrameIdMin()
5539
6250
  local frameMax = session:GetFrameIdMax()
5540
- -- Frame IDs start at 1. Studio cuts a frame only when it renders, so a capture
5541
- -- without frames means nothing was drawn, not that the workload was idle.
5542
- if frameMax <= 0 then
6251
+ -- Frame IDs start at 1. Studio cuts a frame only when it renders. Retained
6252
+ -- history can predate this capture (a recording peer, or frames kept from an
6253
+ -- earlier capture), so analyze only frames from the capture's first analyzed
6254
+ -- frame on. That also drops warm-up frames without scope events and the one
6255
+ -- IsPaused frame a resume adds.
6256
+ local firstCaptureFrame = frameMax + 1
6257
+ local capturedFrames = 0
6258
+ -- Paused frames inside the window (none normally) can never carry events.
6259
+ local pausedFrameIds = {}
6260
+ do
6261
+ local _frameId = frameMax
6262
+ local _shouldIncrement = false
6263
+ while true do
6264
+ local frameId = _frameId
6265
+ if _shouldIncrement then
6266
+ frameId -= 1
6267
+ else
6268
+ _shouldIncrement = true
6269
+ end
6270
+ if not (frameMax > 0 and frameId >= frameMin) then
6271
+ break
6272
+ end
6273
+ local descOk, descOrErr = safeCall(function()
6274
+ return session:GetFrameDesc(frameId)
6275
+ end)
6276
+ if not descOk or not (descOrErr ~= "" and descOrErr) then
6277
+ break
6278
+ end
6279
+ local desc = descOrErr
6280
+ if desc:FrameAbsoluteId() < windowStartAbsolute then
6281
+ break
6282
+ end
6283
+ if desc:IsPaused() then
6284
+ local _frameId_1 = frameId
6285
+ table.insert(pausedFrameIds, _frameId_1)
6286
+ _frameId = frameId
6287
+ continue
6288
+ end
6289
+ capturedFrames += 1
6290
+ firstCaptureFrame = frameId
6291
+ _frameId = frameId
6292
+ end
6293
+ end
6294
+ -- No frame recorded during the capture means nothing was drawn, not that the
6295
+ -- workload was idle.
6296
+ if capturedFrames == 0 then
5543
6297
  session:Dispose()
5544
6298
  return {
5545
6299
  error = "micro_profiler_no_frames",
@@ -5549,8 +6303,18 @@ local function captureMicroProfiler(requestData)
5549
6303
  backend = backend,
5550
6304
  }
5551
6305
  end
5552
- local startFrame = math.max(frameMin, frameMax - frameWindow + 1)
5553
- local framesConsidered = if frameMax >= startFrame then frameMax - startFrame + 1 else 0
6306
+ local startFrame = math.max(firstCaptureFrame, frameMax - frameWindow + 1)
6307
+ local framesConsidered = frameMax - startFrame + 1
6308
+ -- The engine drops its oldest frames once its memory budget fills, often well
6309
+ -- below the frame limit (about 70 frames on a loaded server peer). Frames from
6310
+ -- the window's first frame to the oldest retained one were recorded during
6311
+ -- this capture and are gone (warm-up frames and the IsPaused frame a resume
6312
+ -- adds come before the window and do not count, except after a first-frame
6313
+ -- wait timeout, when the window starts right after the pre-capture frame).
6314
+ -- That matters only if the analysis wanted them: frame_window may ask for
6315
+ -- fewer frames than were retained.
6316
+ local framesEvicted = if prior.known then math.max(0, frameMin - windowStartFrameId) else 0
6317
+ local historyTruncated = framesEvicted > 0 and frameMax - firstCaptureFrame + 1 < frameWindow
5554
6318
  local groupCache = {}
5555
6319
  local timerCache = {}
5556
6320
  local threadCache = {}
@@ -5567,15 +6331,15 @@ local function captureMicroProfiler(requestData)
5567
6331
  return session:FetchGroupDesc(groupId)
5568
6332
  end)
5569
6333
  local desc = if ok then descOrErr else nil
5570
- local _condition_1 = desc
5571
- if _condition_1 then
6334
+ local _condition_2 = desc
6335
+ if _condition_2 then
5572
6336
  local _groupName = desc.GroupName
5573
- _condition_1 = type(_groupName) == "string"
5574
- if _condition_1 then
5575
- _condition_1 = desc.GroupName ~= ""
6337
+ _condition_2 = type(_groupName) == "string"
6338
+ if _condition_2 then
6339
+ _condition_2 = desc.GroupName ~= ""
5576
6340
  end
5577
6341
  end
5578
- local name = if _condition_1 then desc.GroupName else tostring(groupId)
6342
+ local name = if _condition_2 then desc.GroupName else tostring(groupId)
5579
6343
  local _groupId_1 = groupId
5580
6344
  groupCache[_groupId_1] = name
5581
6345
  return name
@@ -5590,25 +6354,25 @@ local function captureMicroProfiler(requestData)
5590
6354
  return session:FetchTimerDesc(timerId)
5591
6355
  end)
5592
6356
  local desc = if ok then descOrErr else nil
5593
- local _condition_1 = desc
5594
- if _condition_1 then
6357
+ local _condition_2 = desc
6358
+ if _condition_2 then
5595
6359
  local _groupId = desc.GroupId
5596
- _condition_1 = type(_groupId) == "number"
6360
+ _condition_2 = type(_groupId) == "number"
5597
6361
  end
5598
- local groupId = if _condition_1 then desc.GroupId else nil
6362
+ local groupId = if _condition_2 then desc.GroupId else nil
5599
6363
  local _object = {
5600
6364
  timer_id = timerId,
5601
6365
  }
5602
6366
  local _left = "name"
5603
- local _condition_2 = desc
5604
- if _condition_2 then
6367
+ local _condition_3 = desc
6368
+ if _condition_3 then
5605
6369
  local _timerName = desc.TimerName
5606
- _condition_2 = type(_timerName) == "string"
5607
- if _condition_2 then
5608
- _condition_2 = desc.TimerName ~= ""
6370
+ _condition_3 = type(_timerName) == "string"
6371
+ if _condition_3 then
6372
+ _condition_3 = desc.TimerName ~= ""
5609
6373
  end
5610
6374
  end
5611
- _object[_left] = if _condition_2 then desc.TimerName else tostring(timerId)
6375
+ _object[_left] = if _condition_3 then desc.TimerName else tostring(timerId)
5612
6376
  _object.group_id = groupId
5613
6377
  _object.group = getGroupName(groupId)
5614
6378
  _object.is_user_timer = if desc and desc.IsUserTimer == true then true else nil
@@ -5631,53 +6395,53 @@ local function captureMicroProfiler(requestData)
5631
6395
  thread_id = threadId,
5632
6396
  }
5633
6397
  local _left = "name"
5634
- local _condition_1 = desc
5635
- if _condition_1 then
6398
+ local _condition_2 = desc
6399
+ if _condition_2 then
5636
6400
  local _threadName = desc.ThreadName
5637
- _condition_1 = type(_threadName) == "string"
5638
- if _condition_1 then
5639
- _condition_1 = desc.ThreadName ~= ""
6401
+ _condition_2 = type(_threadName) == "string"
6402
+ if _condition_2 then
6403
+ _condition_2 = desc.ThreadName ~= ""
5640
6404
  end
5641
6405
  end
5642
- _object[_left] = if _condition_1 then desc.ThreadName else tostring(threadId)
6406
+ _object[_left] = if _condition_2 then desc.ThreadName else tostring(threadId)
5643
6407
  local info = _object
5644
6408
  if desc and desc.IsGpu == true then
5645
6409
  info.is_gpu = true
5646
6410
  end
5647
- local _condition_2 = desc
5648
- if _condition_2 then
6411
+ local _condition_3 = desc
6412
+ if _condition_3 then
5649
6413
  local _bufferSize = desc.BufferSize
5650
- _condition_2 = type(_bufferSize) == "number"
6414
+ _condition_3 = type(_bufferSize) == "number"
5651
6415
  end
5652
- if _condition_2 then
6416
+ if _condition_3 then
5653
6417
  info.buffer_size = desc.BufferSize
5654
6418
  end
5655
6419
  local _threadId_1 = threadId
5656
6420
  threadCache[_threadId_1] = info
5657
6421
  return info
5658
6422
  end
5659
- local function addTimerAggregate(map, timerId, inclusiveRaw, exclusiveRaw)
6423
+ local function addTimerAggregate(map, timerId, inclusiveUs, exclusiveUs)
5660
6424
  local _map = map
5661
6425
  local _timerId = timerId
5662
6426
  local aggregate = _map[_timerId]
5663
6427
  if aggregate == nil then
5664
6428
  aggregate = {
5665
6429
  timer_id = timerId,
5666
- inclusive_raw = 0,
5667
- exclusive_raw = 0,
6430
+ inclusive_us = 0,
6431
+ exclusive_us = 0,
5668
6432
  count = 0,
5669
- max_raw = 0,
6433
+ max_us = 0,
5670
6434
  }
5671
6435
  local _map_1 = map
5672
6436
  local _timerId_1 = timerId
5673
6437
  local _aggregate = aggregate
5674
6438
  _map_1[_timerId_1] = _aggregate
5675
6439
  end
5676
- aggregate.inclusive_raw += inclusiveRaw
5677
- aggregate.exclusive_raw += exclusiveRaw
6440
+ aggregate.inclusive_us += inclusiveUs
6441
+ aggregate.exclusive_us += exclusiveUs
5678
6442
  aggregate.count += 1
5679
- if inclusiveRaw > aggregate.max_raw then
5680
- aggregate.max_raw = inclusiveRaw
6443
+ if inclusiveUs > aggregate.max_us then
6444
+ aggregate.max_us = inclusiveUs
5681
6445
  end
5682
6446
  end
5683
6447
  local focusMasks = FOCUS_GROUP_MASKS[focus] or {}
@@ -5721,6 +6485,8 @@ local function captureMicroProfiler(requestData)
5721
6485
  end
5722
6486
  local checkpoint = createCooperativeCheckpoint()
5723
6487
  local stacks = {}
6488
+ -- Microseconds per tick for each thread: the GPU thread has its own clock.
6489
+ local threadUsPerTick = {}
5724
6490
  local aggregates = {}
5725
6491
  local timerThreadAggregates = {}
5726
6492
  local timerFrameAggregates = {}
@@ -5734,7 +6500,7 @@ local function captureMicroProfiler(requestData)
5734
6500
  local sampledFrameMin
5735
6501
  local sampledFrameMax
5736
6502
  local lastProcessedFrameId
5737
- local lastProcessedTimestampRaw
6503
+ local lastProcessedTimestampUs
5738
6504
  while eventsSampled < maxEvents do
5739
6505
  checkpoint()
5740
6506
  if not iterator:Step() then
@@ -5748,9 +6514,15 @@ local function captureMicroProfiler(requestData)
5748
6514
  local frameId = state:FrameId()
5749
6515
  local threadId = state:ThreadId()
5750
6516
  local timerId = state:TimerId()
5751
- local timestampRaw = state:Timestamp()
6517
+ local timestampTick = state:Timestamp()
6518
+ local usPerTick = threadUsPerTick[threadId]
6519
+ if usPerTick == nil then
6520
+ usPerTick = if state:IsGpuThread() then usPerTickGpu else usPerTickCpu
6521
+ local _usPerTick = usPerTick
6522
+ threadUsPerTick[threadId] = _usPerTick
6523
+ end
5752
6524
  lastProcessedFrameId = frameId
5753
- lastProcessedTimestampRaw = timestampRaw
6525
+ lastProcessedTimestampUs = timestampTick * usPerTick
5754
6526
  if frameId > 0 then
5755
6527
  sampledFrames[frameId] = true
5756
6528
  if sampledFrameMin == nil or frameId < sampledFrameMin then
@@ -5771,8 +6543,8 @@ local function captureMicroProfiler(requestData)
5771
6543
  local _stack = stack
5772
6544
  local _arg0 = {
5773
6545
  timerId = timerId,
5774
- timestampRaw = timestampRaw,
5775
- childRaw = 0,
6546
+ enterTick = timestampTick,
6547
+ childUs = 0,
5776
6548
  frameId = frameId,
5777
6549
  }
5778
6550
  table.insert(_stack, _arg0)
@@ -5796,49 +6568,56 @@ local function captureMicroProfiler(requestData)
5796
6568
  unmatchedExits += 1
5797
6569
  continue
5798
6570
  end
5799
- local inclusiveRaw = timestampRaw - entry.timestampRaw
5800
- if inclusiveRaw < 0 or inclusiveRaw > 1000000000000 then
6571
+ local inclusiveUs = (timestampTick - entry.enterTick) * usPerTick
6572
+ if inclusiveUs < 0 or inclusiveUs > MAX_SPAN_US then
5801
6573
  droppedSpans += 1
5802
6574
  continue
5803
6575
  end
5804
- local exclusiveRaw = math.max(0, inclusiveRaw - entry.childRaw)
6576
+ local exclusiveUs = math.max(0, inclusiveUs - entry.childUs)
5805
6577
  local parent = stack[#stack]
5806
6578
  if parent ~= nil then
5807
- parent.childRaw += inclusiveRaw
6579
+ parent.childUs += inclusiveUs
5808
6580
  local edgeKey = `{parent.timerId}:{timerId}`
5809
6581
  local edge = edgeAggregates[edgeKey]
5810
6582
  if edge == nil then
5811
6583
  edge = {
5812
6584
  parent_timer_id = parent.timerId,
5813
6585
  child_timer_id = timerId,
5814
- inclusive_raw = 0,
6586
+ inclusive_us = 0,
5815
6587
  count = 0,
5816
- max_raw = 0,
6588
+ max_us = 0,
5817
6589
  }
5818
6590
  local _edge = edge
5819
6591
  edgeAggregates[edgeKey] = _edge
5820
6592
  end
5821
- edge.inclusive_raw += inclusiveRaw
6593
+ edge.inclusive_us += inclusiveUs
5822
6594
  edge.count += 1
5823
- if inclusiveRaw > edge.max_raw then
5824
- edge.max_raw = inclusiveRaw
6595
+ if inclusiveUs > edge.max_us then
6596
+ edge.max_us = inclusiveUs
5825
6597
  end
5826
6598
  end
5827
- addTimerAggregate(aggregates, timerId, inclusiveRaw, exclusiveRaw)
6599
+ addTimerAggregate(aggregates, timerId, inclusiveUs, exclusiveUs)
5828
6600
  local frameMap = timerFrameAggregates[timerId]
5829
6601
  if frameMap == nil then
5830
6602
  frameMap = {}
5831
6603
  local _frameMap = frameMap
5832
6604
  timerFrameAggregates[timerId] = _frameMap
5833
6605
  end
5834
- addFrameRaw(frameMap, if entry.frameId > 0 then entry.frameId else frameId, inclusiveRaw)
6606
+ addFrameUs(frameMap, if entry.frameId > 0 then entry.frameId else frameId, inclusiveUs)
5835
6607
  local threadMap = timerThreadAggregates[timerId]
5836
6608
  if threadMap == nil then
5837
6609
  threadMap = {}
5838
6610
  local _threadMap = threadMap
5839
6611
  timerThreadAggregates[timerId] = _threadMap
5840
6612
  end
5841
- addTimerAggregate(threadMap, threadId, inclusiveRaw, exclusiveRaw)
6613
+ addTimerAggregate(threadMap, threadId, inclusiveUs, exclusiveUs)
6614
+ end
6615
+ end
6616
+ -- The iterator skips paused frames (SkipPausedFrames), so they cannot be sampled.
6617
+ local selectedPausedFrames = 0
6618
+ for _, frameId in pausedFrameIds do
6619
+ if frameId >= startFrame then
6620
+ selectedPausedFrames += 1
5842
6621
  end
5843
6622
  end
5844
6623
  -- ▼ ReadonlySet.size ▼
@@ -5847,25 +6626,25 @@ local function captureMicroProfiler(requestData)
5847
6626
  _size += 1
5848
6627
  end
5849
6628
  -- ▲ ReadonlySet.size ▲
5850
- local sampledFrameCoveragePct = percent(_size, framesConsidered)
5851
- local _condition_1 = sampledFrameMin
5852
- if _condition_1 == nil then
5853
- _condition_1 = startFrame
5854
- end
5855
- local analysisFrameMin = _condition_1
5856
- local _condition_2 = sampledFrameMax
6629
+ local sampledFrameCoveragePct = percent(_size, framesConsidered - selectedPausedFrames)
6630
+ local _condition_2 = sampledFrameMin
5857
6631
  if _condition_2 == nil then
5858
- _condition_2 = frameMax
6632
+ _condition_2 = startFrame
5859
6633
  end
5860
- local analysisFrameMax = _condition_2
5861
- local frameSummary = collectFrameSummary(session, analysisFrameMin, analysisFrameMax, checkpoint)
6634
+ local analysisFrameMin = _condition_2
6635
+ local _condition_3 = sampledFrameMax
6636
+ if _condition_3 == nil then
6637
+ _condition_3 = frameMax
6638
+ end
6639
+ local analysisFrameMax = _condition_3
6640
+ local frameSummary = collectFrameSummary(session, analysisFrameMin, analysisFrameMax, usPerTickCpu, checkpoint)
5862
6641
  local _frames = frameSummary.frames
5863
- local _condition_3 = type(_frames) == "number"
5864
- if _condition_3 then
5865
- _condition_3 = (frameSummary.frames) > 0
6642
+ local _condition_4 = type(_frames) == "number"
6643
+ if _condition_4 then
6644
+ _condition_4 = (frameSummary.frames) > 0
5866
6645
  end
5867
6646
  local _result
5868
- if _condition_3 then
6647
+ if _condition_4 then
5869
6648
  _result = frameSummary.frames
5870
6649
  else
5871
6650
  -- ▼ ReadonlySet.size ▼
@@ -5890,11 +6669,11 @@ local function captureMicroProfiler(requestData)
5890
6669
  end
5891
6670
  local analysisFrameCount = _result
5892
6671
  local _total_duration_us = frameSummary.total_duration_us
5893
- local _condition_4 = type(_total_duration_us) == "number"
5894
- if _condition_4 then
5895
- _condition_4 = (frameSummary.total_duration_us) > 0
6672
+ local _condition_5 = type(_total_duration_us) == "number"
6673
+ if _condition_5 then
6674
+ _condition_5 = (frameSummary.total_duration_us) > 0
5896
6675
  end
5897
- local analysisDurationUs = if _condition_4 then frameSummary.total_duration_us else durationMs * 1000
6676
+ local analysisDurationUs = if _condition_5 then frameSummary.total_duration_us else durationMs * 1000
5898
6677
  local analysisDurationMs = analysisDurationUs / 1000
5899
6678
  local rows = {}
5900
6679
  local rowsByTimerId = {}
@@ -5909,7 +6688,7 @@ local function captureMicroProfiler(requestData)
5909
6688
  for timerId, aggregate in aggregates do
5910
6689
  checkpoint()
5911
6690
  local info = getTimerInfo(timerId)
5912
- local totalUs = rawToUs(aggregate.inclusive_raw)
6691
+ local totalUs = roundUs(aggregate.inclusive_us)
5913
6692
  if not includeIdle and isIdleTimer(info) then
5914
6693
  omittedIdle += 1
5915
6694
  continue
@@ -5919,39 +6698,39 @@ local function captureMicroProfiler(requestData)
5919
6698
  continue
5920
6699
  end
5921
6700
  if filter ~= nil then
5922
- local _exp = info.name
5923
- local _condition_5 = info.group
5924
- if _condition_5 == nil then
5925
- _condition_5 = ""
6701
+ local _exp_1 = info.name
6702
+ local _condition_6 = info.group
6703
+ if _condition_6 == nil then
6704
+ _condition_6 = ""
5926
6705
  end
5927
- local searchable = `{_exp} {_condition_5}`
6706
+ local searchable = `{_exp_1} {_condition_6}`
5928
6707
  if not stringContains(searchable, filter) then
5929
6708
  omittedByFilter += 1
5930
6709
  continue
5931
6710
  end
5932
6711
  end
5933
- local _condition_5 = info.group
5934
- if _condition_5 == nil then
5935
- _condition_5 = "<unknown>"
6712
+ local _condition_6 = info.group
6713
+ if _condition_6 == nil then
6714
+ _condition_6 = "<unknown>"
5936
6715
  end
5937
- local group = _condition_5
5938
- local inclusiveUs = rawToUs(aggregate.inclusive_raw)
5939
- local exclusiveUs = rawToUs(aggregate.exclusive_raw)
6716
+ local group = _condition_6
6717
+ local inclusiveUs = roundUs(aggregate.inclusive_us)
6718
+ local exclusiveUs = roundUs(aggregate.exclusive_us)
5940
6719
  local avgUs = if aggregate.count > 0 then round2(totalUs / aggregate.count) else 0
5941
- local maxUs = rawToUs(aggregate.max_raw)
6720
+ local maxUs = roundUs(aggregate.max_us)
5942
6721
  local groupAgg = groupAggregates[group]
5943
6722
  if groupAgg == nil then
5944
6723
  groupAgg = {
5945
6724
  group = group,
5946
- inclusive_raw = 0,
5947
- exclusive_raw = 0,
6725
+ inclusive_us = 0,
6726
+ exclusive_us = 0,
5948
6727
  count = 0,
5949
6728
  }
5950
6729
  local _groupAgg = groupAgg
5951
6730
  groupAggregates[group] = _groupAgg
5952
6731
  end
5953
- groupAgg.inclusive_raw += aggregate.inclusive_raw
5954
- groupAgg.exclusive_raw += aggregate.exclusive_raw
6732
+ groupAgg.inclusive_us += aggregate.inclusive_us
6733
+ groupAgg.exclusive_us += aggregate.exclusive_us
5955
6734
  groupAgg.count += aggregate.count
5956
6735
  local row = {
5957
6736
  timer_id = timerId,
@@ -5996,8 +6775,8 @@ local function captureMicroProfiler(requestData)
5996
6775
  local _groupFrames = groupFrames
5997
6776
  groupFrameAggregates[group] = _groupFrames
5998
6777
  end
5999
- for frameId, raw in timerFrames do
6000
- addFrameRaw(groupFrames, frameId, raw)
6778
+ for frameId, us in timerFrames do
6779
+ addFrameUs(groupFrames, frameId, us)
6001
6780
  checkpoint()
6002
6781
  end
6003
6782
  end
@@ -6010,19 +6789,19 @@ local function captureMicroProfiler(requestData)
6010
6789
  if threadAggregateRow == nil then
6011
6790
  threadAggregateRow = {
6012
6791
  timer_id = threadId,
6013
- inclusive_raw = 0,
6014
- exclusive_raw = 0,
6792
+ inclusive_us = 0,
6793
+ exclusive_us = 0,
6015
6794
  count = 0,
6016
- max_raw = 0,
6795
+ max_us = 0,
6017
6796
  }
6018
6797
  local _threadAggregateRow = threadAggregateRow
6019
6798
  threadAggregates[threadId] = _threadAggregateRow
6020
6799
  end
6021
- threadAggregateRow.inclusive_raw += threadAggregate.inclusive_raw
6022
- threadAggregateRow.exclusive_raw += threadAggregate.exclusive_raw
6800
+ threadAggregateRow.inclusive_us += threadAggregate.inclusive_us
6801
+ threadAggregateRow.exclusive_us += threadAggregate.exclusive_us
6023
6802
  threadAggregateRow.count += threadAggregate.count
6024
- if threadAggregate.max_raw > threadAggregateRow.max_raw then
6025
- threadAggregateRow.max_raw = threadAggregate.max_raw
6803
+ if threadAggregate.max_us > threadAggregateRow.max_us then
6804
+ threadAggregateRow.max_us = threadAggregate.max_us
6026
6805
  end
6027
6806
  local threadRows = threadTimerRows[threadId]
6028
6807
  if threadRows == nil then
@@ -6030,8 +6809,8 @@ local function captureMicroProfiler(requestData)
6030
6809
  local _threadRows = threadRows
6031
6810
  threadTimerRows[threadId] = _threadRows
6032
6811
  end
6033
- local threadTotalUs = rawToUs(threadAggregate.inclusive_raw)
6034
- local threadExclusiveUs = rawToUs(threadAggregate.exclusive_raw)
6812
+ local threadTotalUs = roundUs(threadAggregate.inclusive_us)
6813
+ local threadExclusiveUs = roundUs(threadAggregate.exclusive_us)
6035
6814
  local threadAvgUs = if threadAggregate.count > 0 then round2(threadTotalUs / threadAggregate.count) else 0
6036
6815
  local threadInfo = getThreadInfo(threadId)
6037
6816
  local threadTimerRow = {
@@ -6047,7 +6826,7 @@ local function captureMicroProfiler(requestData)
6047
6826
  count = threadAggregate.count,
6048
6827
  count_per_s = perSecond(threadAggregate.count, analysisDurationMs),
6049
6828
  avg_invocation_us = threadAvgUs,
6050
- max_invocation_us = rawToUs(threadAggregate.max_raw),
6829
+ max_invocation_us = roundUs(threadAggregate.max_us),
6051
6830
  }
6052
6831
  local threadMaxToAvg = ratio(threadTimerRow.max_invocation_us, threadAvgUs)
6053
6832
  if threadMaxToAvg ~= nil then
@@ -6104,8 +6883,8 @@ local function captureMicroProfiler(requestData)
6104
6883
  if parentRow == nil or childRow == nil then
6105
6884
  continue
6106
6885
  end
6107
- local inclusiveUs = rawToUs(edge.inclusive_raw)
6108
- local maxUs = rawToUs(edge.max_raw)
6886
+ local inclusiveUs = roundUs(edge.inclusive_us)
6887
+ local maxUs = roundUs(edge.max_us)
6109
6888
  local avgUs = if edge.count > 0 then round2(inclusiveUs / edge.count) else 0
6110
6889
  local edgeRow = {
6111
6890
  parent = {
@@ -6296,8 +7075,8 @@ local function captureMicroProfiler(requestData)
6296
7075
  for threadId, aggregate in threadAggregates do
6297
7076
  checkpoint()
6298
7077
  local info = getThreadInfo(threadId)
6299
- local inclusiveUs = rawToUs(aggregate.inclusive_raw)
6300
- local exclusiveUs = rawToUs(aggregate.exclusive_raw)
7078
+ local inclusiveUs = roundUs(aggregate.inclusive_us)
7079
+ local exclusiveUs = roundUs(aggregate.exclusive_us)
6301
7080
  local row = {
6302
7081
  thread_id = threadId,
6303
7082
  thread_name = info.name,
@@ -6308,7 +7087,7 @@ local function captureMicroProfiler(requestData)
6308
7087
  exclusive_pct = percent(exclusiveUs, inclusiveUs),
6309
7088
  count = aggregate.count,
6310
7089
  count_per_s = perSecond(aggregate.count, analysisDurationMs),
6311
- max_invocation_us = rawToUs(aggregate.max_raw),
7090
+ max_invocation_us = roundUs(aggregate.max_us),
6312
7091
  pct_of_analyzed_wall = percent(inclusiveUs, analysisDurationUs),
6313
7092
  }
6314
7093
  local timerRows = threadTimerRows[threadId] or {}
@@ -6362,11 +7141,11 @@ local function captureMicroProfiler(requestData)
6362
7141
  for _, aggregate in groupAggregates do
6363
7142
  checkpoint()
6364
7143
  local _group = aggregate.group
6365
- local _condition_5 = groupTimerRows[_group]
6366
- if _condition_5 == nil then
6367
- _condition_5 = {}
7144
+ local _condition_6 = groupTimerRows[_group]
7145
+ if _condition_6 == nil then
7146
+ _condition_6 = {}
6368
7147
  end
6369
- local timerRows = _condition_5
7148
+ local timerRows = _condition_6
6370
7149
  cooperativeSort(timerRows, function(a, b)
6371
7150
  return (a.inclusive_us) > (b.inclusive_us)
6372
7151
  end, checkpoint)
@@ -6397,8 +7176,8 @@ local function captureMicroProfiler(requestData)
6397
7176
  table.insert(topGroupTimers, _arg0)
6398
7177
  end
6399
7178
  end
6400
- local inclusiveUs = rawToUs(aggregate.inclusive_raw)
6401
- local exclusiveUs = rawToUs(aggregate.exclusive_raw)
7179
+ local inclusiveUs = roundUs(aggregate.inclusive_us)
7180
+ local exclusiveUs = roundUs(aggregate.exclusive_us)
6402
7181
  local groupRow = {
6403
7182
  group = aggregate.group,
6404
7183
  inclusive_us = inclusiveUs,
@@ -6494,6 +7273,41 @@ local function captureMicroProfiler(requestData)
6494
7273
  if sampledFrameCoveragePct < 100 then
6495
7274
  table.insert(partialReasons, "selected_frame_event_coverage_below_100")
6496
7275
  end
7276
+ if historyTruncated then
7277
+ table.insert(partialReasons, "capture_history_truncated")
7278
+ end
7279
+ -- Safety net for any other shortfall. Whole frames make up to about two frames
7280
+ -- of slack normal, a frame_window smaller than the capture is intentional, and
7281
+ -- hitting max_events already has its own reason.
7282
+ local eventLimitHit = eventsSampled >= maxEvents
7283
+ local _avg_us = frameSummary.avg_us
7284
+ local avgFrameUs = if type(_avg_us) == "number" then frameSummary.avg_us else 0
7285
+ -- A frame_window the caller chose is intentional; the default (240 frames) is
7286
+ -- not, so a long capture it cuts short is flagged.
7287
+ local frameWindowLimited = startFrame > firstCaptureFrame
7288
+ local _frame_window = requestData.frame_window
7289
+ local frameWindowRequested = type(_frame_window) == "number"
7290
+ local coverageShort = not historyTruncated and not (frameWindowLimited and frameWindowRequested) and not eventLimitHit and captureWallMs - analysisDurationMs > math.max(captureWallMs * 0.1, (2 * avgFrameUs) / 1000)
7291
+ if coverageShort then
7292
+ table.insert(partialReasons, "capture_coverage_below_requested")
7293
+ end
7294
+ local qualityNotes = {}
7295
+ if focus ~= "all" then
7296
+ table.insert(qualityNotes, "focus filters events before stack aggregation; exclusive_us is exclusive within emitted focused events, not the full snapshot.")
7297
+ end
7298
+ if historyTruncated then
7299
+ local _arg0 = `MicroProfiler kept only the newest {frameMax - firstCaptureFrame + 1} frames of this capture (its memory budget filled; {framesEvicted} earlier frames were dropped), so the analysis covers {roundUs(analysisDurationMs)} ms of the {roundUs(captureWallMs)} ms capture. Times and rates are correct for that span; use a shorter duration_ms to analyze the whole capture.`
7300
+ table.insert(qualityNotes, _arg0)
7301
+ end
7302
+ if eventLimitHit then
7303
+ local _arg0 = `Analysis stopped at max_events ({maxEvents} events), so it covers {roundUs(analysisDurationMs)} ms of the {roundUs(captureWallMs)} ms capture. Raise max_events or shorten duration_ms to analyze all of it.`
7304
+ table.insert(qualityNotes, _arg0)
7305
+ end
7306
+ if coverageShort then
7307
+ local cause = if frameWindowLimited then ` The default frame_window ({frameWindow} frames) kept only the newest {framesConsidered} frames; pass a larger frame_window (the engine holds at most {HISTORY_FRAME_LIMIT}) or a shorter duration_ms.` else ""
7308
+ local _arg0 = `The analyzed frames cover {roundUs(analysisDurationMs)} ms of the {roundUs(captureWallMs)} ms capture. Times and rates are correct for that span.{cause}`
7309
+ table.insert(qualityNotes, _arg0)
7310
+ end
6497
7311
  local comparisonIndex
6498
7312
  if includeComparisonIndex then
6499
7313
  local timerFields = { "timer_id", "name", "group", "inclusive_us", "inclusive_us_per_s", "exclusive_us", "count", "count_per_s", "active_frame_count", "inclusive_us_per_frame", "max_frame_inclusive_us", "max_frame_id" }
@@ -6532,13 +7346,20 @@ local function captureMicroProfiler(requestData)
6532
7346
  }
6533
7347
  end
6534
7348
  local _object = {
6535
- schema_version = 1,
7349
+ schema_version = 2,
6536
7350
  ok = true,
6537
7351
  duration_ms = durationMs,
6538
7352
  target = targetRole,
6539
7353
  scope = "micro_profiler",
6540
7354
  time_unit = "microseconds",
6541
- time_basis = "LibMP MicroProfiler timestamps converted from nanosecond ticks. inclusive_us is cumulative nested timer time and can overlap across nested timers/threads; do not sum rows as total frame time.",
7355
+ time_basis = "MicroProfiler ticks converted with the snapshot's clock (GlobalDesc TickToMsCpu; TickToMsGpu for the GPU thread). inclusive_us is cumulative nested timer time and can overlap across nested timers/threads; do not sum rows as total frame time.",
7356
+ clock = {
7357
+ tick_to_ms_cpu = tickToMsCpu,
7358
+ tick_to_ms_gpu = tickToMsGpu,
7359
+ },
7360
+ capture_state = {
7361
+ was_recording = prior.recording,
7362
+ },
6542
7363
  }
6543
7364
  local _left = "analysis_window"
6544
7365
  local _object_1 = {
@@ -6546,6 +7367,7 @@ local function captureMicroProfiler(requestData)
6546
7367
  analysis_duration_us = analysisDurationUs,
6547
7368
  snapshot_frame_min = frameMin,
6548
7369
  snapshot_frame_max = frameMax,
7370
+ capture_start_frame = firstCaptureFrame,
6549
7371
  selected_frame_min = startFrame,
6550
7372
  selected_frame_max = frameMax,
6551
7373
  selected_frame_count = framesConsidered,
@@ -6565,17 +7387,21 @@ local function captureMicroProfiler(requestData)
6565
7387
  _object_1[_left_1] = _size_1
6566
7388
  _object_1.selected_frame_event_coverage_pct = sampledFrameCoveragePct
6567
7389
  _object_1.frame_window = frameWindow
7390
+ _object_1.capture_wall_ms = round2(captureWallMs)
7391
+ _object_1.first_frame_wait_ms = round2(firstFrameWaitMs)
7392
+ _object_1.coverage_pct = percent(analysisDurationMs, captureWallMs)
7393
+ _object_1.frames_evicted = framesEvicted
6568
7394
  _object[_left] = _object_1
6569
7395
  local _left_2 = "applied"
6570
7396
  local _object_2 = {
6571
7397
  focus = focus,
6572
7398
  }
6573
7399
  local _left_3 = "filter"
6574
- local _condition_5 = filter
6575
- if _condition_5 == nil then
6576
- _condition_5 = nil
7400
+ local _condition_6 = filter
7401
+ if _condition_6 == nil then
7402
+ _condition_6 = nil
6577
7403
  end
6578
- _object_2[_left_3] = _condition_5
7404
+ _object_2[_left_3] = _condition_6
6579
7405
  _object_2.include_idle = includeIdle
6580
7406
  _object_2.include_gpu = includeGpu
6581
7407
  _object_2.min_total_us = minTotalUs
@@ -6614,7 +7440,7 @@ local function captureMicroProfiler(requestData)
6614
7440
  _object_3.open_stack_entries_at_end = openStackEntriesAtEnd
6615
7441
  _object_3.iterator_finished = iteratorFinished
6616
7442
  _object_3.last_processed_frame_id = lastProcessedFrameId
6617
- _object_3.last_processed_timestamp_us = if lastProcessedTimestampRaw ~= nil then rawToUs(lastProcessedTimestampRaw) else nil
7443
+ _object_3.last_processed_timestamp_us = if lastProcessedTimestampUs ~= nil then roundUs(lastProcessedTimestampUs) else nil
6618
7444
  _object_3.event_limit_hit = eventsSampled >= maxEvents
6619
7445
  _object[_left_4] = _object_3
6620
7446
  _object.frame_summary = frameSummary
@@ -6631,9 +7457,10 @@ local function captureMicroProfiler(requestData)
6631
7457
  dropped_spans = droppedSpans,
6632
7458
  open_stack_entries_at_end = openStackEntriesAtEnd,
6633
7459
  selected_frame_event_coverage_pct = sampledFrameCoveragePct,
7460
+ history_truncated = historyTruncated,
6634
7461
  partial = #partialReasons > 0,
6635
7462
  partial_reasons = partialReasons,
6636
- notes = if focus ~= "all" then { "focus filters events before stack aggregation; exclusive_us is exclusive within emitted focused events, not the full snapshot." } else nil,
7463
+ notes = if #qualityNotes > 0 then qualityNotes else nil,
6637
7464
  }
6638
7465
  _object.recommended_tools = recommendedToolsForGroups(topGroups, targetRole)
6639
7466
  local result = _object
@@ -7684,12 +8511,14 @@ return {
7684
8511
  local TS = require(script.Parent.Parent.Parent.include.RuntimeLib)
7685
8512
  local Utils = TS.import(script, script.Parent.Parent, "Utils")
7686
8513
  local Recording = TS.import(script, script.Parent.Parent, "Recording")
8514
+ local ScriptReplace = TS.import(script, script.Parent.Parent, "ScriptReplace")
7687
8515
  local _ScriptEdits = TS.import(script, script.Parent.Parent, "ScriptEdits")
7688
8516
  local planScriptEdits = _ScriptEdits.planScriptEdits
7689
8517
  local sourceRevision = _ScriptEdits.sourceRevision
7690
8518
  local _binding = Utils
7691
8519
  local getInstancePath = _binding.getInstancePath
7692
8520
  local getInstanceByPath = _binding.getInstanceByPath
8521
+ local createPathAmbiguityChecker = _binding.createPathAmbiguityChecker
7693
8522
  local readScriptSource = _binding.readScriptSource
7694
8523
  local applyScriptSource = _binding.applyScriptSource
7695
8524
  local splitLines = _binding.splitLines
@@ -7825,14 +8654,45 @@ local function getScriptSource(requestData)
7825
8654
  }
7826
8655
  end
7827
8656
  end
8657
+ -- The revision_mismatch response shared by every revision-checked script
8658
+ -- write, or undefined when no revision was expected or it still matches.
8659
+ local function revisionMismatch(instancePath, source, expectedRevision)
8660
+ if expectedRevision == nil then
8661
+ return nil
8662
+ end
8663
+ local revision = sourceRevision(source)
8664
+ if revision == expectedRevision then
8665
+ return nil
8666
+ end
8667
+ return {
8668
+ error = "Script changed since expected_revision; read it again with get_script_source and retry.",
8669
+ code = "revision_mismatch",
8670
+ instancePath = instancePath,
8671
+ expectedRevision = expectedRevision,
8672
+ revision = revision,
8673
+ }
8674
+ end
8675
+ local function readExpectedRevision(requestData)
8676
+ local expectedRevision = requestData.expectedRevision
8677
+ if expectedRevision == nil then
8678
+ return nil
8679
+ end
8680
+ return if type(expectedRevision) == "string" and expectedRevision ~= "" then expectedRevision else false
8681
+ end
7828
8682
  local function setScriptSource(requestData)
7829
8683
  local instancePath = requestData.instancePath
7830
8684
  local newSource = requestData.source
8685
+ local expectedRevision = readExpectedRevision(requestData)
7831
8686
  if not (instancePath ~= "" and instancePath) or not (type(newSource) == "string") then
7832
8687
  return {
7833
8688
  error = "Instance path and source are required",
7834
8689
  }
7835
8690
  end
8691
+ if expectedRevision == false then
8692
+ return {
8693
+ error = "expectedRevision must be a nonempty string",
8694
+ }
8695
+ end
7836
8696
  local instance = getInstanceByPath(instancePath)
7837
8697
  if not instance then
7838
8698
  return {
@@ -7846,25 +8706,31 @@ local function setScriptSource(requestData)
7846
8706
  end
7847
8707
  -- Communication has already JSON-decoded the transport payload; source text is exact at this boundary.
7848
8708
  local sourceToSet = newSource
7849
- local recordingId = beginRecording(`Set script source: {instance.Name}`)
7850
8709
  local readSuccess, readResult = pcall(function()
7851
- return #readScriptSource(instance)
8710
+ return readScriptSource(instance)
7852
8711
  end)
7853
8712
  if not readSuccess then
7854
- finishRecording(recordingId, false)
7855
8713
  return {
7856
8714
  error = `Failed to read script source before updating: {readResult}`,
7857
8715
  }
7858
8716
  end
7859
- local oldSourceLength = readResult
7860
- local applyResult = applyScriptSource(instance, sourceToSet)
8717
+ local oldSource = readResult
8718
+ local mismatch = revisionMismatch(instancePath, oldSource, expectedRevision)
8719
+ if mismatch then
8720
+ return mismatch
8721
+ end
8722
+ local recordingId = beginRecording(`Set script source: {instance.Name}`)
8723
+ -- A revision-checked replacement is a compare-and-set against the checked text,
8724
+ -- so a draft typed while UpdateSourceAsync yields is not overwritten.
8725
+ local applyResult = if expectedRevision == nil then applyScriptSource(instance, sourceToSet) else applyScriptSource(instance, sourceToSet, oldSource)
7861
8726
  if applyResult.success then
7862
8727
  finishRecording(recordingId, true)
7863
8728
  return {
7864
8729
  success = true,
7865
8730
  instancePath = instancePath,
7866
- oldSourceLength = oldSourceLength,
8731
+ oldSourceLength = #oldSource,
7867
8732
  newSourceLength = #sourceToSet,
8733
+ revision = sourceRevision(sourceToSet),
7868
8734
  method = applyResult.method,
7869
8735
  message = `Script source updated successfully ({if applyResult.method == "UpdateSourceAsync" then "editor-safe" else "direct assignment"})`,
7870
8736
  }
@@ -7965,14 +8831,9 @@ local function editScriptLines(requestData)
7965
8831
  end
7966
8832
  local source = readResult
7967
8833
  local revision = sourceRevision(source)
7968
- if expectedRevision ~= nil and expectedRevision ~= revision then
7969
- return {
7970
- error = "Script changed since expected_revision; read it again with get_script_source and retry.",
7971
- code = "revision_mismatch",
7972
- instancePath = instancePath,
7973
- expectedRevision = expectedRevision,
7974
- revision = revision,
7975
- }
8834
+ local mismatch = revisionMismatch(instancePath, source, expectedRevision)
8835
+ if mismatch then
8836
+ return mismatch
7976
8837
  end
7977
8838
  local plan = planScriptEdits(source, edits, dryRun)
7978
8839
  if not plan.ok then
@@ -8022,11 +8883,17 @@ local function insertScriptLines(requestData)
8022
8883
  end
8023
8884
  local afterLine = _condition
8024
8885
  local newContent = requestData.newContent
8886
+ local expectedRevision = readExpectedRevision(requestData)
8025
8887
  if not (instancePath ~= "" and instancePath) or not (newContent ~= "" and newContent) then
8026
8888
  return {
8027
8889
  error = "Instance path and newContent are required",
8028
8890
  }
8029
8891
  end
8892
+ if expectedRevision == false then
8893
+ return {
8894
+ error = "expectedRevision must be a nonempty string",
8895
+ }
8896
+ end
8030
8897
  local instance = getInstanceByPath(instancePath)
8031
8898
  if not instance then
8032
8899
  return {
@@ -8038,9 +8905,21 @@ local function insertScriptLines(requestData)
8038
8905
  error = `Instance is not a script-like object: {instance.ClassName}`,
8039
8906
  }
8040
8907
  end
8908
+ local readSuccess, readResult = pcall(function()
8909
+ return readScriptSource(instance)
8910
+ end)
8911
+ if not readSuccess then
8912
+ return {
8913
+ error = `Failed to insert script lines: {readResult}`,
8914
+ }
8915
+ end
8916
+ local source = readResult
8917
+ local mismatch = revisionMismatch(instancePath, source, expectedRevision)
8918
+ if mismatch then
8919
+ return mismatch
8920
+ end
8041
8921
  local recordingId = beginRecording(`Insert script lines after line {afterLine}: {instance.Name}`)
8042
8922
  local success, result = pcall(function()
8043
- local source = readScriptSource(instance)
8044
8923
  local lines, hadTrailingNewline = splitLines(source)
8045
8924
  local totalLines = #lines
8046
8925
  if afterLine < 0 or afterLine > totalLines then
@@ -8094,6 +8973,7 @@ local function insertScriptLines(requestData)
8094
8973
  insertedAfterLine = afterLine,
8095
8974
  linesInserted = #newLines,
8096
8975
  newLineCount = #resultLines,
8976
+ revision = sourceRevision(newSource),
8097
8977
  method = applyResult.method,
8098
8978
  message = "Script lines inserted successfully",
8099
8979
  }
@@ -8111,11 +8991,17 @@ local function deleteScriptLines(requestData)
8111
8991
  local instancePath = requestData.instancePath
8112
8992
  local startLine = requestData.startLine
8113
8993
  local endLine = requestData.endLine
8994
+ local expectedRevision = readExpectedRevision(requestData)
8114
8995
  if not (instancePath ~= "" and instancePath) or not (startLine ~= 0 and startLine == startLine and startLine) or not (endLine ~= 0 and endLine == endLine and endLine) then
8115
8996
  return {
8116
8997
  error = "Instance path, startLine, and endLine are required",
8117
8998
  }
8118
8999
  end
9000
+ if expectedRevision == false then
9001
+ return {
9002
+ error = "expectedRevision must be a nonempty string",
9003
+ }
9004
+ end
8119
9005
  local instance = getInstanceByPath(instancePath)
8120
9006
  if not instance then
8121
9007
  return {
@@ -8127,9 +9013,23 @@ local function deleteScriptLines(requestData)
8127
9013
  error = `Instance is not a script-like object: {instance.ClassName}`,
8128
9014
  }
8129
9015
  end
9016
+ local readSuccess, readResult = pcall(function()
9017
+ return readScriptSource(instance)
9018
+ end)
9019
+ if not readSuccess then
9020
+ return {
9021
+ error = `Failed to delete script lines: {readResult}`,
9022
+ }
9023
+ end
9024
+ local source = readResult
9025
+ -- Line numbers name different text once the script changes; a revision
9026
+ -- keeps a retried delete from removing lines it never saw.
9027
+ local mismatch = revisionMismatch(instancePath, source, expectedRevision)
9028
+ if mismatch then
9029
+ return mismatch
9030
+ end
8130
9031
  local recordingId = beginRecording(`Delete script lines {startLine}-{endLine}: {instance.Name}`)
8131
9032
  local success, result = pcall(function()
8132
- local source = readScriptSource(instance)
8133
9033
  local lines, hadTrailingNewline = splitLines(source)
8134
9034
  local totalLines = #lines
8135
9035
  if startLine < 1 or startLine > totalLines then
@@ -8185,6 +9085,7 @@ local function deleteScriptLines(requestData)
8185
9085
  },
8186
9086
  linesDeleted = endLine - startLine + 1,
8187
9087
  newLineCount = #resultLines,
9088
+ revision = sourceRevision(newSource),
8188
9089
  method = applyResult.method,
8189
9090
  message = "Script lines deleted successfully",
8190
9091
  }
@@ -8198,196 +9099,43 @@ local function deleteScriptLines(requestData)
8198
9099
  error = `Failed to delete script lines: {result}`,
8199
9100
  }
8200
9101
  end
8201
- local function escapeLuaPattern(s)
8202
- return (string.gsub(s, "([%(%)%.%%%+%-%*%?%[%]%^%$])", "%%%1"))
8203
- end
8204
- local function escapeLuaReplacement(s)
8205
- return (string.gsub(s, "%%", "%%%%"))
8206
- end
8207
- local function caseInsensitiveLiteralReplace(src, searchStr, repl)
8208
- local lowerSrc = string.lower(src)
8209
- local lowerSearch = string.lower(searchStr)
8210
- local parts = {}
8211
- local lastEnd = 1
8212
- local searchLen = #lowerSearch
8213
- local pos = 1
8214
- local replCount = 0
8215
- while true do
8216
- local foundStart = string.find(lowerSrc, lowerSearch, pos, true)
8217
- if foundStart == nil then
8218
- break
8219
- end
8220
- local _arg0 = string.sub(src, lastEnd, foundStart - 1)
8221
- table.insert(parts, _arg0)
8222
- local _repl = repl
8223
- table.insert(parts, _repl)
8224
- lastEnd = foundStart + searchLen
8225
- pos = foundStart + searchLen
8226
- replCount += 1
8227
- end
8228
- local _arg0 = string.sub(src, lastEnd)
8229
- table.insert(parts, _arg0)
8230
- return { table.concat(parts, ""), replCount }
8231
- end
8232
- local function findAndReplaceInScripts(requestData)
8233
- local searchPattern = requestData.pattern
8234
- local replacement = requestData.replacement
8235
- if not (searchPattern ~= "" and searchPattern) then
8236
- return {
8237
- error = "pattern is required",
8238
- }
8239
- end
8240
- if replacement == nil then
8241
- return {
8242
- error = "replacement is required",
8243
- }
8244
- end
8245
- local _condition = (requestData.caseSensitive)
8246
- if _condition == nil then
8247
- _condition = false
8248
- end
8249
- local caseSensitive = _condition
8250
- local _condition_1 = (requestData.usePattern)
8251
- if _condition_1 == nil then
8252
- _condition_1 = false
8253
- end
8254
- local usePattern = _condition_1
8255
- local _condition_2 = (requestData.path)
8256
- if _condition_2 == nil then
8257
- _condition_2 = ""
8258
- end
8259
- local searchPath = _condition_2
8260
- local classFilter = requestData.classFilter
8261
- local _condition_3 = (requestData.dryRun)
8262
- if _condition_3 == nil then
8263
- _condition_3 = false
8264
- end
8265
- local dryRun = _condition_3
8266
- local _condition_4 = (requestData.maxReplacements)
8267
- if _condition_4 == nil then
8268
- _condition_4 = 1000
8269
- end
8270
- local maxReplacements = _condition_4
8271
- if not caseSensitive and usePattern then
8272
- return {
8273
- error = "Case-insensitive Lua pattern replacement is not supported. Use caseSensitive: true with usePattern: true, or use literal matching.",
8274
- }
8275
- end
8276
- local startInstance = if searchPath ~= "" then getInstanceByPath(searchPath) else game
8277
- if not startInstance then
8278
- return {
8279
- error = `Path not found: {searchPath}`,
8280
- }
8281
- end
8282
- local changes = {}
8283
- local totalReplacements = 0
8284
- local scriptsSearched = 0
8285
- local hitLimit = false
8286
- local recordingId = if dryRun then nil else beginRecording("Find and replace in scripts")
8287
- local function processInstance(instance)
8288
- if hitLimit then
9102
+ local scriptReplace = ScriptReplace.createScriptReplace({
9103
+ resolvePath = function(self, path)
9104
+ return if path == "" then game else getInstanceByPath(path)
9105
+ end,
9106
+ getChildren = function(self, instance)
9107
+ return instance:GetChildren()
9108
+ end,
9109
+ readScript = function(self, instance, classFilter)
9110
+ if not instance:IsA("LuaSourceContainer") then
8289
9111
  return nil
8290
9112
  end
8291
- local _condition_5 = classFilter == nil
8292
- if not _condition_5 then
8293
- local _exp = string.lower(instance.ClassName)
8294
- local _arg0 = string.lower(classFilter)
8295
- _condition_5 = (string.find(_exp, _arg0)) ~= nil
8296
- end
8297
- local matchesClass = _condition_5
8298
- if instance:IsA("LuaSourceContainer") and matchesClass then
8299
- scriptsSearched += 1
8300
- local source = readScriptSource(instance)
8301
- local newSource
8302
- local replCount
8303
- if usePattern then
8304
- local result, count = string.gsub(source, searchPattern, replacement)
8305
- newSource = result
8306
- replCount = count
8307
- elseif caseSensitive then
8308
- local escaped = escapeLuaPattern(searchPattern)
8309
- local escapedRepl = escapeLuaReplacement(replacement)
8310
- local result, count = string.gsub(source, escaped, escapedRepl)
8311
- newSource = result
8312
- replCount = count
8313
- else
8314
- local _binding_2 = caseInsensitiveLiteralReplace(source, searchPattern, replacement)
8315
- newSource = _binding_2[1]
8316
- replCount = _binding_2[2]
8317
- end
8318
- if replCount > 0 then
8319
- if totalReplacements + replCount > maxReplacements then
8320
- hitLimit = true
8321
- return nil
8322
- end
8323
- local applyResult = if dryRun then nil else applyScriptSource(instance, newSource, source)
8324
- if applyResult ~= nil and not applyResult.success then
8325
- local _object = {
8326
- instancePath = getInstancePath(instance),
8327
- name = instance.Name,
8328
- className = instance.ClassName,
8329
- replacements = 0,
8330
- }
8331
- local _left = "error"
8332
- local _condition_6 = applyResult.error
8333
- if _condition_6 == nil then
8334
- _condition_6 = "Script write failed verification"
8335
- end
8336
- _object[_left] = _condition_6
8337
- table.insert(changes, _object)
8338
- else
8339
- totalReplacements += replCount
8340
- local _arg0 = {
8341
- instancePath = getInstancePath(instance),
8342
- name = instance.Name,
8343
- className = instance.ClassName,
8344
- replacements = replCount,
8345
- }
8346
- table.insert(changes, _arg0)
8347
- end
8348
- end
8349
- end
8350
- for _, child in instance:GetChildren() do
8351
- if hitLimit then
8352
- return nil
8353
- end
8354
- processInstance(child)
8355
- end
8356
- end
8357
- local traversalSuccess, traversalResult = pcall(function()
8358
- return processInstance(startInstance)
8359
- end)
8360
- -- ▼ ReadonlyArray.filter ▼
8361
- local _newValue = {}
8362
- local _callback = function(change)
8363
- return change.error ~= nil
8364
- end
8365
- local _length = 0
8366
- for _k, _v in changes do
8367
- if _callback(_v, _k - 1, changes) == true then
8368
- _length += 1
8369
- _newValue[_length] = _v
9113
+ if classFilter ~= nil and instance.ClassName ~= classFilter then
9114
+ return nil
8370
9115
  end
8371
- end
8372
- -- ▲ ReadonlyArray.filter ▲
8373
- local failedScripts = #_newValue
8374
- local scriptsModified = #changes - failedScripts
8375
- if recordingId ~= nil then
8376
- finishRecording(recordingId, scriptsModified > 0)
8377
- end
8378
- return {
8379
- success = traversalSuccess and failedScripts == 0,
8380
- error = if traversalSuccess then nil else `Script traversal failed: {traversalResult}`,
8381
- dryRun = dryRun,
8382
- pattern = searchPattern,
8383
- replacement = replacement,
8384
- totalReplacements = totalReplacements,
8385
- scriptsSearched = scriptsSearched,
8386
- scriptsModified = scriptsModified,
8387
- scriptsFailed = failedScripts,
8388
- changes = changes,
8389
- truncated = hitLimit,
8390
- }
9116
+ return {
9117
+ instancePath = getInstancePath(instance),
9118
+ name = instance.Name,
9119
+ className = instance.ClassName,
9120
+ source = readScriptSource(instance),
9121
+ }
9122
+ end,
9123
+ createAmbiguityChecker = function(self)
9124
+ return createPathAmbiguityChecker()
9125
+ end,
9126
+ writeScript = function(self, instance, newSource, expectedSource)
9127
+ -- Only planned scripts are written, and planning admits LuaSourceContainers only.
9128
+ return applyScriptSource(instance, newSource, expectedSource)
9129
+ end,
9130
+ beginRecording = function(self, label)
9131
+ return beginRecording(label)
9132
+ end,
9133
+ finishRecording = function(self, recording, commit)
9134
+ finishRecording(recording, commit)
9135
+ end,
9136
+ })
9137
+ local function findAndReplaceInScripts(requestData)
9138
+ return scriptReplace.run(requestData)
8391
9139
  end
8392
9140
  return {
8393
9141
  getScriptSource = getScriptSource,
@@ -11653,6 +12401,41 @@ return {
11653
12401
  </Properties>
11654
12402
  </Item>
11655
12403
  <Item class="ModuleScript" referent="37">
12404
+ <Properties>
12405
+ <string name="Name">ScriptClasses</string>
12406
+ <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
12407
+ -- Script classes a caller can select with classFilter. Class names are
12408
+ -- compared exactly: "Script" must not also select LocalScript or ModuleScript.
12409
+ -- An omitted filter selects every LuaSourceContainer the corpus can read.
12410
+ local SCRIPT_CLASS_FILTERS = { "Script", "LocalScript", "ModuleScript" }
12411
+ local function isScriptClassFilter(value)
12412
+ local _value = value
12413
+ local _condition = type(_value) == "string"
12414
+ if _condition then
12415
+ local _value_1 = value
12416
+ _condition = table.find(SCRIPT_CLASS_FILTERS, _value_1) ~= nil
12417
+ end
12418
+ return _condition
12419
+ end
12420
+ --* Returns an error message when classFilter is present but not a supported script class.
12421
+ local function classFilterError(value)
12422
+ if value == nil or isScriptClassFilter(value) then
12423
+ return nil
12424
+ end
12425
+ return `classFilter must be one of {table.concat(SCRIPT_CLASS_FILTERS, ", ")}`
12426
+ end
12427
+ local function matchesClassFilter(className, classFilter)
12428
+ return classFilter == nil or className == classFilter
12429
+ end
12430
+ return {
12431
+ SCRIPT_CLASS_FILTERS = SCRIPT_CLASS_FILTERS,
12432
+ classFilterError = classFilterError,
12433
+ matchesClassFilter = matchesClassFilter,
12434
+ }
12435
+ ]]></string>
12436
+ </Properties>
12437
+ </Item>
12438
+ <Item class="ModuleScript" referent="38">
11656
12439
  <Properties>
11657
12440
  <string name="Name">ScriptEdits</string>
11658
12441
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -11755,9 +12538,16 @@ local function locateEdit(source, starts, edit, label)
11755
12538
  if first == nil then
11756
12539
  return `{label}old_string not found in script. If old_string contains repeated patterns (e.g. closing braces), pass line_range to anchor the edit.`
11757
12540
  end
11758
- local second = string.find(source, edit.oldString, first + searchLength, true)
12541
+ -- Search again from the byte after the first match's start, not its end:
12542
+ -- "aa" occurs twice in "aaa", and "end\nend" twice in "end\nend\nend".
12543
+ local second = string.find(source, edit.oldString, first + 1, true)
11759
12544
  if second ~= nil then
11760
- return `{label}old_string matches multiple locations (lines {lineAt(starts, first)} and {lineAt(starts, second)}). Provide more surrounding context, or pass line_range to anchor the edit.`
12545
+ local firstLine = lineAt(starts, first)
12546
+ local secondLine = lineAt(starts, second)
12547
+ if firstLine == secondLine then
12548
+ return `{label}old_string matches multiple locations on line {firstLine}. Provide more surrounding context; line_range only anchors a match that starts the line.`
12549
+ end
12550
+ return `{label}old_string matches multiple locations (lines {firstLine} and {secondLine}). Provide more surrounding context, or pass line_range to anchor the edit.`
11761
12551
  end
11762
12552
  return first
11763
12553
  end
@@ -11846,7 +12636,10 @@ local function editLastLine(starts, edit)
11846
12636
  end
11847
12637
  -- Unified diff of whole changed lines, without context lines. Edits that share
11848
12638
  -- a line become one hunk; lines the edit left unchanged are trimmed away.
11849
- local function buildDiff(source, starts, resolved)
12639
+ local function buildDiff(source, starts, resolved, charBudget)
12640
+ if charBudget == nil then
12641
+ charBudget = DIFF_CHAR_BUDGET
12642
+ end
11850
12643
  local output = {}
11851
12644
  local outputSize = 0
11852
12645
  local truncated = false
@@ -11897,7 +12690,7 @@ local function buildDiff(source, starts, resolved)
11897
12690
  pushHunkLines(hunk, oldRegion, prefix, oldCount, "-")
11898
12691
  pushHunkLines(hunk, newRegion, prefix, newCount, "+")
11899
12692
  for _, line in hunk do
11900
- if outputSize + #line + 1 > DIFF_CHAR_BUDGET then
12693
+ if outputSize + #line + 1 > charBudget then
11901
12694
  truncated = true
11902
12695
  break
11903
12696
  end
@@ -11995,17 +12788,655 @@ local function planScriptEdits(source, edits, includeDiff)
11995
12788
  diffTruncated = built.truncated,
11996
12789
  }
11997
12790
  end
12791
+ -- Text of a line including its terminator, as lineStarts numbers lines.
12792
+ local function lineText(source, starts, line)
12793
+ return string.sub(source, starts[line], lineEnd(starts, source, line) - 1)
12794
+ end
12795
+ --[[
12796
+ *
12797
+ * Unified diff from one whole source to another, for edits whose positions
12798
+ * are not tracked (Lua pattern replacement). Unchanged leading and trailing
12799
+ * lines are trimmed. When the changed window keeps its line count, lines pair
12800
+ * one to one and each changed line is its own edit; otherwise the window is a
12801
+ * single edit. charBudget bounds the returned diff's characters.
12802
+
12803
+ ]]
12804
+ local function diffSources(oldSource, newSource, charBudget)
12805
+ if charBudget == nil then
12806
+ charBudget = DIFF_CHAR_BUDGET
12807
+ end
12808
+ if oldSource == newSource then
12809
+ return {
12810
+ diff = "",
12811
+ truncated = false,
12812
+ }
12813
+ end
12814
+ local oldStarts = lineStarts(oldSource)
12815
+ local newStarts = lineStarts(newSource)
12816
+ local oldCount = #oldStarts
12817
+ local newCount = #newStarts
12818
+ local prefix = 0
12819
+ while prefix < oldCount and prefix < newCount and lineText(oldSource, oldStarts, prefix + 1) == lineText(newSource, newStarts, prefix + 1) do
12820
+ prefix += 1
12821
+ end
12822
+ local suffix = 0
12823
+ while suffix < oldCount - prefix and suffix < newCount - prefix and lineText(oldSource, oldStarts, oldCount - suffix) == lineText(newSource, newStarts, newCount - suffix) do
12824
+ suffix += 1
12825
+ end
12826
+ local resolved = {}
12827
+ if oldCount == newCount then
12828
+ do
12829
+ local line = prefix + 1
12830
+ local _shouldIncrement = false
12831
+ while true do
12832
+ if _shouldIncrement then
12833
+ line += 1
12834
+ else
12835
+ _shouldIncrement = true
12836
+ end
12837
+ if not (line <= oldCount - suffix) then
12838
+ break
12839
+ end
12840
+ local replacement = lineText(newSource, newStarts, line)
12841
+ if lineText(oldSource, oldStarts, line) ~= replacement then
12842
+ local _arg0 = {
12843
+ index = #resolved,
12844
+ start = oldStarts[line],
12845
+ finish = lineEnd(oldStarts, oldSource, line),
12846
+ newString = replacement,
12847
+ }
12848
+ table.insert(resolved, _arg0)
12849
+ end
12850
+ end
12851
+ end
12852
+ else
12853
+ local _condition = newStarts[prefix + 1]
12854
+ if _condition == nil then
12855
+ _condition = #newSource + 1
12856
+ end
12857
+ local newWindowStart = _condition
12858
+ local _object = {
12859
+ index = 0,
12860
+ }
12861
+ local _left = "start"
12862
+ local _condition_1 = oldStarts[prefix + 1]
12863
+ if _condition_1 == nil then
12864
+ _condition_1 = #oldSource + 1
12865
+ end
12866
+ _object[_left] = _condition_1
12867
+ _object.finish = lineEnd(oldStarts, oldSource, oldCount - suffix)
12868
+ _object.newString = string.sub(newSource, newWindowStart, lineEnd(newStarts, newSource, newCount - suffix) - 1)
12869
+ table.insert(resolved, _object)
12870
+ end
12871
+ return buildDiff(oldSource, oldStarts, resolved, charBudget)
12872
+ end
11998
12873
  return {
11999
12874
  sourceRevision = sourceRevision,
12000
12875
  planScriptEdits = planScriptEdits,
12876
+ diffSources = diffSources,
12001
12877
  }
12002
12878
  ]]></string>
12003
12879
  </Properties>
12004
12880
  </Item>
12005
- <Item class="ModuleScript" referent="38">
12881
+ <Item class="ModuleScript" referent="39">
12882
+ <Properties>
12883
+ <string name="Name">ScriptReplace</string>
12884
+ <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
12885
+ local TS = require(script.Parent.Parent.include.RuntimeLib)
12886
+ local _ScriptEdits = TS.import(script, script.Parent, "ScriptEdits")
12887
+ local diffSources = _ScriptEdits.diffSources
12888
+ local sourceRevision = _ScriptEdits.sourceRevision
12889
+ local ScriptClasses = TS.import(script, script.Parent, "ScriptClasses")
12890
+ -- Find-and-replace across scripts, planned against one snapshot of every
12891
+ -- matching script before anything is written. The whole plan is checked (the
12892
+ -- replacement cap and any expected revisions) before the first write. Each
12893
+ -- write is a compare-and-set against the planned source, and a failed write
12894
+ -- restores the scripts already written wherever they still hold the written
12895
+ -- text, so a newer editor draft is never overwritten. ChangeHistoryService is
12896
+ -- not relied on to undo Source. Free of Studio services so it can run outside
12897
+ -- Studio.
12898
+ local DEFAULT_MAX_REPLACEMENTS = 1000
12899
+ local PREVIEW_DIFF_CHAR_BUDGET = 20000
12900
+ -- Originals returned when a restore was refused, so the caller can recover them.
12901
+ local RETAINED_SOURCE_CHAR_BUDGET = 200000
12902
+ local function readRequest(data)
12903
+ local pattern = data.pattern
12904
+ if not (type(pattern) == "string") or pattern == "" then
12905
+ return "pattern is required"
12906
+ end
12907
+ local replacement = data.replacement
12908
+ if not (type(replacement) == "string") then
12909
+ return "replacement is required"
12910
+ end
12911
+ for _, option in { "caseSensitive", "usePattern", "dryRun" } do
12912
+ local value = data[option]
12913
+ if value ~= nil and not (type(value) == "boolean") then
12914
+ return `{option} must be a boolean`
12915
+ end
12916
+ end
12917
+ local _condition = (data.caseSensitive)
12918
+ if _condition == nil then
12919
+ _condition = false
12920
+ end
12921
+ local caseSensitive = _condition
12922
+ local _condition_1 = (data.usePattern)
12923
+ if _condition_1 == nil then
12924
+ _condition_1 = false
12925
+ end
12926
+ local usePattern = _condition_1
12927
+ if not caseSensitive and usePattern then
12928
+ return "Case-insensitive Lua pattern replacement is not supported. Use caseSensitive: true with usePattern: true, or use literal matching."
12929
+ end
12930
+ local _condition_2 = data.path
12931
+ if _condition_2 == nil then
12932
+ _condition_2 = ""
12933
+ end
12934
+ local path = _condition_2
12935
+ if not (type(path) == "string") then
12936
+ return "path must be a string"
12937
+ end
12938
+ local classError = ScriptClasses.classFilterError(data.classFilter)
12939
+ if classError ~= nil then
12940
+ return classError
12941
+ end
12942
+ local _condition_3 = data.maxReplacements
12943
+ if _condition_3 == nil then
12944
+ _condition_3 = DEFAULT_MAX_REPLACEMENTS
12945
+ end
12946
+ local maxReplacements = _condition_3
12947
+ if not (type(maxReplacements) == "number") or maxReplacements < 1 or maxReplacements % 1 ~= 0 then
12948
+ return "maxReplacements must be a positive whole number"
12949
+ end
12950
+ local expectedRevisions
12951
+ local rawRevisions = data.expectedRevisions
12952
+ if rawRevisions ~= nil then
12953
+ if not (type(rawRevisions) == "table") then
12954
+ return "expectedRevisions must map script paths to revisions"
12955
+ end
12956
+ expectedRevisions = {}
12957
+ for key, value in pairs(rawRevisions) do
12958
+ if not (type(key) == "string") or not (type(value) == "string") or value == "" then
12959
+ return "expectedRevisions must map script paths to revisions"
12960
+ end
12961
+ expectedRevisions[key] = value
12962
+ end
12963
+ end
12964
+ local _object = {
12965
+ pattern = pattern,
12966
+ replacement = replacement,
12967
+ caseSensitive = caseSensitive,
12968
+ usePattern = usePattern,
12969
+ path = path,
12970
+ classFilter = data.classFilter,
12971
+ }
12972
+ local _left = "dryRun"
12973
+ local _condition_4 = (data.dryRun)
12974
+ if _condition_4 == nil then
12975
+ _condition_4 = false
12976
+ end
12977
+ _object[_left] = _condition_4
12978
+ _object.maxReplacements = maxReplacements
12979
+ _object.expectedRevisions = expectedRevisions
12980
+ return _object
12981
+ end
12982
+ -- Replaces every non-overlapping occurrence, left to right. Case-insensitive
12983
+ -- matching compares lowered copies; string.lower keeps byte offsets.
12984
+ local function replaceLiteral(source, search, replacement, caseSensitive)
12985
+ local haystack = if caseSensitive then source else string.lower(source)
12986
+ local needle = if caseSensitive then search else string.lower(search)
12987
+ local parts = {}
12988
+ local cursor = 1
12989
+ local count = 0
12990
+ while true do
12991
+ local found = string.find(haystack, needle, cursor, true)
12992
+ if found == nil then
12993
+ break
12994
+ end
12995
+ local _arg0 = string.sub(source, cursor, found - 1)
12996
+ table.insert(parts, _arg0)
12997
+ local _replacement = replacement
12998
+ table.insert(parts, _replacement)
12999
+ cursor = found + #needle
13000
+ count += 1
13001
+ end
13002
+ if count == 0 then
13003
+ return { source, 0 }
13004
+ end
13005
+ local _arg0 = string.sub(source, cursor)
13006
+ table.insert(parts, _arg0)
13007
+ return { table.concat(parts, ""), count }
13008
+ end
13009
+ local function createScriptReplace(corpus)
13010
+ local function replaceIn(request, source)
13011
+ if request.usePattern then
13012
+ local result, count = string.gsub(source, request.pattern, request.replacement)
13013
+ return { result, count }
13014
+ end
13015
+ return replaceLiteral(source, request.pattern, request.replacement, request.caseSensitive)
13016
+ end
13017
+ local function planScripts(request, root)
13018
+ local _self = corpus
13019
+ local _result = _self.createAmbiguityChecker
13020
+ if _result ~= nil then
13021
+ _result = _result(_self)
13022
+ end
13023
+ local _condition = _result
13024
+ if _condition == nil then
13025
+ _condition = (function()
13026
+ return false
13027
+ end)
13028
+ end
13029
+ local isAmbiguous = _condition
13030
+ local planned = {}
13031
+ local scriptsSearched = 0
13032
+ local stack = { root }
13033
+ while #stack > 0 do
13034
+ -- ▼ Array.pop ▼
13035
+ local _length = #stack
13036
+ local _result_1 = stack[_length]
13037
+ stack[_length] = nil
13038
+ -- ▲ Array.pop ▲
13039
+ local node = _result_1
13040
+ local snapshot = corpus:readScript(node, request.classFilter)
13041
+ if snapshot ~= nil and ScriptClasses.matchesClassFilter(snapshot.className, request.classFilter) then
13042
+ scriptsSearched += 1
13043
+ local _binding = replaceIn(request, snapshot.source)
13044
+ local newSource = _binding[1]
13045
+ local replacements = _binding[2]
13046
+ if replacements > 0 then
13047
+ local _arg0 = {
13048
+ node = node,
13049
+ snapshot = snapshot,
13050
+ newSource = newSource,
13051
+ replacements = replacements,
13052
+ revision = sourceRevision(snapshot.source),
13053
+ resultRevision = sourceRevision(newSource),
13054
+ ambiguous = isAmbiguous(node),
13055
+ }
13056
+ table.insert(planned, _arg0)
13057
+ end
13058
+ end
13059
+ local children = corpus:getChildren(node)
13060
+ for index = #children - 1, 0, -1 do
13061
+ local _arg0 = children[index + 1]
13062
+ table.insert(stack, _arg0)
13063
+ end
13064
+ end
13065
+ -- A path shared by two planned scripts cannot key a revision either.
13066
+ local pathCounts = {}
13067
+ for _, entry in planned do
13068
+ local _exp = entry.snapshot.instancePath
13069
+ local _instancePath = entry.snapshot.instancePath
13070
+ local _condition_1 = pathCounts[_instancePath]
13071
+ if _condition_1 == nil then
13072
+ _condition_1 = 0
13073
+ end
13074
+ pathCounts[_exp] = _condition_1 + 1
13075
+ end
13076
+ for _, entry in planned do
13077
+ local _instancePath = entry.snapshot.instancePath
13078
+ if pathCounts[_instancePath] > 1 then
13079
+ entry.ambiguous = true
13080
+ end
13081
+ end
13082
+ return { planned, scriptsSearched }
13083
+ end
13084
+ local function checkRevisions(planned, expected)
13085
+ local mismatches = {}
13086
+ local plannedPaths = {}
13087
+ for _, entry in planned do
13088
+ local instancePath = entry.snapshot.instancePath
13089
+ plannedPaths[instancePath] = true
13090
+ local expectedRevision = expected[instancePath]
13091
+ if entry.ambiguous then
13092
+ local _arg0 = {
13093
+ instancePath = instancePath,
13094
+ reason = "ambiguous_path",
13095
+ expectedRevision = expectedRevision,
13096
+ revision = entry.revision,
13097
+ }
13098
+ table.insert(mismatches, _arg0)
13099
+ elseif expectedRevision == nil then
13100
+ local _arg0 = {
13101
+ instancePath = instancePath,
13102
+ reason = "not_reviewed",
13103
+ revision = entry.revision,
13104
+ }
13105
+ table.insert(mismatches, _arg0)
13106
+ elseif expectedRevision ~= entry.revision then
13107
+ local _arg0 = {
13108
+ instancePath = instancePath,
13109
+ reason = "changed",
13110
+ expectedRevision = expectedRevision,
13111
+ revision = entry.revision,
13112
+ }
13113
+ table.insert(mismatches, _arg0)
13114
+ end
13115
+ end
13116
+ local reviewedOnly = {}
13117
+ for instancePath in expected do
13118
+ if not (plannedPaths[instancePath] ~= nil) then
13119
+ table.insert(reviewedOnly, instancePath)
13120
+ end
13121
+ end
13122
+ table.sort(reviewedOnly)
13123
+ for _, instancePath in reviewedOnly do
13124
+ local expectedRevision = expected[instancePath]
13125
+ local node = corpus:resolvePath(instancePath)
13126
+ local snapshot = if node == nil then nil else corpus:readScript(node)
13127
+ if snapshot == nil then
13128
+ local _arg0 = {
13129
+ instancePath = instancePath,
13130
+ reason = "missing",
13131
+ expectedRevision = expectedRevision,
13132
+ }
13133
+ table.insert(mismatches, _arg0)
13134
+ continue
13135
+ end
13136
+ local revision = sourceRevision(snapshot.source)
13137
+ local _arg0 = {
13138
+ instancePath = instancePath,
13139
+ reason = if revision == expectedRevision then "no_longer_matches" else "changed",
13140
+ expectedRevision = expectedRevision,
13141
+ revision = revision,
13142
+ }
13143
+ table.insert(mismatches, _arg0)
13144
+ end
13145
+ return mismatches
13146
+ end
13147
+ local function describePlanned(entry)
13148
+ local change = {
13149
+ instancePath = entry.snapshot.instancePath,
13150
+ name = entry.snapshot.name,
13151
+ className = entry.snapshot.className,
13152
+ replacements = entry.replacements,
13153
+ revision = entry.revision,
13154
+ resultRevision = entry.resultRevision,
13155
+ }
13156
+ if entry.ambiguous then
13157
+ change.ambiguous = true
13158
+ end
13159
+ return change
13160
+ end
13161
+ local function run(data)
13162
+ local request = readRequest(data)
13163
+ if type(request) == "string" then
13164
+ return {
13165
+ success = false,
13166
+ error = request,
13167
+ }
13168
+ end
13169
+ local root = corpus:resolvePath(request.path)
13170
+ if root == nil then
13171
+ return {
13172
+ success = false,
13173
+ error = `Path not found: {request.path}`,
13174
+ }
13175
+ end
13176
+ local summary = {
13177
+ dryRun = request.dryRun,
13178
+ pattern = request.pattern,
13179
+ replacement = request.replacement,
13180
+ maxReplacements = request.maxReplacements,
13181
+ }
13182
+ -- Planning reads and computes only; a malformed Lua pattern fails here,
13183
+ -- before any write.
13184
+ local scanned, scanResult = pcall(function()
13185
+ return planScripts(request, root)
13186
+ end)
13187
+ if not scanned then
13188
+ local _object = table.clone(summary)
13189
+ setmetatable(_object, nil)
13190
+ _object.success = false
13191
+ _object.error = `Script traversal failed: {scanResult}`
13192
+ _object.totalReplacements = 0
13193
+ _object.scriptsSearched = 0
13194
+ _object.scriptsMatched = 0
13195
+ _object.scriptsModified = 0
13196
+ _object.scriptsFailed = 0
13197
+ _object.changes = {}
13198
+ return _object
13199
+ end
13200
+ local _binding = scanResult
13201
+ local scripts = _binding[1]
13202
+ local scriptsSearched = _binding[2]
13203
+ local totalReplacements = 0
13204
+ for _, entry in scripts do
13205
+ totalReplacements += entry.replacements
13206
+ end
13207
+ summary.totalReplacements = totalReplacements
13208
+ summary.scriptsSearched = scriptsSearched
13209
+ summary.scriptsMatched = #scripts
13210
+ -- ▼ ReadonlyArray.map ▼
13211
+ local _newValue = table.create(#scripts)
13212
+ for _k, _v in scripts do
13213
+ _newValue[_k] = describePlanned(_v, _k - 1, scripts)
13214
+ end
13215
+ -- ▲ ReadonlyArray.map ▲
13216
+ local changes = _newValue
13217
+ local revisions = {}
13218
+ for _, entry in scripts do
13219
+ if not entry.ambiguous then
13220
+ local _instancePath = entry.snapshot.instancePath
13221
+ local _revision = entry.revision
13222
+ revisions[_instancePath] = _revision
13223
+ end
13224
+ end
13225
+ local refused = function(code, message, extra)
13226
+ if extra == nil then
13227
+ extra = {}
13228
+ end
13229
+ local _object = table.clone(summary)
13230
+ setmetatable(_object, nil)
13231
+ for _k, _v in extra do
13232
+ _object[_k] = _v
13233
+ end
13234
+ _object.success = false
13235
+ _object.code = code
13236
+ _object.error = message
13237
+ _object.scriptsModified = 0
13238
+ _object.scriptsFailed = 0
13239
+ _object.changes = changes
13240
+ return _object
13241
+ end
13242
+ if request.expectedRevisions ~= nil then
13243
+ local mismatches = checkRevisions(scripts, request.expectedRevisions)
13244
+ if #mismatches > 0 then
13245
+ return refused("revision_mismatch", "The scripts this replacement would change differ from the reviewed expected_revisions; nothing was written. Preview again with dryRun and pass its revisions.", {
13246
+ mismatches = mismatches,
13247
+ })
13248
+ end
13249
+ end
13250
+ if totalReplacements > request.maxReplacements then
13251
+ return refused("max_replacements_exceeded", `This replacement makes {totalReplacements} replacements, more than maxReplacements ({request.maxReplacements}); nothing was written. Narrow path or classFilter, or raise maxReplacements.`)
13252
+ end
13253
+ if request.dryRun then
13254
+ local diffBudget = PREVIEW_DIFF_CHAR_BUDGET
13255
+ local anyDiffTruncated = false
13256
+ for index = 0, #scripts - 1 do
13257
+ local entry = scripts[index + 1]
13258
+ local change = changes[index + 1]
13259
+ if diffBudget <= 0 then
13260
+ change.diffTruncated = true
13261
+ anyDiffTruncated = true
13262
+ continue
13263
+ end
13264
+ local built = diffSources(entry.snapshot.source, entry.newSource, diffBudget)
13265
+ change.diff = built.diff
13266
+ diffBudget -= #built.diff + 1
13267
+ if built.truncated then
13268
+ change.diffTruncated = true
13269
+ anyDiffTruncated = true
13270
+ end
13271
+ end
13272
+ local _object = table.clone(summary)
13273
+ setmetatable(_object, nil)
13274
+ _object.success = true
13275
+ _object.scriptsModified = #scripts
13276
+ _object.scriptsFailed = 0
13277
+ _object.changes = changes
13278
+ local preview = _object
13279
+ -- Pass back as expected_revisions to apply exactly this plan. Omitted
13280
+ -- when empty: Luau encodes an empty table as a JSON array.
13281
+ -- ▼ ReadonlyArray.some ▼
13282
+ local _result = false
13283
+ local _callback = function(entry)
13284
+ return not entry.ambiguous
13285
+ end
13286
+ for _k, _v in scripts do
13287
+ if _callback(_v, _k - 1, scripts) then
13288
+ _result = true
13289
+ break
13290
+ end
13291
+ end
13292
+ -- ▲ ReadonlyArray.some ▲
13293
+ if _result then
13294
+ preview.revisions = revisions
13295
+ end
13296
+ if anyDiffTruncated then
13297
+ preview.diffTruncated = true
13298
+ end
13299
+ return preview
13300
+ end
13301
+ if #scripts == 0 then
13302
+ local _object = table.clone(summary)
13303
+ setmetatable(_object, nil)
13304
+ _object.success = true
13305
+ _object.scriptsModified = 0
13306
+ _object.scriptsFailed = 0
13307
+ _object.changes = changes
13308
+ return _object
13309
+ end
13310
+ local recording = corpus:beginRecording("Find and replace in scripts")
13311
+ local write = function(node, newSource, expectedSource)
13312
+ local ok, result = pcall(function()
13313
+ return corpus:writeScript(node, newSource, expectedSource)
13314
+ end)
13315
+ return if ok then result else {
13316
+ success = false,
13317
+ error = tostring(result),
13318
+ }
13319
+ end
13320
+ local failedAt
13321
+ local failure
13322
+ for index = 0, #scripts - 1 do
13323
+ local entry = scripts[index + 1]
13324
+ local result = write(entry.node, entry.newSource, entry.snapshot.source)
13325
+ if not result.success then
13326
+ failedAt = index
13327
+ local _condition = result.error
13328
+ if _condition == nil then
13329
+ _condition = "Script write failed verification"
13330
+ end
13331
+ failure = _condition
13332
+ break
13333
+ end
13334
+ changes[index + 1].status = "applied"
13335
+ end
13336
+ if failedAt == nil then
13337
+ corpus:finishRecording(recording, true)
13338
+ local _object = table.clone(summary)
13339
+ setmetatable(_object, nil)
13340
+ _object.success = true
13341
+ _object.scriptsModified = #scripts
13342
+ _object.scriptsFailed = 0
13343
+ _object.changes = changes
13344
+ return _object
13345
+ end
13346
+ local statuses = {}
13347
+ for index = 0, #scripts - 1 do
13348
+ local _arg0 = if index < failedAt then "applied" elseif index == failedAt then "failed" else "not_attempted"
13349
+ table.insert(statuses, _arg0)
13350
+ end
13351
+ changes[failedAt + 1].error = failure
13352
+ -- A failed write can still have landed (verification refused it); if the
13353
+ -- script holds the written text, undo it like the others.
13354
+ local failedEntry = scripts[failedAt + 1]
13355
+ local holds = function(entry, source)
13356
+ local readOk, current = pcall(function()
13357
+ return corpus:readScript(entry.node)
13358
+ end)
13359
+ return readOk and current ~= nil and current.source == source
13360
+ end
13361
+ local restoreFrom = if holds(failedEntry, failedEntry.newSource) then failedAt else failedAt - 1
13362
+ local retainedBudget = RETAINED_SOURCE_CHAR_BUDGET
13363
+ local restored = 0
13364
+ local restoreFailed = 0
13365
+ do
13366
+ local index = restoreFrom
13367
+ local _shouldIncrement = false
13368
+ while true do
13369
+ if _shouldIncrement then
13370
+ index -= 1
13371
+ else
13372
+ _shouldIncrement = true
13373
+ end
13374
+ if not (index >= 0) then
13375
+ break
13376
+ end
13377
+ local entry = scripts[index + 1]
13378
+ local change = changes[index + 1]
13379
+ local result = write(entry.node, entry.snapshot.source, entry.newSource)
13380
+ -- A restore refused by verification can still have landed.
13381
+ if result.success or holds(entry, entry.snapshot.source) then
13382
+ statuses[index + 1] = "restored"
13383
+ restored += 1
13384
+ continue
13385
+ end
13386
+ statuses[index + 1] = "restore_failed"
13387
+ restoreFailed += 1
13388
+ local _condition = result.error
13389
+ if _condition == nil then
13390
+ _condition = "Script restore failed verification"
13391
+ end
13392
+ change.restoreError = _condition
13393
+ if #entry.snapshot.source <= retainedBudget then
13394
+ change.originalSource = entry.snapshot.source
13395
+ retainedBudget -= #entry.snapshot.source
13396
+ else
13397
+ change.originalSourceOmitted = true
13398
+ end
13399
+ end
13400
+ end
13401
+ for index = 0, #scripts - 1 do
13402
+ changes[index + 1].status = statuses[index + 1]
13403
+ end
13404
+ corpus:finishRecording(recording, restoreFailed > 0)
13405
+ local notAttempted = 0
13406
+ for _, status in statuses do
13407
+ if status == "not_attempted" then
13408
+ notAttempted += 1
13409
+ end
13410
+ end
13411
+ local restoreSummary = if restoreFailed > 0 then `{restored} written script(s) were restored; {restoreFailed} changed again after the write and were left as they are, with their original source in changes[].originalSource where it fits.` else `{restored} written script(s) were restored.`
13412
+ local _object = table.clone(summary)
13413
+ setmetatable(_object, nil)
13414
+ _object.success = false
13415
+ _object.code = "apply_failed"
13416
+ _object.error = `Failed to write {failedEntry.snapshot.instancePath}: {failure}. {restoreSummary}`
13417
+ _object.scriptsModified = restoreFailed
13418
+ _object.scriptsRestored = restored
13419
+ _object.scriptsFailed = 1
13420
+ _object.scriptsNotAttempted = notAttempted
13421
+ _object.changes = changes
13422
+ return _object
13423
+ end
13424
+ return {
13425
+ run = run,
13426
+ }
13427
+ end
13428
+ return {
13429
+ createScriptReplace = createScriptReplace,
13430
+ }
13431
+ ]]></string>
13432
+ </Properties>
13433
+ </Item>
13434
+ <Item class="ModuleScript" referent="40">
12006
13435
  <Properties>
12007
13436
  <string name="Name">ScriptSearch</string>
12008
13437
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
13438
+ local TS = require(script.Parent.Parent.include.RuntimeLib)
13439
+ local ScriptClasses = TS.import(script, script.Parent, "ScriptClasses")
12009
13440
  local function splitLuaAlternation(pattern)
12010
13441
  local parts = {}
12011
13442
  local current = ""
@@ -12179,6 +13610,13 @@ local function createScriptSearch(corpus)
12179
13610
  _condition_4 = 0
12180
13611
  end
12181
13612
  local maxResultsPerScript = _condition_4
13613
+ local classError = ScriptClasses.classFilterError(requestData.classFilter)
13614
+ if classError ~= nil then
13615
+ return {
13616
+ error = "invalid_request",
13617
+ message = classError,
13618
+ }
13619
+ end
12182
13620
  local classFilter = requestData.classFilter
12183
13621
  local _condition_5 = (requestData.path)
12184
13622
  if _condition_5 == nil then
@@ -12219,7 +13657,7 @@ local function createScriptSearch(corpus)
12219
13657
  -- ▲ Array.pop ▲
12220
13658
  local instance = _result_2
12221
13659
  local snapshot = corpus:readScript(instance, classFilter)
12222
- if snapshot ~= nil and (classFilter == nil or snapshot.className == classFilter) then
13660
+ if snapshot ~= nil and ScriptClasses.matchesClassFilter(snapshot.className, classFilter) then
12223
13661
  scriptsSearched += 1
12224
13662
  local scriptMatches = {}
12225
13663
  local before = {}
@@ -12344,7 +13782,7 @@ return {
12344
13782
  ]]></string>
12345
13783
  </Properties>
12346
13784
  </Item>
12347
- <Item class="ModuleScript" referent="39">
13785
+ <Item class="ModuleScript" referent="41">
12348
13786
  <Properties>
12349
13787
  <string name="Name">ServerUrlSettings</string>
12350
13788
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -12458,11 +13896,11 @@ return {
12458
13896
  ]]></string>
12459
13897
  </Properties>
12460
13898
  </Item>
12461
- <Item class="ModuleScript" referent="40">
13899
+ <Item class="ModuleScript" referent="42">
12462
13900
  <Properties>
12463
13901
  <string name="Name">State</string>
12464
13902
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
12465
- local CURRENT_VERSION = "3.3.0"
13903
+ local CURRENT_VERSION = "3.4.0"
12466
13904
  local PLUGIN_VARIANT = "inspector"
12467
13905
  local BASE_PORT = 58741
12468
13906
  local SENSITIVE_DIAGNOSTIC_TERMS = { "token", "authorization", "bearer", "password", "cookie", "secret" }
@@ -12600,7 +14038,7 @@ return {
12600
14038
  ]]></string>
12601
14039
  </Properties>
12602
14040
  </Item>
12603
- <Item class="ModuleScript" referent="41">
14041
+ <Item class="ModuleScript" referent="43">
12604
14042
  <Properties>
12605
14043
  <string name="Name">StopPlayMonitor</string>
12606
14044
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -12886,7 +14324,7 @@ return {
12886
14324
  ]]></string>
12887
14325
  </Properties>
12888
14326
  </Item>
12889
- <Item class="ModuleScript" referent="42">
14327
+ <Item class="ModuleScript" referent="44">
12890
14328
  <Properties>
12891
14329
  <string name="Name">StudioWebSocket</string>
12892
14330
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -14044,7 +15482,7 @@ return {
14044
15482
  ]]></string>
14045
15483
  </Properties>
14046
15484
  </Item>
14047
- <Item class="ModuleScript" referent="43">
15485
+ <Item class="ModuleScript" referent="45">
14048
15486
  <Properties>
14049
15487
  <string name="Name">TopologyId</string>
14050
15488
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -14089,7 +15527,7 @@ return {
14089
15527
  ]]></string>
14090
15528
  </Properties>
14091
15529
  </Item>
14092
- <Item class="ModuleScript" referent="44">
15530
+ <Item class="ModuleScript" referent="46">
14093
15531
  <Properties>
14094
15532
  <string name="Name">UI</string>
14095
15533
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -14614,7 +16052,7 @@ return {
14614
16052
  ]]></string>
14615
16053
  </Properties>
14616
16054
  </Item>
14617
- <Item class="ModuleScript" referent="45">
16055
+ <Item class="ModuleScript" referent="47">
14618
16056
  <Properties>
14619
16057
  <string name="Name">Utils</string>
14620
16058
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -15486,11 +16924,11 @@ return {
15486
16924
  </Properties>
15487
16925
  </Item>
15488
16926
  </Item>
15489
- <Item class="Folder" referent="50">
16927
+ <Item class="Folder" referent="52">
15490
16928
  <Properties>
15491
16929
  <string name="Name">include</string>
15492
16930
  </Properties>
15493
- <Item class="ModuleScript" referent="46">
16931
+ <Item class="ModuleScript" referent="48">
15494
16932
  <Properties>
15495
16933
  <string name="Name">LibMP</string>
15496
16934
  <string name="Source"><![CDATA[-- =============================================================================
@@ -171874,7 +173312,7 @@ return LibMP
171874
173312
  ]]></string>
171875
173313
  </Properties>
171876
173314
  </Item>
171877
- <Item class="ModuleScript" referent="47">
173315
+ <Item class="ModuleScript" referent="49">
171878
173316
  <Properties>
171879
173317
  <string name="Name">Promise</string>
171880
173318
  <string name="Source"><![CDATA[--[[
@@ -173948,7 +175386,7 @@ return Promise
173948
175386
  ]]></string>
173949
175387
  </Properties>
173950
175388
  </Item>
173951
- <Item class="ModuleScript" referent="48">
175389
+ <Item class="ModuleScript" referent="50">
173952
175390
  <Properties>
173953
175391
  <string name="Name">RuntimeLib</string>
173954
175392
  <string name="Source"><![CDATA[local Promise = require(script.Parent.Promise)
@@ -174215,15 +175653,15 @@ return TS
174215
175653
  </Properties>
174216
175654
  </Item>
174217
175655
  </Item>
174218
- <Item class="Folder" referent="51">
175656
+ <Item class="Folder" referent="53">
174219
175657
  <Properties>
174220
175658
  <string name="Name">node_modules</string>
174221
175659
  </Properties>
174222
- <Item class="Folder" referent="52">
175660
+ <Item class="Folder" referent="54">
174223
175661
  <Properties>
174224
175662
  <string name="Name">@rbxts</string>
174225
175663
  </Properties>
174226
- <Item class="ModuleScript" referent="49">
175664
+ <Item class="ModuleScript" referent="51">
174227
175665
  <Properties>
174228
175666
  <string name="Name">services</string>
174229
175667
  <string name="Source"><![CDATA[return setmetatable({}, {