portacode 1.3.26__tar.gz → 1.3.27__tar.gz

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.

Potentially problematic release.


This version of portacode might be problematic. Click here for more details.

Files changed (94) hide show
  1. {portacode-1.3.26 → portacode-1.3.27}/.claude/settings.local.json +1 -2
  2. portacode-1.3.27/MANIFEST.in +3 -0
  3. {portacode-1.3.26 → portacode-1.3.27}/PKG-INFO +2 -1
  4. {portacode-1.3.26 → portacode-1.3.27}/portacode/_version.py +2 -2
  5. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/WEBSOCKET_PROTOCOL.md +131 -13
  6. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/base.py +70 -12
  7. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/file_handlers.py +5 -10
  8. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/project_state/handlers.py +9 -6
  9. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/registry.py +15 -4
  10. portacode-1.3.27/portacode/static/js/test-ntp-clock.html +63 -0
  11. portacode-1.3.27/portacode/static/js/utils/ntp-clock.js +141 -0
  12. portacode-1.3.27/portacode/utils/NTP_ARCHITECTURE.md +136 -0
  13. portacode-1.3.27/portacode/utils/__init__.py +1 -0
  14. portacode-1.3.27/portacode/utils/ntp_clock.py +151 -0
  15. {portacode-1.3.26 → portacode-1.3.27}/portacode.egg-info/PKG-INFO +2 -1
  16. {portacode-1.3.26 → portacode-1.3.27}/portacode.egg-info/SOURCES.txt +8 -1
  17. {portacode-1.3.26 → portacode-1.3.27}/portacode.egg-info/requires.txt +1 -0
  18. {portacode-1.3.26 → portacode-1.3.27}/setup.py +7 -0
  19. portacode-1.3.27/test_request_id.py +146 -0
  20. portacode-1.3.27/tools/test_python_ntp_clock.py +39 -0
  21. portacode-1.3.26/MANIFEST.in +0 -2
  22. {portacode-1.3.26 → portacode-1.3.27}/.claude/agents/communication-manager.md +0 -0
  23. {portacode-1.3.26 → portacode-1.3.27}/.gitignore +0 -0
  24. {portacode-1.3.26 → portacode-1.3.27}/.gitmodules +0 -0
  25. {portacode-1.3.26 → portacode-1.3.27}/LICENSE +0 -0
  26. {portacode-1.3.26 → portacode-1.3.27}/Makefile +0 -0
  27. {portacode-1.3.26 → portacode-1.3.27}/README.md +0 -0
  28. {portacode-1.3.26 → portacode-1.3.27}/backup.sh +0 -0
  29. {portacode-1.3.26 → portacode-1.3.27}/connect.py +0 -0
  30. {portacode-1.3.26 → portacode-1.3.27}/connect.sh +0 -0
  31. {portacode-1.3.26 → portacode-1.3.27}/docker-compose.yaml +0 -0
  32. {portacode-1.3.26 → portacode-1.3.27}/portacode/README.md +0 -0
  33. {portacode-1.3.26 → portacode-1.3.27}/portacode/__init__.py +0 -0
  34. {portacode-1.3.26 → portacode-1.3.27}/portacode/__main__.py +0 -0
  35. {portacode-1.3.26 → portacode-1.3.27}/portacode/cli.py +0 -0
  36. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/README.md +0 -0
  37. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/__init__.py +0 -0
  38. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/client.py +0 -0
  39. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/README.md +0 -0
  40. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/__init__.py +0 -0
  41. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/chunked_content.py +0 -0
  42. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/project_aware_file_handlers.py +0 -0
  43. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/project_state/README.md +0 -0
  44. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/project_state/__init__.py +0 -0
  45. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/project_state/file_system_watcher.py +0 -0
  46. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/project_state/git_manager.py +0 -0
  47. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/project_state/manager.py +0 -0
  48. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/project_state/models.py +0 -0
  49. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/project_state/utils.py +0 -0
  50. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/project_state_handlers.py +0 -0
  51. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/session.py +0 -0
  52. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/system_handlers.py +0 -0
  53. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/tab_factory.py +0 -0
  54. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/handlers/terminal_handlers.py +0 -0
  55. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/multiplex.py +0 -0
  56. {portacode-1.3.26 → portacode-1.3.27}/portacode/connection/terminal.py +0 -0
  57. {portacode-1.3.26 → portacode-1.3.27}/portacode/data.py +0 -0
  58. {portacode-1.3.26 → portacode-1.3.27}/portacode/keypair.py +0 -0
  59. {portacode-1.3.26 → portacode-1.3.27}/portacode/logging_categories.py +0 -0
  60. {portacode-1.3.26 → portacode-1.3.27}/portacode/service.py +0 -0
  61. {portacode-1.3.26 → portacode-1.3.27}/portacode.egg-info/dependency_links.txt +0 -0
  62. {portacode-1.3.26 → portacode-1.3.27}/portacode.egg-info/entry_points.txt +0 -0
  63. {portacode-1.3.26 → portacode-1.3.27}/portacode.egg-info/top_level.txt +0 -0
  64. {portacode-1.3.26 → portacode-1.3.27}/pyproject.toml +0 -0
  65. {portacode-1.3.26 → portacode-1.3.27}/restore.sh +0 -0
  66. {portacode-1.3.26 → portacode-1.3.27}/run_tests.py +0 -0
  67. {portacode-1.3.26 → portacode-1.3.27}/setup.cfg +0 -0
  68. {portacode-1.3.26 → portacode-1.3.27}/test.sh +0 -0
  69. {portacode-1.3.26 → portacode-1.3.27}/test_modules/README.md +0 -0
  70. {portacode-1.3.26 → portacode-1.3.27}/test_modules/__init__.py +0 -0
  71. {portacode-1.3.26 → portacode-1.3.27}/test_modules/test_device_online.py +0 -0
  72. {portacode-1.3.26 → portacode-1.3.27}/test_modules/test_file_operations.py +0 -0
  73. {portacode-1.3.26 → portacode-1.3.27}/test_modules/test_git_status_ui.py +0 -0
  74. {portacode-1.3.26 → portacode-1.3.27}/test_modules/test_login_flow.py +0 -0
  75. {portacode-1.3.26 → portacode-1.3.27}/test_modules/test_navigate_testing_folder.py +0 -0
  76. {portacode-1.3.26 → portacode-1.3.27}/test_modules/test_terminal_buffer_performance.py +0 -0
  77. {portacode-1.3.26 → portacode-1.3.27}/test_modules/test_terminal_interaction.py +0 -0
  78. {portacode-1.3.26 → portacode-1.3.27}/test_modules/test_terminal_loading_race_condition.py +0 -0
  79. {portacode-1.3.26 → portacode-1.3.27}/test_modules/test_terminal_start.py +0 -0
  80. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/.env.example +0 -0
  81. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/README.md +0 -0
  82. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/__init__.py +0 -0
  83. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/cli.py +0 -0
  84. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/core/__init__.py +0 -0
  85. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/core/base_test.py +0 -0
  86. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/core/cli_manager.py +0 -0
  87. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/core/hierarchical_runner.py +0 -0
  88. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/core/playwright_manager.py +0 -0
  89. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/core/runner.py +0 -0
  90. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/core/shared_cli_manager.py +0 -0
  91. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/core/test_discovery.py +0 -0
  92. {portacode-1.3.26 → portacode-1.3.27}/testing_framework/requirements.txt +0 -0
  93. {portacode-1.3.26 → portacode-1.3.27}/todo/issues/indefinite_resource_loading.md +0 -0
  94. {portacode-1.3.26 → portacode-1.3.27}/todo/issues/premature_terminal_exit.md +0 -0
