Long-Running AI Agents: Tunnel Failure Recovery
Keep local AI agents reachable with tunnel monitoring, connectivity webhooks, checkpointing, idempotent callbacks, and restart-safe recovery.
In this article 11 sections
Design local AI agent workflows that detect lost reachability, resume safely, and never duplicate work
A public endpoint is only one part of running an AI agent for hours. The agent process, its durable state, the Localtonet client, the device's AuthToken, and the tunnel must all stay healthy, and callers must handle short disconnections safely. This guide separates network availability from application correctness and shows how to monitor both. It covers checkpointing, idempotent callbacks, and the documented setup of an HTTP tunnel and its timeout limit. It also explains how our Token and Tunnel webhooks deliver events, how to create and verify them, and the access controls that protect an endpoint left online for a long time.
📋 What's in this guide
Why long-running AI agents need more than a public endpoint

A short request can often be retried from the beginning. A long-running agent workflow is different. It may research a topic, call tools, update records, wait for approvals, receive callbacks, generate artifacts, and revise its output over several hours. Restarting that whole sequence after a brief connectivity interruption wastes time and can repeat actions that should happen only once.
Reliable operation therefore needs several independent capabilities. The agent must keep task state outside process memory. Its tools and callback handlers must tolerate retries. The local service must expose a meaningful health signal. The tunnel must be running on a connected device. Monitoring must tell an unreachable public endpoint apart from an application that is reachable but unhealthy.
With Localtonet, the client application on your device opens an outbound connection to one of our relay servers. That lets you expose a service running on the device, or another service reachable from it, without inbound router port forwarding, firewall changes, VPN setup, or a public IP address. For an HTTP tunnel, the result is a public HTTPS address with a certificate we provide and renew.
Connectivity does not make application state durable. A tunnel carries traffic to a local target. It does not checkpoint an agent, preserve a model conversation, commit a database transaction, or decide whether a callback has already been processed. Those responsibilities stay in the agent application and its operational design.
Creating a Localtonet tunnel does not start it. You start it with the start button in the Actions column, and it carries traffic only while the Localtonet app for its AuthToken is connected and the tunnel is running. If the local agent process stops while the tunnel stays connected, the public address still answers at the network level even though the application cannot complete requests.
Availability is a chain, not a single status
Treat the public endpoint as the end of a dependency chain. A caller reaches the public address, traffic crosses the running tunnel, the Localtonet app forwards it to the configured local IP address and port, the local service accepts the request, and the agent loads the relevant durable state. Success at one layer does not imply success at the next.
A tunnel can be Connected while the agent process is stopped. The process can be running while its database is unavailable. The health endpoint can answer while the task queue is stalled. A callback can return a success status while a deduplication bug applies the same action twice. Operations become much clearer when each layer has its own signal.
Separate agent failures from connectivity failures

Recovery begins with classification. If every problem is reported as “the agent is down,” operators cannot choose the right response. A process crash needs a service restart and a checkpoint resume. A disconnected AuthToken needs the Localtonet app or the device's outbound connectivity restored. A callback timeout needs a safe retry, not an agent restart. A tunnel stopped by its own expiration date needs a configuration change, not debugging of the agent.
| Failure domain | Typical observation | What it does not prove | First response |
|---|---|---|---|
| Local agent process | The local health request fails even when tested directly on the host | That the tunnel or relay path failed | Inspect the process, dependencies, logs, and last durable checkpoint |
| Application dependency | The process answers, but readiness reports a database, queue, tool, or model failure | That public routing is unavailable | Restore the dependency and leave completed task steps intact |
| Local target configuration | The tunnel runs, but requests cannot reach the configured local IP address and port | That the device is disconnected | Check the listening address, port, and whether the service uses HTTPS locally (Is SslStream?) |
| Localtonet app or device | A Token webhook reports Disconnected | Whether the cause is power, the app, internet access, or another local condition | Restore the device and app connection, then recheck tunnel and application state |
| Tunnel lifecycle | A Tunnel webhook reports Disconnected, or the tunnel shows as not running | That the local agent lost its task state | Check the Activity Log, the expiration date and bandwidth limits, then start the tunnel |
| Request timeout at the tunnel | A long synchronous request fails while the agent is still working | That the agent crashed or the tunnel dropped | Compare the request duration with the tunnel's HTTP Timeout and move long work to async jobs |
| Callback delivery | The sender times out or receives an error while the agent may still have processed the request | That the operation was never applied | Query by operation or idempotency key before retrying a side effect |
| Agent logic | The endpoint is reachable, but the workflow loops, stalls, or produces an invalid result | A network failure | Stop unsafe progression, inspect checkpoints and validation results, then resume from a known state |
Build a small but meaningful health model
A health URL that always returns success is not enough. At minimum, distinguish liveness from readiness. Liveness answers whether the process can respond. Readiness answers whether it can currently do the work the endpoint represents. A long-running worker can be alive but not ready because its state store, task queue, model provider, or a required tool is unavailable.
Do not make every optional dependency a reason to report total failure. Decide which dependencies are essential for accepting new work, which affect only certain task types, and which can degrade temporarily. The health response must stay fast and must never start expensive agent work.
Keep health checks separate from task status. “Service is ready” and “task 47 completed step 8” answer different questions. A status request should identify one task and report a durable state such as queued, running, waiting for approval, retry scheduled, completed, failed, or cancelled. Choose vocabulary that fits your implementation and define the allowed transitions before deployment.
A timeout is an ambiguous result. The request may have reached the agent and committed its side effect before the response was lost. Check the operation record or idempotency key first. Blindly restarting or resubmitting can duplicate tool calls, notifications, payments, file writes, or other irreversible actions.
Design the agent to survive process and network interruptions

