@allansantos-dev/smart-tool 0.9.48 → 0.9.50

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.50 - beta
4
+
5
+ - Windows refused the setup-audit toast of a project whose path made the toast tag longer than 64 characters
6
+ (`ToastNotification.Tag` limit since the Creators Update); before 0.9.49 that refusal became a second notification
7
+ "Could not show a Smart Tool notice". `toast_notice.show` now fits a longer tag to 64 characters (its start plus a hash
8
+ of the whole, so each project still replaces its own toast), and each notice in `_show_notices` is shown on its own: a
9
+ refused one goes to `tray.log` and the next ones are still shown. The toast script no longer writes PowerShell's
10
+ progress records, so a refusal in the log reads as the error itself (`tests/test_tray_notices.py`).
11
+
12
+ ## 0.9.49 - beta
13
+
14
+ - No more "Could not show a Smart Tool notice: [WinError 10061]" right after logon. The tray's notice loop asked the
15
+ daemon at once, using the address of the previous run from the registry, before the daemon was listening, and turned the
16
+ refused connection into a notification. Now a daemon that is not accepting connections yet (or no address yet) is asked
17
+ again every 15 s without showing anything; any other failure is written to `tray.log` in the data folder, once per
18
+ message, never shown as another notification. The same boot ordering applied to the update check: with no network yet
19
+ at logon it waited 24 h for the next try; it now retries every 5 min until npm answers (`tests/test_tray_notices.py`).
20
+
3
21
  ## 0.9.48 - beta
4
22
 
5
23
  - Smart Tool spawns far fewer Git processes. A Git view (`index_views.describe`, `pin`) is now resolved once per
package/README.md CHANGED
@@ -17,7 +17,7 @@ registered as the `playwright` server where this machine lets a browser be drive
17
17
  An optional hook routes the agent's native Grep/Glob/Read/Bash/WebSearch/WebFetch calls to these tools when they
18
18
  are cheaper, or just tells the agent what Smart Tool would do.
19
19
 
20
- **Status:** 0.9.48 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
20
+ **Status:** 0.9.50 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
21
21
 
22
22
  ## How it works
23
23
 
@@ -864,7 +864,6 @@
864
864
  "Could not open the projects: {error}": "Não foi possível abrir os projetos: {error}",
865
865
  "Could not select the folder: {error}": "Não foi possível selecionar a pasta: {error}",
866
866
  "Failed to change automatic start: {error}": "Não foi possível mudar a inicialização automática: {error}",
867
- "Could not show a Smart Tool notice: {error}": "Não foi possível mostrar um aviso do Smart Tool: {error}",
868
867
  "Could not save the update check: {error}": "Não foi possível salvar a verificação de atualização: {error}",
869
868
  "Automatic update skipped: {error}": "Atualização automática ignorada: {error}",
870
869
  "Smart Tool {version} is available: use \"Update to {version}\" in this menu.": "O Smart Tool {version} está disponível: use \"Atualizar para {version}\" neste menu.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allansantos-dev/smart-tool",
3
- "version": "0.9.48",
3
+ "version": "0.9.50",
4
4
  "description": "Local MCP server that gives coding agents (Claude Code, Codex) cheaper, sharper tools than their built-in search. Windows.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Allan Santos",
package/toast_notice.py CHANGED
@@ -7,6 +7,7 @@ only HKCU keys (no admin): one AppUserModelId key (name and icon of the toast) a
7
7
  write the config file, never state held by the tray.
8
8
  """
9
9
  import base64
10
+ import hashlib
10
11
  import os
11
12
  import subprocess
12
13
  import sys
@@ -15,10 +16,12 @@ from xml.sax.saxutils import quoteattr, escape
15
16
 
16
17
  APP_ID = "SmartTool.Notifications"
17
18
  PROTOCOL = "smart-tool-action"
19
+ TAG_MAX = 64
18
20
  ACTION_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "notice_action.py")
19
21
 
20
22
  _SHOW_SCRIPT = r"""
21
23
  $ErrorActionPreference = 'Stop'