@@ -17,7 +17,6 @@
17
17
  "Bash(git -C /home/menas/testing_folder status --porcelain)",
18
18
  "Bash(docker-compose restart:*)"
19
19
  ],
20
- "deny": [],
21
- "defaultMode": "acceptEdits"
20
+ "deny": []
22
21
  }
23
22
  }
@@ -0,0 +1,3 @@
1
+ prune server
2
+ exclude .pypirc
3
+ recursive-include portacode/static *.js *.html
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: portacode
3
- Version: 1.3.26
3
+ Version: 1.3.27
4
4
  Summary: Portacode CLI client and SDK
5
5
  Home-page: https://github.com/portacode/portacode
6
6
  Author: Meena Erian
@@ -23,6 +23,7 @@ Requires-Dist: GitPython>=3.1.45
23
23
  Requires-Dist: watchdog>=3.0
24
24
  Requires-Dist: diff-match-patch>=20230430
25
25
  Requires-Dist: Pygments>=2.14.0
26
+ Requires-Dist: ntplib>=0.4.0
26
27
  Provides-Extra: dev
27
28
  Requires-Dist: black; extra == "dev"
28
29
  Requires-Dist: flake8; extra == "dev"
@@ -28,7 +28,7 @@ version_tuple: VERSION_TUPLE
28
28
  commit_id: COMMIT_ID