Tunnel recovery is safest when the application already treats interruptions as normal events. The core principle is to make progress durable at boundaries where replay is safe. Never rely on an in-memory conversation, an open HTTP connection, or a single callback response as the only record of progress.
Give every run and operation a stable identity
Assign a durable task identifier when work is accepted. Within the task, give each retryable operation its own stable identifier. Store the request, its state, its constraints, and the result or error of each completed operation. A recovery process should be able to answer three questions without memory: what was requested, what has definitely completed, and what is safe to do next.
Stable identities also help support and monitoring. A request log entry, a local process log, a callback record, and a checkpoint can all refer to the same task identifier without exposing credentials. Keep sensitive prompts, tokens, and private user data out of identifiers, because identifiers end up in logs and metrics.
Checkpoint verified milestones
A checkpoint should mark a meaningful, durable boundary rather than a periodic memory dump. Good examples include completing a research phase, validating an artifact, committing a tool result, receiving human approval, or finishing a task-graph node whose output passed its acceptance check.
Store enough to resume deterministically: the task version, completed node identifiers, output locations, decision records, pending approvals, retry counts, known errors, and the next eligible operation. Write the checkpoint before acknowledging completion to an external caller whenever that acknowledgement would make the caller discard its own retry state.
Checkpoint frequency is a tradeoff. Sparse checkpoints increase replay after a crash. Very frequent writes add cost without creating useful recovery points. Base checkpoints on verified state transitions and on the cost or risk of repeating the preceding work.
Make callbacks idempotent
Network clients retry because they cannot always tell “not received” from “processed but response lost.” An idempotent handler accepts an operation key that stays the same across retries and records it durably before or as part of applying the side effect. If the same request arrives again, it returns the recorded outcome instead of acting again.
Idempotency must cover concurrent duplicates as well as sequential retries. Two copies can arrive almost together after a reconnect. Use a uniqueness constraint, a transaction, a compare-and-set operation, or another atomic mechanism in your state store. A check followed by an unprotected insert can still race.
Decide how conflicting reuse is handled. If the same key arrives with a materially different payload, reject it or flag it for review rather than treating it as the original. Keep deduplication records at least as long as senders may retry.
Bound retries and preserve evidence
Retries need a limit, increasing delays, and a terminal outcome. A permanent authorization error should not be retried like a transient disconnection. Persist the last error and the retry count so a restart does not reset an exhausted operation into an endless loop. For high-impact actions, route repeated ambiguity to a recovery queue or a human approval step.
Use a reconciliation pass after connectivity returns
Reconnection should trigger verification, not immediate replay of everything marked incomplete. Reconcile local state with every external system involved. Confirm whether an ambiguous operation was committed, whether a callback is still expected, whether the task was cancelled while offline, and whether credentials and approvals are still valid.
Sort work into three groups: definitely complete, definitely not started, and ambiguous. Resume incomplete work from its checkpoint, leave completed work untouched, and route ambiguous side effects through a status query, deduplication lookup, or human review.
Expose the agent API with a Localtonet HTTP tunnel
Verify the agent locally before adding remote access. Confirm that it starts with your application's own method, listens on the intended interface and port, reloads its durable state after a restart, and serves the health and task-status routes you plan to monitor. The start command, port, environment variables, and credentials depend on your agent framework, so take them from that application's configuration.
For an HTTP-based agent API or webhook receiver, the HTTP tunnel is the right family: it points at a local IP address and port and gives you a public HTTPS address. For other transports, choose the family that matches the protocol. We also provide TCP, UDP, combined UDP/TCP, and TLS tunnels. Do not pick a raw-port tunnel for an HTTP API just because both use a port.
Before you start
- The Localtonet client is installed on the device and connected with an AuthToken. If it is not, follow the Quick start in our documentation first.
- Your agent service is running and you know its port, for example
3000. - For a Custom subdomain or a Custom domain, your account needs balance.
- For a Custom domain, you also need a domain that you have added in DNS Manager.
Create and start the tunnel
Open the HTTP page
In the dashboard, open My Tunnels › HTTP and select Create HTTP Tunnel to open the form.
Choose the URL type
Random subdomain gives a generated name on the selected domain, such as https://<RANDOM_NAME>.localto.net, and needs nothing extra. Custom subdomain uses the name you type in Subdomain (letters, digits and hyphens) and needs balance. Custom domain uses a domain of your own and needs balance plus a domain in DNS Manager.
Choose the device and the region
In Device token, select the token used by the Localtonet app on the device running the agent. In Server region, choose a region close to that device for lower latency.
Enter the local address and create the tunnel
Set Domain (localto.net or one of your own domains; for Custom domain the list only contains your domains). Fill in Subdomain only for Custom subdomain. Enter the Local IP address of the service (127.0.0.1 for the same device; an IPv4 or IPv6 address or localhost is accepted) and the Local port, from 1 to 65535. Select Create tunnel. It appears under Your tunnels as Tunnel # followed by its ID.
Start the tunnel and open the URL
Select the start button in the Actions column. When the tunnel runs, its address in the URL column becomes a link. Open it, then test your health route and a non-destructive authenticated request from a network outside your own.
If the Localtonet app for the selected token is offline when you press start, a dialog tells you so. You can start the app, or select Start anyway, and the tunnel goes live as soon as the app connects. For a device that reboots or loses connectivity, this means the tunnel is already set to run and comes back with the app instead of waiting for someone to press start again.
Your public address survives restarts
The public address is https:// followed by the host name in the URL column, with no port number. An HTTP tunnel keeps its subdomain until you delete the tunnel. Stopping and starting it does not change the address. This matters for recovery: callers, webhook senders, and agent clients that have your URL configured keep working after a tunnel restart without any reconfiguration. Deleting and recreating a tunnel with a Random subdomain, however, gives you a new name, so for anything long-lived prefer stopping over deleting, or use a Custom subdomain or Custom domain.
WebSocket connections pass through an HTTP tunnel, so agents that stream progress over WebSockets can use the same address.
HTTPS, certificates and settings that restart a tunnel
Visitors reach an HTTP tunnel over HTTPS with a certificate we provide and renew. TLS ends at the Localtonet server, and from there the request travels through the tunnel to your device, where the Localtonet app passes it to your service. Your local service can therefore stay on plain HTTP. If your service must present its own certificate end to end, use a TLS tunnel instead. The relevant switches sit under Settings in the Tunnel settings panel:
| Setting | What it does | Recommendation for agent APIs |
|---|---|---|
| Is Only Https? | Serves the public URL over HTTPS only and redirects http:// requests to https://. While off, the address answers on both. |
Turn it on for any agent API that carries credentials, tokens, or private data. |
| Is HTTP/3 Active? | Lets clients reach the public URL over HTTP/3. A new tunnel has it on. | Turn it off only if a client has trouble with HTTP/3. |
| Is SslStream? | Makes the Localtonet app connect to your local service with TLS, accepting the local certificate as it is, so self-signed certificates work. | Turn it on when the agent itself listens on HTTPS, for example https://localhost:5001. |
| Legacy Connect? | Connects the tunnel with the legacy method instead of the normal one. | Try it only if the tunnel cannot connect with the normal method. |
Changing Is SslStream? or Legacy Connect? on a running tunnel restarts it, so the Localtonet app must be connected. Expect a brief interruption, and if a Tunnel webhook is configured, expect Disconnected and Connected events. Make these changes outside critical agent runs.
When the local server expects a specific Host header
Your service receives the host name the visitor used, which is the tunnel address. Some local web servers choose a site by host name and answer with the wrong site or an error. In that case, open Headers in the tunnel settings and add a request header named Host with the value your server expects. Your service then receives that host name instead of the tunnel address.
Exposing an MCP Gateway instead of a plain API
If your agents reach their tools through McpNet Gateway, you do not need a separate gateway install or a manual HTTP tunnel. McpNet Gateway is bundled with the Localtonet client and runs automatically alongside it on port 5050. The bundled gateway never starts in the unauthenticated Dev mode, and you set its admin token in Localtonet's Settings. The MCP Gateway tunnel type forwards to the gateway's /mcp and /dashboard routes with no manual host or port entry.
One recovery nuance matters here. If an upstream MCP server runs through npx, its package downloads on first connect, which can take 60 to 120 seconds. McpNet uses a 120 second per-server timeout, and the tool list fills in on the next background refresh about 60 seconds later. A first tool call that times out right after you start the tunnel is the gateway warming up, not a tunnel failure, so give it one retry before troubleshooting. For production agents, use a fixed subdomain where your plan supports it, because every MCP client configuration hardcodes the server URL. Our MCP Gateway tunnel guide walks through the full setup, and the Localtonet MCP Server guide shows how coding assistants can create, start, and stop tunnels directly.
The full field reference lives in the Localtonet HTTP tunnel documentation, but everything you need to create, start, and secure the tunnel for an agent is covered in this guide.
Long agent requests and the HTTP Timeout setting
The most common mismatch between an AI agent and any HTTP proxy is duration. Our HTTP tunnels have an HTTP Timeout setting that controls how long the server waits for a response from your local application, from 1 to 600 seconds. You find it in the Tunnel settings panel. A request that takes longer than the configured value fails at the edge even if the agent keeps working and eventually finishes.
Raising the timeout helps for requests that take a few minutes. It cannot help for work that runs for an hour, because 600 seconds is the upper bound. More importantly, a held-open HTTP request is a fragile container for long work in any architecture. Client libraries, corporate proxies, mobile networks, and the caller's own infrastructure may close idle connections well before your tunnel does, and a tunnel restart drops any request in flight.
Use accept-then-poll or a callback
Design long agent work as an asynchronous job. The submit request validates the input, persists the task, and returns immediately with a task identifier. The caller then polls a status route, or your agent calls the caller back when the job reaches a terminal state. Each HTTP exchange is short, so the HTTP Timeout only needs to cover your slowest status or submit call, and a tunnel restart costs one failed poll rather than hours of work.
# 1. Submit: returns quickly with a task id (illustrative application API)
curl -X POST "https://<YOUR_SUBDOMAIN>.localto.net/tasks" \
-H "Authorization: Bearer <CALLER_TOKEN>" \
-H "Idempotency-Key: <STABLE_OPERATION_KEY>" \
-H "Content-Type: application/json" \
-d '{"goal":"<TASK_DESCRIPTION>"}'
# => 202 Accepted {"taskId":"<TASK_ID>","state":"queued"}
# 2. Poll: short request, safe to repeat after any interruption
curl "https://<YOUR_SUBDOMAIN>.localto.net/tasks/<TASK_ID>" \
-H "Authorization: Bearer <CALLER_TOKEN>"
# => {"taskId":"<TASK_ID>","state":"running","checkpoint":"research-complete"}
The routes and headers above belong to your application, not to Localtonet. What makes the pattern work is that the submit call is idempotent (the same key returns the same task rather than creating a second one) and the status call is read-only. Poll with a sensible interval and backoff, and treat a failed poll as “unknown,” not “failed.”
If you stream progress over Server-Sent Events or WebSockets, design the client to reconnect and resume from the last event or checkpoint it received. The stream is a convenience for live updates. The durable task record remains the source of truth.
How Localtonet Token and Tunnel webhooks deliver events