24
+ $ProgressPreference = 'SilentlyContinue'
22
25
  [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
23
26
  [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
24
27
  $xml = New-Object Windows.Data.Xml.Dom.XmlDocument
@@ -84,6 +87,15 @@ def toast_xml(title, lines, buttons):
84
87
  + (f'<actions>{actions}</actions>' if actions else '') + '</toast>')
85
88
 
86
89
 
90
+ def _fit_tag(tag):
91
+ """Windows refuses a toast whose Tag is longer than 64 characters. A longer tag (one built from a project path) keeps
92
+ its start and ends in a hash of the whole, so each project still replaces its own toast."""
93
+ if len(tag) <= TAG_MAX:
94
+ return tag
95
+ digest = hashlib.sha256(tag.encode("utf-8")).hexdigest()[:24]
96
+ return tag[:TAG_MAX - len(digest) - 1] + "~" + digest
97
+
98
+
87
99
  def show(title, lines, buttons, tag=None):
88
100
  """Shows the toast; raises RuntimeError with PowerShell's message when Windows refuses it."""
89
101
  if sys.platform != "win32":
@@ -91,7 +103,7 @@ def show(title, lines, buttons, tag=None):
91
103
  register()
92
104
  script = base64.b64encode(_SHOW_SCRIPT.encode("utf-16-le")).decode("ascii")
93
105
  env = {**os.environ, "SMART_TOOL_TOAST_XML": toast_xml(title, lines, buttons),
94
- "SMART_TOOL_TOAST_APPID": APP_ID, "SMART_TOOL_TOAST_TAG": tag or ""}
106
+ "SMART_TOOL_TOAST_APPID": APP_ID, "SMART_TOOL_TOAST_TAG": _fit_tag(tag or "")}
95
107
  done = subprocess.run(
96
108
  ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", script],
97
109
  env=env, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30,
package/tray.py CHANGED
@@ -12,6 +12,7 @@ import os
12
12
  import sys
13
13
  import threading
14
14
  import time
15
+ import urllib.error
15
16
  import urllib.request
16
17
  import webbrowser
17
18
 
@@ -23,6 +24,7 @@ import autostart
23
24
  import config
24
25
  import daemon_launcher
25
26
  import i18n
27
+ import paths
26
28
  import setup_audit
27
29
  import toast_notice
28
30
  import update_check
@@ -31,6 +33,10 @@ import version
31
33
  POLL_INTERVAL_S = 45
32
34
  UPDATE_CHECK_INTERVAL_S = 24 * 3600
33
35
  NOTICE_INTERVAL_S = 600
36
+ NOTICE_RETRY_S = 15
37
+ UPDATE_RETRY_S = 300
38
+ NOTICE_UNREACHABLE_LOG_S = 600
39
+ LOG_PATH = os.path.join(paths.DATA_DIR, "tray.log")
34
40
  SETUP_URL = "http://127.0.0.1:8765/setup"
35
41
 
36
42
  _STATE_LOCK = threading.Lock()
@@ -139,6 +145,14 @@ def _poll_loop(icon):
139
145
  time.sleep(POLL_INTERVAL_S)
140
146
 
141
147
 
148
+ def _toast(title, lines, buttons, tag):
149
+ """One notice: a toast Windows refuses goes to `tray.log` and does not keep the next notices from being shown."""
150
+ try:
151
+ toast_notice.show(title, lines, buttons, tag=tag)
152
+ except Exception as exc:
153
+ _log(f"notice {tag}: {type(exc).__name__}: {exc}")
154
+
155
+
142
156
  def _show_notices(icon, notices):
143
157
  """Shows a toast for each pending notice: the new-default-models offer, each model over the failure limit and each
144
158
  project whose scheduled setup audit found new errors or warnings."""
@@ -146,41 +160,74 @@ def _show_notices(icon, notices):
146
160
  if offer:
147
161
  lines = [f"{role}: {change['current']} -> {change['new']}" for role, change in offer["changes"].items()]
148
162
  nonce = offer["nonce"]
149
- toast_notice.show(i18n.t("Smart Tool has new recommended models"), lines, [
163
+ _toast(i18n.t("Smart Tool has new recommended models"), lines, [
150
164
  (i18n.t("Apply now"), toast_notice.action_uri("models-apply", n=nonce)),
151
165
  (i18n.t("Don't show again"), toast_notice.action_uri("models-decline", n=nonce)),
152
- ], tag="models-upgrade")
166
+ ], "models-upgrade")
153
167
  for row in notices.get("failing") or []:
154
168
  last = row.get("last_error") or i18n.t("see the failure log in the settings")
155
- toast_notice.show(
169
+ _toast(
156
170
  i18n.t("{model} is failing", model=row["model"]),
157
171
  [i18n.t("{errors} of {calls} calls failed in 24 h as {role}.", errors=row["errors"], calls=row["calls"],
158
172
  role=row["role"]), last[:160]],
159
173
  [(i18n.t("Switch model"), toast_notice.action_uri("open-setup", section="models")),
160
174
  (i18n.t("Mute 7 days"), toast_notice.action_uri("mute-model", model=row["model"]))],
161
- tag="model-failing:" + row["model"])
175
+ "model-failing:" + row["model"])
162
176
  for row in notices.get("audit") or []:
163
177
  title, lines = setup_audit.toast_text(row)
164
- toast_notice.show(title, lines, [(i18n.t("Open the audit"), toast_notice.action_uri("open-setup", section="audit"))],
165
- tag="setup-audit:" + row["project"])
178
+ _toast(title, lines, [(i18n.t("Open the audit"), toast_notice.action_uri("open-setup", section="audit"))],
179
+ "setup-audit:" + row["project"])
180
+
181
+
182
+ def _log(text):
183
+ """Appends a line to `tray.log` in the data folder: what the tray cannot tell with a notification (a notice that could
184
+ not be fetched or shown) is kept where the user can read it, never turned into another notification."""
185
+ try:
186
+ os.makedirs(os.path.dirname(LOG_PATH), exist_ok=True)
187
+ with open(LOG_PATH, "a", encoding="utf-8") as log:
188
+ log.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} {text}\n")
189
+ except OSError:
190
+ pass # no console and no other channel here; a full disk must not kill the notice thread
191
+
192
+
193
+ def _daemon_not_ready(exc):
194
+ """The daemon is not accepting connections yet (refused, reset or no answer in time), as right after boot, when the
195
+ registry still holds the address of the previous run. An HTTP answer, even an error, is not that."""
196
+ if isinstance(exc, urllib.error.HTTPError):
197
+ return False
198
+ reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc
199
+ return isinstance(reason, (ConnectionError, TimeoutError))
166
200
 