29
29
  __commit_id__: COMMIT_ID
30
30
 
31
- __version__ = version = '1.3.26'
32
- __version_tuple__ = version_tuple = (1, 3, 26)
31
+ __version__ = version = '1.3.27'
32
+ __version_tuple__ = version_tuple = (1, 3, 27)
33
33
 
34
34
  __commit_id__ = commit_id = None
@@ -1,10 +1,38 @@
1
1
  # WebSocket Communication Protocol
2
2
 
3
- This document outlines the WebSocket communication protocol between the Portacode server and the connected client devices.
3
+ This document outlines the WebSocket communication protocol used in Portacode. The protocol involves three main participants: client sessions, the Portacode server, and devices.
4
+
5
+ ## Architecture Overview
6
+
7
+ ```
8
+ ┌─────────────┐ ┌──────────────────┐ ┌─────────────────────────┐
9
+ │ Client │ │ Portacode │ │ Device │
10
+ │ Session │◄────────►│ Server │◄────────►│ (Portacode CLI or │
11
+ │ │ │ │ │ Python package) │
12
+ └─────────────┘ └──────────────────┘ └─────────────────────────┘
13
+ │ │ │
14
+ │ │ │
15
+ Client-Side Acts as middleman Device-Side
16
+ Protocol - Routes messages Protocol
17
+ - Manages sessions
18
+ ```
19
+
20
+ The Portacode server acts as a **routing middleman** between client sessions and devices. It manages routing fields that are included in messages to specify routing destinations but are removed or transformed before reaching the final recipient:
21
+
22
+ **Routing Fields Behavior:**
23
+
24
+ - **`device_id`** (Client → Server): Client includes this to specify which device to route to. Server uses it for routing, then **removes it** before forwarding to the device (the device knows the message is for them). Server **adds it** when routing device responses back to clients (so clients know which device the message came from).
25
+
26
+ - **`client_sessions`** (Device → Server): Device includes this to specify which client session(s) to route to. Server uses it for routing, then **removes it** before forwarding to clients (clients just receive the message without seeing routing metadata).
27
+
28
+ - **`source_client_session`** (Server → Device): Server **adds this** when forwarding client commands to devices (so device knows which client sent the command and can target responses back). Clients never include this field.
29
+
30
+ This document describes the complete protocol for communicating with devices through the server, guiding app developers on how to get their client sessions to communicate with devices.
4
31
 
5
32
  ## Table of Contents
6
33
 