Our webhooks make Localtonet call a URL of yours when a device (AuthToken) or a tunnel connects or disconnects. A webhook belongs to a token group. It watches the AuthTokens in that group, the tunnels of those tokens, or both. When a watched token or tunnel changes to Connected or Disconnected, Localtonet sends an HTTP POST with a small JSON body to your URL. You choose whether you want connect events, disconnect events, or both. A Token event means the Localtonet client of that device came online or went offline.
The request format
The method is POST, the content type is application/json; charset=utf-8, and the body is a JSON object with four fields:
| Field | Documented meaning | Operational use |
|---|---|---|
Id |
For Type Token, identifies the AuthToken. For Type Tunnel, the numeric tunnel ID sent as a string, the same ID our API uses as tunnelId. |
Map tunnel events to your agent endpoints and API calls. Treat token values as secrets and redact them. |
ActionDate |
When Localtonet registered the change, in ISO 8601 format with an offset | Parse with a standard ISO 8601 parser and keep the offset. Do not assume a fixed time zone. |
Type |
Token or Tunnel |
Distinguish a device connection change from a tunnel connection change |
Status |
Connected or Disconnected |
Start the matching verification or incident workflow |
A token event looks like this:
{
"Id": "<YOUR_TOKEN>",
"ActionDate": "2026-01-15T10:30:00.1234567+03:00",
"Type": "Token",
"Status": "Disconnected"
}
A tunnel event looks like this:
{
"Id": "<TUNNEL_ID>",
"ActionDate": "2026-01-15T10:31:12.7654321+03:00",
"Type": "Tunnel",
"Status": "Connected"
}
Delivery behavior you must design around
Id, Type, Status, and ActionDate.
Two consequences follow for a long-running agent. First, persist-then-enqueue is essential. The receiver should check the secret, store the event, and return a success status at once, leaving slow health checks to a separate worker. Doing recovery work inside the webhook request makes your endpoint slow, and a slow or failing endpoint loses events permanently. Second, webhooks cannot be your only signal. Because a missed call is never repeated, active probes of the public endpoint and local health must back them up. If the receiver was offline during an incident, the probes are what tell you the current state.
Treat each event as a state-change signal, not a root cause. A Token Disconnected event does not say whether the device lost power, the client stopped, or internet access failed. A Tunnel Connected event does not prove that the agent is ready or that a specific task is progressing.
Recommended event-handling sequence
- Reject any request whose path or query parameter does not contain your long random secret. Compare it in constant time if your platform offers that.
- Parse the JSON body and validate
Id,ActionDate,Type, andStatus. ParseActionDateas ISO 8601 with its offset. - Build the deduplication key from
Id+Type+Status+ActionDateand store the event durably, ignoring an exact duplicate. - Return a success status immediately and enqueue verification work.
- In the worker, update the connectivity view for the device or tunnel. Order observations by the parsed
ActionDate, not by arrival time. - On Disconnected, pause outbound callbacks that cannot succeed and open or update an incident after your chosen debounce period.
- On Connected, verify the public endpoint and local readiness before releasing queued work, then reconcile ambiguous operations.
Correlate events without leaking tokens
When Type is Token, the Id field identifies an AuthToken, so treat the whole body as sensitive. Do not write raw request bodies to broadly accessible logs. Replace the value with a hash or a protected lookup to a device name before it reaches alerts, dashboards, tickets, or chat. Tunnel events are easier: the numeric tunnel ID is the same tunnelId our API uses, so it maps directly to a tunnel you manage. When a webhook arrives and you want to act on that tunnel programmatically, our API is the documented route for doing so.
Token and Tunnel webhooks report Connected and Disconnected changes for a token group and carry no signature. File Server webhooks report file-level upload, delete, rename, and move events and support optional HMAC signing. Do not assume features of one apply to the other.
Create, receive and test a connectivity webhook
Before you start
- A token group that contains the AuthTokens you want to watch. Create groups under My Tokens and add the device tokens of your agent hosts.
- An HTTP or HTTPS endpoint reachable from the internet that accepts a POST request with a JSON body.
localhostand private addresses will not work. - Your own account dashboard. The Webhooks menu item is not shown while you work in a team dashboard.
Open Webhooks
Open Webhooks in the dashboard menu of your own account.
Choose what to be told about
Turn on Token Webhook Enable, Tunnel Webhook Enable, or both. Then turn on Send When Connected, Send When Disconnected, or both. At least one webhook type and at least one notification type are required. For agent recovery, watching both types and both states gives the clearest picture.
Select the Auth Token Group
Choose the token group to watch. This field is required.
Enter the Webhook URL
Enter the address Localtonet should call, including your long random secret as a path segment or query parameter, for example https://<YOUR_HOST>/localtonet/<YOUR_SECRET>. This field is required.
Select Create
The webhook appears in the list below the form, showing Token Webhook, Tunnel Webhook, Group Name, URL, Connected Notify and Disconnected Notify, each as Active or Passive.
A webhook cannot be edited. To change its URL, group, or switches, delete it with the delete button in the Action column and create a new one. This includes rotating the secret in the URL. You can create several webhooks for the same group, for example one URL for connect events and another for disconnect events, which lets a paging system receive only disconnects while a status page receives both.
A minimal receiver with a secret path
Any web framework works. The receiver only has to check the secret, read the JSON body, and answer with a success status. The following Node.js example has no dependencies and is adapted from our documented receiver. It reads the secret from an environment variable, rejects other paths, builds the deduplication key, and hands the event to a placeholder you replace with a durable write and queue.
const http = require('http');
const SECRET = process.env.WEBHOOK_SECRET; // long random value, never commit it
const seen = new Set(); // replace with a durable store with a unique constraint
function persistAndEnqueue(event) {
// Write the event durably, then enqueue verification work.
// Do not run health checks or recovery here.
}
http.createServer((req, res) => {
if (req.method !== 'POST' || req.url !== `/localtonet/${SECRET}`) {
res.writeHead(404);
return res.end();
}
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const event = JSON.parse(body);
const when = new Date(event.ActionDate); // ISO 8601 with offset
const key = [event.Id, event.Type, event.Status, event.ActionDate].join('|');
if (!seen.has(key)) {
seen.add(key);
persistAndEnqueue({ ...event, at: when.toISOString() });
}
res.writeHead(200);
} catch {
res.writeHead(400);
}
res.end();
});
}).listen(8080);
With this receiver, the Webhook URL is https://<YOUR_HOST>/localtonet/<YOUR_SECRET>. In production, keep the in-memory set only as a fast path and enforce uniqueness in durable storage, so a receiver restart does not forget which events it already processed.
Test the webhook end to end
- Put one AuthToken of a test device into the token group of the webhook.
- Start the Localtonet client on that device with the token. If Send When Connected is on, your endpoint receives Type
Token, StatusConnected. - Stop the client with
Ctrl + C. Your endpoint receives StatusDisconnected, possibly a little after the client stops. - If Tunnel Webhook Enable is on, start and stop a tunnel of that token under My Tunnels to get the tunnel events.
You can also test that your URL is reachable and that your receiver parses the body by sending a request yourself:
curl -X POST "<YOUR_WEBHOOK_URL>" \
-H "Content-Type: application/json" \
-d '{"Id":"test","ActionDate":"2026-01-15T10:30:00+00:00","Type":"Token","Status":"Connected"}'
No public endpoint yet? Run the receiver on your computer and publish it with a Localtonet HTTP tunnel on a different AuthToken than the one you are watching. The tunnel's request inspector then shows every webhook call. Using a separate token matters: if the receiver's own device disconnected, it could not receive its own Disconnected event.
Webhook setup errors
| Symptom | Cause | Fix |
|---|---|---|
| “Turn on at least one webhook type.” | Neither Token Webhook Enable nor Tunnel Webhook Enable is on | Turn on at least one of them before selecting Create |
| “Turn on at least one notification type.” | Neither Send When Connected nor Send When Disconnected is on | Turn on at least one of them before selecting Create |
| “Group is required!” | No token group selected | Select a group under Auth Token Group. If the list is empty, create a group under My Tokens and add your tokens. |
| No request arrives | Token not in the group, switches Passive, or URL not reachable from the internet | Check group membership, confirm the switches show Active, avoid localhost and private addresses, and test the URL with curl |
| Token events arrive but no tunnel events | Tunnel Webhook is not Active, or the tunnel belongs to a token outside the group | Recreate the webhook with Tunnel Webhook Enable on, and confirm the tunnel's AuthToken is in the group |
A practical recovery runbook
Write and rehearse the recovery procedure before a multi-hour production run. The runbook should say who or what performs each check, which actions are automatic, which need approval, and when the system must stop rather than guess. This sequence avoids both premature replay and unnecessary full-task restarts.
Record the signal
Persist the webhook event or failed probe result. Redact token values. Correlate it with recent public checks and local telemetry, remembering that a Disconnected event may lag the real loss slightly and that an event may be missing entirely if the receiver was down.
Pause unsafe delivery, not durable progress
Stop sending callbacks or starting externally dependent actions that cannot succeed while the endpoint is unavailable. Do not erase completed milestones or reset the task. Let independent local work continue only if the application is designed for it.
Test the agent locally
On the device, test liveness, readiness, and the configured local IP address and port. If the local check fails, repair the application or dependency first, restart it with its own service controls, and load the last durable checkpoint.
Restore device and tunnel connectivity
Confirm outbound connectivity and that the Localtonet app is running with the right AuthToken. Check the tunnel's Activity Log for stops and setting changes, and check its Expiration Date and bandwidth limits. Start the tunnel; if the app is still offline, Start anyway brings it live when the app connects.
Verify the public path
Test the public URL from outside the local network. The address is unchanged after a stop and start, so use the same URL your callers use. Begin with the health route, then a non-destructive authenticated request. Do not release queued work on a Connected status alone.
Reconcile ambiguous operations
Review operations active around the interruption. Query their durable records and any external systems. Mark each one complete, safe to retry, or needing review, and keep the original idempotency key for any retry.
Resume from the last verified checkpoint
Continue from the first incomplete verified boundary. Rebuild working context from durable artifacts, decisions, and checkpoint data instead of rerunning completed tool calls.
Close the incident after sustained verification
Confirm that connectivity, public health, task progress, and callback delivery stay stable for the observation period your team chose. Record the cause when known and improve checkpoints, probes, or retry controls if recovery needed guesswork.
Test recovery before depending on it
Run controlled failure exercises in a non-production environment. Stop the agent during a checkpointed task and confirm it resumes without repeating a completed side effect. Stop the Localtonet client with Ctrl + C while the agent stays healthy, and confirm that monitoring reports a connectivity problem rather than an application crash. Stop the webhook receiver during a tunnel restart and confirm that active probes still detect the outage, since that event will not be redelivered. Restart the tunnel and confirm the public URL is unchanged and queued callbacks are reconciled before delivery.
Also test ambiguous failures. Interrupt a client after the server accepted an operation but before the response arrived. The retry should use the same idempotency key and return the recorded result. Finally, run a long task through a deliberately low HTTP Timeout to confirm that your async submit-and-poll path handles it and that nothing depends on a held-open request.
Protect a persistent agent endpoint
Reliability work must not weaken security. A public endpoint that stays up for days sees more scanning and misuse than a short development tunnel. The tunnel solves reachability. Your access controls, at the tunnel and in the application, decide who can invoke the agent and what each caller may do.
Access controls on the tunnel
Our HTTP tunnels offer several controls that stop unwanted traffic before it reaches your agent. Combine them with application-level authorization rather than replacing it.
| Control | What it does | Good fit for agents |
|---|---|---|
| Basic Authentication? | Asks visitors for a username and password | Simple machine-to-machine callers that support basic credentials |
| IP Restriction | Controls which client IP addresses can access the tunnel | Callers with known, stable egress addresses, such as a CI system or an orchestration server |
| SSO Providers | Visitors sign in with one of your identity providers before they can open the tunnel; the SSO button at the top of the page manages providers | Human-facing agent dashboards and approval pages |
| WAF button in the Actions column | Opens WAF Setting; the button shows whether the Web Application Firewall is not configured, active or inactive | Public agent APIs that should filter malicious requests at the edge |
| Is Only Https? | Redirects HTTP to HTTPS so the URL is served over HTTPS only | Every agent API that carries credentials or private data |
Logs, health and limits
Request Log lets you inspect requests that reached the tunnel, Activity Log records starts, stops and setting changes, and Tunnel Health shows the health checks. Together they answer “did the request reach us?” and “did someone or something stop this tunnel?” without logging into the agent host.
Under limits and expiration you can set an Expiration Date, Speed Limits and a Bandwidth Limit, reset the counter with Bandwidth Usage, and view Bandwidth Traffic over time. These are useful guardrails for a temporary demo, but they also explain outages: an expiration date stops the tunnel on that date, and a bandwidth cap can end a busy agent's reachability midway through a run. Review both before starting a long job.
For resilience, Load Balance lets you distribute traffic across devices or use a backup target. If your agent can run on more than one machine with shared durable state, a backup target is a way to keep the public address answering when the primary device goes offline. Your application still has to make the backup safe, for example by preventing two workers from processing the same task.
Our HTTP tunnel documentation includes a section on a warning page that applies on the Free plan. Read the current behavior there before pointing automated callers or webhook senders at a Free-plan tunnel, because this guide does not describe how that page interacts with machine clients.
Application-level controls
Treat inbound content as untrusted even on an authenticated endpoint. Authentication identifies a caller but does not make every prompt, URL, document, filename, or tool argument safe. Apply validation and policy checks before the agent invokes local tools or reads data. Give downstream credentials the least privilege the task needs, and store human approvals as durable state so a restart neither forgets nor invents them.
Because the connectivity webhook URL contains its own secret, treat that URL as a credential: keep it out of screenshots and tickets, and rotate it by deleting and recreating the webhook if it leaks. Rotate a device token if exposure is suspected and update the client through the supported workflow. Never include a real token in a sample payload, issue report, or monitoring label.
Troubleshooting long-running agent reachability
The public endpoint is unavailable and a Token event says Disconnected
Start with the device. Confirm it is powered on, has outbound connectivity, and is running the Localtonet client. If the device sits behind a strict firewall, the Outbound Port setting lets the app use fixed outbound ports for its server connection. Once the device reconnects, check tunnel state and application health. Do not restart the agent if its process and state stayed intact.
The outage happened but no webhook arrived
If your receiver was down, slow, or returned an error at that moment, the event was lost: failed calls are not repeated. This is why active probes must run alongside webhooks. Check the tunnel's Activity Log for what happened, then fix receiver availability by keeping it lightweight and persisting before responding. If no events arrive at all, work through the webhook setup errors table above.
The Disconnected event arrived later than the outage
This is expected. A disconnect is reported when Localtonet registers that the client is gone, which can be a little later than the moment the device lost its connection. If you need tighter detection, shorten the interval of your own public health probes. Use the parsed ActionDate for timeline reconstruction and remember it reflects when the change was registered.
The token is Connected but the tunnel is not running
Creating a tunnel does not start it. Check the Activity Log for a stop, then check whether an Expiration Date passed or a Bandwidth Limit was reached, since either stops the tunnel. Confirm the tunnel uses the right Device token, then select the start button in the Actions column and verify the public URL.
The tunnel restarted unexpectedly
Changing Is SslStream? or Legacy Connect? on a running tunnel restarts it. The Activity Log shows setting changes, so check whether someone edited the tunnel. Schedule such changes between agent runs.
Long agent requests fail with a timeout while the agent keeps working
The request probably exceeded the tunnel's HTTP Timeout, which can be set from 1 to 600 seconds. The caller typically sees a gateway-timeout style error even though the agent finishes later. Raise the timeout for requests that legitimately take a few minutes, and move anything longer to the accept-then-poll or callback pattern. Make sure the retried submission reuses its idempotency key so the caller does not start a second job.
The first MCP tool call times out right after the tunnel starts
If upstream MCP servers run through npx, their packages download on first connect, which can take 60 to 120 seconds against a 120 second per-server timeout. This is gateway warm-up, not a tunnel failure. Retry once before troubleshooting.
The tunnel runs but the public health check fails
Test the target on the device using the same local IP address and port configured in the tunnel. If the service itself uses HTTPS, turn on Is SslStream?. If the server answers with the wrong site or an error tied to host names, add a Host request header under Headers. Use the Request Log to confirm the request reached the tunnel.
Webhooks are missing from the dashboard menu
The Webhooks menu item is not shown in a team dashboard. Switch to your own account dashboard to create or manage webhooks.
Callbacks are duplicated after reconnection
Check whether the sender reused the same idempotency key and whether the receiver enforced uniqueness atomically. Confirm deduplication records survive restarts and are kept for the sender's retry period. A new key per retry makes duplicates unrecognizable.
The agent restarts from the beginning after a crash
This is an application-state problem, not a tunnel problem. Move task state out of process memory, persist verified checkpoints, and record completed operations before acknowledging them. The tunnel restores reachability, and the address stays the same, but it cannot recreate missing task state.
Alerts flap between Connected and Disconnected
Keep every observation, deduplicated on Id + Type + Status + ActionDate, but correlate transitions into one incident with a debounce period chosen for your environment. Use active probes to judge current impact, and do not hide prolonged instability just because the endpoint briefly reconnects.
Frequently asked questions
Does a Localtonet tunnel keep an AI agent running?
No. A tunnel provides reachability to a local target while the Localtonet app for its AuthToken is connected and the tunnel is running. Process supervision, task queues, durable state, checkpoints, and restart behavior belong to your application environment.
Does a Connected tunnel prove that the agent is healthy?
No. Connected describes tunnel connectivity. The local process may still be stopped, misconfigured, blocked on a dependency, or logically stalled. Combine tunnel state with liveness, readiness, public health checks, and task-level progress monitoring.
Does the public URL change when I stop and start an HTTP tunnel?
No. An HTTP tunnel keeps its subdomain until you delete it. Stopping and starting does not change the address, so callers and agent clients keep working after a restart. Deleting and recreating a tunnel with a Random subdomain gives a new name.
How long can a single request through an HTTP tunnel take?
The HTTP Timeout setting controls how long the server waits for your local application, from 1 to 600 seconds. Work that can run longer, such as a multi-hour agent task, should use an accept-then-poll or callback pattern instead of a held-open request.
Are Localtonet connectivity webhooks retried or signed?
Neither. A failed call is not repeated, so your endpoint must be available and answer quickly, and active probes should back up any missed events. The request has no signature or secret header. To verify origin, put a long random value in the webhook URL as a path segment or query parameter and check it in your receiver. No unique event ID is documented, so deduplicate on Id, Type, Status and ActionDate.
What does a Localtonet connectivity webhook contain?
A POST with content type application/json; charset=utf-8 and four fields. Id identifies the AuthToken for Token events, or carries the numeric tunnel ID as a string (the API's tunnelId) for Tunnel events. ActionDate is ISO 8601 with an offset, Type is Token or Tunnel, and Status is Connected or Disconnected.
Can I edit a webhook after creating it?
No. To change the URL, group, or switches, delete the webhook and create a new one. You can create several webhooks for the same token group, for example separate URLs for connect and disconnect events.
Are connectivity webhooks the same as File Server webhooks?
No. Token and Tunnel webhooks report Connected and Disconnected changes and carry no signature. File Server webhooks report file-level upload, delete, rename, and move events and support optional HMAC signing.
Should queued callbacks be sent immediately after a Connected event?
Not on that event alone. Verify the public endpoint and application readiness first, reconcile operations whose outcome became ambiguous, and retry only callbacks that are still needed, with their original idempotency keys.
Can Localtonet expose an agent when the device has no public IP address?
Yes. The Localtonet client opens an outbound connection to our relay servers, so no public IP address, router port forwarding, firewall changes, or VPN setup is needed. The tunnel carries traffic only while the app is connected and the tunnel is running.
Make your local agent reachable without making recovery fragile
Start with a checkpointed, retry-safe agent. Then publish it through a Localtonet HTTP tunnel with a stable address, protect it with Is Only Https?, IP Restriction, SSO or WAF, and wire Token and Tunnel webhooks plus active probes into your recovery runbook.
Get Started Free →Corrections & updates
Substantive changes approved by the Localtonet editorial team are listed transparently below.
Localtonet is a secure multi-protocol tunneling and proxy platform designed to expose localhost, devices, private services, and AI agents to the public internet supporting HTTP/HTTPS tunnels, TCP/UDP forwarding, mobile proxy infrastructure, file server publishing, latency-optimized game connectivity, and developer-ready AI agent endpoint exposure from a single unified control plane.