167
201
 
168
202
  def _notice_loop(icon):
169
203
  """Asks the daemon every 10 minutes whether a toast is due. The daemon decides (once a day per notice) and marks it
170
- announced, so a restart of the tray never repeats one."""
204
+ announced, so a restart of the tray never repeats one. While the daemon is still starting the question is asked again
205
+ every few seconds and nothing is shown: the tray icon already says "starting". Any other failure goes to `tray.log`."""
206
+ waiting_since = None
171
207
  while True:
208
+ delay = NOTICE_INTERVAL_S
172
209
  try:
173
210
  daemon_url = (daemon_launcher.read_registry() or {}).get("url")
174
211
  if daemon_url:
175
212
  request = urllib.request.Request(daemon_url.rstrip("/") + "/setup/notices", data=b"{}", method="POST",
176
213
  headers={"Content-Type": "application/json"})
177
214
  with urllib.request.urlopen(request, timeout=60) as response:
178
- _show_notices(icon, json.load(response))
215
+ notices = json.load(response)
216
+ waiting_since = None
217
+ _show_notices(icon, notices)
218
+ else:
219
+ delay = NOTICE_RETRY_S
179
220
  except Exception as exc:
180
- if str(exc) != _state.get("notice_error"):
221
+ if _daemon_not_ready(exc):
222
+ delay = NOTICE_RETRY_S
223
+ waiting_since = waiting_since if waiting_since is not None else time.monotonic()
224
+ if time.monotonic() - waiting_since >= NOTICE_UNREACHABLE_LOG_S and not _state.get("notice_unreachable"):
225
+ _state["notice_unreachable"] = True
226
+ _log(f"notices: the daemon has not answered for {NOTICE_UNREACHABLE_LOG_S // 60} min: {exc}")
227
+ elif str(exc) != _state.get("notice_error"):
181
228
  _state["notice_error"] = str(exc)
182
- _notify(icon, "Could not show a Smart Tool notice: {error}", error=exc)
183
- time.sleep(NOTICE_INTERVAL_S)
229
+ _log(f"notices: could not fetch or show them: {type(exc).__name__}: {exc}")
230
+ time.sleep(delay)
184
231
 
185
232
 
186
233
  def _announce_start(icon):
@@ -197,17 +244,20 @@ def _announce_start(icon):
197
244
 
198
245
 
199
246
  def _update_loop(icon):
200
- """Checks npm at start and every 24 h. A newer version is installed right away when automatic updates are on (once
247
+ """Checks npm at start and every 24 h (every 5 min while npm cannot be reached, as when the network is not up yet right
248
+ after boot; nothing is shown for that). A newer version is installed right away when automatic updates are on (once
201
249
  per version, again 24 h after a failed try); otherwise the user is told and the menu offers it."""
202
250
  try:
203
251
  _announce_start(icon)
204
252
  except Exception as exc:
205
253
  _notify(icon, "Could not read the update state: {error}", error=exc)
206
254
  while True:
255
+ unreachable = False
207
256
  try:
208
257
  latest = update_check.newer_version()
209
258
  except Exception:
210
259
  latest = None
260
+ unreachable = True
211
261
  else:
212
262
  try:
213
263
  update_check.record_check(latest)
@@ -228,7 +278,7 @@ def _update_loop(icon):
228
278
  elif not known:
229
279
  _notify(icon, "Smart Tool {version} is available: use \"Update to {version}\" in this menu.",
230
280
  version=latest)
231
- time.sleep(UPDATE_CHECK_INTERVAL_S)
281
+ time.sleep(UPDATE_RETRY_S if unreachable else UPDATE_CHECK_INTERVAL_S)
232
282
 
233
283
 
234
284
  def _update_label(item):
package/version.py CHANGED
@@ -1,7 +1,7 @@
1
1
  """Single source of the Smart Tool version and of the User-Agent sent to public APIs."""
2
2
  import re
3
3
 
4
- VERSION = "0.9.48"
4
+ VERSION = "0.9.50"
5
5
  _CONTACT_RE = re.compile(r"^(?:[^\s@()<>;]+@[^\s@()<>;]+\.[^\s@()<>;]+|https?://[^\s()<>;]+)$")
6
6
 
7
7