7
- - [Raw Message Format](#raw-message-format)
34
+ - [Raw Message Format On Device Side](#raw-message-format-on-device-side)
35
+ - [Raw Message Format On Client Side](#raw-message-format-on-client-side)
8
36
  - [Actions](#actions)
9
37
  - [Terminal Actions](#terminal-actions)
10
38
  - [`terminal_start`](#terminal_start)
@@ -82,11 +110,11 @@ This document outlines the WebSocket communication protocol between the Portacod
82
110
  - [`device_status`](#device_status)
83
111
  - [`devices`](#devices)
84
112
 
85
- ## Raw Message Format
113
+ ## Raw Message Format On Device Side
86
114
 
87
- All communication over the WebSocket is managed by a [multiplexer](./multiplex.py) that wraps every message in a JSON object with a `channel` and a `payload`. This allows for multiple virtual communication channels over a single connection.
115
+ Communication between the server and devices uses a [multiplexer](./multiplex.py) that wraps every message in a JSON object with a `channel` and a `payload`. This allows for multiple virtual communication channels over a single WebSocket connection.
88
116
 
89
- **Raw Message Structure:**
117
+ **Device-Side Message Structure:**
90
118
 
91
119
  ```json
92
120
  {
@@ -97,9 +125,99 @@ All communication over the WebSocket is managed by a [multiplexer](./multiplex.p
97
125
  }
98
126
  ```
99
127
 
100
- * `channel` (string|integer, mandatory): Identifies the virtual channel the message is for. When sending control commands to the device, they should be sent to channel 0 and when the device responsed to such control commands or sends system events, they will also be send on the zero channel. When a terminal session is created in the device, it is assigned a uuid, the uuid becomes the channel for communicating to that specific terminal.
128
+ **Field Descriptions:**
129
+
130
+ * `channel` (string|integer, mandatory): Identifies the virtual channel the message is for. When sending control commands to the device, they should be sent to channel 0 and when the device responds to such control commands or sends system events, they will also be sent on the zero channel. When a terminal session is created in the device, it is assigned a uuid, the uuid becomes the channel for communicating to that specific terminal.
101
131
  * `payload` (object, mandatory): The content of the message, which will be either an [Action](#actions) or an [Event](#events) object.
102
132
 
133
+ **Channel Types:**
134
+ - **Channel 0** (control channel): Used for system commands, terminal management, file operations, and project state management
135
+ - **Channel UUID** (terminal channel): Used for terminal I/O to a specific terminal session
136
+
137
+ ---
138
+
139
+ ## Raw Message Format On Client Side
140
+
141
+ Client sessions communicate with the server using a unified message format with the same field names as the device protocol, plus routing information.
142
+
143
+ **Client-Side Message Structure (Client → Server):**
144
+
145
+ ```json
146
+ {
147
+ "device_id": <number>,
148
+ "channel": <number|string>,
149
+ "payload": {
150
+ "cmd": "<command_name>",
151
+ ...command-specific fields
152
+ }
153
+ }
154
+ ```
155
+
156
+ **Field Descriptions:**
157
+
158
+ * `device_id` (number, mandatory): Routing field - specifies which device to send the message to. The server validates that the client has access to this device before forwarding.
159
+ * `channel` (number|string, mandatory): Same as device protocol - the target channel (0 for control, UUID for terminal). Uses the same field name for consistency.
160
+ * `payload` (object, mandatory): Same as device protocol - the command payload. Uses the same field name for consistency.
161
+
162
+ **Server Transformation (Client → Device):**
163
+
164
+ When the server receives a client message, it:
165
+ 1. Validates client has access to the specified `device_id`
166
+ 2. **Removes** `device_id` from the message (device doesn't need to be told "this is for you")
167
+ 3. **Adds** `source_client_session` to the payload (so device knows which client to respond to)
168
+ 4. Forwards to device: `{channel, payload: {...payload, source_client_session}}`
169
+
170
+ **Server Transformation (Device → Client):**
171
+
172
+ When the server receives a device response, it:
173
+ 1. **Adds** `device_id` to the message (so client knows which device it came from, based on authenticated device connection)
174
+ 2. **Removes** `client_sessions` routing metadata (clients don't need to see routing info)
175
+ 3. Routes to appropriate client session(s)
176
+
177
+ **Server Response Format (Server → Client):**
178
+
179
+ ```json
180
+ {
181
+ "event": "<event_name>",
182
+ "device_id": <number>,
183
+ ...event-specific fields
184
+ }
185
+ ```
186
+
187
+ **Field Descriptions:**
188
+
189
+ * `event` (string, mandatory): The name of the event being sent.
190
+ * `device_id` (number, mandatory): Authenticated field - identifies which device the event came from (added by server based on authenticated device connection).
191
+ * Additional fields depend on the specific event type.
192
+
193
+ **Example Client Message:**
194
+ ```json
195
+ {
196
+ "device_id": 42,
197
+ "channel": 0,
198
+ "payload": {
199
+ "cmd": "terminal_start",
200
+ "shell": "bash",
201
+ "cwd": "/home/user/project"
202
+ }
203
+ }
204
+ ```
205
+
206
+ **Example Server Response:**
207
+ ```json
208
+ {
209
+ "event": "terminal_started",
210
+ "device_id": 42,
211
+ "terminal_id": "uuid-1234-5678",
212
+ "channel": "uuid-1234-5678",
213
+ "pid": 12345
214
+ }
215
+ ```
216
+
217
+ **Note:** The server acts as a translator between the client-side and device-side protocols:
218
+ - When a client sends a command, the server transforms it from the client format to the device format
219
+ - When a device sends an event, the server adds the `device_id` and routes it to the appropriate client sessions
220
+
103
221
  ---
104
222
 
105
223
  ## Actions
@@ -110,18 +228,18 @@ Actions are messages sent from the server to the device, placed within the `payl
110
228
 
111
229
  ```json
112
230
  {
113
- "command": "<command_name>",
114
- "payload": {
115
- "arg1": "value1",
116
- "...": "..."
117
- },
231
+ "cmd": "<command_name>",
232
+ "arg1": "value1",
233
+ "arg2": "value2",
118
234
  "source_client_session": "channel.abc123"
119
235
  }
120
236
  ```
121
237
 
122
- * `command` (string, mandatory): The name of the action to be executed (e.g., `terminal_start`).
123
- * `payload` (object, mandatory): An object containing the specific arguments for the action.
238
+ **Field Descriptions:**
239
+
240
+ * `cmd` (string, mandatory): The name of the action to be executed (e.g., `terminal_start`, `file_read`, `system_info`).
124
241
  * `source_client_session` (string, mandatory): The channel name of the client session that originated this command. This field is automatically added by the server and allows devices to identify which specific client sent the command.
242
+ * Additional fields depend on the specific command (see individual command documentation below).
125
243
 
126
244
  **Note**: Actions do not require targeting information - responses are automatically routed using the client session management system.
127
245
 
@@ -4,6 +4,7 @@ import asyncio
4
4
  import logging
5
5
  from abc import ABC, abstractmethod
6
6
  from typing import Any, Dict, Optional, TYPE_CHECKING
7
+ from portacode.utils.ntp_clock import ntp_clock
7
8
 
8
9
  if TYPE_CHECKING:
9
10
  from ..multiplex import Channel
@@ -42,35 +43,45 @@ class BaseHandler(ABC):
42
43
 
43
44
  async def send_response(self, payload: Dict[str, Any], reply_channel: Optional[str] = None, project_id: str = None) -> None:
44
45
  """Send a response back to the gateway with client session awareness.
45
-
46
+
46
47
  Args:
47
48
  payload: Response payload
48
49
  reply_channel: Optional reply channel for backward compatibility
49
50
  project_id: Optional project filter for targeting specific sessions
50
51
  """
52
+ # Add device_send timestamp if trace present
53
+ if "trace" in payload and "request_id" in payload:
54
+ device_send_time = ntp_clock.now_ms()
55
+ if device_send_time is not None:
56
+ payload["trace"]["device_send"] = device_send_time
57
+ # Update ping to show total time from client_send
58
+ if "client_send" in payload["trace"]:
59
+ payload["trace"]["ping"] = device_send_time - payload["trace"]["client_send"]
60
+ logger.info(f"📤 Device sending traced response: {payload['request_id']}")
61
+
51
62
  # Get client session manager from context
52
63
  client_session_manager = self.context.get("client_session_manager")
53
-
64
+
54
65
  if client_session_manager and client_session_manager.has_interested_clients():
55
66
  # Get target sessions
56
67
  target_sessions = client_session_manager.get_target_sessions(project_id)
57
68
  if not target_sessions:
58
69
  logger.debug("handler: No target sessions found, skipping response send")
59
70
  return
60
-
71
+
61
72
  # Add session targeting information
62
73
  enhanced_payload = dict(payload)
63
74
  enhanced_payload["client_sessions"] = target_sessions
64
-
75
+
65
76
  # Add backward compatibility reply_channel (first session if not provided)
66
77
  if not reply_channel:
67
78
  reply_channel = client_session_manager.get_reply_channel_for_compatibility()
68
79
  if reply_channel:
69
80
  enhanced_payload["reply_channel"] = reply_channel
70
-
71
- logger.debug("handler: Sending response to %d client sessions: %s",
81
+
82
+ logger.debug("handler: Sending response to %d client sessions: %s",
72
83
  len(target_sessions), target_sessions)
73
-
84
+
74
85
  await self.control_channel.send(enhanced_payload)
75
86
  else:
76
87
  # Fallback to original behavior if no client session manager or no clients
@@ -107,18 +118,43 @@ class AsyncHandler(BaseHandler):
107
118
 
108
119
  async def handle(self, message: Dict[str, Any], reply_channel: Optional[str] = None) -> None:
109
120
  """Handle the command by executing it and sending the response."""
110
- logger.info("handler: Processing command %s with reply_channel=%s",
121
+ logger.info("handler: Processing command %s with reply_channel=%s",
111
122
  self.command_name, reply_channel)
112
-
123
+
124
+ # Add handler_dispatch timestamp if trace present
125
+ if "trace" in message and "request_id" in message:
126
+ handler_dispatch_time = ntp_clock.now_ms()
127
+ if handler_dispatch_time is not None:
128
+ message["trace"]["handler_dispatch"] = handler_dispatch_time
129
+ # Update ping to show total time from client_send
130
+ if "client_send" in message["trace"]:
131
+ message["trace"]["ping"] = handler_dispatch_time - message["trace"]["client_send"]
132
+ logger.info(f"🔧 Handler dispatching: {message['request_id']} ({self.command_name})")
133
+
113
134
  try:
114
135
  response = await self.execute(message)
115
136
  logger.info("handler: Command %s executed successfully", self.command_name)
116
-
137
+
117
138
  # Handle cases where execute() sends responses directly and returns None
118
139
  if response is not None:
140
+ # Automatically copy request_id if present in the incoming message
141
+ if "request_id" in message and "request_id" not in response:
142
+ response["request_id"] = message["request_id"]
143
+
144
+ # Pass through trace from request to response (add to existing trace, don't create new one)
145
+ if "trace" in message and "request_id" in message:
146
+ response["trace"] = dict(message["trace"])
147
+ handler_complete_time = ntp_clock.now_ms()
148
+ if handler_complete_time is not None:
149
+ response["trace"]["handler_complete"] = handler_complete_time
150
+ # Update ping to show total time from client_send
151
+ if "client_send" in response["trace"]:
152
+ response["trace"]["ping"] = handler_complete_time - response["trace"]["client_send"]
153
+ logger.info(f"✅ Handler completed: {message['request_id']} ({self.command_name})")
154
+
119
155
  # Extract project_id from response for session targeting
120
156
  project_id = response.get("project_id")
121
- logger.info("handler: %s response project_id=%s, response=%s",
157
+ logger.info("handler: %s response project_id=%s, response=%s",
122
158
  self.command_name, project_id, response)
123
159
  await self.send_response(response, reply_channel, project_id)
124
160
  else:
@@ -147,10 +183,32 @@ class SyncHandler(BaseHandler):
147
183
 
148
184
  async def handle(self, message: Dict[str, Any], reply_channel: Optional[str] = None) -> None:
149
185
  """Handle the command by executing it in an executor and sending the response."""
186
+ # Add handler_dispatch timestamp if trace present
187
+ if "trace" in message and "request_id" in message:
188
+ handler_dispatch_time = ntp_clock.now_ms()
189
+ if handler_dispatch_time is not None:
190
+ message["trace"]["handler_dispatch"] = handler_dispatch_time
191
+ # Update ping to show total time from client_send
192
+ if "client_send" in message["trace"]:
193
+ message["trace"]["ping"] = handler_dispatch_time - message["trace"]["client_send"]
194
+ logger.info(f"🔧 Handler dispatching: {message['request_id']} ({self.command_name})")
195
+
150
196
  try:
151
197
  loop = asyncio.get_running_loop()
152
198
  response = await loop.run_in_executor(None, self.execute, message)
153
-
199
+
200
+ # Automatically copy request_id if present in the incoming message
201
+ if "request_id" in message and "request_id" not in response:
202
+ response["request_id"] = message["request_id"]
203
+
204
+ # Pass through trace from request to response (add to existing trace, don't create new one)
205
+ if "trace" in message and "request_id" in message:
206
+ response["trace"] = dict(message["trace"])
207
+ handler_complete_time = ntp_clock.now_ms()
208
+ if handler_complete_time is not None:
209
+ response["trace"]["handler_complete"] = handler_complete_time
210
+ logger.info(f"✅ Handler completed: {message['request_id']} ({self.command_name})")
211
+
154
212
  # Extract project_id from response for session targeting
155
213
  project_id = response.get("project_id")
156
214
  await self.send_response(response, reply_channel, project_id)
@@ -382,22 +382,18 @@ class ContentRequestHandler(AsyncHandler):
382
382
  async def execute(self, message: Dict[str, Any]) -> None:
383
383
  """Return content by hash if available, chunked for large content."""
384
384
  content_hash = message.get("content_hash")
385
- request_id = message.get("request_id")
386
385
  source_client_session = message.get("source_client_session")
387
-
386
+
388
387
  if not content_hash:
389
388
  raise ValueError("content_hash parameter is required")
390
- if not request_id:
391
- raise ValueError("request_id parameter is required")
392
-
389
+
393
390
  # Check if content is in cache
394
391
  content = _content_cache.get(content_hash)
395
-
392
+
396
393
  if content is not None:
397
- # Create base response
394
+ # Create base response (request_id will be added automatically by base class)
398
395
  base_response = {
399
396
  "event": "content_response",
400
- "request_id": request_id,
401
397
  "content_hash": content_hash,
402
398
  "success": True,
403
399
  }
@@ -411,10 +407,9 @@ class ContentRequestHandler(AsyncHandler):
411
407
 
412
408
  logger.info(f"Sent content response in {len(responses)} chunk(s) for hash: {content_hash[:16]}...")
413
409
  else:
414
- # Content not found in cache
410
+ # Content not found in cache (request_id will be added automatically by base class)
415
411
  response = {
416
412
  "event": "content_response",
417
- "request_id": request_id,
418
413
  "content_hash": content_hash,
419
414
  "content": None,
420
415
  "success": False,
@@ -683,9 +683,8 @@ class ProjectStateDiffContentHandler(AsyncHandler):
683
683
  from_hash = message.get("from_hash")
684
684
  to_hash = message.get("to_hash")
685
685
  content_type = message.get("content_type") # 'original', 'modified', 'html_diff'
686
- request_id = message.get("request_id")
687
686
  source_client_session = message.get("source_client_session")
688
-
687
+
689
688
  # Validate required fields
690
689
  if not server_project_id:
691
690
  raise ValueError("project_id is required")
@@ -697,8 +696,6 @@ class ProjectStateDiffContentHandler(AsyncHandler):
697
696
  raise ValueError("to_ref is required")
698
697
  if not content_type:
699
698
  raise ValueError("content_type is required")
700
- if not request_id:
701
- raise ValueError("request_id is required")
702
699
  if not source_client_session:
703
700
  raise ValueError("source_client_session is required")
704
701
 
@@ -816,9 +813,12 @@ class ProjectStateDiffContentHandler(AsyncHandler):
816
813
  "from_ref": from_ref,
817
814
  "to_ref": to_ref,
818
815
  "content_type": content_type,
819
- "request_id": request_id,
820
816
  "success": success
821
817
  }
818
+
819
+ # Add request_id if present in original message
820
+ if "request_id" in message:
821
+ base_response["request_id"] = message["request_id"]
822
822
 
823
823
  if from_hash:
824
824
  base_response["from_hash"] = from_hash
@@ -850,9 +850,12 @@ class ProjectStateDiffContentHandler(AsyncHandler):
850
850
  "from_ref": from_ref,
851
851
  "to_ref": to_ref,
852
852
  "content_type": content_type,
853
- "request_id": request_id,
854
853
  "success": False,
855
854
  "error": str(e),
856
855
  "chunked": False
857
856
  }
857
+
858
+ # Add request_id if present in original message
859
+ if "request_id" in message:
860
+ error_response["request_id"] = message["request_id"]
858
861
  await self.send_response(error_response, project_id=server_project_id)
@@ -2,6 +2,7 @@
2
2
 
3
3
  import logging
4
4
  from typing import Dict, Type, Any, Optional, List, TYPE_CHECKING
5
+ from portacode.utils.ntp_clock import ntp_clock
5
6
 
6
7
  if TYPE_CHECKING:
7
8
  from ..multiplex import Channel
@@ -72,22 +73,32 @@ class CommandRegistry:
72
73
 
73
74
  async def dispatch(self, command_name: str, message: Dict[str, Any], reply_channel: Optional[str] = None) -> bool:
74
75
  """Dispatch a command to its handler.
75
-
76
+
76
77
  Args:
77
78
  command_name: The command name
78
79
  message: The command message
79
80
  reply_channel: Optional reply channel
80
-
81
+
81
82
  Returns:
82
83
  True if handler was found and executed, False otherwise
83
84
  """
84
85
  logger.info("registry: Dispatching command '%s' with reply_channel=%s", command_name, reply_channel)
85
-
86
+
87
+ # Add device_receive timestamp if trace present
88
+ if "trace" in message and "request_id" in message:
89
+ device_receive_time = ntp_clock.now_ms()
90
+ if device_receive_time is not None:
91
+ message["trace"]["device_receive"] = device_receive_time
92
+ # Update ping to show total time from client_send
93
+ if "client_send" in message["trace"]:
94
+ message["trace"]["ping"] = device_receive_time - message["trace"]["client_send"]
95
+ logger.info(f"📨 Device received traced message: {message['request_id']}")
96
+
86
97
  handler = self.get_handler(command_name)
87
98
  if handler is None:
88
99
  logger.warning("registry: No handler found for command: %s", command_name)
89
100
  return False
90
-
101
+
91
102
  try:
92
103
  await handler.handle(message, reply_channel)
93
104
  logger.info("registry: Successfully dispatched command '%s'", command_name)
@@ -0,0 +1,63 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>NTP Clock Test</title>
5
+ <style>
6
+ body {
7
+ font-family: monospace;
8
+ padding: 20px;
9
+ background: #1e1e1e;
10
+ color: #d4d4d4;
11
+ }
12
+ h1 {
13
+ color: #4ec9b0;
14
+ }
15
+ #status {
16
+ background: #252526;
17
+ padding: 15px;
18
+ border-radius: 5px;
19
+ border: 1px solid #3e3e42;
20
+ }
21
+ .synced {
22
+ color: #4ec9b0;
23
+ }
24
+ .not-synced {
25
+ color: #f48771;
26
+ }
27
+ .label {
28
+ color: #9cdcfe;
29
+ font-weight: bold;
30
+ }
31
+ </style>
32
+ </head>
33
+ <body>
34
+ <h1>NTP Clock Test - time.cloudflare.com</h1>
35
+ <div id="status"></div>
36
+ <script type="module">
37
+ import ntpClock from './utils/ntp-clock.js';
38
+
39
+ function updateDisplay() {
40
+ const status = ntpClock.getStatus();
41
+ const syncClass = status.isSynced ? 'synced' : 'not-synced';
42
+
43
+ document.getElementById('status').innerHTML = `
44
+ <p><span class="label">Sync Status:</span> <span class="${syncClass}">${status.isSynced ? '✅ SYNCED' : '❌ NOT SYNCED'}</span></p>
45
+ <p><span class="label">NTP Server:</span> ${status.server}</p>
46
+ <p><span class="label">NTP Time:</span> ${ntpClock.nowISO() || 'null (not synced)'}</p>
47
+ <p><span class="label">Local Time:</span> ${new Date().toISOString()}</p>
48
+ <p><span class="label">Offset:</span> ${status.offset !== null ? status.offset.toFixed(2) + 'ms' : 'null'}</p>
49
+ <p><span class="label">Last Sync:</span> ${status.lastSync || 'Never'}</p>
50
+ <p><span class="label">Time Since Sync:</span> ${status.timeSinceSync ? (status.timeSinceSync / 1000).toFixed(0) + 's' : 'N/A'}</p>
51
+ `;
52
+ }
53
+
54
+ // Update display every 100ms
55
+ setInterval(updateDisplay, 100);
56
+
57
+ // Log status to console every 5 seconds
58
+ setInterval(() => {
59
+ console.log('NTP Clock Status:', ntpClock.getStatus());
60
+ }, 5000);
61
+ </script>
62
+ </body>
63
+ </html>